diff --git a/.devops/openvino.Dockerfile b/.devops/openvino.Dockerfile
index e290bde9bdd1..c88cc2bbb5f9 100644
--- a/.devops/openvino.Dockerfile
+++ b/.devops/openvino.Dockerfile
@@ -3,11 +3,11 @@ ARG OPENVINO_VERSION_FULL=2026.4.1.22982.07f9c262b05
ARG UBUNTU_VERSION=24.04
# Intel GPU driver versions. https://github.com/intel/compute-runtime/releases
-ARG IGC_VERSION=v2.41.5
-ARG IGC_VERSION_FULL=2_2.41.5+22716
-ARG COMPUTE_RUNTIME_VERSION=26.35.39758.10
-ARG COMPUTE_RUNTIME_VERSION_FULL=26.35.39758.10-0
-ARG IGDGMM_VERSION=22.10.0
+ARG IGC_VERSION=v2.42.6
+ARG IGC_VERSION_FULL=2_2.42.6+23070
+ARG COMPUTE_RUNTIME_VERSION=26.40.40196.8
+ARG COMPUTE_RUNTIME_VERSION_FULL=26.40.40196.8-0
+ARG IGDGMM_VERSION=22.10.2
# Intel NPU driver versions. https://github.com/intel/linux-npu-driver/releases
ARG NPU_DRIVER_VERSION=v1.38.0
diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml
index 96fb5162579d..10d7ed0ed5e4 100644
--- a/.github/workflows/ui.yml
+++ b/.github/workflows/ui.yml
@@ -93,6 +93,11 @@ jobs:
run: npm run lint
working-directory: ui/apps/chat
+ - name: Check DESIGN.md is current with the tokens
+ if: ${{ always() && steps.setup.conclusion == 'success' }}
+ run: npm run check:design
+ working-directory: ui/apps/chat
+
- name: Install Playwright browsers
id: playwright
if: ${{ always() && steps.setup.conclusion == 'success' }}
diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md
index 00effa9a85e1..0b5615ca2460 100644
--- a/docs/backend/OPENVINO.md
+++ b/docs/backend/OPENVINO.md
@@ -3,9 +3,9 @@
> [!NOTE]
> Performance and memory optimizations, accuracy validation, broader quantization coverage, broader operator and model support are work in progress.
-[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware, including CPUs, GPUs, and NPUs, in the cloud, on-premises, and on the edge. [OpenVINO backend for llama.cpp](../../ggml/src/ggml-openvino) enables hardware-accelerated inference on **Intel® CPUs, GPUs, and NPUs** while remaining compatible with the existing **GGUF model ecosystem**. The backend translates GGML compute graphs into OpenVINO graphs and leverages graph compilation, kernel fusion, and device-specific optimizations to improve inference performance on supported Intel hardware.
+[OpenVINO](https://docs.openvino.ai/) is an open-source toolkit for optimizing and deploying high-performance AI inference, specifically designed for Intel hardware, including CPUs, GPUs (integrated and discrete), and NPUs, in the cloud, on-premises, and on the edge. The [OpenVINO backend](../../ggml/src/ggml-openvino) runs the same GGUF model files on **Intel® CPUs, GPUs and NPUs**, without changes to the model or the rest of llama.cpp.
-The OpenVINO backend is implemented in `ggml/src/ggml-openvino` and provides a translation layer for core GGML operations. The OpenVINO backend replaces the standard GGML graph execution path with Intel's OpenVINO inference engine. This approach allows the same GGUF model file to run on Intel CPUs, Intel GPUs (integrated and discrete), and Intel NPUs without changes to the model or the rest of the llama.cpp stack. When a `ggml_cgraph` is dispatched to OpenVINO backend, it:
+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.
@@ -16,9 +16,10 @@ For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend
## Contents
+- [Quick Start](#quick-start)
- [Supported Devices](#supported-devices)
- [Supported Model Precisions](#supported-model-precisions)
-- [Supported Llama.cpp Tools](#supported-llamacpp-tools)
+- [Supported llama.cpp Tools](#supported-llamacpp-tools)
- [Validated Models](#validated-models)
- [Build Instructions](#build-instructions)
- [0. Prerequisites](#0-prerequisites)
@@ -29,10 +30,44 @@ For guidance on contributing to the OpenVINO backend, see the [OpenVINO Backend
- [3. Download Sample Model](#3-download-sample-model)
- [4. Run Inference with OpenVINO Backend](#4-run-inference-with-openvino-backend)
- [5. Docker Build](#5-docker-build)
-- [GGML OpenVINO Backend Runtime Configurations](#ggml-openvino-backend-runtime-configurations)
+- [Runtime Configuration](#runtime-configuration)
+ - [Basic](#basic)
+ - [Plugin properties](#plugin-properties)
+ - [Advanced tuning](#advanced-tuning)
+ - [Compiled model cache](#compiled-model-cache)
+ - [Deprecated](#deprecated)
+ - [Debugging and development](#debugging-and-development)
+ - [Example Usage](#example-usage)
+ - [GPU Inference with Profiling](#gpu-inference-with-profiling)
- [Known Limitations](#known-limitations)
- [Work in Progress](#work-in-progress)
+## Quick Start
+
+On Ubuntu, with the [prerequisites](#0-prerequisites) and the [OpenVINO Runtime](#1-install-openvino-runtime) installed:
+
+```bash
+# 1. Build
+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
+
+# 2. Download a model
+mkdir -p ~/models/
+wget https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf \
+ -O ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+
+# 3. Run on CPU, GPU or NPU
+export GGML_OPENVINO_DEVICE=GPU
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+```
+
+The [Ubuntu Build Script](#ubuntu-build-script) and the [Windows Build Script](#windows-build-script) do the setup in one step: they install the prerequisites and the OpenVINO Runtime, and build llama.cpp with the OpenVINO backend.
+
+See [Build Instructions](#build-instructions) for Windows and Docker, and [Runtime Configuration](#runtime-configuration) for the environment variables.
+
## Supported Devices
OpenVINO backend supports the following hardware:
@@ -41,7 +76,7 @@ OpenVINO backend supports the following hardware:
- Intel GPUs (integrated and discrete)
- Intel NPUs
-Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), the llama.cpp OpenVINO backend has been validated specifically on AI PCs such as the Intel® Core™ Ultra Series 1 and Series 2.
+Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), the llama.cpp OpenVINO backend has been validated specifically on AI PCs such as the Intel® Core™ Ultra Series 2 (Lunar Lake) and Series 3 (Panther Lake).
## Supported Model Precisions
@@ -51,101 +86,123 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
- `Q4_0`
- `Q4_1`
- `Q4_K`
-- `Q4_K_M`
-- `Q5_K` (converted to `Q8_0_C` at runtime by default)
-- `Q6_K` (converted to `Q8_0_C` at runtime by default)
+- `Q5_0` (converted at runtime, see the details below)
+- `Q5_1`
+- `Q5_K` (converted at runtime, see the details below)
+- `Q6_K` (converted at runtime, see the details below)
-> [!NOTE]
-> Accuracy validation and performance optimizations for quantized models are a work in progress.
+`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_1` and `Q8_0` tensors keep their layout: weights, scales and zero points are extracted directly.
+- `Q5_K` and `Q6_K` tensors are converted to `Q8_0_C`. `GGML_OPENVINO_REQUANT_KQUANT` selects a 4-bit layout instead.
+- `Q5_0` tensors are converted to `Q4_0_64`.
-**CPU and GPU Quantization Details:**
-- `Q5_K` and `Q6_K` tensors are converted to `Q8_0_C`
+**GPU:**
+- `Q4_K`, `Q5_K` and `Q6_K` MoE expert tensors are converted to `Q4_1_64`. This lets the GPU plugin use its fused MoE op, which is much faster for prompt processing. `GGML_OPENVINO_REQUANT_KQUANT` does not change this. `GGML_OPENVINO_MOE_OP=0` turns the fused MoE op off.
-**NPU Quantization Details:**
-- Primary supported quantization scheme is `Q4_0`
-- `Q6_K` tensors are requantized to `Q4_0_128` in general. For embedding weights, `Q6_K` tensors are requantized to `Q8_0_C` except for the token embedding matrix which is dequantized to fp16
+**NPU:**
+- All other quantized tensors are requantized to `Q4_0_128`.
+- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout.
+- 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.
**Additional Notes:**
- Both `Q4_0` and `Q4_1` models use `Q6_K` for the token embedding tensor and the final matmul weight tensor (often the same tensor)
- `Q4_0` models may produce some `Q4_1` tensors if an imatrix is provided during quantization using `llama-quantize`
- `Q4_K_M` models may include both `Q6_K` and `Q5_K` tensors (observed in Phi-3)
-- `Q5_1` tensors are dequantized natively (weights, scales, and zero-points extracted directly)
-## Supported Llama.cpp Tools
+
+
+## Supported llama.cpp Tools
-The OpenVINO backend integrates with the standard llama.cpp tools listed below.
-However, all the tools coverage across all devices is not uniform and exhaustive validation is work in progress.
+The OpenVINO backend works with the standard llama.cpp tools listed below. Tool coverage is not uniform across devices.
- llama-bench
- llama-cli
- llama-completion
- llama-embedding
- llama-perplexity
-- llama-run
- llama-server
- llama-simple
## Validated Models
-Although, the validated models below were tested with `llama-cli` using the `Q4_K_M` quantization format on Intel® Core™ Ultra Series 2 (Lunar Lake), the OpenVINO backend is expected to work across a broader range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), [supported model precisions](#supported-model-precisions), [supported llama.cpp tools](#supported-llamacpp-tools) and additional model architectures.
-
-> [!NOTE]
-> Extensive accuracy validation, performance optimizations, and broader architecture coverage are work in progress.
+The models below were tested with `llama-cli` and `Q4_K_M` files on an Intel® Core™ Ultra Series 2 (Lunar Lake). The OpenVINO backend is expected to work on a broader range of [Intel hardware](https://docs.openvino.ai/2026/about-openvino/release-notes-openvino/system-requirements.html), [model precisions](#supported-model-precisions), [llama.cpp tools](#supported-llamacpp-tools) and model architectures.
**Legend & Test Configuration:**
- **Status:** ✓ = Passed | ~ = Accuracy issues | ✗ = Failed or Unsupported
-- **Execution Modes:**
- - **SL** = Stateless (`GGML_OPENVINO_STATEFUL_EXECUTION=0`)
- - **SF** = Stateful (`GGML_OPENVINO_STATEFUL_EXECUTION=1`)
- - Note: The NPU operates in stateless mode only.
-- **Validation system:** Intel® Core™ Ultra 5 238V (Lunar Lake) | 32 GB RAM | Ubuntu 24.04 | Intel Graphics Compiler 2.41.5 | Intel OpenCL GPU Driver 26.35.39758.10-0 | Intel NPU Driver 1.38.0.
+- **Execution mode:** stateless (`GGML_OPENVINO_STATEFUL_EXECUTION=0`) on every device.
+- **Validation system:** Intel® Core™ Ultra 7 258V (Lunar Lake) | 32 GB RAM | Ubuntu 26.04.1 | Intel Graphics Compiler 2.42.6 | Intel OpenCL GPU Driver 26.40.40196.8-0 | Intel NPU Driver 1.38.0.
- See [Known Limitations](#known-limitations) for context on observed failures.
-| Model | CPU (SL / SF) | GPU (SL / SF) | NPU (SL) |
+
+Validated models
+
+| Model | CPU | GPU | NPU |
| :--- | :---: | :---: | :---: |
-| [bartowski/Llama-3.2-1B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Llama-3.2-3B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Llama-3.2-3B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Meta-Llama-3.1-8B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [bartowski/Llama-3.2-1B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Llama-3.2-3B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Llama-3.2-3B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Meta-Llama-3.1-8B-Instruct-Q4_K_M](https://huggingface.co/bartowski/Meta-Llama-3.1-8B-Instruct-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [Qwen/qwen2.5-1.5b-instruct-q4_k_m](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [Qwen/qwen2.5-coder-7b-instruct-q4_k_m](https://huggingface.co/Qwen/Qwen2.5-Coder-7B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Qwen_Qwen3-0.6B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-0.6B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Qwen_Qwen3-1.7B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-1.7B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [Qwen/Qwen3-4B-Q4_K_M](https://huggingface.co/Qwen/Qwen3-4B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [lm-kit/Qwen3-8B-Q4_K_M](https://huggingface.co/lm-kit/qwen-3-8b-instruct-gguf) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Qwen_Qwen3.5-0.8B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-0.8B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ |
-| [bartowski/Qwen_Qwen3.5-2B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ |
-| [bartowski/Qwen_Qwen3.5-4B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ |
-| [lmstudio-community/Qwen3.5-9B-Q4_K_M](https://huggingface.co/lmstudio-community/Qwen3.5-9B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ |
+| [Qwen/qwen2.5-1.5b-instruct-q4_k_m](https://huggingface.co/Qwen/Qwen2.5-1.5B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [Qwen/qwen2.5-coder-7b-instruct-q4_k_m](https://huggingface.co/Qwen/Qwen2.5-Coder-7B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Qwen_Qwen3-0.6B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-0.6B-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Qwen_Qwen3-1.7B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3-1.7B-GGUF) | ✓ | ✓ | ✓ |
+| [Qwen/Qwen3-4B-Q4_K_M](https://huggingface.co/Qwen/Qwen3-4B-GGUF) | ✓ | ✓ | ✓ |
+| [lm-kit/Qwen3-8B-Q4_K_M](https://huggingface.co/lm-kit/qwen-3-8b-instruct-gguf) | ✓ | ✓ | ✓ |
+| [bartowski/Qwen_Qwen3.5-0.8B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-0.8B-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Qwen_Qwen3.5-2B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-2B-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Qwen_Qwen3.5-4B-Q4_K_M](https://huggingface.co/bartowski/Qwen_Qwen3.5-4B-GGUF) | ✓ | ✓ | ✓ |
+| [lmstudio-community/Qwen3.5-9B-Q4_K_M](https://huggingface.co/lmstudio-community/Qwen3.5-9B-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [unsloth/gemma-3-4b-it-Q4_K_M](https://huggingface.co/unsloth/gemma-3-4b-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/google_gemma-4-E2B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ~ |
-| [bartowski/google_gemma-4-E4B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E4B-it-GGUF) | ✓ / ✓ | ✗ / ✗ | ✓ |
-| [bartowski/gemma-4-12B-it-Q4_K_M](https://huggingface.co/bartowski/gemma-4-12B-it-GGUF) | ✓ / ✓ | ✓ / ✓ | ✗ |
+| [unsloth/gemma-3-4b-it-Q4_K_M](https://huggingface.co/unsloth/gemma-3-4b-it-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/google_gemma-4-E2B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E2B-it-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/google_gemma-4-E4B-it-Q4_K_M](https://huggingface.co/bartowski/google_gemma-4-E4B-it-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/gemma-4-12B-it-Q4_K_M](https://huggingface.co/bartowski/gemma-4-12B-it-GGUF) | ✓ | ✓ | ✗ |
| | | | |
-| [bartowski/Phi-3-mini-4k-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3-mini-4k-instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Phi-3.5-mini-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/microsoft_Phi-4-mini-instruct-Q4_K_M](https://huggingface.co/bartowski/microsoft_Phi-4-mini-instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [bartowski/Phi-3-mini-4k-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3-mini-4k-instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Phi-3.5-mini-instruct-Q4_K_M](https://huggingface.co/bartowski/Phi-3.5-mini-instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/microsoft_Phi-4-mini-instruct-Q4_K_M](https://huggingface.co/bartowski/microsoft_Phi-4-mini-instruct-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [bartowski/Mistral-7B-Instruct-v0.3-Q4_K_M](https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [QuantFactory/Ministral-3b-instruct.Q4_K_M](https://huggingface.co/QuantFactory/Ministral-3b-instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/Ministral-8B-Instruct-2410-Q4_K_M](https://huggingface.co/bartowski/Ministral-8B-Instruct-2410-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [bartowski/Mistral-7B-Instruct-v0.3-Q4_K_M](https://huggingface.co/bartowski/Mistral-7B-Instruct-v0.3-GGUF) | ✓ | ✓ | ✓ |
+| [QuantFactory/Ministral-3b-instruct.Q4_K_M](https://huggingface.co/QuantFactory/Ministral-3b-instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/Ministral-8B-Instruct-2410-Q4_K_M](https://huggingface.co/bartowski/Ministral-8B-Instruct-2410-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [bartowski/DeepSeek-R1-Distill-Llama-8B-Q4_K_M](https://huggingface.co/bartowski/DeepSeek-R1-Distill-Llama-8B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/DeepSeek-R1-Distill-Qwen-7B-Q4_K_M](https://huggingface.co/bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [bartowski/DeepSeek-R1-Distill-Llama-8B-Q4_K_M](https://huggingface.co/bartowski/DeepSeek-R1-Distill-Llama-8B-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/DeepSeek-R1-Distill-Qwen-7B-Q4_K_M](https://huggingface.co/bartowski/DeepSeek-R1-Distill-Qwen-7B-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [ibm-granite/granite-4.0-350m-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-350m-GGUF) | ✓ / ✓ | ~ / ~ | ✓ |
-| [ibm-granite/granite-4.0-micro-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-micro-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [ibm-granite/granite-4.0-1b-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-1b-GGUF) | ✓ / ✓ | ~ / ~ | ~ |
-| [ibm-research/granite-3.2-8b-instruct-Q4_K_M](https://huggingface.co/ibm-research/granite-3.2-8b-instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [ibm-granite/granite-4.0-350m-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-350m-GGUF) | ✓ | ✓ | ✓ |
+| [ibm-granite/granite-4.0-micro-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-micro-GGUF) | ✓ | ✓ | ✓ |
+| [ibm-granite/granite-4.0-1b-Q4_K_M](https://huggingface.co/ibm-granite/granite-4.0-1b-GGUF) | ✓ | ✓ | ~ |
+| [ibm-research/granite-3.2-8b-instruct-Q4_K_M](https://huggingface.co/ibm-research/granite-3.2-8b-instruct-GGUF) | ✓ | ✓ | ✓ |
| | | | |
-| [HuggingFaceTB/smollm2-1.7b-instruct-q4_k_m](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [openbmb/MiniCPM-V-2_6-Q4_K_M](https://huggingface.co/openbmb/MiniCPM-V-2_6-gguf) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/tencent_Hunyuan-7B-Instruct-Q4_K_M](https://huggingface.co/bartowski/tencent_Hunyuan-7B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-Q4_K_M](https://huggingface.co/LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
-| [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ / ✓ | ✓ / ✓ | ✓ |
+| [HuggingFaceTB/smollm2-1.7b-instruct-q4_k_m](https://huggingface.co/HuggingFaceTB/SmolLM2-1.7B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [openbmb/MiniCPM-V-2_6-Q4_K_M](https://huggingface.co/openbmb/MiniCPM-V-2_6-gguf) | ✓ | ✓ | ✓ |
+| [openbmb/MiniCPM-V-4_5-Q4_K_M](https://huggingface.co/openbmb/MiniCPM-V-4_5-gguf) | ✓ | ✓ | ✓ |
+| [bartowski/tencent_Hunyuan-7B-Instruct-Q4_K_M](https://huggingface.co/bartowski/tencent_Hunyuan-7B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-Q4_K_M](https://huggingface.co/LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct-GGUF) | ✓ | ✓ | ✓ |
+| [bartowski/prism-ml_Bonsai-8B-unpacked-Q4_K_M](https://huggingface.co/bartowski/prism-ml_Bonsai-8B-unpacked-GGUF) | ✓ | ✓ | ✓ |
+| [LiquidAI/LFM2.5-2.6B-Q4_K_M](https://huggingface.co/LiquidAI/LFM2.5-2.6B-GGUF) | ✓ | ✓ | ✗ |
+| [bartowski/inclusionAI_Ling-mini-2.0-Q4_K_M](https://huggingface.co/bartowski/inclusionAI_Ling-mini-2.0-GGUF) | ✓ | ✓ | ✗ |
| | | | |
-| [gpustack/bge-m3-Q4_K_M.gguf](https://huggingface.co/gpustack/bge-m3-GGUF) | ✓ | ✗ | ✗ |
+| [Qwen/Qwen3-Embedding-0.6B-Q8_0](https://huggingface.co/Qwen/Qwen3-Embedding-0.6B-GGUF) | ✓ | ✓ | ✗ |
+| [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 Instructions
@@ -154,39 +211,51 @@ Although, the validated models below were tested with `llama-cli` using the `Q4_
- Linux or Windows system with Intel hardware (CPU, GPU, or NPU)
- **For Intel GPU or NPU Usage**: Install the appropriate hardware drivers for your Intel GPU or NPU. For detailed instructions, see: [Additional Configurations for Hardware Acceleration](https://docs.openvino.ai/2026/get-started/install-openvino/configurations.html).
-- **Linux:**
- - Git, CMake, and Ninja software tools are needed for building.
- ```bash
- sudo apt-get update
- sudo apt-get install -y build-essential libcurl4-openssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar
- ```
- - OpenCL
- ```bash
- sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
- ```
-
-- **Windows:**
- - Download and install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe). During installation, select the **"Desktop development with C++"** workload.
-
- - Install required tools:
- ```powershell
- # Windows PowerShell
- winget install Git.Git
- winget install GNU.Wget
- winget install Ninja-build.Ninja
- ```
-
- - Install **OpenCL** using **vcpkg**:
- ```powershell
- # Windows PowerShell
- cd C:\
- git clone https://github.com/microsoft/vcpkg
- cd vcpkg
- .\bootstrap-vcpkg.bat
- .\vcpkg install opencl
- # Optional but recommended: Integrate vcpkg with Visual Studio / CMake:
- .\vcpkg integrate install
- ```
+
+Linux
+
+Build tools (Git, CMake, Ninja):
+
+```bash
+sudo apt-get update
+sudo apt-get install -y build-essential libcurl4-openssl-dev libtbb12 cmake ninja-build python3-pip curl wget tar
+```
+
+OpenCL:
+
+```bash
+sudo apt install ocl-icd-opencl-dev opencl-headers opencl-clhpp-headers intel-opencl-icd
+```
+
+
+
+
+Windows
+
+1. Download and install [Microsoft Visual Studio 2022 Build Tools](https://aka.ms/vs/17/release/vs_BuildTools.exe). During installation, select the **"Desktop development with C++"** workload.
+2. Install the required tools:
+
+ ```powershell
+ # Windows PowerShell
+ winget install Git.Git
+ winget install GNU.Wget
+ winget install Ninja-build.Ninja
+ ```
+
+3. Install **OpenCL** using **vcpkg**:
+
+ ```powershell
+ # Windows PowerShell
+ cd C:\
+ git clone https://github.com/microsoft/vcpkg
+ cd vcpkg
+ .\bootstrap-vcpkg.bat
+ .\vcpkg install opencl
+ # Optional but recommended: Integrate vcpkg with Visual Studio / CMake:
+ .\vcpkg integrate install
+ ```
+
+
### 1. Install OpenVINO Runtime
@@ -199,21 +268,25 @@ Although, the validated models below were tested with `llama-cli` using the `Q4_
### 2. Build llama.cpp with OpenVINO Backend
-Clone llama.cpp repo and build :
+Clone the llama.cpp repository:
```bash
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
```
-- **Linux:**
+Build on Linux:
+
```bash
source /opt/intel/openvino/setupvars.sh
cmake -B build/ReleaseOV -G Ninja -DCMAKE_BUILD_TYPE=Release -DGGML_OPENVINO=ON
cmake --build build/ReleaseOV --parallel
```
-- **Windows:** Open **x64 Native Tools Command Prompt for VS** (so the MSVC toolchain is on `PATH`), then run:
+
+Build on Windows
+
+Open **x64 Native Tools Command Prompt for VS** (so the MSVC toolchain is on `PATH`), then run:
```cmd
C:\Intel\openvino\setupvars.bat
@@ -224,9 +297,11 @@ cmake --build build\ReleaseOV --parallel
> [!NOTE]
> The Windows install path is `C:\Intel\openvino` (no spaces) to avoid quoting problems some CMake/Ninja toolchains have with `C:\Program Files (x86)\...`. Adjust to wherever you installed OpenVINO Runtime. From `cmd`, run `C:\Intel\openvino\setupvars.bat`; from PowerShell, run `& "C:\Intel\openvino\setupvars.ps1"` instead. Once the build is finished you can launch the binaries from any `cmd` or `PowerShell` window after sourcing the matching `setupvars` script for that shell.
+
+
#### Ubuntu Build Script
-For Ubuntu24 users, the following shell script automates the prerequisite installs (build tools, OpenCL ICD), the OpenVINO Runtime download/extract/setup, and the Ninja-based llama.cpp build.
+For Ubuntu users, the following shell script automates the prerequisite installs (build tools, OpenCL ICD), the OpenVINO Runtime download/extract/setup, and the Ninja-based llama.cpp build.
Save the following as `build-llamacpp-ov.sh` next to where you want the `llama.cpp` folder to land, then run it:
```bash
@@ -556,81 +631,102 @@ endlocal
-
### 3. Download Sample Model
-Download sample model for testing.
+Download a sample model for testing.
```bash
-# Linux
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
+```
+
+Windows
+
+```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
+```
-# Windows Command Line
+```cmd
+REM Windows Command Prompt
mkdir C:\models
curl -L https://huggingface.co/bartowski/Llama-3.2-1B-Instruct-GGUF/resolve/main/Llama-3.2-1B-Instruct-Q4_K_M.gguf -o C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf
```
+
+
### 4. Run Inference with OpenVINO Backend
-When using the OpenVINO backend, the first inference token may have slightly higher latency due to on-the-fly conversion to the OpenVINO graph. Subsequent tokens and runs will be faster.
+The first run of a model converts and compiles it for the device. This takes seconds on CPU and GPU, and can take minutes on the NPU for large models. Later tokens are faster, and the [compiled model cache](#compiled-model-cache) makes later runs start faster.
> [!NOTE]
-> Default context size is set to the model training context, which may be very large. For example, 131072 for Llama 3.2 1B, which may result in lower performance, especially on edge/laptop devices. Use `-c` to limit context size in supported llama.cpp tools for better performance. For example, `-c 512`.
+> Default context size is set to the model training context, which may be very large. For example, 131072 for Llama 3.2 1B, which may result in lower performance, especially on edge/laptop devices. Use `-c` to limit context size in supported llama.cpp tools for better performance:
+> - CPU and GPU: for example `-c 1024`.
+> - NPU: keep the context small, for example `-c 512`, or `-c 256` for larger models. Decode may slow down as the context grows.
```bash
-# If device is unset or unavailable, defaults to CPU.
-# If the system has multiple GPUs, use GPU.0 or GPU.1 to explicitly target a specific GPU.
-
-# Linux
+# If the device is unset, the CPU is used.
export GGML_OPENVINO_DEVICE=GPU
-# Optional: enable stateful execution for improved GPU performance (recommended).
-export GGML_OPENVINO_STATEFUL_EXECUTION=1
# To run llama-simple:
./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
# To run in chat mode:
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
-# To run llama-bench, -fa 1 is needed
-GGML_OPENVINO_STATEFUL_EXECUTION=1 GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -fa 1
+# To run llama-bench:
+GGML_OPENVINO_DEVICE=GPU ./build/ReleaseOV/bin/llama-bench -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
# NPU: keep context small to avoid failures from very large model context windows.
export GGML_OPENVINO_DEVICE=NPU
./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
+```
-# Windows Command Line
-set GGML_OPENVINO_DEVICE=GPU
-# Optional: enable stateful execution for improved GPU performance (recommended).
-set GGML_OPENVINO_STATEFUL_EXECUTION=1
-# Windows PowerShell
-$env:GGML_OPENVINO_DEVICE = "GPU"
-$env:GGML_OPENVINO_STATEFUL_EXECUTION = "1"
+
+Windows
-# To run llama-simple
+```cmd
+REM Windows Command Prompt
+set GGML_OPENVINO_DEVICE=GPU
+REM To run llama-simple:
build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
-# To run in chat mode:
+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
-# To run llama-bench, -fa 1 is needed
-build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -fa 1
+REM To run llama-bench:
+build\ReleaseOV\bin\llama-bench.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf"
-# NPU: keep context small to avoid failures from very large model context windows.
-# Windows Command Line
+REM NPU: keep the context small.
set GGML_OPENVINO_DEVICE=NPU
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
+```
+
+```powershell
# Windows PowerShell
+$env:GGML_OPENVINO_DEVICE = "GPU"
+build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 1024
+
+# NPU: keep the context small.
$env:GGML_OPENVINO_DEVICE = "NPU"
build\ReleaseOV\bin\llama-cli.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -c 512
```
+
+
+
> [!NOTE]
-> On systems with multiple GPUs, use `GPU.0` or `GPU.1` to explicitly target specific GPU. A device that is not available is an error (no fallback to CPU), and the error message lists the available OpenVINO devices with their names. Run `llama-cli --list-devices` to see the valid values: each OpenVINO device shows the `GGML_OPENVINO_DEVICE=` to set, and `(selected)` marks the active one. Select the OpenVINO device with this variable, not with `-dev`. See [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html) for more details.
+> - Select the OpenVINO device with `GGML_OPENVINO_DEVICE`, not with `-dev`.
+> - On systems with multiple GPUs, use `GPU.0` or `GPU.1` to explicitly target specific GPU.
+> - To split a model across several GPUs, set a comma-separated list, e.g. `GPU.0,GPU.1`, and use `-sm layer`.
+> - A device that is not available is an error (no fallback to CPU). The error message lists the available OpenVINO devices with their names.
+> - Run `llama-cli --list-devices` to see the valid values: each OpenVINO device shows the `GGML_OPENVINO_DEVICE=` to set, and `(selected)` marks the active one.
+> - See [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html) for more details.
### 5. Docker Build
You can build and run llama.cpp with OpenVINO backend using Docker.
+
+Build the images
+
```bash
# Build the base runtime image with compiled shared libraries and minimal dependencies.
docker build -t llama-openvino:base -f .devops/openvino.Dockerfile .
@@ -648,9 +744,12 @@ docker build --target=server -t llama-openvino:server -f .devops/openvino.Docker
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 llama.cpp with OpenVINO backend Docker container.
-Save sample models in `~/models` as [shown above](#3-download-sample-model). It will be mounted to the container in the examples below.
+
+
+
+Run a container (CPU, GPU, NPU)
+Run llama.cpp with OpenVINO backend Docker container. Save sample models in `~/models` as [shown above](#3-download-sample-model). It will be mounted to the container in the examples below.
```bash
# Run Docker container
@@ -659,19 +758,20 @@ docker run --rm -it -v ~/models:/models llama-openvino:light --no-warmup -c 1024
# 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 --env=GGML_OPENVINO_STATEFUL_EXECUTION=1 \
+--env=GGML_OPENVINO_DEVICE=GPU \
llama-openvino:light --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
# With Intel NPU access
docker run --rm -it -v ~/models:/models \
---device=/dev/accel --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
+--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 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
+llama-openvino:light --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf
```
-Run Llama.cpp Server with OpenVINO Backend.
-> [!NOTE]
-> `llama-server` with OpenVINO backend supports only one chat session/thread, when `GGML_OPENVINO_STATEFUL_EXECUTION=1` is enabled.
+
+
+
+Run llama-server (container or local build) and test it
```bash
# Run the llama-openvino:server Docker container (CPU)
@@ -685,9 +785,9 @@ llama-openvino:server --no-warmup -c 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_
# Run the llama-openvino:server Docker container with Intel NPU access
docker run --rm -it -v ~/models:/models \
---device=/dev/accel --group-add=$(stat -c "%g" /dev/dri/render* | head -n 1) -u $(id -u):$(id -g) \
+--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 1024 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0
+llama-openvino:server --no-warmup -c 512 -m /models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --host 0.0.0.0
# Or Using llama-server executable
./build/ReleaseOV/bin/llama-server -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf --port 8080 -c 1024
@@ -706,101 +806,221 @@ curl -X POST "http://localhost:8080/v1/chat/completions" -H "Content-Type: appli
-d '{"messages":[{"role":"user","content":"Write a poem about OpenVINO"}],"max_tokens":100}' | jq .
```
-## GGML OpenVINO Backend Runtime Configurations
-
-The OpenVINO backend can be configured using the following environment variables at runtime to control device selection, caching, debugging, and profiling behavior.
-Boolean flags follow a uniform convention: set to a **positive integer** (e.g. `1`) to enable; unset, empty, `0`, negative, or non-numeric values are treated as disabled.
-
-| Variable | Type | Default | Description |
-|-----------------------------------|-----------|------------|-------------------------------------------------------------------------------------------------------------|
-| `GGML_OPENVINO_DEVICE` | String | `CPU` | Specify the target device (CPU, GPU, NPU). On systems with multiple GPUs, use `GPU.0` or `GPU.1` to explicitly target specific GPU. A device that is not available is an error (no fallback to CPU), and the error message lists the available OpenVINO devices with their names. See [OpenVINO GPU Device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html). When set to **NPU**, static compilation mode is enabled for optimal performance. |
-| `GGML_OPENVINO_CACHE_DIR` | String | `not set` | Directory for OpenVINO's separate plugin cache. On NPU, this sets `NPUW_CACHE_DIR`. |
-| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | String | `not set` | Directory for standalone compiled blobs with weights. Dynamic CPU/GPU graphs can import matching blobs on later runs. |
-| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | Boolean | `0` | Require an existing compiled blob and skip weight uploads and compilation. Requires Linux or Windows mmap loading and a full dynamic CPU/GPU graph on OpenVINO. |
-| `GGML_OPENVINO_PREFILL_CHUNK_SIZE`| Integer | `256` | Token chunk size for **NPU** prefill (NPU-only; ignored on CPU/GPU). Must be a positive integer; otherwise the default is used. |
-| `GGML_OPENVINO_NPU_COMPILE_CONFIG` | String | `not set` | NPU-only compiler mode parameters forwarded to OpenVINO as `NPU_COMPILATION_MODE_PARAMS`, for example `optimization-level=3`. |
-| `GGML_OPENVINO_STATEFUL_EXECUTION`| Boolean | `0` | Keep KV and supported recurrent caches inside the model. Single-slot CPU/GPU execution only. |
-| `GGML_OPENVINO_DISABLE_CACHE` | Boolean | `0` | Disable the in-process compiled-model / decoder cache (cache is on by default). Set to `1` to disable. |
-| `GGML_OPENVINO_DISABLE_KV_SLICE` | Boolean | `0` | Disable the KV-cache input-tensor slicing optimization (slicing is on by default on CPU/GPU). Set to `1` to disable. |
-| `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | Boolean | `0` | Disable the stateful KV-state sequence-axis relayout (relayout is on by default). It moves the KV state sequence axis from dim 1 to dim 2, so the GPU plugin can append new tokens in place instead of copying the whole state every token, and the reader side no longer transposes the whole accumulated state. Set to `1` to disable. |
-| `GGML_OPENVINO_MANUAL_GQA_ATTN` | Boolean | device-based | Tri-state. When **unset**, manual GQA attention is enabled by default on `GPU` and disabled on other devices. Set to a positive integer to force-enable, or `0` to force-disable. |
-| `GGML_OPENVINO_MEMORY_OPTIMIZE` | Boolean | `0` | Umbrella switch for compile-time memory reductions. Enables `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS` unless those fine-grained variables are explicitly set. |
-| `GGML_OPENVINO_REDUCE_COMPILE_MEM`| Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` | Reduce compile-time host memory use by streaming weight requantization and avoiding extra weight-node materialization where possible. Set explicitly to override the umbrella switch. |
-| `GGML_OPENVINO_RELEASE_WEIGHTS` | Boolean | inherits from `GGML_OPENVINO_MEMORY_OPTIMIZE` on GPU | GPU-only. Release host weight buffers after the compiled model cache can reuse the device/plugin copy. Requires stable graph shapes; dynamic workloads that need recompilation should leave this disabled. |
-| `GGML_OPENVINO_SPILL_DIR` | String | `not set` | Directory for a disk-backed weight buffer. When set, the repacked weight buffer is mapped from an unlinked file on this path instead of anonymous memory, so its pages are reclaimable under memory pressure instead of staying pinned, cutting the load-time host memory peak. Must point at real storage; a tmpfs mount (e.g. `/tmp` on many systems) backs it with RAM and makes the peak worse. |
-| `GGML_OPENVINO_REQUANT_KQUANT` | String | `not set` | Requantize Q6_K/Q5_K weights (and matching MoE expert weights) to a 4-bit target instead of the default Q8_0_C, trading accuracy for less memory traffic. One of `q4_asym64` (Q6_K/Q5_K only, keeps a real zero point at group 64), `q4_asym64_all` (also requantizes Q4_K), `q4_sym128` (Q6_K/Q5_K only), `q4_sym128_all` (Q4_K too, drops its per-group zero point), or `native` (no requantization). |
-| `GGML_OPENVINO_PROFILING` | Integer | `0` | `1` logs execution timing; `2` or higher also enables OpenVINO and OpenCL profiling. |
-| `GGML_OPENVINO_DEBUG_NODE` | String | `not set` | Add the named graph nodes as compiled outputs for debugging. Separate multiple names with commas. |
-| `GGML_OPENVINO_MOE_OP` | Boolean | `1` | On GPU, set to `0` to keep the unfused GatherMatmul path. |
-| `GGML_OPENVINO_DUMP_CGRAPH` | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. |
-| `GGML_OPENVINO_DUMP_IR` | Boolean | `0` | Serialize OpenVINO IR files with timestamps. |
-| `GGML_OPENVINO_DEBUG_INPUT` | Boolean | `0` | Enable input debugging and print input tensor info. |
-| `GGML_OPENVINO_DEBUG_OUTPUT` | Boolean | `0` | Enable output debugging and print output tensor info. |
-| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | Boolean | `0` | Print tensor address map once. |
-| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS`| Boolean | `0` | Log warning messages with tensor details and rejection reasons for any ops not supported by the OpenVINO backend. Emits at `WARN` level (requires `--log-verbosity >= 2`, enabled by default). |
+
-> [!NOTE]
-> - `GGML_OPENVINO_STATEFUL_EXECUTION` is an **Experimental** feature for managing caches internally inside the OpenVINO model on CPUs and GPUs. Use a single slot (`-np 1`). KV caches retain the append-based state layout and sequence-axis optimization. Qwen3.5 adds recurrent cache states in their GGML layouts. Qwen3.5 requires an unsplit graph with model caching enabled and no recurrent rollback. A prompt starting at position 0 resets all states. State save/restore, sequence rewind, context shift, and mid-sequence graph replacement are unsupported. Stateful execution is not effective on NPUs.
-> - `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` emits logs at `WARN` level (`GGML_LOG_WARN`), which requires application log verbosity `--log-verbosity >= 2` (or `-lv 2`).
-> - With `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1`, use the same compilation settings as the export run. One directory can hold blobs for different models and settings; `GGML_OPENVINO_SPILL_DIR` does not affect the cache key and is ignored in cache-only mode. See [Compiled model cache](../../ggml/src/ggml-openvino/README.md) for the workflow and restrictions.
+## Runtime Configuration
+
+The backend needs no environment variable: it runs on the CPU with its defaults. Set `GGML_OPENVINO_DEVICE` to use the GPU or the NPU. All other variables are optional.
+
+```bash
+export GGML_OPENVINO_DEVICE=GPU # String
+export GGML_OPENVINO_PROFILING=1 # Integer
+export GGML_OPENVINO_EXACT_ZERO_POINT=1 # Boolean: 1 (on) or 0 (off)
+
+# Show the variables in effect (log verbosity 4)
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024 -lv 4 2>&1 | grep "settings from the environment"
+```
+
+- The backend reads the variables once, at start. Unset or empty means the default.
+- To lower the memory a model needs, see [Tips for Memory Optimization](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#tips-for-memory-optimization).
+- A value that is not valid stops the backend. A `GGML_OPENVINO_*` name that the backend does not know gives a warning:
+
+```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
+```
+
+### Basic
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_DEVICE` | all | String | `CPU` | Target device: `CPU`, `GPU` or `NPU`. For several GPUs, see the [device notes](#4-run-inference-with-openvino-backend). Examples: `GGML_OPENVINO_DEVICE=NPU`, `GGML_OPENVINO_DEVICE=GPU.0,GPU.1`. |
+| `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` | all | String | `not set` | Directory for the backend's cache of compiled models. A later start with the same model and settings loads faster. See [Compiled model cache](#compiled-model-cache). Example: `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache`. |
+| `GGML_OPENVINO_NPU_CONFIG` | NPU | String | `not set` | OpenVINO properties for the NPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN"`. |
+| `GGML_OPENVINO_GPU_CONFIG` | GPU | String | `not set` | OpenVINO properties for the GPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. |
+| `GGML_OPENVINO_CPU_CONFIG` | CPU | String | `not set` | OpenVINO properties for the CPU plugin, as comma-separated `KEY=VALUE` pairs. See [Plugin properties](#plugin-properties). Example: `GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"`. |
+| `GGML_OPENVINO_PROFILING` | all | Integer | `0` | `1` logs execution timing. `2` or higher also turns on OpenVINO and OpenCL profiling. Example: `GGML_OPENVINO_PROFILING=1`. |
+
+### Plugin properties
+
+`GGML_OPENVINO_NPU_CONFIG`, `GGML_OPENVINO_GPU_CONFIG` and `GGML_OPENVINO_CPU_CONFIG` pass OpenVINO plugin properties to the device in their name.
+
+```bash
+# Format: comma-separated KEY=VALUE pairs. The backend uses the variable of the selected device only.
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=4"
+
+# CPU: compute in FP16, as the GPU and the NPU do. This helps to debug the accuracy of a quantized model.
+export GGML_OPENVINO_DEVICE=CPU
+export GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16"
+```
+
+- 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.
+- OpenVINO checks the properties when the model loads. If it rejects one, the load fails and the error names the variable.
+- All properties and their values are in the OpenVINO documentation: [NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html), [GPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/gpu-device.html), [CPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/cpu-device.html).
+- NPU: the backend sets several properties by default. They are listed in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties).
+- GPU and CPU: the backend sets no property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+
+`NPU_COMPILER_TYPE` selects the NPU compiler. Both forms below work; use the first one. If both are set, `GGML_OPENVINO_NPU_CONFIG` takes precedence.
+
+```bash
+# Values: DRIVER (the compiler in the NPU driver; backend default), PLUGIN (the compiler in OpenVINO),
+# PREFER_PLUGIN (OpenVINO default: PLUGIN when it is available, DRIVER if not).
+export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN" # recommended form
+export GGML_OPENVINO_NPU_COMPILER_TYPE=PLUGIN # older name, still works
+```
+
+### Advanced tuning
+
+The defaults fit most models. The variables below trade one property for another, for example speed for accuracy.
+
+
+Advanced tuning variables
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
+| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. |
+| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
+| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
+| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
+| `GGML_OPENVINO_EXACT_ZERO_POINT` | CPU, GPU | Boolean | `0` | Keep the exact zero point of asymmetric weights (`Q4_1`, `Q4_K`, `Q5_1`, `Q5_K`) instead of rounding it to an integer. This improves accuracy and lowers speed. Use it when accuracy matters more than speed. |
+
+
+
+### Compiled model cache
+
+The cache keeps compiled models on disk, so later starts of the same model load faster. Use the same model and the same settings in every run.
+
+```bash
+# CPU or GPU: the first run compiles the model and writes the cache. Later runs read it.
+export GGML_OPENVINO_DEVICE=GPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 1024
+
+# CPU or GPU, later runs (optional): require the cached model and skip the weight upload and the compilation.
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
+
+# NPU: add the weightless bank.
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
+export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
+./build/ReleaseOV/bin/llama-cli -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -c 512
+
+# NPU, later runs (optional): use less memory. The run fails if a cached model is missing.
+export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
+```
+
+
+Cache variables
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
+| `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode models without weights, plus one shared weights file. Later runs read the weights from that file and keep one copy in memory. |
+| `GGML_OPENVINO_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1` and an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing; run once without it to build the cache. |
+| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
+
+- One directory can hold the cached models of different models and settings.
+- NPU: each prefill length enters the cache in a run without `GGML_OPENVINO_SELF_CONTAINED_MMAP`.
+- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
+
+
+
+### Deprecated
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_STATEFUL_EXECUTION` | CPU, GPU | Boolean | `0` | **Deprecated**, to be removed. Keep the KV cache inside the OpenVINO model. Use the default, stateless execution (`0`). |
+
+
+Limits of stateful execution
+
+- CPU and GPU only; it has no effect on the NPU.
+- One slot only (`-np 1`).
+- State save and restore, sequence rewind, context shift and recurrent rollback are not supported.
+- Qwen3.5 needs a graph that runs fully on OpenVINO, with model caching on.
+- A prompt that starts at position 0 resets all states.
+
+
+
+### Debugging and development
+
+Debug output, switches that turn a default optimization off, experimental options and older variable names are in the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md).
### Example Usage
#### GPU Inference with Profiling
```bash
-# If the system has multiple GPUs, use GPU.0 or GPU.1 to explicitly target a specific GPU.
-
-# Linux
-export GGML_OPENVINO_CACHE_DIR=/tmp/ov_cache
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
export GGML_OPENVINO_PROFILING=1
export GGML_OPENVINO_DEVICE=GPU
-export GGML_OPENVINO_STATEFUL_EXECUTION=1
./build/ReleaseOV/bin/llama-simple -m ~/models/Llama-3.2-1B-Instruct-Q4_K_M.gguf -n 50 "The story of AI is "
+```
+
+
+Windows
-# Windows Command Line
-set GGML_OPENVINO_CACHE_DIR=C:\tmp\ov_cache
+```cmd
+REM Windows Command Prompt
+set GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=C:\tmp\ov_cache
set GGML_OPENVINO_PROFILING=1
set GGML_OPENVINO_DEVICE=GPU
-set GGML_OPENVINO_STATEFUL_EXECUTION=1
+build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.gguf" -n 50 "The story of AI is "
+```
+```powershell
# Windows PowerShell
-$env:GGML_OPENVINO_CACHE_DIR = "C:\tmp\ov_cache"
+$env:GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR = "C:\tmp\ov_cache"
$env:GGML_OPENVINO_PROFILING = "1"
$env:GGML_OPENVINO_DEVICE = "GPU"
-$env:GGML_OPENVINO_STATEFUL_EXECUTION = "1"
-
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 "
-
```
+
+
## Known Limitations
**General (all devices)**
- Llama.cpp OpenVINO backend currently supports a subset of GGML ops and text-only models. Unsupported ops or unsupported op shapes/cases fail during OpenVINO translation.
- Multimodal features (audio/image/video) are a work in progress.
-- Limited Embedding and Reranking model support.
+- Embedding models: reranking models are not validated.
- Llama.cpp tool coverage across CPU/GPU/NPU is not uniform.
-**Tool-specific**
-
-- `llama-bench`: requires `-fa 1` (flash-attention).
-- `llama-cli --context-shift`: stateless only (`GGML_OPENVINO_STATEFUL_EXECUTION=0`). In stateful mode the KV cache is owned by the OpenVINO model and cannot be shifted externally.
-- `llama-server`: only one chat session/thread when `GGML_OPENVINO_STATEFUL_EXECUTION=1`.
-
**GPU-specific**
-- `llama-server -np > 1`: concurrent requests are batched together, which may slightly reduce per-request throughput.
+- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
+ - `-sm tensor` is not supported.
+ - Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
+ - Only GPUs can be combined. A list with several NPUs, or with a GPU and the CPU or the NPU, is rejected.
+- MoE models use the GPU plugin's fused MoE op, which runs in f16 only:
+ - granitemoe models (e.g. `granite-3.1-1b-a400m`) give wrong output.
+ - **Workaround:** `GGML_OPENVINO_MOE_OP=0`. Output is correct, but prompt processing is much slower.
+ - `GGML_OPENVINO_GPU_CONFIG="INFERENCE_PRECISION_HINT=f32"` fails to compile.
+- `llama-perplexity` with MoE models: set `-b` to the same value as `-c`, so that each batch holds one sequence.
**NPU-specific**
- Default context resolves to the model's training context (e.g. 131072 for Llama 3.2 1B), which can OOM or fail or degrade performance on NPU. Inspect the resolved value with `-lv 3`.
- - **Workaround:** Pass an explicit `-c `, e.g. `-c 1024`.
+ - **Workaround:** Pass an explicit `-c `, e.g. `-c 512`.
- NPU device uses a static graph with a fixed prefill chunk size (defaults to 256), configurable with `GGML_OPENVINO_PREFILL_CHUNK_SIZE`. Large prefill/batch settings may need tuning.
- `llama-server -np > 1` (multiple parallel sequences) is not supported.
- `llama-perplexity`: requires `-b 512` or smaller.
+- Flash attention must stay on, which is the default (`-fa auto`). With `-fa off`, the run fails on the NPU.
+- `llama-embedding` fails on the NPU.
+- Lunar Lake NPU: decode slows down sharply when the context is large. The context size at which this starts depends on the model.
+ - **Workaround:** Pass the smallest context that fits the use, e.g. `-c 512`, or `-c 256` for larger models.
+- Panther Lake NPU: the load of a Qwen3.5 model can end with a segmentation fault in the NPU compiler of OpenVINO 2026.4.1.
+ - **Workaround:** Set `GGML_OPENVINO_NPU_CONFIG=COMPILATION_NUM_THREADS=1`.
+- Panther Lake NPU: `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=f16` and `q4_0_128` can give wrong output. Keep the default.
+- Lunar Lake NPU: `granite-4.0-1b` gives wrong output. The activations of the model exceed the FP16 range, and the NPU computes in FP16. The model runs correctly on CPU and GPU.
+- Lunar Lake NPU: `gemma-4-12B` does not run. The first inference fails with `ZE_RESULT_ERROR_UNINITIALIZED` from the NPU driver. The model runs on CPU and GPU.
+- The first load of a model on the NPU compiles it for the device, which can take minutes for large models.
+ - **Workaround:** Use the [compiled model cache](#compiled-model-cache).
> [!NOTE]
> The OpenVINO backend is actively under development. Fixes and improvements are underway, and this document will continue to be updated.
diff --git a/ggml/src/ggml-cuda/mmq-config-pascal-dp4a.cuh b/ggml/src/ggml-cuda/mmq-config-pascal-dp4a.cuh
index 83eb7c146e11..85199444e75d 100644
--- a/ggml/src/ggml-cuda/mmq-config-pascal-dp4a.cuh
+++ b/ggml/src/ggml-cuda/mmq-config-pascal-dp4a.cuh
@@ -2,86 +2,86 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q1_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q1_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q1_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q1_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q2_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q2_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q2_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q2_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q4_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q4_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q4_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q4_1, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q4_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q4_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q4_1, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q5_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q5_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q5_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q5_1, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q5_1, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q5_1, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q5_1, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_1, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_Q8_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_Q8_0, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_Q8_0, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_Q8_0, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
// ---------------------------------------------------------------------------------------------
@@ -162,14 +162,14 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_IQ2_XXS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_IQ2_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_IQ2_XXS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ2_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q3_K, MMQ_ITER_K, false, true);
@@ -198,14 +198,14 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_IQ3_XXS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_IQ3_XXS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_IQ3_XXS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ3_S, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
@@ -222,26 +222,26 @@ static constexpr __host__ __device__ ggml_cuda_mmq_config ggml_cuda_mmq_get_conf
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_IQ4_XS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_IQ4_XS, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_IQ4_XS, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
- CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
+ CASE(GGML_TYPE_IQ4_NL, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, true);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 8, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 16, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 24, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 32, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 40, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 48, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
- CASE(GGML_TYPE_IQ4_NL, 256, 2, 64, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
+ CASE(GGML_TYPE_IQ4_NL, 256, 2, 128, 64, GGML_CUDA_MMQ_SRAM_LAYOUT_Q8_0, MMQ_ITER_K, false, false);
// ---------------------------------------------------------------------------------------------
diff --git a/ggml/src/ggml-cuda/mmq.cu b/ggml/src/ggml-cuda/mmq.cu
index 2e6199766839..c9bcbc2aa3a9 100644
--- a/ggml/src/ggml-cuda/mmq.cu
+++ b/ggml/src/ggml-cuda/mmq.cu
@@ -460,7 +460,7 @@ bool ggml_cuda_should_use_mmq(enum ggml_type type, int cc, int64_t ne11, int64_t
#endif //GGML_CUDA_FORCE_MMQ
if (GGML_CUDA_CC_IS_NVIDIA(cc)) {
- return !fp16_mma_hardware_available(cc) || ne11 < MMQ_DP4A_MAX_BATCH_SIZE;
+ return !fp16_mma_hardware_available(cc) || ne11 < MMQ_DP4A_MAX_BATCH_SIZE || n_experts > 0;
}
if (amd_mfma_available(cc)) {
diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt
index 347c24f4f526..3ed43b9fab27 100644
--- a/ggml/src/ggml-openvino/CMakeLists.txt
+++ b/ggml/src/ggml-openvino/CMakeLists.txt
@@ -31,3 +31,20 @@ if (GGML_OPENVINO)
message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
endif()
endif()
+
+# Released runtimes retain the ordinary cache translators.
+include(CheckCXXSourceCompiles)
+unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
+set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
+set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
+check_cxx_source_compiles("#include
+int main() {
+ auto conv = std::make_shared(ov::OutputVector{}, 3);
+ auto gdn = std::make_shared(ov::OutputVector{});
+}"
+ GGML_OPENVINO_HAS_CACHE_UPDATE)
+unset(CMAKE_REQUIRED_LIBRARIES)
+unset(CMAKE_REQUIRED_INCLUDES)
+if(GGML_OPENVINO_HAS_CACHE_UPDATE)
+ target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
+endif()
diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md
index 6a23f62bf246..0b4f31291ac6 100644
--- a/ggml/src/ggml-openvino/README.md
+++ b/ggml/src/ggml-openvino/README.md
@@ -1,3 +1,38 @@
+# Qwen MTP
+
+The default Qwen3.5/Qwen3.6 GPU path is dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling. Build against the matching OpenVINO runtime/GPU plugin with independent `RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` ops. The native Update ops return computation results and update writable cache inputs in place, including rollback snapshots where required. No recurrent/sampling opt-in flag is needed on supported graphs. See the [development documentation index](dev_doc/README.md) for the implementation and the MTP sampling graph.
+
+Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported.
+
+Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP.
+
+The matched stateless GPU path uses `RecurrentConvCacheUpdate` and
+`RecurrentGatedDeltaNetUpdate`. Each cache is a writable Parameter backed by one
+stable caller-owned USM allocation. The ops return only convolution or attention;
+there are no recurrent cache Results. Required source rows are staged before
+writes, preserving resets, cyclic reorders and rollback. Cache readers must be
+exclusive, including Reshape aliases.
+`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary cache decomposition.
+Unmatched snapshot GDN uses ordinary GDN token prefixes with functional writeback.
+Build both repos against the matching single-output op spec. Translation revision
+15 requires regenerating compiled-model blobs once without cache-only mode.
+
+Cache-only MTP serving still requires the separate OpenVINO dynamic output-binding fix (PR #39354). Removing recurrent cache Results does not eliminate that independent trigger in imported MTP graphs.
+
+Set `GGML_OPENVINO_ENABLE_KV_4D=1` to enable the upstream stateless in-place
+attention KV update pattern where eligible. It binds full-capacity cache tensors
+and lets the GPU fusion expose the live prefix to attention. The current upstream
+eligibility check supports one physical stream (including unified KV); explicit
+split multi-slot KV retains the ordinary full-cache path. This option does not
+change recurrent cache handling. Unified KV is recommended for multi-slot GPU
+execution because it enables this in-place attention update.
+
+The recommended Qwen3.6-35B-A3B Q4_K_M setup uses GPU with `GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all` and `GGML_OPENVINO_NATIVE_SOFTPLUS=1`. Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). See [attention KV layout](dev_doc/OPENVINO-RECURRENT-CACHE.md#attention-kv-layout) for eligibility.
+
+`q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy.
+
+See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and rollback.
+
# Compiled model cache
`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` exports compiled CPU/GPU graphs with their weights. It bypasses the plugin-level `GGML_OPENVINO_CACHE_DIR` and uses `OPTIMIZE_SPEED`, so weightless caching is disabled.
@@ -7,7 +42,6 @@ One directory can hold blobs for different models and compilation settings. Run
```sh
GGML_OPENVINO_DEVICE=GPU \
GGML_OPENVINO_NATIVE_SOFTPLUS=1 \
-GGML_OPENVINO_DISABLE_KV_SLICE=1 \
GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
./build/ReleaseOV/bin/llama-bench -m /path/to/model.gguf -r 1
@@ -20,7 +54,6 @@ On later runs, supply the same compilation settings and enable `GGML_OPENVINO_CO
```sh
GGML_OPENVINO_DEVICE=GPU \
GGML_OPENVINO_NATIVE_SOFTPLUS=1 \
-GGML_OPENVINO_DISABLE_KV_SLICE=1 \
GGML_OPENVINO_REQUANT_KQUANT=q4_asym64_all \
GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/path/to/qwen-cache \
GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \
@@ -29,10 +62,22 @@ GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1 \
Cache-only mode allocates backend address space without filling weight pages. On Windows, this also uses system commit capacity. The model-buffer size in the loader log is this virtual size. Weight uploads only record source identity; they do not read or requantize the weights. Graph conversion and compilation are skipped. Runtime buffers are still allocated and populated normally.
-Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_DISABLE_KV_SLICE`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, and `GGML_OPENVINO_DEBUG_NODE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode.
+Cache-only mode uses the settings provided by the current process. Keep these values exactly the same, including set versus unset: `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`, `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS`, `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_PROFILING`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`, and `GGML_OPENVINO_DEBUG_NODE`, `GGML_OPENVINO_ENABLE_KV_4D`, and `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE`. On GPU, also repeat `GGML_OPENVINO_MOE_OP=0` if used. `GGML_OPENVINO_SPILL_DIR` is optional on the first run and ignored in cache-only mode; host-weight release is disabled in cache-only mode.
+
+`GGML_OPENVINO_KV_SLICE` is a runtime binding option for dynamic graphs and can differ between cache population and cache-only runs. The same dynamic compiled graph accepts full-capacity and live-prefix attention K/V tensors. Slicing is enabled by default for contiguous ordinary K/V roots with one allocated stream, one active sequence at offset zero, and no sliding-window attention. Recurrent convolution/GDN caches and their rollback snapshots always retain their full stored row bank. Other layouts use full bindings. Repopulate caches made before this option was removed from the fingerprint once without cache-only mode.
A missing or incompatible graph fails with an error instead of compiling with absent weights. The fingerprint uses the dynamic graph's topology, ports, model parameters, weights, settings, and OpenVINO version; changing only dynamic token or KV sizes does not require a new entry. A different workload can still require another graph; populate it first without cache-only mode.
+## MTP sampling and active slots
+
+Qwen3.5/Qwen3.6 MTP uses a pure top-k backend sampler. Dynamic stateless execution retains its sampling branches for every configured slot and output row, including inactive branches. One packed `sampling_rows` input selects logits rows at runtime. Graph node names and candidate-output ports stay fixed, so changing the active subset of four slots reuses the same compiled draft model instead of creating up to 15 variants.
+
+Active candidate IDs and scores are written to the normal GGML outputs. Inactive branches read row 0 (the padding row when there are no logits) and write to private scratch tensors (device USM on GPU), without changing sampler state or touching inactive GGML buffers. The top-k computations remain separate per branch; this trades some extra sampling work for a stable graph interface. Other sampler chains retain their existing branch-selection behavior.
+
+This is one draft model per compatible graph configuration, not one compiled blob for the whole server. The trunk and other graph stages still have their own entries. Different sampler configurations, recurrent capacities, rollback modes or incompatible KV layouts can require additional models. Cache-only mode still requires initial preparation; changing just the active subset no longer requires exhaustive subset priming.
+
+The generic recurrent-cache translation invalidates blobs made with the former single-slot shortcuts. Run once without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` to populate compatible entries before enabling cache-only mode again.
+
## Restrictions
- Cache-only mode requires Linux or Windows and mmap loading (`--load-mode mmap`, or the default when all selected devices support mmap). Do not use tensor validation or mlock when trying to avoid weight reads.
diff --git a/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
new file mode 100644
index 000000000000..ef50e153d0e2
--- /dev/null
+++ b/ggml/src/ggml-openvino/dev_doc/MTP-SAMPLING-GRAPH.md
@@ -0,0 +1,45 @@
+# Stable multislot MTP graph
+
+The captured UD draft graph contains 107 nodes regardless of which of four slots are active. It is the single MTP attention/MoE layer, not the recurrent trunk. Two speculative tokens require two consecutive draft calls, batched over active sequences.
+
+```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.
+
+| Active slots | Sampling COMPUTE flags, slots 0-3 | Raw/current nodes | Old filtered nodes | Packed sampling_rows |
+|---|---|---:|---:|---|
+| 3 | `[0,0,0,1]` | 107 | 92 | `[0,0,0,0]` |
+| 0,2 | `[1,0,1,0]` | 107 | 97 | `[0,0,1,0]` |
+| All four | `[1,1,1,1]` | 107 | 107 | `[0,1,2,3]` |
+
+Old counts apply the old COMPUTE filter to the captures. Unselected nodes remain in the raw cgraph. Previously, removing them changed translated topology, slot-specific row Parameter names and output ports; even equal-sized subsets such as `{0,1}` and `{0,2}` differed. This could trigger up to 15 draft variants, with compilation/import on first use or a missing-cache error in cache-only mode.
+
+Now all pure top-k branches remain. Their names include stable graph ordinals even when inactive. One int64 `sampling_rows` Parameter supplies row indices at runtime. For `{0,2}`, the two logits rows belong to slots 0 and 2:
+
+```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
+```
+
+The vector is not an active mask. Host-side COMPUTE flags select normal versus scratch output destinations. PAD provides a valid row when there are no logits. Inactive outputs use device USM on GPU and do not affect sampler state or acceptance. Other sampler chains retain their selected-branch semantics.
+
+Only small sampling work executes for inactive slots. The MTP layer and output projection still process N active rows. Top-k is separate per branch, not yet one batched TopK. The observed draft interface has 10 inputs and 12 outputs: eight candidate ID/score outputs, hidden state, full logits and two KV Results.
+
+Dump shapes use GGML order `[width, rows, dim2, dim3]`; OV reverses it. `view_offs` is in bytes: one logits row occupies `248320 * 4 = 993280` bytes. Buffer labels describe GGML storage, not the device executing imported GPU operations.
+
+The captures used cache-only mode, four slots, context 8192 and the default two-token MTP settings.
diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
new file mode 100644
index 000000000000..7dfb742b141a
--- /dev/null
+++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
@@ -0,0 +1,62 @@
+# Current Qwen GPU implementation
+
+The default Qwen3.5/Qwen3.6 path is dynamic stateless execution with `RecurrentConvCacheUpdate`, `RecurrentGatedDeltaNetUpdate`, and stable pure-top-k MTP translation. It supports one or multiple slots and rollback. The implementation applies to `qwen35` and `qwen35moe`; the reference model is the UD Qwen3.6-35B-A3B MTP GGUF.
+
+Build against the matching OpenVINO runtime/GPU plugin with single-output Update ops. Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The cache translation revision is 15. Historical measurements retain their original source revisions.
+
+The separate dynamic output-binding fix in OpenVINO PR #39354 remains required for cache-only MTP serving. Native cache-op export/import tests pass without it, but Qwen3.6 imported MTP graphs still trigger the missing-input-memory error without the fix.
+
+## Buffer ownership and operation boundaries
+
+| State | Storage and lifetime | Update path |
+|---|---|---|
+| Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA consumes the live prefix |
+| Convolution `cache_r` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, convolution and ordered history/snapshot writes |
+| GDN `cache_s` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, GDN and ordered final/snapshot writes |
+| Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs |
+| Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps |
+| Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers |
+
+Attention context capacity does not set recurrent-cache size. Each cache input Parameter binds a stable writable allocation; recurrent cache Results are omitted. There are no rotation banks or pointer swaps.
+
+The GPU plugin uses two stages: first preserve required original rows in scratch while applying logical reset and precision rounding; then compute and perform ordered writes. This avoids overwriting a source before another destination has read it. Identity reorder sources need no scratch writes. In-place execution removes the spare full output bank, not every cache read or internal memory transaction.
+
+`RecurrentConvCacheUpdate` has nine inputs, including depthwise weights, and returns convolution `[1,B,T,C]`. `RecurrentGatedDeltaNetUpdate` returns attention and writes the newest `min(T,snapshot_count)` states into its cache input, newest first. Neither op returns a cache tensor.
+
+## Convolution cache stores
+
+`build_conv_state_store` emits one CPY for the final history when rollback is disabled. With rollback enabled, it emits one SET_ROWS from overlapping `[history, window, channel, sequence]` views into strided snapshot planes. Window starts advance in time while destination planes descend, so plane zero holds the newest history. The fixed ARANGE/scale/cast chain supplies this descending slot order.
+
+The backend recognizes this structure and refreshes source starts, cache heads, sequence counts, window counts and plane strides on every batch. Native fusion passes runtime `[source column, destination slot]` pairs to the existing convolution op; the pair-count dimension is dynamic. Functional translation gathers the same windows, scatters them into the full cache, and preserves unwritten slots and features. The native op spec is unchanged.
+
+## Generic fallback and restrictions
+
+Writable cache inputs must be GPU RemoteTensors with exclusive graph readers, optionally through Reshape aliases. The GPU plugin rejects shared cache readers and computed cache banks. Other inputs and the computation output must not overlap the cache. The frontend skips fusion for unmatched cache reads and retains functional cache writeback. Restore or clear state after a failed inference before retrying.
+
+`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains ordinary cache decomposition. Naive graphs skip full-model recurrence fusion. Unmatched snapshot GDN uses ordinary GDN token prefixes to preserve state outputs. The fused path requires the matching native runtime; otherwise dynamic CPU and GPU execution uses ordinary GDN. Stateful and NPU MTP are outside this change.
+
+## Attention KV layout
+
+`GGML_OPENVINO_ENABLE_KV_4D=1` enables eligible native stateless in-place attention updates. The current eligibility covers one physical stream, including unified KV. Explicit split multi-slot KV retains the full-cache path and can be much slower even with only one active slot. Use `--kv-unified` for multi-slot OV GPU serving.
+
+Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). Live-prefix slicing applies to eligible ordinary attention K/V roots, not recurrent caches. In-place KV fusion can bind the full allocation while exposing a live prefix internally. KV-slice on/off is a runtime binding choice and does not require different compiled blobs; incompatible graph layouts/capacities can still do so.
+
+## Stable MTP sampling
+
+The [graph walkthrough](MTP-SAMPLING-GRAPH.md) describes the fixed sampling interface. The backend keeps pure top-k branches for all configured slots, packs runtime row indices, and uses scratch for inactive outputs. It does not change the original cgraph or execute inactive stateful sampler chains. Only the small sampling branches stay at configured capacity; the expensive draft layer processes active rows.
+
+One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare a compatible revision-15 cache once, then use cache-only mode. Exhaustive active-subset priming is no longer required, though first-use model import and runtime preparation still have a cost.
+
+## Validation
+
+Native OV tests cover shape/attribute serialization, reset, cycles, duplicates, overlapping writes, mixed precision, changing shapes, writable cache input rebinding, exclusive Reshapes, shared readers, host/device USM and export/import. Convolution is checked against a host reference; GDN uses an independent cache mapping around ordinary GDN. See `docs/dev/qwen35-llamacpp-recurrent-cache.md` and `recurrent_cache_update.cpp` in the OV checkout for contracts and tests.
+
+## Debugging and source map
+
+- `ggml-decoder.cpp`: dynamic dimensions, control inputs, output names and `cgraph_ov.txt` dump.
+- `utils.cpp`: compute-branch filtering, compiled reuse and input/output binding.
+- `openvino/recurrent_cache_fusion.cpp`: structural pattern matching and native Update op translation.
+- `openvino/translate_session.cpp`: runtime sampling aliases and model construction.
+- OV `recurrent_cache_update` implementation: writable-input validation, source staging and GPU computation.
+
+`GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before filtering. It includes COMPUTE/OUTPUT flags and byte offsets and overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis; use the captured examples for a static view. GPU profiles and OpenCL copy traces add overhead, and lack of an explicit copy call does not prove zero traffic inside a kernel.
diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
new file mode 100644
index 000000000000..a43ac1d6af38
--- /dev/null
+++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
@@ -0,0 +1,221 @@
+# OpenVINO backend environment variables for development
+
+The variables for users, and the rules for values, are in [docs/backend/OPENVINO.md](../../../../docs/backend/OPENVINO.md#runtime-configuration). This file lists the other `GGML_OPENVINO_*` variables. They are for debugging, comparisons and experiments, and they can change or be removed.
+
+## Debug output
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_DUMP_CGRAPH` | all | Boolean | `0` | Dump the GGML compute graph to `cgraph_ov.txt`. |
+| `GGML_OPENVINO_DUMP_IR` | all | Boolean | `0` | Write the OpenVINO IR files, with timestamps. |
+| `GGML_OPENVINO_DEBUG_INPUT` | all | Boolean | `0` | Print the input tensors. |
+| `GGML_OPENVINO_DEBUG_OUTPUT` | all | Boolean | `0` | Print the output tensors. |
+| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
+| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
+| `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_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. |
+| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. |
+| `GGML_OPENVINO_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`. |
+
+```bash
+# Dump the GGML graph and the OpenVINO IR of a run
+GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
+ ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+
+# 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
+
+# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
+export GGML_OPENVINO_NPUW_DUMP_SUBS_DIR=/tmp/npuw_dump # optional
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+```
+
+## Switches for default optimizations
+
+Each variable turns off an optimization that is on by default, or sets its strength. Use them to find the cause of a wrong result or of a speed change.
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_KV_SLICE` | all | Boolean | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. CPU and GPU: a view over the cache. NPU: the prefill graph is compiled at the attended length, rounded up to a power of two, and replaced when that size changes. With `0`, `llama-bench -d` fails on the NPU. |
+| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | Decode attends the smallest `1024 * 2^k` rows that cover the next position, with one decode graph for each window. All windows are built, or read from the cache, together with the first prefill and decode pair. `0`: one decode graph attends the whole context. Use the same value in the run that writes the cache and in the runs that read it. |
+| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
+| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
+| `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_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` | Stateless execution only, with an OpenVINO build newer than 2026.4.1 (2026.4.1 does not build the fusion). By default the recurrent-state cache updates (Qwen3.5, LFM2) are fused into the OpenVINO model. `1` keeps the separate copies. |
+| `GGML_OPENVINO_DISABLE_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. |
+
+```bash
+# Find out whether an optimization causes a wrong result: turn it off and compare the output
+GGML_OPENVINO_DEVICE=NPU GGML_OPENVINO_NPU_FAST_MASK=0 \
+ ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 32 --temp 0 -no-cnv -p "The capital of France is"
+```
+
+## Experimental options
+
+These options are off by default. They are not validated for general use: some help on one model or device and give a wrong or slower result on another.
+
+| Variable | Device | Type | Default | Description |
+|---|---|---|---|---|
+| `GGML_OPENVINO_NPU_DECODE_UNFOLD` | NPU | Boolean | `0` | Set `NPUW_UNFOLD_IREQS=YES` on the decode graph only. An explicit `GGML_OPENVINO_NPUW_UNFOLD_IREQS` or `GGML_OPENVINO_NPU_CONFIG` value takes precedence. |
+| `GGML_OPENVINO_NPU_PARALLEL_COMPILE` | NPU | Boolean | `0` | Compile the prefill and decode graphs in parallel. The load is shorter and the host memory peak during compilation is higher. |
+| `GGML_OPENVINO_NPU_KV_ON_DEMAND` | NPU | Boolean | `0` | Keep the ggml KV buffer non-resident and bind storage for each layer that grows with the rows in use, so a large `-c` costs memory only for the context that is reached. K is stored head-major and V transposed, as OpenVINO GenAI does. `llama-perplexity` fails with it. |
+| `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). |
+| `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. |
+| `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. |
+| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. |
+| `GGML_OPENVINO_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) + log(1 + exp(-abs(x)))`. |
+| `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. |
+| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. |
+| `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. |
+| `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. |
+| `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. |
+| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. |
+| `GGML_OPENVINO_SELF_CONTAINED_BLOB` | NPU | Boolean | `0` | Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`. Write the prefill and decode graphs as blobs with the weights inside; each blob takes about the size of the model on disk. Decode then attends the whole context. `GGML_OPENVINO_NPU_WEIGHTLESS_BANK` is the recommended cache layout for the NPU. |
+| `GGML_OPENVINO_NPU_SHARED_BANK` | NPU | Boolean | `0` | With `GGML_OPENVINO_SELF_CONTAINED_BLOB=1`: one weights bank for the prefill and decode blobs. With OpenVINO 2026.4.1 the blobs cannot be read back, so decode is compiled again. |
+| `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. |
+
+```bash
+# NPU cache with the weights inside the blobs (experimental). Keep all other NPU settings the same in both runs.
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
+export GGML_OPENVINO_SELF_CONTAINED_BLOB=1
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: log shows "model cache WROTE"
+
+export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
+```
+
+## Tips for Memory Optimization
+
+With the default settings, the GPU and CPU plugins keep their own copy of the weights next to the backend's copy while a model compiles. On integrated GPUs both copies are in system RAM. The settings below lower that peak. They do not change the output.
+
+```bash
+# GPU or CPU, large model: back the weight buffer with a file, so the kernel can drop its pages.
+# Use a directory on a local disk (not tmpfs) with free space of about the model size. Can lower prompt speed.
+export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill
+mkdir -p $GGML_OPENVINO_SPILL_DIR
+```
+
+```bash
+# GPU or CPU, the same model started again and again: compile once, then load the compiled model only.
+export GGML_OPENVINO_DEVICE=GPU # or CPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
+GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill ./build/ReleaseOV/bin/llama-cli -m model.gguf # first run writes the cache
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1
+./build/ReleaseOV/bin/llama-cli -m model.gguf # later runs skip the weight upload
+```
+
+```bash
+# GPU, one long-running model (llama-server): release the host copy of the weights after compilation.
+# One model per process; a graph that must compile again later stops the run.
+export GGML_OPENVINO_DEVICE=GPU
+export GGML_OPENVINO_MEMORY_OPTIMIZE=1
+```
+
+```bash
+# CPU, MoE model: build fewer weight nodes during compilation.
+export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
+```
+
+```bash
+# NPU: weightless cache, then use the memory-mapped GGUF as the model buffer.
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
+export GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # first run writes the cache
+export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 # later runs
+```
+
+- A cache hit without `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY=1` shortens the load, but it uses about as much memory as a run without the cache.
+- MoE models are not written to the cache on CPU, so cache-only mode does not work for them on CPU.
+- `GGML_OPENVINO_SPILL_DIR` is ignored on Windows and in cache-only mode.
+- `-lm none` (no mmap) does not lower the memory in use, and it turns cache-only mode off.
+
+## NPU plugin properties
+
+The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` can change them and add others.
+
+- **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`.
+
+| Property | Type | Backend default | OpenVINO default | Description |
+|---|---|---|---|---|
+| `NPU_USE_NPUW` | Boolean | `YES` | `NO` | Use NPUW, the OpenVINO layer that splits a model into parts and compiles them for the NPU. |
+| `NPUW_DEVICES` | String | `NPU` | `NPU,CPU` | Devices that NPUW tries for each part, in order. With `NPU` only, no part runs on the CPU. |
+| `NPUW_FOLD` | Boolean | `YES` | `NO` | Compile the repeating blocks of the model once and reuse them. |
+| `NPUW_FUNCALL_FOR_ALL` | Boolean | `YES` | `NO` | Make every part of the model a function, not only the repeating blocks. |
+| `NPUW_FUNCALL_ASYNC` | Boolean | `YES` | `NO` | Run a function and the preparation of the next one as a pipeline. |
+| `NPUW_WEIGHTS_BANK` | String | `shared` | empty | Name of the weights bank. Graphs with the same name share one copy of the weights. |
+| `NPUW_DQ` | Boolean | `YES` | `NO` | Apply the dynamic quantization transformations in the plugin. |
+| `NPUW_DQ_FULL` | Boolean | `NO` | `YES` | Apply the full dynamic quantization pipeline in the plugin. |
+| `NPU_COMPILER_DYNAMIC_QUANTIZATION` | Boolean | `YES` | `NO` | Dynamic quantization in the NPU compiler. |
+| `NPU_COMPILER_TYPE` | String | `DRIVER` | `PREFER_PLUGIN` | The NPU compiler: `DRIVER` (in the NPU driver), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not). Models with `GATED_DELTA_NET` layers (Qwen3.5) compile with `PLUGIN` unless the user sets this property. |
+| `NPUW_CACHE_DIR` | String | value of `GGML_OPENVINO_CACHE_DIR` | empty | Directory for the compiled parts. |
+
+Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them.
+
+| Property | Type | Backend default | OpenVINO default | Description |
+|---|---|---|---|---|
+| `COMPILATION_NUM_THREADS` | Integer | `not set` | number of CPU cores | Threads of the NPU compiler. A lower value lowers the host memory peak when a large model compiles. |
+| `NPUW_UNFOLD_IREQS` | Boolean | `not set` | `NO` | One infer request for each part, also for repeating blocks. |
+| `LOG_LEVEL` | String | `not set` | `LOG_ERROR` | Log level of the NPU plugin, for example `LOG_INFO`. |
+
+```bash
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
+```
+
+```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";
+}
+```
+
+- All NPU properties: [OpenVINO NPU device](https://docs.openvino.ai/2026/openvino-workflow/running-inference/inference-devices-and-modes/npu-device.html).
+- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
+- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
+
+## GPU and CPU plugin properties
+
+The backend sets no GPU or CPU property, except `CACHE_DIR` and `CACHE_MODE=OPTIMIZE_SIZE` when `GGML_OPENVINO_CACHE_DIR` is set.
+
+```bash
+# CPU in FP16, to compare with the GPU and the NPU, which compute in FP16
+GGML_OPENVINO_DEVICE=CPU GGML_OPENVINO_CPU_CONFIG="INFERENCE_PRECISION_HINT=f16" \
+ ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+```
+
+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.
+
+| 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`. |
+
+```bash
+# These two lines do the same. Use the first form.
+export GGML_OPENVINO_NPU_CONFIG="NPUW_UNFOLD_IREQS=YES"
+export GGML_OPENVINO_NPUW_UNFOLD_IREQS=YES
+```
diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md
new file mode 100644
index 000000000000..4b1021e74ba9
--- /dev/null
+++ b/ggml/src/ggml-openvino/dev_doc/README.md
@@ -0,0 +1,8 @@
+# OpenVINO Qwen development documentation
+
+The default supported Qwen3.5/Qwen3.6 GPU path is **dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling**. Unified KV is the recommended multi-slot layout because it enables native in-place attention KV updates. No new inference switch is needed for the recurrent/sampling default.
+
+- [Backend setup and cache usage](../README.md): runtime requirements, environment settings and restrictions.
+- [Implementation](OPENVINO-RECURRENT-CACHE.md): buffer ownership, fusion, rollback, fallback and source map.
+- [Multislot MTP graph](MTP-SAMPLING-GRAPH.md): why active-slot variants occurred and how stable translation works.
+- [Environment variables for development](OpenVINO-ENV-VARS.md): debug output, switches for default optimizations, experimental options, plugin properties and older variable names.
diff --git a/ggml/src/ggml-openvino/device/npu_config.cpp b/ggml/src/ggml-openvino/device/npu_config.cpp
new file mode 100644
index 000000000000..637083066ee7
--- /dev/null
+++ b/ggml/src/ggml-openvino/device/npu_config.cpp
@@ -0,0 +1,113 @@
+#include "npu_config.h"
+
+#include "ggml-impl.h"
+#include "ggml-openvino/ggml-decoder.h"
+#include "ggml-openvino/ggml-openvino-extra.h"
+
+#include
+#include
+
+// The environment does not set the NPU compiler type. Set by ggml_openvino_npu_build_compile_config().
+static bool npu_compiler_type_is_default = false;
+
+ov::AnyMap ggml_openvino_npu_build_compile_config(const char * cache_dir) {
+ ov::AnyMap compile_config = {
+ {"NPU_COMPILER_DYNAMIC_QUANTIZATION", "YES" },
+ {"NPU_USE_NPUW", "YES" },
+ {"NPUW_DEVICES", "NPU" },
+ {"NPUW_FOLD", "YES" },
+ {"NPUW_WEIGHTS_BANK", "shared"},
+ {"NPUW_FUNCALL_FOR_ALL", "YES" },
+ {"NPUW_FUNCALL_ASYNC", "YES" },
+ {"NPUW_DQ", "YES" },
+ {"NPUW_DQ_FULL", "NO" },
+ };
+ if (cache_dir && strlen(cache_dir) > 0) {
+ // Keep the default cache mode: CACHE_MODE=OPTIMIZE_SIZE makes the NPU plugin compile the NPUW submodels with
+ // weights separation, which fails for them.
+ compile_config["NPUW_CACHE_DIR"] = cache_dir;
+ }
+ // Copy an optional string env var into the compile config only when it is set and non-empty.
+ auto set_compile_option_from_env = [&](const char * env_var, const char * config_key) {
+ const char * value = ggml_openvino_getenv_str(env_var);
+ if (value && strlen(value) > 0) {
+ compile_config[config_key] = value;
+ }
+ };
+ // Legacy alias for GGML_OPENVINO_NPU_CONFIG=NPU_COMPILATION_MODE_PARAMS=...
+ set_compile_option_from_env("GGML_OPENVINO_NPU_COMPILE_CONFIG", "NPU_COMPILATION_MODE_PARAMS");
+ // PLUGIN | DRIVER | PREFER_PLUGIN. The in-plugin compiler and the driver compiler
+ // can differ substantially in generated code quality for the same op. On the Intel
+ // NPU the driver compiler emits markedly faster prefill kernels (~1940 vs ~1540 t/s
+ // pp1024 on phi-4-mini), matching OpenVINO GenAI, so default to DRIVER below.
+ set_compile_option_from_env("GGML_OPENVINO_NPU_COMPILER_TYPE", "NPU_COMPILER_TYPE");
+ // NPUW_FUNCALL_FOR_ALL=YES hangs the NPU (device lost via TDR) for context
+ // lengths >= ~786 on the 2026.3 in-plugin compiler. Allow turning it off.
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL", "NPUW_FUNCALL_FOR_ALL");
+ // Unfolds function calls into separate infer requests, trading memory for the
+ // per-call dispatch overhead that repeated funcalls otherwise pay.
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_UNFOLD_IREQS", "NPUW_UNFOLD_IREQS");
+ // The compiler runs one llvm worker per core by default; each carries its own
+ // working set, so large graphs can exhaust host RAM. Capping the workers trades
+ // compile time for peak memory.
+ set_compile_option_from_env("GGML_OPENVINO_COMPILATION_NUM_THREADS", "COMPILATION_NUM_THREADS");
+ // NPUW profiling dumps; need an OpenVINO build with NPU_PLUGIN_DEVELOPER_BUILD.
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_DUMP_SUBS", "NPUW_DUMP_SUBS");
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_DUMP_SUBS_DIR", "NPUW_DUMP_SUBS_DIR");
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_DUMP_SUBS_ON_FAIL", "NPUW_DUMP_SUBS_ON_FAIL");
+ set_compile_option_from_env("GGML_OPENVINO_NPUW_DUMP_IO", "NPUW_DUMP_IO");
+ // Comma-separated KEY=VALUE pairs appended last, so they override anything above.
+ // Escape hatch for bisecting plugin options without a rebuild.
+ ggml_openvino_apply_config_overrides(compile_config, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_CONFIG"), "NPU");
+ npu_compiler_type_is_default = compile_config.find("NPU_COMPILER_TYPE") == compile_config.end();
+ if (npu_compiler_type_is_default) {
+ compile_config["NPU_COMPILER_TYPE"] = "DRIVER";
+ }
+ return compile_config;
+}
+
+bool ggml_openvino_npu_gdn_uses_plugin_compiler() {
+ return ggml_openvino_is_npu() && npu_compiler_type_is_default;
+}
+
+ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base) {
+ ov::AnyMap gdn_config = base;
+ if (ggml_openvino_npu_gdn_uses_plugin_compiler()) {
+ gdn_config["NPU_COMPILER_TYPE"] = "PLUGIN";
+ }
+ return gdn_config;
+}
+
+ov::AnyMap ggml_openvino_npu_without_npuw(const ov::AnyMap & config) {
+ ov::AnyMap out;
+ for (const auto & kv : config) {
+ if (kv.first.rfind("NPUW", 0) == 0 || kv.first == "NPU_USE_NPUW") {
+ continue;
+ }
+ out.insert(kv);
+ }
+ return out;
+}
+
+ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlOvDecoder & decoder) {
+ ov::AnyMap prefill_config = base;
+ if (ggml_openvino_npu_hfa_prefill_enabled()) {
+ prefill_config["NPUW_ATTN_HISTORY_SIZE_INPUT"] = decoder.get_hfa_history_input_name();
+ prefill_config["NPUW_ONLINE_PIPELINE"] = "REP";
+ prefill_config["NPUW_ONLINE_ISOLATE"] = "ATTN";
+ prefill_config["NPUW_ONLINE_KEEP_BLOCK_SIZE"] = "4";
+ prefill_config["NPUW_UNFOLD_IREQS"] = "NO";
+ prefill_config["NPUW_ATTN"] = "HFA";
+ prefill_config["NPUW_ATTN_HFA_FUSED"] = "YES";
+ }
+ return prefill_config;
+}
+
+ov::AnyMap ggml_openvino_npu_decode_config(const ov::AnyMap & base, const std::string & device) {
+ ov::AnyMap decode_config = base;
+ if (device == "NPU" && ggml_openvino_npu_decode_unfold_enabled() &&
+ decode_config.find("NPUW_UNFOLD_IREQS") == decode_config.end()) {
+ decode_config["NPUW_UNFOLD_IREQS"] = "YES";
+ }
+ return decode_config;
+}
diff --git a/ggml/src/ggml-openvino/device/npu_config.h b/ggml/src/ggml-openvino/device/npu_config.h
new file mode 100644
index 000000000000..89f41da5402b
--- /dev/null
+++ b/ggml/src/ggml-openvino/device/npu_config.h
@@ -0,0 +1,33 @@
+#pragma once
+
+// NPU (NPUW) compile configuration. Everything that decides which OpenVINO properties an NPU graph is
+// compiled with lives here, so "what does the NPU compile with" is answered in one place:
+// * the backend-wide base config (NPUW defaults, named env aliases, GGML_OPENVINO_NPU_CONFIG overrides)
+// * the per-graph variants of it (cacheless graphs, GATED_DELTA_NET graphs, static prefill, static decode)
+
+#include
+#include
+
+class GgmlOvDecoder;
+
+// Base config for every NPU graph, built once at backend init. GGML_OPENVINO_NPU_CONFIG ("K=V,...") is
+// applied last, so it overrides the defaults and the named aliases.
+ov::AnyMap ggml_openvino_npu_build_compile_config(const char * cache_dir);
+
+// Cacheless (encoder) graphs compile on the plain NPU plugin: drop every NPUW key.
+ov::AnyMap ggml_openvino_npu_without_npuw(const ov::AnyMap & config);
+
+// Graphs with GATED_DELTA_NET (Qwen3.5). The driver compiler gives wrong output for them and the compiler bundled
+// with OpenVINO does not, so they compile with NPU_COMPILER_TYPE=PLUGIN unless the environment sets the compiler
+// type (GGML_OPENVINO_NPU_COMPILER_TYPE, or NPU_COMPILER_TYPE in GGML_OPENVINO_NPU_CONFIG).
+ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base);
+
+// True when ggml_openvino_npu_gdn_config() switches the compiler. Part of the model cache key.
+bool ggml_openvino_npu_gdn_uses_plugin_compiler();
+
+// Static prefill graph. With GGML_OPENVINO_NPU_HFA_PREFILL, switches NPUW to the HFA attention pipeline.
+ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlOvDecoder & decoder);
+
+// Static decode graph. With GGML_OPENVINO_NPU_DECODE_UNFOLD, unfolds NPUW function calls into separate infer
+// requests, unless NPUW_UNFOLD_IREQS is already set.
+ov::AnyMap ggml_openvino_npu_decode_config(const ov::AnyMap & base, const std::string & device);
diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
new file mode 100644
index 000000000000..1f7343bba4c2
--- /dev/null
+++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
@@ -0,0 +1,50 @@
+#include "npu_quant_policy.h"
+
+#include "ggml-impl.h"
+#include "ggml.h"
+
+#include
+#include
+
+ExtraQuantType ggml_openvino_get_npu_requant_type() {
+ const std::string policy = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_REQUANT_POLICY", "group-128");
+ if (policy == "group-128") {
+ return ExtraQuantType::Q4_0_128;
+ }
+ if (policy == "channel-wise") {
+ return ExtraQuantType::Q4_0_C;
+ }
+ GGML_ABORT("Unknown GGML_OPENVINO_NPU_REQUANT_POLICY: %s", policy.c_str());
+}
+
+std::optional ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor) {
+ // A Q6_K embedding table is stored as q8_0_c by default on the NPU. The int4 layouts only pay off for a tied
+ // embedding, where the table is also the lm_head weight and GET_ROWS gathers the packed rows
+ // before dequantizing them (see gather_compressed_rows).
+ if (tensor->type != GGML_TYPE_Q6_K) {
+ return std::nullopt;
+ }
+ const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "q8_0_c");
+ ExtraQuantType type;
+ if (quant == "f16") {
+ type = ExtraQuantType::F16;
+ } else if (quant == "q8_0_c") {
+ type = ExtraQuantType::Q8_0_C;
+ } else if (quant == "q4_0_128") {
+ type = ExtraQuantType::Q4_0_128;
+ } else if (quant == "q4_0_c") {
+ type = ExtraQuantType::Q4_0_C;
+ } else {
+ GGML_ABORT("Unknown GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT: %s", quant.c_str());
+ }
+ static std::once_flag logged;
+ std::call_once(logged, [&] {
+ GGML_LOG_INFO("ggml-openvino: NPU token_embd.weight requant type: %s\n", quant.c_str());
+ });
+ return type;
+}
+
+std::optional ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) {
+ GGML_UNUSED(tensor);
+ return ggml_openvino_get_npu_requant_type();
+}
diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.h b/ggml/src/ggml-openvino/device/npu_quant_policy.h
new file mode 100644
index 000000000000..01fc399867f8
--- /dev/null
+++ b/ggml/src/ggml-openvino/device/npu_quant_policy.h
@@ -0,0 +1,19 @@
+#pragma once
+
+// NPU weight requantization rules. ggml_openvino_get_requant_type() (ggml-openvino-extra.cpp) delegates
+// the NPU-specific decisions here.
+
+#include "ggml-openvino/ggml-openvino-extra.h"
+
+#include
+
+struct ggml_tensor;
+
+// Layout selected by GGML_OPENVINO_NPU_REQUANT_POLICY (group-128 | channel-wise).
+ExtraQuantType ggml_openvino_get_npu_requant_type();
+
+// token_embd.weight on NPU. nullopt: no NPU-specific rule, use the common default.
+std::optional ggml_openvino_npu_token_embd_requant_type(const ggml_tensor * tensor);
+
+// Any other weight on NPU.
+std::optional ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor);
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index 10e82f3e602a..38db895c532f 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -82,9 +82,15 @@ void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
m_model_inputs.clear();
m_model_outputs.clear();
m_node_info_list.clear();
+ m_node_dynamic_dims.clear();
set_input_output();
+ compute_node_dynamic_dims();
compute_model_inputs();
compute_model_outputs();
+ for (int i = 0; i < cgraph->n_nodes; ++i) {
+ m_node_info_list[i].node_op_case = compute_op_case(m_node_info_list[i].node);
+ m_node_info_list[i].node_op_type = compute_op_type(m_node_info_list[i].node);
+ }
}
// llama keeps separate graphs for batches with and without outputs, so a cache hit can come from a
@@ -99,6 +105,14 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::mapn_nodes; ++i) {
+ if ((cgraph->nodes[i]->op == GGML_OP_GATED_DELTA_NET && cgraph->nodes[i]->op_params[0] > 1) ||
+ is_sampling_view(cgraph->nodes[i]) || is_conv_state_snapshot_writeback(cgraph->nodes[i])) {
+ std::tie(m_model_params, m_compute_params) = compute_llm_params(cgraph, false);
+ add_extra_inputs();
+ break;
+ }
+ }
set_input_output();
compute_model_inputs();
compute_model_outputs();
@@ -110,7 +124,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::mapop == GGML_OP_SET_ROWS || node->op == GGML_OP_CPY || (node->op == GGML_OP_SCALE && node->view_src);
+ const bool is_scale_or_fill = node->op == GGML_OP_SCALE || node->op == GGML_OP_FILL;
+ return node->op == GGML_OP_SET_ROWS || node->op == GGML_OP_CPY || (is_scale_or_fill && node->view_src);
}
bool is_same_shape(const ggml_tensor * a, const ggml_tensor * b) {
@@ -126,13 +141,63 @@ bool is_conv_states_all_tensor(const ggml_tensor * tensor) {
return tensor != nullptr && strncmp(tensor->name, "conv_states_all", strlen("conv_states_all")) == 0;
}
-bool is_full_single_slot_writeback(const ggml_tensor * node) {
- return node->view_src != nullptr && node->view_src->ne[1] == 1 && node->src[1] != nullptr &&
- node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src &&
- node->src[1]->view_offs == 0 && ggml_nbytes(node->src[1]) == ggml_nbytes(node->view_src);
+bool is_descending_snapshot_order(const ggml_tensor * order, int64_t capacity, int64_t windows) {
+ if (!order || order->op != GGML_OP_VIEW || capacity < 1 || windows < 1 || windows > capacity) {
+ return false;
+ }
+ const auto cast = order->src[0];
+ if (!cast || cast->op != GGML_OP_CPY || cast->type != GGML_TYPE_I32 || !cast->src[0] ||
+ cast->src[0]->op != GGML_OP_SCALE || !cast->src[0]->src[0] ||
+ cast->src[0]->src[0]->op != GGML_OP_ARANGE) {
+ return false;
+ }
+ float scale[2], range[3];
+ memcpy(scale, cast->src[0]->op_params, sizeof(scale));
+ memcpy(range, cast->src[0]->src[0]->op_params, sizeof(range));
+ return cast->ne[0] == capacity && scale[0] == -1 && scale[1] == capacity - 1 &&
+ range[0] == 0 && range[1] == capacity && range[2] == 1 &&
+ order->ne[0] == windows && ggml_is_contiguous(order) &&
+ order->view_offs == size_t(capacity - windows) * sizeof(int32_t);
}
} // namespace
+bool GgmlOvDecoder::is_conv_state_snapshot_writeback(const ggml_tensor * node) {
+ if (!node || node->op != GGML_OP_SET_ROWS || !is_recurrent_cache(node->view_src) ||
+ !node->src[0] || node->src[0]->op != GGML_OP_VIEW || !node->src[0]->src[0] ||
+ node->src[0]->src[0]->op != GGML_OP_CONCAT || !node->src[2] || node->src[2]->op != GGML_OP_VIEW ||
+ node->src[2]->view_src != node->view_src) {
+ return false;
+ }
+ const auto source = node->src[0];
+ const auto concat = source->src[0];
+ const auto dest = node->src[2];
+ const auto cache = node->view_src;
+ const auto count = dest->ne[1];
+ if (!is_descending_snapshot_order(node->src[1], count, source->ne[1])) {
+ return false;
+ }
+ const size_t elem = ggml_type_size(cache->type);
+ const size_t row = cache->nb[1];
+ const int64_t tokens = concat->ne[0] - source->ne[0];
+ return (cache->type == GGML_TYPE_F32 || cache->type == GGML_TYPE_F16) &&
+ source->type == cache->type && dest->type == cache->type && ggml_is_contiguous(cache) &&
+ cache->ne[2] == 1 && cache->ne[3] == 1 && row > 0 && concat->op_params[0] == 0 &&
+ concat->ne[3] == 1 && concat->src[0] && source->ne[0] > 0 && source->ne[2] > 0 && source->ne[3] > 0 &&
+ size_t(source->ne[0]) <= row / elem &&
+ source->ne[0] == concat->src[0]->ne[0] &&
+ source->ne[2] == concat->ne[1] && source->ne[3] == concat->ne[2] &&
+ source->nb[0] == elem && source->nb[1] == elem && source->nb[2] == concat->nb[1] &&
+ source->nb[3] == concat->nb[2] && source->ne[1] == std::min(tokens, count) &&
+ source->view_offs == size_t(tokens - source->ne[1] + 1) * elem &&
+ dest->ne[0] == source->ne[0] && dest->ne[2] == source->ne[2] && dest->ne[3] == source->ne[3] &&
+ dest->nb[0] == elem && dest->nb[1] > 0 && dest->nb[1] % row == 0 &&
+ dest->nb[2] == size_t(source->ne[0]) * elem && dest->nb[3] == row &&
+ size_t(source->ne[2]) <= (row - dest->view_offs % row) / dest->nb[2] &&
+ size_t(count) <= size_t(cache->ne[1]) / (dest->nb[1] / row) &&
+ size_t(dest->ne[3]) <= dest->nb[1] / row &&
+ dest->view_offs / row <= dest->nb[1] / row - size_t(dest->ne[3]);
+}
+
// MoE expert aggregation (build_moe_ffn in llama-graph.cpp): each expert plane is
// `ggml_view_2d(experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1])` and the planes
// are summed with a chain of ADDs: moe_out = ((view_0 + view_1) + view_2) + ... + view_{n-1}.
@@ -184,10 +249,10 @@ std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggm
if (tensor == nullptr) {
return "";
}
- if ((tensor->flags & GGML_TENSOR_FLAG_COMPUTE) || is_kvcache(tensor, nullptr)) {
+ if (tensor->op != GGML_OP_NONE || is_kvcache(tensor, nullptr)) {
// Hash-table slots depend on tensor addresses and differ between contexts.
// Graph ordinals disambiguate duplicate names while keeping compiled-model
- // ports identical for equivalent graphs in different contexts.
+ // ports identical for equivalent graphs in different contexts, including inactive sampling branches.
const auto * node = std::find(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, tensor);
if (node != cgraph->nodes + cgraph->n_nodes) {
return std::string(tensor->name) + "#n" + std::to_string(node - cgraph->nodes);
@@ -196,6 +261,17 @@ std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggm
if (leaf != cgraph->leafs + cgraph->n_leafs) {
return std::string(tensor->name) + "#l" + std::to_string(leaf - cgraph->leafs);
}
+ if (cgraph->leafs == nullptr || cgraph->n_leafs == 0) {
+ // ggml_graph_view sets n_leafs to 0, loop over all node srcs to give each leaf a unique name
+ for (int i = 0; i < cgraph->n_nodes; i++) {
+ auto *cur_node = cgraph->nodes[i];
+ for (int j = 0; j < GGML_MAX_SRC; j++) {
+ if (cur_node->src[j] == tensor) {
+ return std::string(tensor->name) + "#l" + std::to_string(i * GGML_MAX_SRC + j);
+ }
+ }
+ }
+ }
}
return tensor->name;
}
@@ -214,7 +290,9 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
return "embd";
}
- if (GgmlOvDecoder::is_inp_mask(tensor, op)) {
+ // gemma-4's KV-shared layers read the mask rows of their output tokens through GET_ROWS, which is not a mask
+ // consumer, so match the masks by identity too
+ if (GgmlOvDecoder::is_inp_mask(tensor, op) || decoder->is_kq_mask(tensor)) {
// Give the two attention masks distinct OV parameter names. build_attn_inp_kq_mask()
// names the full-attention mask and the sliding-window mask identically, so keying a
// parameter off the name alone makes the second mask overwrite the first and both
@@ -229,6 +307,15 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
return get_tensor_ov_name(cgraph, tensor) + "_swa";
}
}
+ if (!decoder->get_model_params().swa_layers.empty() && GgmlOvDecoder::is_kv_idx(tensor, op) &&
+ op->src[2] != nullptr) {
+ // same as the masks: the full and the sliding-window cache get KV write indices of the same name
+ const ggml_tensor * cache = op->src[2]->view_src != nullptr ? op->src[2]->view_src : op->src[2];
+ auto layer = extract_layer_from_name(cache->name);
+ if (layer.has_value() && decoder->is_swa_layer(layer.value())) {
+ return get_tensor_ov_name(cgraph, tensor) + "_swa";
+ }
+ }
return get_tensor_ov_name(cgraph, tensor);
}
@@ -253,6 +340,10 @@ void GgmlOvDecoder::set_input_output() {
if (src->flags & GGML_TENSOR_FLAG_INPUT) {
src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
}
+ // Same name as in create_weight_nodes(), so ROPE reads the weight Constant.
+ if (is_rope_freqs_weight(src->view_src ? src->view_src : src, node)) {
+ src_name = "rope_freqs.weight";
+ }
current_node_info.node_inputs[src_name] = src;
current_node_info.node_inputs_names.push_back(src_name);
@@ -284,6 +375,33 @@ void GgmlOvDecoder::set_input_output() {
}
}
+// True if the GDN attention output is only read by rms_norm (gated norm, e.g. qwen3.5) and the state by
+// cache writeback CPYs. Then q may be pre-scaled, since rms_norm cancels the scale. Static (NPU) path only.
+bool GgmlOvDecoder::is_gdn_out_prescaled(const ggml_tensor * gdn) const {
+ if (!ggml_openvino_is_npu()) {
+ return false;
+ }
+ bool has_norm = false;
+ for (int i = 0; i < m_cgraph->n_nodes; i++) {
+ const ggml_tensor * n = m_cgraph->nodes[i];
+ for (int j = 0; j < GGML_MAX_SRC; j++) {
+ const ggml_tensor * s = n->src[j];
+ if (s == gdn && n->op != GGML_OP_VIEW) {
+ return false;
+ }
+ if (s == nullptr || s->op != GGML_OP_VIEW || s->src[0] != gdn) {
+ continue;
+ }
+ if (n->op == GGML_OP_RMS_NORM) {
+ has_norm = true;
+ } else if (n->op != GGML_OP_CPY) {
+ return false;
+ }
+ }
+ }
+ return has_norm;
+}
+
int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
int op_case = 0;
switch (node->op) {
@@ -293,21 +411,66 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
}
auto name = std::string(node->name);
auto * src = node->src[0];
+ if (src->op == GGML_OP_MUL && node->ne[0] == src->ne[0] * src->ne[1] && node->ne[3] == 1) {
+ for (int j = 0; j < 2; ++j) {
+ const auto * norm = src->src[j];
+ if (norm->op == GGML_OP_MUL) {
+ norm = norm->src[0];
+ }
+ if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
+ norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
+ // The post-GDN projection rejoins the flat token stream.
+ return node->ne[2] == 1 ? 5 : 6;
+ }
+ }
+ }
// Identify recurrent sequence reshapes before size checks, which are ambiguous for one token.
bool recurrent_sequence = false;
for (int i = 0; i < m_cgraph->n_nodes && !recurrent_sequence; ++i) {
const auto * consumer = m_cgraph->nodes[i];
- if (consumer->op == GGML_OP_MUL_MAT_ID && consumer->src[1] == node) {
+ if (consumer->op == GGML_OP_ROPE && consumer->src[1] == node) {
+ return 11;
+ } else if (consumer->op == GGML_OP_MUL_MAT_ID && consumer->src[1] == node) {
return 1;
+ } else if (consumer->op == GGML_OP_GATED_DELTA_NET) {
+ for (int j : {3, 4}) {
+ const auto * gate = consumer->src[j];
+ if (gate->op == GGML_OP_UNARY) {
+ gate = gate->src[0];
+ }
+ if (gate == node) {
+ return 10;
+ }
+ }
} else if (consumer->op == GGML_OP_SSM_CONV) {
const auto * concat = consumer->src[0];
- if (concat->op == GGML_OP_CONCAT) {
- const auto * transposed = concat->src[1];
- recurrent_sequence = transposed->op == GGML_OP_TRANSPOSE && transposed->src[0] == node;
+ if (concat->op == GGML_OP_CONCAT && concat->src[1]->op == GGML_OP_TRANSPOSE) {
+ const auto * seq = concat->src[1]->src[0];
+ // LFM2 short convolutions gate the input first: transpose(mul(view(node), view(node))).
+ if (seq->op == GGML_OP_MUL && seq->src[0]->op == GGML_OP_VIEW && seq->src[0]->src[0] == node &&
+ seq->src[1]->op == GGML_OP_VIEW && seq->src[1]->src[0] == node) {
+ seq = node;
+ }
+ recurrent_sequence = seq == node;
}
} else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) {
const auto * biased = consumer->src[0];
recurrent_sequence = biased->op == GGML_OP_ADD && biased->src[0] == node;
+ } else if (consumer->op == GGML_OP_MUL) {
+ for (int j = 0; j < 2; ++j) {
+ const auto * gate = consumer->src[j];
+ const auto * norm = consumer->src[1 - j];
+ if (gate->op != GGML_OP_UNARY || gate->src[0] != node) {
+ continue;
+ }
+ if (norm->op == GGML_OP_MUL) {
+ norm = norm->src[0];
+ }
+ if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
+ norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
+ return 10;
+ }
+ }
}
}
if (recurrent_sequence && node->ne[0] == src->ne[0] && node->ne[3] == 1) {
@@ -318,6 +481,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
}
if (src->op == GGML_OP_RESHAPE && src->src[0]->ne[0] == node->ne[0] && src->src[0]->ne[1] == node->ne[1]) {
op_case = 4;
+ } else if (node->ne[0] == 1 && node->ne[1] == src->ne[0] && ggml_nrows(src) == 1) {
+ // [n] -> [1, n] (gemma-4 gathers the positions of its output rows this way): the source dim
+ // becomes dim 1. The next check matches too, but would make dim 2 dynamic.
+ op_case = 3;
} else if (node->ne[0] * node->ne[1] == src->ne[0]) {
op_case = 1;
} else if (src->ne[0] * src->ne[1] == node->ne[0]) {
@@ -334,6 +501,23 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
} else if (name.find("state_predelta") == 0) {
op_case = 8;
}
+ const auto it = m_node_dynamic_dims.find(const_cast(node));
+ const int dynamic_dim = it != m_node_dynamic_dims.end() ? it->second : -1;
+ // op_case 5 flattens to [x, n_tokens]; a deeper dynamic dim means the size match above held only because
+ // there is one token, e.g. the last-layer expert groups with a single output row. op_case 3 ([n] -> [1, n])
+ // matches the same way, e.g. the last-layer expert probabilities [n_expert, 1] -> [1, n_expert, 1]
+ if (op_case == 1 || op_case == 2 || op_case == 3 || (op_case == 5 && dynamic_dim > 1)) {
+ // The rules above read the token dim off a 2D source. With a deeper source, e.g. the MoE expert groups
+ // [n_exp_per_group, n_groups, n_tokens], the tracked dynamic dim is the reliable one:
+ // op_case 2 marks ggml dim 1, op_case 1 dim 2, op_case 8 dim 3
+ if (dynamic_dim == 1) {
+ op_case = 2;
+ } else if (dynamic_dim == 2) {
+ op_case = 1;
+ } else if (dynamic_dim == 3) {
+ op_case = 8;
+ }
+ }
if (op_case == 1 && m_is_stateful) {
// Recurrent convolution and GDN gates retain their rank-4 layout.
// The gathered states may come through a view of the one gather of all states (see build_rs).
@@ -377,7 +561,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
// kv cache tensor
std::string src_name(node->view_src->name);
int layer = extract_layer_from_name(src_name).value();
- if (ggml_is_contiguous(node->src[0])) {
+ // a transposed V cache view is contiguous too when the attended length is the whole cache (one ubatch
+ // that fills it)
+ const bool v_trans_cache = m_model_params.v_trans && src_name.rfind("cache_v_l", 0) == 0;
+ if (ggml_is_contiguous(node->src[0]) && !v_trans_cache) {
// - 19: [ 64, 8, 256, 1] VIEW cache_k_l0 (view) [ 2, 128, 1024, 1048576]
// [ 512, 1024, 1, 1] 0: NONE cache_k_l0 [ 2, 1024, 1048576, 1048576]
// - 20: [ 64, 256, 8, 1] PERMUTE cache_k_l0 (view) (permuted) [ 2, 1024, 128, 1048576]
@@ -405,6 +592,20 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
}
break;
}
+ case GGML_OP_SET_ROWS: {
+ if (is_conv_state_snapshot_writeback(node)) {
+ op_case = 3;
+ break;
+ }
+ // `-fa off` writes the V cache transposed, through a [1, n] reshape of the cache: one element per row
+ if (node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE && node->src[2]->ne[0] == 1 &&
+ is_kvcache(node->src[2]->src[0], nullptr)) {
+ op_case = 1;
+ } else if (!is_kvcache_write(node)) {
+ op_case = 2;
+ }
+ break;
+ }
case GGML_OP_MUL_MAT: {
if (node->src[1]->op == GGML_OP_SOFT_MAX) {
// In the case of `-fa off`, softmax is used, v_trans=true, the dynamic dim is ne[0] for cache_v
@@ -416,16 +617,17 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
// GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list:
// src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf, or the leaf itself
// when one gather covers all states (see build_rs).
- // op_case 1/2: active/extra rows of a multi-slot cache
- // op_case 3/4: active/extra rows of a single-slot cache
+ // op_case 1/2: active/extra rows, independent of cache capacity.
if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr &&
is_recurrent_cache(node->src[0]->src[0])) {
- const bool single_slot = node->src[0]->src[0]->ne[1] == 1;
if (node->src[1]->op == GGML_OP_VIEW) {
- op_case = (node->src[1]->view_offs == 0 ? 1 : 2) + (single_slot ? 2 : 0);
- } else if (single_slot) {
- // a single-slot cache holds exactly the one state the gather selects
- op_case = 3;
+ op_case = node->src[1]->view_offs == 0 ? 1 : 2;
+ }
+ } else if (is_get_rows_batched_4d(node)) {
+ // with one token the batch dims look like a 3D gather; the tracked token dim tells them apart
+ const auto it = m_node_dynamic_dims.find(const_cast(node));
+ if (node->ne[3] > 1 || (it != m_node_dynamic_dims.end() && it->second == 3)) {
+ op_case = 5;
}
}
break;
@@ -456,8 +658,17 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
break;
}
case GGML_OP_VIEW: {
- if (!m_model_params.has_rs_rollback && node->src[0] != nullptr &&
- node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
+ if (is_sampling_view(node)) {
+ return 3;
+ }
+ if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS &&
+ is_recurrent_cache(node->src[0]->src[0]) && node->ne[0] == node->src[0]->ne[0] &&
+ node->ne[2] == 1 && node->ne[3] == 1 && m_compute_params.s_copy_active_slot_len != -1) {
+ // build_rs gathers active and inactive rows together; consumers need only the
+ // active prefix, whose length changes independently of the gather's row count.
+ return 4;
+ }
+ if (is_direct_gdn_view(node)) {
// The GDN translator publishes native attention/state outputs under these VIEW names.
op_case = 2;
break;
@@ -519,16 +730,23 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
if (node->src[0]->op == GGML_OP_VIEW) {
if (is_same_shape(node->src[0]->src[0], node->src[0])) {
op_case = 1;
- } else if (!m_model_params.has_rs_rollback &&
- node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
- // GDN attention is routed directly to this VIEW by get_output_names().
- op_case = 3;
+ } else if (is_direct_gdn_view(node->src[0])) {
+ // GDN attention is routed directly to this VIEW by get_output_names(). 3: the GDN q input may be
+ // pre-scaled, and the norm then scales its eps to match; 4: it is not.
+ op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4;
} else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
- op_case = 2;
+ op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2;
}
}
break;
}
+ case GGML_OP_GATED_DELTA_NET: {
+ if (is_gdn_out_prescaled(node)) {
+ op_case = 1;
+ }
+ break;
+ }
+ case GGML_OP_POOL_1D:
case GGML_OP_POOL_2D: {
const ggml_op_pool pool_mode = static_cast(node->op_params[0]);
switch (pool_mode) {
@@ -571,15 +789,16 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
case GGML_OP_CPY: {
if (node->src[0]->op == GGML_OP_VIEW) {
if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
- if (!m_model_params.has_rs_rollback) {
- // op_case 7 replaces a single-slot cache; op_case 10 writes native GDN state
- // into an active range of a larger non-rollback cache.
- op_case = is_full_single_slot_writeback(node) ? 7 : 10;
+ if (is_gdn_snapshot_writeback(node)) {
+ op_case = is_direct_gdn_view(node->src[0]) ? 12 : 11;
+ } else if (!m_model_params.has_rs_rollback) {
+ // Write native GDN state into the runtime active range of the cache.
+ op_case = 10;
} else {
op_case = 1;
}
} else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
- op_case = is_full_single_slot_writeback(node) ? 8 : 2;
+ op_case = 2;
break;
} else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
@@ -587,16 +806,15 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
break;
} else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
- is_recurrent_cache(node->src[1]->view_src) && node->src[1]->view_src->ne[1] == 1) {
- // defrag remainder writeback of a single-slot cache, taken from a view of the one gather of
- // all states (see build_rs)
- op_case = 9;
+ is_recurrent_cache(node->src[1]->view_src)) {
+ // Remainder view of the combined state gather (see build_rs).
+ op_case = 3;
}
} else if (node->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
is_recurrent_cache(node->src[1]->view_src)) {
// s_copy defrag remainder writeback: gathered extra state rows copied back into the cache
- op_case = node->src[1]->view_src->ne[1] == 1 ? 9 : 3;
+ op_case = 3;
} else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) {
// op_case 5: KV write for decoder self-attention (dynamic write offset)
// op_case 6: KV write for encoder self-attn or cross-attn (static offset)
@@ -633,9 +851,10 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
}
break;
}
- case GGML_OP_SCALE: {
+ case GGML_OP_SCALE:
+ case GGML_OP_FILL: {
if (node->view_src && node->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) {
- op_case = node->view_src->ne[1] == 1 ? 2 : 1;
+ op_case = 1;
}
break;
}
@@ -709,6 +928,16 @@ static int get_swa_window_from_mask(const ggml_tensor * mask) {
return window > 0 ? (int) window : -1;
}
+// The KQ product that the SOFT_MAX of an attention reads: directly, or through the logit soft-capping of gemma-2
+// (SCALE, TANH, SCALE)
+static const ggml_tensor * softmax_scores_source(const ggml_tensor * scores) {
+ while (scores != nullptr && (scores->op == GGML_OP_SCALE ||
+ (scores->op == GGML_OP_UNARY && ggml_get_unary_op(scores) == GGML_UNARY_OP_TANH))) {
+ scores = scores->src[0];
+ }
+ return scores;
+}
+
std::pair GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) {
ModelParams model_params;
ComputeParams compute_params;
@@ -751,12 +980,12 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
break;
}
break;
- case GGML_OP_SOFT_MAX:
- // case 2: node op is SOFT_MAX, src 0 not null & op is MUL_MAT & the src 0 of MUL_MAT is PERMUTE & the permuted tensor src is the view of cache k
- if (node->src[0] != nullptr && node->src[1] != nullptr && node->src[0]->op == GGML_OP_MUL_MAT &&
- node->src[0]->src[0] != nullptr && node->src[0]->src[1] != nullptr &&
- node->src[0]->src[0]->op == GGML_OP_PERMUTE && node->src[0]->src[0]->src[0] != nullptr &&
- node->src[0]->src[0]->src[0]->op == GGML_OP_VIEW) {
+ case GGML_OP_SOFT_MAX: {
+ // case 2: node op is SOFT_MAX, its scores come from a MUL_MAT (see softmax_scores_source) & the src 0 of MUL_MAT is PERMUTE & the permuted tensor src is the view of cache k
+ const ggml_tensor * kq = softmax_scores_source(node->src[0]);
+ if (kq != nullptr && node->src[1] != nullptr && kq->op == GGML_OP_MUL_MAT && kq->src[0] != nullptr &&
+ kq->src[1] != nullptr && kq->src[0]->op == GGML_OP_PERMUTE && kq->src[0]->src[0] != nullptr &&
+ kq->src[0]->src[0]->op == GGML_OP_VIEW) {
return 2;
}
// case 3: node op is SOFT_MAX, src 0 not null & op is ADD & the src 0 of ADD is MUL_MAT & the src 0 of MUL_MAT is PERMUTE
@@ -766,6 +995,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
return 3;
}
break;
+ }
default:
break;
}
@@ -788,6 +1018,22 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
}
};
+ // The PERMUTE of the K cache view an attention node reads, for the same src layouts
+ auto get_attention_cache_k_permute = [&get_attention_pattern_case](const ggml_tensor * node) -> ggml_tensor * {
+ switch (get_attention_pattern_case(node)) {
+ case 0:
+ return node->src[1];
+ case 1:
+ return node->src[1]->src[0];
+ case 2:
+ return softmax_scores_source(node->src[0])->src[0];
+ case 3:
+ return node->src[0]->src[0]->src[0];
+ default:
+ return nullptr;
+ }
+ };
+
// Pre-pass: classify sliding-window vs full-attention layers.
//
// An interleaved-SWA model keeps two KV caches and two attention masks, and hands each layer
@@ -803,10 +1049,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
// from the first graph onwards, while the view grows with context depth and would invert the
// comparison at shallow depth.
//
- // Layers whose leaf is smaller than the largest leaf are the windowed ones. When every layer
- // reports the same extent there is no distinction to draw -- either the model has no windowed
- // layers, or the window is at least as large as the context so the two caches coincide, in
- // which case a windowed layer and a full-attention one compute the same thing.
+ // Layers whose leaf is smaller than the largest leaf are the windowed ones. Equal extents do not
+ // rule them out: the windowed cache is padded to n_swa + n_ubatch, which can equal the full
+ // context (gemma-4 at -c 1024 -ub 512). See the mask fallback below.
//
// Getting this wrong is silent and severe: with the windowed layers classified as
// full-attention, permute's KV slicing uses attention_size instead of attention_size_swa. The
@@ -822,14 +1067,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
if (mask == nullptr) {
continue;
}
- const ggml_tensor * cache_k_permute = nullptr;
- switch (get_attention_pattern_case(cgraph->nodes[i])) {
- case 0: cache_k_permute = cgraph->nodes[i]->src[1]; break;
- case 1: cache_k_permute = cgraph->nodes[i]->src[1]->src[0]; break;
- case 2: cache_k_permute = cgraph->nodes[i]->src[0]->src[0]; break;
- default: cache_k_permute = cgraph->nodes[i]->src[0]->src[0]->src[0]; break;
- }
- const ggml_tensor * cache_k_view = cache_k_permute->src[0];
+ const ggml_tensor * cache_k_view = get_attention_cache_k_permute(cgraph->nodes[i])->src[0];
if (cache_k_view->op != GGML_OP_VIEW) {
continue;
}
@@ -839,8 +1077,13 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
continue;
}
layer_extent[layer.value()] = leaf->ne[1];
- layer_mask[layer.value()] = mask;
+ // the layer's own attention comes first: gemma-4's KV-shared layers read the same cache with mask rows
+ // taken from the graph input
+ layer_mask.emplace(layer.value(), mask);
max_extent = std::max(max_extent, leaf->ne[1]);
+ if (mask->op == GGML_OP_NONE) {
+ model_params.kq_masks.insert(mask);
+ }
}
for (const auto & [layer, extent] : layer_extent) {
@@ -851,6 +1094,32 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
}
}
}
+
+ // equal extents: tell the two masks apart by the layers that read them, the larger group gets the swa role
+ // (gemma-4: 4 of 5 layers). Groups of equal size can not be told apart, so leave the layers unclassified.
+ // Two masks do not imply swa (deepseek sparse attention builds two full masks), but the role does not need
+ // them to: it gives each group its own mask, KV write indices and attention size, which is right either way.
+ // The only use of the window itself, the stateful mask rebuild, reads it back from the mask, and on a full
+ // mask that gives back the causal mask. Decide from the first graph, before the window shows in the mask, so
+ // the graph does not change, and is not recompiled, when it does.
+ // TODO: "larger group is swa" is a model-level guess. Revisit when llama.cpp tells the backend which layers
+ // use a sliding window. Stateless graphs only need the two groups kept apart (separate mask, KV write index
+ // and attention size inputs), not the swa role itself, so the guess could be limited to stateful execution.
+ if (model_params.swa_layers.empty()) {
+ std::map> mask_layers;
+ for (const auto & [layer, mask] : layer_mask) {
+ mask_layers[mask].push_back(layer);
+ }
+ if (mask_layers.size() == 2 &&
+ mask_layers.begin()->second.size() != std::next(mask_layers.begin())->second.size()) {
+ auto swa = mask_layers.begin();
+ if (std::next(swa)->second.size() > swa->second.size()) {
+ swa = std::next(swa);
+ }
+ model_params.swa_layers = swa->second;
+ model_params.swa_mask = swa->first;
+ }
+ }
std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end());
if (ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SWA_LAYERS")) {
@@ -867,26 +1136,28 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
bool rope_seen = false;
for (int i = 0; i < cgraph->n_nodes; i++) {
ggml_tensor * node = cgraph->nodes[i];
+ // `-fa off` stores the V cache transposed: SET_ROWS writes it through a [1, n] reshape, one element per row
+ if (node->op == GGML_OP_SET_ROWS && node->src[2] != nullptr && node->src[2]->op == GGML_OP_RESHAPE &&
+ node->src[2]->ne[0] == 1 && is_kvcache(node->src[2]->src[0], nullptr)) {
+ model_params.v_trans = true;
+ }
+ if (node->op == GGML_OP_FLASH_ATTN_EXT) {
+ float logit_softcap = 0.0f;
+ memcpy(&logit_softcap, (const float *) node->op_params + 2, sizeof(float));
+ model_params.softcap_attn = model_params.softcap_attn || logit_softcap != 0.0f;
+ }
const int attention_pattern_case = get_attention_pattern_case(node);
if (attention_pattern_case != -1) {
- ggml_tensor * cache_k_permute = nullptr;
+ ggml_tensor * cache_k_permute = get_attention_cache_k_permute(node);
ggml_tensor * mask = nullptr;
switch (attention_pattern_case) {
case 0:
- cache_k_permute = node->src[1];
- mask = node->src[3];
- break;
case 1:
- cache_k_permute = node->src[1]->src[0];
mask = node->src[3];
break;
case 2:
- cache_k_permute = node->src[0]->src[0];
- mask = node->src[1];
- break;
case 3:
- cache_k_permute = node->src[0]->src[0]->src[0];
mask = node->src[1];
break;
case 4:
@@ -909,8 +1180,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
model_params.head_size = cache_k_permute->ne[0];
model_params.n_heads_kv = cache_k_permute->ne[2];
- compute_params.input_len = node->src[0]->ne[1];
- compute_params.token_len_per_seq = node->src[0]->ne[1];
+ // gemma-4's KV-shared layers attend for the output tokens only, so the batch is the largest query
+ compute_params.input_len = std::max(compute_params.input_len, node->src[0]->ne[1]);
+ compute_params.token_len_per_seq = std::max(compute_params.token_len_per_seq, node->src[0]->ne[1]);
auto * cache_k_view = cache_k_permute->src[0];
if (cache_k_view->op != GGML_OP_VIEW || mask == nullptr) {
@@ -940,14 +1212,30 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
memcpy(&offset, cache_k_view->op_params, sizeof(size_t));
compute_params.seq_active_start = offset / seq_size;
+ // a mask that is itself a graph input has the shape of its OV parameter
+ const std::string mask_name = mask->op != GGML_OP_NONE ? std::string() :
+ mask == model_params.swa_mask ? get_tensor_ov_name(cgraph, mask) + "_swa" :
+ get_tensor_ov_name(cgraph, mask);
+ // gemma-4's KV-shared layers come last and take their mask rows from the input masks with GET_ROWS: keep
+ // the name and window read from the input
+ const bool derived_mask = mask_name.empty();
if (layer_is_swa) {
compute_params.attention_size_swa = mask->ne[0];
- compute_params.swa_window = get_swa_window_from_mask(mask);
+ if (!derived_mask || compute_params.mask_swa_name.empty()) {
+ compute_params.swa_window = get_swa_window_from_mask(mask);
+ compute_params.mask_swa_name = mask_name;
+ }
} else {
compute_params.attention_size = mask->ne[0];
+ if (!derived_mask || compute_params.mask_name.empty()) {
+ compute_params.mask_name = mask_name;
+ }
}
if (is_static) {
- compute_params.attention_size = model_params.ctx_per_seq;
+ const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
+ if (!slice_prefill) {
+ compute_params.attention_size = model_params.ctx_per_seq;
+ }
compute_params.attention_size_swa = model_params.ctx_per_seq_swa;
compute_params.token_len_per_seq = 1;
}
@@ -958,6 +1246,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
if (node->src[1]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->op == GGML_OP_VIEW &&
node->src[1]->src[0]->src[0]->op == GGML_OP_ROPE) {
compute_params.attention_size = node->ne[0];
+ compute_params.mask_name.clear();
}
}
@@ -965,7 +1254,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
if (node->op == GGML_OP_TRANSPOSE && node->src[0]->op == GGML_OP_PERMUTE &&
node->src[0]->src[0]->op == GGML_OP_VIEW) {
compute_params.attention_size = node->ne[0];
- if (is_static) {
+ compute_params.mask_name.clear();
+ if (is_static && !(ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1)) {
compute_params.attention_size = model_params.ctx_per_seq;
}
}
@@ -988,15 +1278,44 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
}
if (node->op == GGML_OP_GATED_DELTA_NET) {
model_params.state_size = node->src[0]->ne[0];
- }
- if (node->op == GGML_OP_SCALE && node->view_src != nullptr && is_recurrent_cache(node->view_src)) {
+ model_params.has_rs_rollback |= node->op_params[0] > 1;
+ compute_params.gdn_attention_rows[get_tensor_ov_name(cgraph, node)] = node->src[2]->ne[2] * node->src[2]->ne[3];
+ }
+ if (is_sampling_view(node)) {
+ compute_params.sampling_rows[get_tensor_ov_name(cgraph, node)] =
+ (node->flags & GGML_TENSOR_FLAG_COMPUTE) ? node->view_offs / node->src[0]->nb[1] : 0;
+ }
+ if (is_gdn_snapshot_writeback(node)) {
+ const auto * source = node->src[0];
+ const auto * destination = node->src[1];
+ const auto * packed = source->src[0];
+ ComputeParams::RsWriteback writeback;
+ writeback.slot_begin = destination->view_offs / destination->nb[1];
+ writeback.src_begin = source->view_offs / packed->nb[1];
+ writeback.seq_count = destination->ne[1];
+ writeback.snapshot_stride = destination->nb[2] / destination->nb[1];
+ compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
+ }
+ if (is_conv_state_snapshot_writeback(node)) {
+ const auto source = node->src[0];
+ const auto dest = node->src[2];
+ ComputeParams::RsWriteback writeback;
+ writeback.slot_begin = dest->view_offs / node->view_src->nb[1];
+ writeback.src_begin = source->view_offs / source->nb[0];
+ writeback.seq_count = dest->ne[3];
+ writeback.snapshot_stride = dest->nb[1] / node->view_src->nb[1];
+ writeback.window_count = source->ne[1];
+ compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
+ compute_params.s_copy_active_slot_len = dest->ne[3];
+ }
+ if (is_recurrent_cache_reset(node)) {
if (model_params.n_rs_slots == -1) {
model_params.n_rs_slots = node->view_src->ne[1];
} else {
GGML_ASSERT(model_params.n_rs_slots == node->view_src->ne[1]);
}
compute_params.cache_rs_reset_len = ggml_nelements(node) / node->view_src->ne[0];
- compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->ne[0];
+ compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->nb[1];
}
// Capture the destination slot block of every recurrent state cache writeback, plus the
// source window needed by conv state and packed GDN rollback writes. The active sequences
@@ -1007,7 +1326,9 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
const bool is_conv = is_conv_state_writeback(node);
const bool is_gdn = node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET;
- const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS;
+ const bool is_extra_view = node->src[0]->op == GGML_OP_VIEW &&
+ node->src[0]->src[0]->op == GGML_OP_GET_ROWS;
+ const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS || is_extra_view;
const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]);
const ggml_tensor * dest_view = node->src[1];
@@ -1020,17 +1341,20 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
// signature is local to the CPY and still works when fallback splits the graph.
model_params.has_rs_rollback = true;
}
- if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !is_full_single_slot_writeback(node)) {
+ if (row_bytes > 0 && (is_conv || is_gdn || is_extra) &&
+ !(is_gdn && node->src[0]->src[0]->op_params[0] > 1)) {
ComputeParams::RsWriteback writeback;
writeback.slot_begin = (int) (dest_view->view_offs / row_bytes);
if (is_conv) {
writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[0]);
} else if (is_gdn_rollback) {
writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[1]);
+ } else if (is_extra_view) {
+ writeback.src_begin = (int) (node->src[0]->view_offs / row_bytes);
}
compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
}
- if ((is_conv || is_gdn) && !is_full_single_slot_writeback(node)) {
+ if (is_conv || is_gdn) {
compute_params.s_copy_active_slot_len = (int) dest_view->ne[1];
}
}
@@ -1061,7 +1385,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
auto * output_tensor = cgraph->nodes[cgraph->n_nodes - 1];
compute_params.output_len = output_tensor->ne[1];
- if (model_params.is_cacheless_attn) {
+ {
for (int i = 0; i < cgraph->n_nodes; i++) {
const auto * node = cgraph->nodes[i];
if (node->op == GGML_OP_GET_ROWS && is_output_idx(node->src[1], node)) {
@@ -1074,6 +1398,14 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr
if (is_static && compute_params.output_len == 0) {
compute_params.output_len = 1;
}
+ // A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled
+ // prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch.
+ // Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two.
+ if (is_static && ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1 &&
+ !model_params.is_cacheless_attn && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) {
+ compute_params.attention_size =
+ ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq);
+ }
model_params.ctx = model_params.ctx_per_seq * model_params.n_seq;
return {model_params, compute_params};
}
@@ -1090,6 +1422,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
if (m_naive) {
return input != nullptr ? ov::PartialShape{get_shape(input)} : ov::PartialShape{get_shape(op)};
}
+ const std::string name = input != nullptr ? std::string(input->name) : std::string();
ov::PartialShape input_shape;
if (is_inp_tok(input, op) || is_inp_pos(input, op)) {
@@ -1105,6 +1438,9 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
// output index
input_shape = ov::PartialShape{1, 1, 1, m_is_static ? m_compute_params.output_len : -1};
+ } else if (!m_is_static && is_activation_input(input, op)) {
+ input_shape = ov::PartialShape{1, 1, -1, input->ne[0]};
+
} else if (is_inp_mean(input, op)) {
input_shape = m_is_static ? ov::PartialShape{1, 1, input->ne[1], m_prefill_chunk_size} :
ov::PartialShape{1, 1, -1, -1};
@@ -1115,7 +1451,17 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
} else if (is_inp_mask(input, op)) {
// mask
if (m_is_static) {
- input_shape = ov::PartialShape{1, 1, m_is_prefill ? m_prefill_chunk_size : 1, m_model_params.ctx};
+ // The sliding-window mask spans the window cache, which is smaller than the context once
+ // the context exceeds n_swa + n_ubatch (gemma-4 at -c 4096 -ub 1024: 1536 vs 4096 cells).
+ // Both masks are named "attn_inp_kq_mask", so tell them apart by tensor identity.
+ const bool swa_mask = is_swa_mask(input);
+ int attention_size = swa_mask ? m_model_params.ctx_per_seq_swa * m_model_params.n_seq : m_model_params.ctx;
+ const bool kv_window =
+ m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0;
+ if (kv_window) {
+ attention_size = swa_mask ? m_compute_params.attention_size_swa : m_compute_params.attention_size;
+ }
+ input_shape = ov::PartialShape{1, 1, m_is_prefill ? m_prefill_chunk_size : 1, attention_size};
} else if (m_is_stateful) {
input_shape = ov::PartialShape{1, 1, -1, -1};
} else {
@@ -1138,10 +1484,27 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
if (!m_is_static && !is_flat_kv) {
// do not fix ctx size to make llama-bench work across test params
input_shape[2] = -1;
- }
- if (is_stateful() && !is_flat_kv) {
+ } else if (m_is_prefill ? ggml_openvino_kv_slice_enabled() :
+ m_is_static && ggml_openvino_npu_decode_bucket() > 0) {
+ const auto layer = extract_layer_from_name(name);
+ if (layer.has_value() && !is_swa_layer(*layer) && m_compute_params.attention_size > 0 &&
+ m_compute_params.attention_size < input_shape[2].get_length()) {
+ const int attention_size = m_compute_params.attention_size;
+ input_shape[2] = attention_size;
+ }
+ if (layer.has_value() && !is_swa_layer(*layer) && ggml_openvino_npu_kv_head_major_enabled()) {
+ GGML_ASSERT(input_shape[1].get_length() == 1);
+ const int64_t heads = get_n_heads_kv_for_tensor(input);
+ const int64_t head_size = input_shape[3].get_length() / heads;
+ input_shape = name.rfind("cache_v_l", 0) == 0 ?
+ ov::PartialShape{1, heads, head_size, input_shape[2]} :
+ ov::PartialShape{1, heads, input_shape[2], head_size};
+ }
+ }
+ if ((is_stateful() && !is_flat_kv) || is_kvcache_4d(input)) {
// Convert stateless KV cache layout [1, 1, seq, n_heads_kv * head_size]
- // to stateful layout [1, seq, n_heads_kv, head_size].
+ // to stateful layout [1, seq, n_heads_kv, head_size]. Stateless GPU graphs use the same
+ // layout for the caches that qualify (see is_kvcache_4d), bound over the same memory.
// NOTE: Gemma4 uses per-layer-type KV shapes, so no single scalar describes every
// layer. E2B varies only the head size (sliding 256, full 512); 12B also varies the
// head COUNT (sliding 8 x 256, full 1 x 512). Take the head count for this tensor's
@@ -1167,7 +1530,13 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
// index list has a static length; on CPU/GPU it may change across compiles (defrag).
input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1};
- } else {
+ } else if (input != nullptr && op != nullptr && is_inp_emb(input, op)) {
+ input_shape = ov::PartialShape{get_shape(input)};
+ if (!m_is_static) {
+ input_shape[2] = -1;
+ }
+ }
+ else {
input_shape = ov::PartialShape{get_shape(input)};
}
if (dynamic_dim_index != -1 && m_model_is_splitted) {
@@ -1218,13 +1587,15 @@ bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
}
void GgmlOvDecoder::add_extra_inputs() {
+ m_model_extra_inputs.clear();
+
// Extra inputs:
// 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
// see llama_kv_cache_unified::get_n_kv and llama_kv_cache_unified::get_padding.
// 2. `n_seq_active` and `seq_active_start`, used in FLASH_ATTN_EXT to indicate the active sequences in the batch
auto create_1d_input = [this](const std::string & name, int64_t value, bool force_parameter = false) {
- m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static};
+ m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1};
};
if (m_compute_params.attention_size != -1) {
@@ -1246,13 +1617,66 @@ void GgmlOvDecoder::add_extra_inputs() {
if (m_compute_params.token_len_per_seq != -1) {
create_1d_input("token_len_per_seq", m_compute_params.token_len_per_seq);
}
+ if (m_is_static && m_is_prefill && ggml_openvino_npu_hfa_prefill_enabled()) {
+ if (m_compute_params.n_seq_active != 1) {
+ throw std::runtime_error("GGML_OPENVINO_NPU_HFA_PREFILL currently requires one active sequence");
+ }
+ if (!m_model_params.swa_layers.empty()) {
+ throw std::runtime_error("GGML_OPENVINO_NPU_HFA_PREFILL does not yet support sliding-window layers");
+ }
+ const auto chunk_size = static_cast(m_prefill_chunk_size);
+ const auto input_len = static_cast(m_compute_params.input_len);
+ const auto num_chunks = (input_len + chunk_size - 1) / chunk_size;
+ // Head-major KV: the past is the whole cache storage [1, heads, attention_size, head_size].
+ const bool head_major = ggml_openvino_npu_kv_head_major_enabled();
+ const auto past_capacity = head_major ? static_cast(m_compute_params.attention_size) :
+ std::max(chunk_size, (num_chunks - 1) * chunk_size);
+ for (const auto & [kv_name, kv_tensor] : m_inputs) {
+ if (kv_name.rfind("cache_k_l", 0) != 0 && kv_name.rfind("cache_v_l", 0) != 0) {
+ continue;
+ }
+ const auto n_heads_kv = static_cast(get_n_heads_kv_for_tensor(kv_tensor));
+ const auto combined_dim = static_cast(kv_tensor->ne[0]);
+ GGML_ASSERT(n_heads_kv > 0 && combined_dim % n_heads_kv == 0);
+ const auto head_size = combined_dim / n_heads_kv;
+ // flash_attn_ext looks the past input up by layer, so drop the graph-ordinal suffix ("#l12").
+ const std::string cache_name = kv_name.substr(0, kv_name.find('#'));
+ const bool v_transposed = head_major && kv_name.rfind("cache_v_l", 0) == 0;
+ m_model_extra_inputs["ggml_hfa_past_" + cache_name] = {
+ get_ov_type(kv_tensor),
+ v_transposed ? ov::Shape{1, n_heads_kv, head_size, past_capacity} :
+ head_major ? ov::Shape{1, n_heads_kv, past_capacity, head_size} :
+ ov::Shape{1, past_capacity, n_heads_kv, head_size},
+ 0, true, {}, -1};
+ }
+ m_model_extra_inputs["ggml_hfa_mask"] = {
+ ov::element::f16, ov::Shape{1, 1, chunk_size, past_capacity + chunk_size}, 0, true, {}, -1};
+ }
// create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);
- if (m_compute_params.cache_rs_reset_idx != -1 && m_model_params.n_rs_slots != 1) {
+ // n_seq_active and attention_size(_swa) are dimensions of the KQ masks. Read them from the mask shape inside the
+ // model: the GPU plugin then gets the Q Reshape and KV Slice shapes from shape inference instead of waiting for
+ // the input values on the device
+ if (!m_is_static && !m_is_stateful && ggml_openvino_shape_from_mask_enabled()) {
+ auto from_mask = [this](const std::string & name, const std::string & mask, int64_t axis) {
+ auto it = m_model_extra_inputs.find(name);
+ if (it != m_model_extra_inputs.end() && !mask.empty() && m_model_inputs.count(mask) != 0) {
+ it->second.shape_source = mask;
+ it->second.shape_axis = axis;
+ }
+ };
+ const auto & full = m_compute_params.mask_name;
+ const auto & swa = m_compute_params.mask_swa_name;
+ from_mask("attention_size", full, 3);
+ from_mask("attention_size_swa", swa, 3);
+ from_mask("n_seq_active", full.empty() ? swa : full, 0);
+ }
+
+ if (m_compute_params.cache_rs_reset_idx != -1) {
// Whether/which cache slot to reset varies per compute call (e.g. a new sequence starting
// vs. continued decoding). can_reuse_statically() does not invalidate the cached static
// model on ComputeParams changes, so these must stay runtime Parameters even when static
- // (scale.cpp op_case 1 only uses them in value comparisons, never as Slice bounds, so this
+ // (translate_recurrent_cache_reset only uses them in value comparisons, never as Slice bounds, so this
// does not reintroduce dynamic shapes).
create_1d_input("cache_rs_reset_idx", m_compute_params.cache_rs_reset_idx, /*force_parameter=*/true);
create_1d_input("cache_rs_reset_len", m_compute_params.cache_rs_reset_len, /*force_parameter=*/true);
@@ -1260,6 +1684,13 @@ void GgmlOvDecoder::add_extra_inputs() {
if (m_compute_params.s_copy_active_slot_len != -1) {
create_1d_input("s_copy_active_slot_len", m_compute_params.s_copy_active_slot_len);
+ if (m_model_inputs.count("rs_active_rows") != 0) {
+ // The row-map prefix is rebound with its current length on every compute.
+ // Shape consumers must not wait for a scalar uploaded to the GPU.
+ auto & active = m_model_extra_inputs.at("s_copy_active_slot_len");
+ active.shape_source = "rs_active_rows";
+ active.shape_axis = 3;
+ }
if (m_is_static) {
// Number of real tokens in the current prefill chunk. The last chunk is padded with
// fabricated token ids; attention masks them out, but the recurrent (GDN/conv) path
@@ -1275,6 +1706,80 @@ void GgmlOvDecoder::add_extra_inputs() {
if (!m_is_static && writeback.src_begin >= 0) {
create_1d_input("rs_src_begin_" + node_name, writeback.src_begin);
}
+ if (writeback.seq_count >= 0) {
+ create_1d_input("rs_seq_count_" + node_name, writeback.seq_count);
+ create_1d_input("rs_snapshot_stride_" + node_name, writeback.snapshot_stride);
+ }
+ if (writeback.window_count >= 0) {
+ create_1d_input("rs_window_count_" + node_name, writeback.window_count);
+ }
+ }
+#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
+ m_compute_params.recurrent_controls.clear();
+ // Naive graphs have no full-model cache fusion and node cases are not initialized here.
+ if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() &&
+ !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) {
+ for (int i = 0; i < m_cgraph->n_nodes; ++i) {
+ const auto node = m_cgraph->nodes[i];
+ const auto op_case = m_node_info_list[i].node_op_case;
+ if (node->op == GGML_OP_CPY && (op_case == 10 || op_case == 12)) {
+ m_model_extra_inputs["rs_update_" + get_tensor_ov_name(m_cgraph, node)] =
+ {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1};
+ }
+ }
+ for (const auto & [name, write] : m_compute_params.rs_writebacks) {
+ if (write.src_begin >= 0) {
+ auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name];
+ values = {write.slot_begin, write.src_begin};
+ m_model_extra_inputs["rs_offsets_" + name] =
+ {ov::element::i64, ov::Shape{1, 1, 1, 2}, 0, true, {}, -1};
+ }
+ }
+ for (int i = 0; i < m_cgraph->n_nodes; ++i) {
+ const auto concat = m_cgraph->nodes[i];
+ if (concat->op != GGML_OP_CONCAT || !concat->src[0] || concat->src[0]->op != GGML_OP_RESHAPE ||
+ !concat->src[0]->src[0] || concat->src[0]->src[0]->op != GGML_OP_VIEW ||
+ concat->src[0]->src[0]->src[0]->op != GGML_OP_GET_ROWS) {
+ continue;
+ }
+ std::vector values;
+ for (int j = i + 1; j < m_cgraph->n_nodes; ++j) {
+ const auto write = m_cgraph->nodes[j];
+ if ((is_conv_state_writeback(write) || is_conv_state_snapshot_writeback(write)) &&
+ write->src[0]->src[0] == concat) {
+ const auto it = m_compute_params.rs_writebacks.find(get_tensor_ov_name(m_cgraph, write));
+ if (it == m_compute_params.rs_writebacks.end()) {
+ values.clear();
+ break;
+ }
+ const auto & wb = it->second;
+ const int64_t count = wb.window_count >= 0 ? wb.window_count : 1;
+ for (int64_t w = 0; w < count; ++w) {
+ values.push_back(wb.src_begin + w);
+ values.push_back(wb.slot_begin + (count - 1 - w) *
+ (wb.window_count >= 0 ? wb.snapshot_stride : 0));
+ }
+ break;
+ }
+ }
+ if (!values.empty()) {
+ const auto name = "rs_windows_" + get_tensor_ov_name(m_cgraph, concat);
+ m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1, 1, values.size() / 2, 2}, 0, true, {}, -1};
+ m_compute_params.recurrent_controls[name] = std::move(values);
+ }
+ }
+ }
+#endif
+ if (!m_is_static && !m_compute_params.sampling_rows.empty()) {
+ m_model_extra_inputs["sampling_rows"] =
+ {ov::element::i64, ov::Shape{m_compute_params.sampling_rows.size()}, 0, true, {}, -1};
+ } else {
+ for (const auto & [node_name, row] : m_compute_params.sampling_rows) {
+ create_1d_input("sampling_row_" + node_name, row);
+ }
+ }
+ for (const auto & [node_name, rows] : m_compute_params.gdn_attention_rows) {
+ create_1d_input("gdn_attention_rows_" + node_name, rows);
}
}
@@ -1294,6 +1799,14 @@ bool GgmlOvDecoder::node_is_used_as_src(const int node_idx) {
void GgmlOvDecoder::compute_model_inputs() {
m_model_inputs.clear();
m_inputs.clear();
+ m_kvcache_4d.clear();
+ // remember the KV caches that get_graph_input_shape gave the 4-D layout, so that they are bound with that shape
+ auto note_kvcache_4d = [this](const ggml_tensor * input, const ggml_tensor * op, const ov::PartialShape & shape) {
+ if (!m_is_stateful && is_kvcache(input, op) && shape.rank().is_static() && shape.rank().get_length() == 4 &&
+ shape[1].is_dynamic()) {
+ m_kvcache_4d.insert(input);
+ }
+ };
for (int i = 0; i < m_cgraph->n_nodes; i++) {
ggml_tensor * node = m_cgraph->nodes[i];
// the node op is NONE means this node maybe as input of later nodes, we should add it to model inputs for this node.
@@ -1303,6 +1816,7 @@ void GgmlOvDecoder::compute_model_inputs() {
m_inputs[node_name] = node;
m_model_inputs[node_name] = {get_ov_type(node),
get_graph_input_shape(node, nullptr, m_node_dynamic_dims[node])};
+ note_kvcache_4d(node, nullptr, m_model_inputs[node_name].shape);
}
continue;
}
@@ -1315,6 +1829,13 @@ void GgmlOvDecoder::compute_model_inputs() {
if (src->flags & GGML_TENSOR_FLAG_INPUT) {
src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
}
+ // ROPE frequency factors (rope_factors_short/long in Phi-3, Phi-4 and MiniCPM) are registered as
+ // "rope_freqs.weight" in create_weight_nodes(). Without the same name here they become a
+ // Parameter fed from the host weight buffer, which is empty in cache-only mode and after
+ // GGML_OPENVINO_RELEASE_WEIGHTS.
+ if (is_rope_freqs_weight(src->view_src ? src->view_src : src, node)) {
+ src_name = "rope_freqs.weight";
+ }
if (m_model_weights.find(src_name) != m_model_weights.end()) {
continue;
}
@@ -1356,6 +1877,23 @@ void GgmlOvDecoder::compute_model_inputs() {
m_inputs[src_name] = src;
m_model_inputs[src_name] = {get_ov_type(src),
get_graph_input_shape(node, src, m_node_dynamic_dims[src])};
+ note_kvcache_4d(src, node, m_model_inputs[src_name].shape);
+ }
+ }
+ if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() &&
+ m_compute_params.s_copy_active_slot_len > 0) {
+ const ggml_tensor * rows = nullptr;
+ for (const auto & [name, tensor] : m_inputs) {
+ if (tensor->type == GGML_TYPE_I32 && is_s_copy_leaf(tensor)) {
+ if (rows && rows != tensor) {
+ return; // Different recurrent row maps cannot share one active shape.
+ }
+ rows = tensor;
+ }
+ }
+ if (rows && m_compute_params.s_copy_active_slot_len <= ggml_nelements(rows)) {
+ m_inputs["rs_active_rows"] = const_cast(rows);
+ m_model_inputs["rs_active_rows"] = {ov::element::i32, ov::PartialShape{1, 1, 1, -1}};
}
}
}
@@ -1369,13 +1907,29 @@ void GgmlOvDecoder::compute_model_outputs() {
if (cur_node->op == GGML_OP_NONE || cur_node->op == GGML_OP_VIEW || cur_node->op == GGML_OP_RESHAPE) {
continue;
}
- if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0) {
+ const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(cur_node->view_src) &&
+ ::is_inplace_op(cur_node) &&
+ (is_recurrent_cache_reset(cur_node) || !m_is_static);
+ if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0 && !runtime_recurrent_write) {
continue;
}
+ const bool inactive_top_k = is_sampling_top_k(cur_node) && !(cur_node->flags & GGML_TENSOR_FLAG_COMPUTE);
+ if ((cur_node->flags & GGML_TENSOR_FLAG_OUTPUT) || inactive_top_k) {
+ const auto name = get_tensor_ov_name(m_cgraph, cur_node);
+ m_model_outputs[name] = cur_node;
+ m_model_output_names.insert(name);
+ }
+ if (is_gdn_snapshot_writeback(cur_node)) {
+ auto * cache = cur_node->view_src;
+ const auto name = get_tensor_ov_name(m_cgraph, cache);
+ m_model_outputs[name] = cache;
+ m_model_output_names.insert(name);
+ }
auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)];
if (cur_node_use_count == 0) {
// The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src.
- if (cur_node != nullptr && ::is_inplace_op(cur_node) && ggml_nbytes(cur_node) > 0) {
+ if (cur_node != nullptr && ::is_inplace_op(cur_node) &&
+ (ggml_nbytes(cur_node) > 0 || runtime_recurrent_write)) {
cur_node = cur_node->view_src;
}
} else {
@@ -1415,6 +1969,80 @@ const ggml_tensor * GgmlOvDecoder::get_tensor_used_op(const ggml_tensor * tensor
return nullptr;
}
+bool GgmlOvDecoder::is_kvcache_4d(const ggml_tensor * cache) const {
+ static const bool enabled = ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0;
+ if (!enabled || m_is_static || m_is_stateful || m_model_is_splitted || !ggml_openvino_is_gpu()) {
+ return false;
+ }
+ // `-fa off` (transposed V cache): keep the [1, 1, ctx, n_heads_kv * head_size] layout. The 4-D K cache breaks the
+ // MUL_MAT attention of the Phi-3 models (Phi-3.5 mini, Phi-4 mini), and the soft-capped manual attention of
+ // gemma-2 with `-fa on` ("could not construct a memory descriptor using strides" in the GPU plugin's oneDNN path).
+ if (m_model_params.v_trans || m_model_params.softcap_attn) {
+ return false;
+ }
+ if (cache->op != GGML_OP_NONE || cache->view_src != nullptr || !is_kvcache(cache, nullptr)) {
+ return false;
+ }
+ // one sequence, [n_heads_kv * head_size, ctx, 1, 1]; whisper's flat KV buffer has ctx == 1
+ if (cache->ne[1] <= 1 || cache->ne[2] != 1 || cache->ne[3] != 1) {
+ return false;
+ }
+ const int n_heads_kv = get_n_heads_kv_for_tensor(cache);
+ if (n_heads_kv <= 0 || cache->ne[0] % n_heads_kv != 0) {
+ return false;
+ }
+ // check the nodes that take the cache itself as a source (views of those views, such as the PERMUTE of the read
+ // VIEW, are checked through them)
+ auto feeds_only_permutes = [this](const ggml_tensor * view) {
+ for (int i = 0; i < m_cgraph->n_nodes; i++) {
+ const auto * node = m_cgraph->nodes[i];
+ for (int j = 0; j < GGML_MAX_SRC; j++) {
+ if (node->src[j] == view && node->op != GGML_OP_PERMUTE) {
+ return false;
+ }
+ }
+ }
+ return true;
+ };
+ for (int i = 0; i < m_cgraph->n_nodes; i++) {
+ const auto * node = m_cgraph->nodes[i];
+ bool uses_cache = false;
+ for (int j = 0; j < GGML_MAX_SRC; j++) {
+ uses_cache = uses_cache || node->src[j] == cache;
+ }
+ if (!uses_cache) {
+ continue;
+ }
+ // write: whole rows into the cache itself
+ if (node->op == GGML_OP_SET_ROWS && node->src[2] == cache && node->src[0]->ne[0] == cache->ne[0]) {
+ continue;
+ }
+ // read: the first rows of the cache, each row split into heads, permuted for attention
+ if (node->op == GGML_OP_VIEW && node->src[0] == cache && node->view_offs == 0 &&
+ node->ne[0] * node->ne[1] == cache->ne[0] && node->nb[2] == cache->nb[1] && node->ne[3] == 1 &&
+ feeds_only_permutes(node)) {
+ continue;
+ }
+ return false;
+ }
+ return true;
+}
+
+bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
+ for (int i = 0; i < m_cgraph->n_nodes; i++) {
+ const auto * node = m_cgraph->nodes[i];
+ if (node->op != GGML_OP_SET_ROWS) {
+ continue;
+ }
+ // SET_ROWS writes whole rows of src[2], which is the cache or a view of it
+ const auto * dst = node->src[2];
+ if (dst != nullptr && (dst == cache || dst->view_src == cache) && dst->ne[0] != cache->ne[0]) {
+ return false;
+ }
+ }
+ return true;
+}
+
const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
for (int i = 0; i < m_cgraph->n_nodes; i++) {
const auto * node = m_cgraph->nodes[i];
@@ -1431,6 +2059,16 @@ const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name
return nullptr;
}
+std::string GgmlOvDecoder::get_hfa_history_input_name() const {
+ for (const auto & [name, tensor] : m_inputs) {
+ const auto * op = get_tensor_used_op(tensor);
+ if (op != nullptr && is_inp_pos(tensor, op)) {
+ return name;
+ }
+ }
+ throw std::runtime_error("HFA prefill position input was not found");
+}
+
std::map GgmlOvDecoder::get_kv_param_res_names() const {
std::map kv_param_res_names;
for (const auto & name : m_model_params.kv_names) {
@@ -1560,7 +2198,10 @@ std::shared_ptr GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
// pointer to avoid re-extracting on every recompile. Opt-in via
// GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
// for `naive` (test/naive path) since use_bias changes the produced node.
- const bool cacheable_nonov = ggml_openvino_reduce_compile_mem_enabled() && !is_ov_buffer &&
+ // Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
+ // token_embd vocab on the pair's NPUW bank uid instead of embedding and importing a second copy.
+ const bool keep_for_windows = ggml_openvino_npu_raw_weight_cache_enabled() && ggml_openvino_npu_decode_bucket() > 0;
+ const bool cacheable_nonov = (ggml_openvino_reduce_compile_mem_enabled() || keep_for_windows) && !is_ov_buffer &&
!naive && tensor->data != nullptr;
if (cacheable_nonov) {
std::lock_guard lock(g_nonov_weight_cache_mutex);
@@ -1577,7 +2218,7 @@ std::shared_ptr GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
// GGML_LOG_DEBUG("%s: creating new weight node for %s\n", __func__, tensor->name);
static const std::set weight_types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0,
- GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K,
+ GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_0, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K,
GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4};
if (weight_types.find(tensor->type) == weight_types.end()) {
throw std::runtime_error("Unexpected weight tensor type: " + std::string(tensor->name) + " with type " +
@@ -1588,14 +2229,19 @@ std::shared_ptr GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
if (ggml_is_quantized(tensor->type)) {
auto use_bias = naive;
if (is_ov_buffer) {
- // For quantized weights, copy raw data to a temp buffer first because
- // process_weight_tensor reads from data and writes extracted results
- // (weights/scales/zp) to output_base_ptr — they would overlap if both
- // point to tensor->data.
- size_t raw_size = ggml_nbytes(tensor);
- std::vector tmp(raw_size);
- memcpy(tmp.data(), tensor->data, raw_size);
- ov_weight = process_weight_tensor(tensor, tmp.data(), tensor->data, use_bias);
+ const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
+ if (preserve_raw) {
+ // A later context must fingerprint the same raw GGUF bytes before importing its
+ // self-contained blob, so keep the model buffer immutable in this mode.
+ ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
+ } else {
+ // The regular path stores extracted weights in the model buffer. Copy raw data
+ // first because input and output ranges would otherwise overlap.
+ size_t raw_size = ggml_nbytes(tensor);
+ std::vector tmp(raw_size);
+ memcpy(tmp.data(), tensor->data, raw_size);
+ ov_weight = process_weight_tensor(tensor, tmp.data(), tensor->data, use_bias);
+ }
} else {
ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
}
@@ -1670,6 +2316,9 @@ void GgmlOvDecoder::dump_cgraph(const ggml_cgraph * cgraph, std::string & filena
<< std::setw(5) << node->nb[2] << ", "
<< std::setw(5) << node->nb[3] << "] "
<< std::right << std::setw(15) << buf_name << std::right
+ << " compute=" << ((node->flags & GGML_TENSOR_FLAG_COMPUTE) != 0)
+ << " output=" << ((node->flags & GGML_TENSOR_FLAG_OUTPUT) != 0)
+ << " view_offs=" << node->view_offs
<< "\n";
for (int i = 0; i < GGML_MAX_SRC; i++) {
@@ -1977,9 +2626,22 @@ std::vector GgmlOvDecoder::get_output_stride(int node_idx) const {
return get_stride(ggml_tensor);
}
+bool GgmlOvDecoder::is_direct_gdn_view(const ggml_tensor * node) const {
+ if (node == nullptr || node->op != GGML_OP_VIEW || node->src[0] == nullptr ||
+ node->src[0]->op != GGML_OP_GATED_DELTA_NET) {
+ return false;
+ }
+ for (int i = 0; i < m_cgraph->n_nodes; ++i) {
+ if (m_cgraph->nodes[i] == node->src[0]) {
+ return get_output_names(i).size() > 1;
+ }
+ }
+ return false;
+}
+
std::vector GgmlOvDecoder::get_output_names(int node_idx) const {
auto * node = m_node_info_list[node_idx].node;
- if (node->op == GGML_OP_GATED_DELTA_NET && !m_model_params.has_rs_rollback) {
+ if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
std::string attn_name;
std::string state_name;
for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
@@ -1996,6 +2658,9 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const {
name = get_tensor_ov_name(m_cgraph, consumer);
}
if (!attn_name.empty() && !state_name.empty()) {
+ if (m_model_params.has_rs_rollback) {
+ return {m_node_info_list[node_idx].node_name, attn_name, state_name};
+ }
return {attn_name, state_name};
}
}
@@ -2004,7 +2669,12 @@ std::vector GgmlOvDecoder::get_output_names(int node_idx) const {
std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const {
auto * node = m_node_info_list[node_idx].node;
- if (!::is_inplace_op(node) || node->view_src == nullptr || ggml_nbytes(node) == 0) {
+ // Reset lengths (also in static mode) and dynamic remainder views can become nonempty
+ // after compilation. Keep their alias updates in the translated cache chain.
+ const bool runtime_recurrent_write = !m_naive && is_recurrent_cache(node->view_src) &&
+ (is_recurrent_cache_reset(node) || !m_is_static);
+ if (!::is_inplace_op(node) || node->view_src == nullptr ||
+ (ggml_nbytes(node) == 0 && !runtime_recurrent_write)) {
return "";
}
const int op_case = m_node_info_list[node_idx].node_op_case;
@@ -2104,7 +2774,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
// root_src = src->org_src;
// }
if (root_src) {
- if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_output_idx(root_src, node)) {
+ if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_get_rows_input_idx(root_src, node)) {
m_node_dynamic_dims[root_src] = 0;
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
continue;
@@ -2112,7 +2782,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
self(self, root_src);
m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
} else {
- if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_output_idx(src, node)) {
+ if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_get_rows_input_idx(src, node)) {
m_node_dynamic_dims[src] = 0;
continue;
}
@@ -2120,7 +2790,13 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[src] = 1;
continue;
}
- if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted) {
+ if (!m_is_static && is_activation_input(src, node)) {
+ m_node_dynamic_dims[src] = 1;
+ continue;
+ }
+ // a view of a model weight (BERT's token type row) has no token dim
+ if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted &&
+ !(src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) {
m_node_dynamic_dims[src] = 1;
continue;
}
@@ -2137,6 +2813,9 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[1]];
if (dynamic_dim_idx == 0) {
m_node_dynamic_dims[node] = 1;
+ } else if (dynamic_dim_idx == 2 && node->ne[3] == node->src[1]->ne[2]) {
+ // indices [k, ne11, ne12] -> result [ne00, k, ne11, ne12]
+ m_node_dynamic_dims[node] = 3;
} else {
auto dynamic_dim_stride = node->src[1]->nb[dynamic_dim_idx] / ggml_type_size(node->src[1]->type) *
ggml_type_size(node->src[0]->type);
@@ -2167,11 +2846,9 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
if (m_node_dynamic_dims[node->src[0]] != -1) {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
// auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
- for (int i = 0; i < GGML_MAX_DIMS; i++) {
- if (node->op_params[i] == dynamic_dim_idx) {
- m_node_dynamic_dims[node] = i;
- break;
- }
+ // src dim i moves to dim op_params[i]
+ if (dynamic_dim_idx >= 0 && dynamic_dim_idx < GGML_MAX_DIMS) {
+ m_node_dynamic_dims[node] = node->op_params[dynamic_dim_idx];
}
// OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
// "Dynamic dim value mismatch for node: " + std::string(node->name) +
@@ -2179,23 +2856,45 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
}
break;
case GGML_OP_VIEW: {
+ if (is_sampling_view(node)) {
+ m_node_dynamic_dims[node] = -1;
+ break;
+ }
+
+ if (node->src[0]->op == GGML_OP_GATED_DELTA_NET && node->view_offs == 0) {
+ m_node_dynamic_dims[node] = 2;
+ break;
+ }
// Use stride-based matching: the stride of a VIEW dimension directly
// encodes which source dimension it indexes into, so it uniquely
// identifies the dynamic dim even when two dims share the same size.
m_node_dynamic_dims[node] = -1;
if (m_node_dynamic_dims[node->src[0]] != -1) {
- if (node->src[0]->op == GGML_OP_NONE) {
- m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
- break;
- }
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
auto dynamic_dim_stride =
node->src[0]->nb[dynamic_dim_idx] / ggml_type_size(node->src[0]->type) * ggml_type_size(node->type);
+ if (node->src[0]->op == GGML_OP_NONE) {
+ // A view of a KV cache covers fewer cells than the cache holds, so only the stride identifies the
+ // dim: [n_embd, kv_size] viewed as [head_dim, n_head_kv, n_kv] moves the cells from dim 1 to 2.
+ m_node_dynamic_dims[node] = dynamic_dim_idx;
+ for (int i = 0; i < GGML_MAX_DIMS; i++) {
+ if (node->nb[i] == dynamic_dim_stride && node->ne[i] != 1) {
+ m_node_dynamic_dims[node] = i;
+ break;
+ }
+ }
+ break;
+ }
+ // A size-1 dim may carry any stride (MLA's k_pe = ggml_view_3d(.., ne1 = 1, ..) gives it the row
+ // stride), so among the dims with the source's stride take the outermost one of the same size.
+ // With a dynamic size of 1 every trailing size-1 dim matches (Qwen3.5's Qcur view: ne2 = n_tokens = 1,
+ // nb3 == nb2), so keep the innermost match there.
for (int i = 0; i < GGML_MAX_DIMS; i++) {
- if (node->nb[i] == dynamic_dim_stride) {
+ const bool first_match = m_node_dynamic_dims[node] == -1;
+ const bool same_size = dynamic_dim_value != 1 && node->ne[i] == dynamic_dim_value;
+ if (node->nb[i] == dynamic_dim_stride && (first_match || same_size)) {
m_node_dynamic_dims[node] = i;
- break;
}
}
if (m_node_dynamic_dims[node] != -1 && dynamic_dim_value != node->ne[m_node_dynamic_dims[node]]) {
@@ -2219,14 +2918,23 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
// have standard compact strides: nb[i] = type_size * prod(ne[0..i-1]).
// Match src->nb[dynamic_dim] against result->nb[i] to find the output
// dimension whose flat-memory boundary aligns with the source dynamic
- // boundary. This is unambiguous (result strides are strictly monotone)
- // and handles merged-lower-dim cases that ne-value matching misses.
+ // boundary. This handles merged-lower-dim cases that ne-value matching
+ // misses. A size-1 dim has the same stride as the dim after it
+ // ([head_dim, T] -> [head_dim, 1, T] with one KV head), so prefer the
+ // matching dim that also has the source dim's size.
m_node_dynamic_dims[node] = -1;
if (m_node_dynamic_dims[node->src[0]] != -1) {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
+ auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
auto dynamic_dim_stride = node->src[0]->nb[dynamic_dim_idx];
for (int i = 0; i < GGML_MAX_DIMS; i++) {
- if (node->nb[i] == dynamic_dim_stride && node->ne[i] == node->src[0]->ne[dynamic_dim_idx]) {
+ if (node->nb[i] != dynamic_dim_stride) {
+ continue;
+ }
+ if (m_node_dynamic_dims[node] == -1) {
+ m_node_dynamic_dims[node] = i;
+ }
+ if (node->ne[i] == dynamic_dim_value) {
m_node_dynamic_dims[node] = i;
break;
}
@@ -2299,14 +3007,25 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
}
}
break;
- case GGML_OP_CONCAT:
- for (int i = 0; i < GGML_MAX_DIMS; i++) {
- if (node->src[0]->ne[i] != node->ne[i]) {
- m_node_dynamic_dims[node] = i;
+ case GGML_OP_CONCAT: {
+ const int axis = node->op_params[0];
+ const int src0_dynamic_dim = m_node_dynamic_dims[node->src[0]];
+ const int src1_dynamic_dim = m_node_dynamic_dims[node->src[1]];
+ if (src0_dynamic_dim != -1 && src0_dynamic_dim != axis &&
+ src1_dynamic_dim != -1 && src1_dynamic_dim != axis && src0_dynamic_dim != src1_dynamic_dim) {
+ GGML_LOG_WARN("ggml-openvino: different dynamic dims for CONCAT node '%s', src[0]: '%s', src[1]: '%s'\n",
+ node->name, node->src[0]->name, node->src[1]->name);
+ }
+ m_node_dynamic_dims[node] = axis;
+ for (int i = 0; i < 2; ++i) {
+ const int dynamic_axis = m_node_dynamic_dims[node->src[i]];
+ if (dynamic_axis != -1 && dynamic_axis != axis) {
+ m_node_dynamic_dims[node] = dynamic_axis;
break;
}
}
break;
+ }
case GGML_OP_SSM_CONV:
case GGML_OP_GATED_DELTA_NET:
m_node_dynamic_dims[node] = 1;
@@ -2321,6 +3040,7 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
case GGML_OP_SCALE:
case GGML_OP_SOFT_MAX:
case GGML_OP_ARGSORT:
+ case GGML_OP_TOP_K:
case GGML_OP_ADD_ID:
case GGML_OP_UNARY:
case GGML_OP_CUMSUM:
@@ -2347,8 +3067,9 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
break;
case GGML_OP_SUM_ROWS:
- // SUM_ROWS reduces ggml axis 0 to size 1 and preserves all other axes, so the
- // dynamic dim is preserved unless it was axis 0 (then it is summed away).
+ case GGML_OP_POOL_1D:
+ // SUM_ROWS/POOL_1D change only ggml axis 0 and preserve all other axes, so the
+ // dynamic dim is preserved unless it was axis 0.
m_node_dynamic_dims[node] =
(m_node_dynamic_dims[node->src[0]] == 0) ? -1 : m_node_dynamic_dims[node->src[0]];
break;
@@ -2357,11 +3078,15 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[1]];
break;
case GGML_OP_CPY:
- case GGML_OP_SET_ROWS:
case GGML_OP_SUM:
case GGML_OP_MEAN:
m_node_dynamic_dims[node] = -1;
break;
+ case GGML_OP_SET_ROWS:
+ // a cache write returns the cache; other rows writes keep the shape of their destination
+ m_node_dynamic_dims[node] = (is_kvcache_write(node) || is_conv_state_snapshot_writeback(node)) ?
+ -1 : m_node_dynamic_dims[node->src[2]];
+ break;
case GGML_OP_IM2COL: {
m_node_dynamic_dims[node] = -1;
if (m_node_dynamic_dims[node->src[1]] != -1) {
diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h
index a614d291acb5..b7ff4b715f06 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.h
+++ b/ggml/src/ggml-openvino/ggml-decoder.h
@@ -10,9 +10,11 @@
#include