Commit e0b9fd7d7 for llama.cpp
commit e0b9fd7d7601258a5aa4fc1784f242d6a43f6a6f
Author: Xuejun Zhai <xuejun.zhai@intel.com>
Date: Fri Nov 27 10:26:55 2026 +0800
ggml-openvino: CI op-test fixes and NPU improvements (#33088)
* ggml-openvino: KV-only prefill on the static path, with one decode step for the outputs
On the static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC=1) the prefill model of a graph with
KV-shared attention layers is compiled with only the cache writes as outputs. The new conversion pass
KeepCacheResults (openvino/pass/keep_cache_results.cpp, registered in pass_registry/common.cpp from
GraphTraits::kv_only_outputs) removes the other Results and the Parameters nothing reads any more, so OpenVINO
drops everything that only feeds the logits: for models whose tail layers read an earlier layer's KV (Gemma 3n/4
E-series) every KV-shared layer and the LM head. When the batch needs logits, the decode model is run once on the
output token: it rewrites that token's KV rows with the same values and runs the dropped layers against the
complete cache. The decoder keeps its full output list and only reports which outputs are caches; an imported
cached model takes the cache outputs as its output names.
It is on by default and applies only where it pays off and is valid: graphs with KV-shared attention, at most one
output token per batch, and no HFA prefill or decode KV windows. GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off; the
earlier name GGML_OPENVINO_NPU_KV_ONLY_PREFILL is still accepted.
Gemma 4 E2B Q4_0 on NPU (KV_SLICE=0, NPU_TURBO=YES): llama-bench pp512 1320-1375 -> 2349-2454 t/s,
pp2048 1146-1202 -> 2268-2513 t/s; E4B pp512 587 -> 773, pp2048 591 -> 847 t/s. llama-server, E2B, 3016-token
prompt, prefill chunk 512, context checkpoints off: 1097-1108 -> 2136-2448 t/s. Greedy outputs match the full
prefill on 3 of 4 needle prompts; the fourth differs by one near-tie token that also flips between baseline runs.
* ggml-openvino: NPU host gather for large embedding tables
GGML_OPENVINO_NPU_HOST_GATHER=1 gathers the rows of large host-resident embedding tables (at least
64 MiB, raw GGUF data, ids from a graph input) on the host. The static graph gets the rows through a
ggml_host_rows_<node> input instead of an OpenVINO Gather over the table. With NPUW function calls the
table becomes a function input, and gathering from an input that large costs about as much as
streaming the whole table every call: 21.6 ms of the ~62 ms Gemma 4 E2B decode step, against 0.45 ms
for the same partition with the table baked in. A table used only for such lookups (the Gemma 3n/4
per-layer embedding table) is no longer converted, requantized or bound to the NPU.
Gemma 4 on NPU (NPU_TURBO=YES, KV_SLICE=0, 868-token prompt), together with KV-only prefill: E2B decode
65.3 -> 40.3 ms/token, prefill 925 -> 392 ms, system commit 8.5 -> 4.4 GB, load 109 -> 61 s; E4B decode
150 -> 72 ms/token, prefill 1931 -> 1022 ms, commit 14.6 -> 9.1 GB. Greedy outputs match the default on
3 of 4 needle prompts; the fourth differs by one near-tie token that also flips between baseline runs.
* ggml-openvino: NPU host gather and KV-only prefill with the weightless blob cache
Make the two NPU options work with GGML_OPENVINO_NPU_WEIGHTLESS_BANK / SELF_CONTAINED_MMAP:
- host gather also accepts tables in OpenVINO buffers when a raw-weight cache mode keeps (or, with
SELF_CONTAINED_MMAP, wraps) the raw GGUF bytes there;
- a warm import binds only the decoder inputs present in the compiled blob, since KV-only prefill
(out_ids) and host gather (token ids) can leave inputs unused, as HFA prefill already did;
- a weights file that cannot be written (e.g. a full disk) no longer fails the graph: the pair is
compiled and run without being cached.
Gemma 4 on NPU (NPU_TURBO=YES, KV_SLICE=0, 868-token prompt), weightless cache + MMAP warm start with
host gather and KV-only prefill: E2B load 1.8 s, system commit 2.5 GB, prefill 385-414 ms, decode
39.5-41 ms/token, cache 1.5 GB; E4B load 3.3-3.6 s, commit 4.7-4.8 GB, prefill ~1.0 s, decode 68.5-69.8
ms/token, cache 3.3 GB. Greedy outputs are byte-identical to the default path on export and import.
* ggml-openvino: let GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT apply to Q4_K/Q5_K tables when set
Q4_K and Q5_K token_embd tables default to the channel-wise int8 of ggml_openvino_get_requant_type() on NPU and
ignored GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT. They now follow it when it is set explicitly; the Q6_K behaviour and
all defaults are unchanged. Gemma 4 E2B ties a Q4_K table to the output layer: int8 stores it in 384 MiB,
q4_0_128 in 198 MiB (llama-server working set -0.18 GB; accuracy not yet measured).
* ggml-openvino: export prefill model of every KV window for weightless bank cache
With a weightless-bank model cache and sliced (non head-major) KV, round the static prefill attention size up to the decode KV window, so prefill sizes are the window sizes (1024/2048/4096/8192). The export run (SELF_CONTAINED_MMAP=0) then builds the prefill model of every window at startup, so an import-only run (SELF_CONTAINED_MMAP=1) has a pair for any prompt length.
* ggml-openvino: integer KV_SLICE, KV-only with decode windows, gemma-4 pruned masks
- GGML_OPENVINO_KV_SLICE takes 0, 1 or a multiple of 256 as the base of the
attended KV windows; decode windows (BLOB_PREBUILD) use the same base.
- KV-only prefill works together with decode KV windows: the output step runs
the decode model of the window the next decode step uses.
- gemma-4 prune_shared (upstream #32342) adds host-filled out_mask/out_mask_swa
and inp_prune_ids/inp_prune_keep inputs. The pruned masks are not graph
inputs: their rows are gathered in the OV model from the (sliced, padded)
input masks with inp_prune_ids. The KV-only output step ignores
inp_prune_keep, and HFA prefill is not used for the pruned masks.
* ggml-openvino: keep the compiled model alive while reading its inputs (-Wdangling-reference)
* ggml-openvino: make the NPU weightless-bank cache automatic with the model cache dir
Remove GGML_OPENVINO_SELF_CONTAINED_BLOB, GGML_OPENVINO_NPU_WEIGHTLESS_BANK and
GGML_OPENVINO_NPU_SHARED_BANK. On NPU, setting GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR
alone now selects the weightless-bank cache layout.
Why
---
The self-contained (SC) mode embedded the full weights into every exported blob
and kept separate ggml-sc-prefill / ggml-sc-decode NPUW banks. Compared to the
weightless bank (WB) it:
- wrote the weights once per blob (prefill, decode and every KV window), so the
cache was several times larger;
- disabled the decode KV windows (decode_bucket returned 0), so decode always
ran at the full context;
- needed an in-process keep-alive workaround;
- was much slower and heavier to import. Earlier phi-4-mini data: SC import
38 s / 8.8 GB InUse / 636 prefill t/s vs WB 3.7 s / 3.3 GB / 1245 t/s.
WB was strictly better, so it becomes the only NPU cache layout and the
three opt-in switches are dropped.
New behaviour
-------------
- If the directory holds valid blobs, manifests and the shared weights file
for the prefill/decode pair, they are imported directly
("model cache HIT (weightless bank)").
- Otherwise the models are compiled and exported as weightless blobs plus one
<weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair and
KV window, and a warning is logged ("no usable cached blob(s) in <dir> ...;
compiling and exporting ... as weightless-bank blobs"). The same warning is
logged for each decode KV window and each prefill KV window that has to be
compiled.
- NPU graphs without a KV cache no longer use the model cache and always
compile.
- GGML_OPENVINO_SELF_CONTAINED_MMAP is kept (GGUF mmap as weight buffer, lazy
large compute buffers). It now needs only NPU + cache dir, stays import-only
and its error messages name the cache directory.
- The fingerprint tag of weightless blobs is unchanged, so existing weightless
caches (exported with NPU_WEIGHTLESS_BANK=1) remain valid.
Code changes
------------
- ggml-openvino-extra.{h,cpp}: drop the SELF_CONTAINED_BLOB, NPU_WEIGHTLESS_BANK
and NPU_SHARED_BANK entries from the env table; replace
ggml_openvino_npu_raw_weight_cache_enabled() and
ggml_openvino_npu_weightless_bank_enabled() with
ggml_openvino_npu_weightless_cache_enabled() (NPU && cache dir set); drop the
SELF_CONTAINED_BLOB early return in ggml_openvino_npu_decode_bucket().
- ggml-openvino.cpp: raw weight upload, keeping the raw weights on Windows and
the self-contained mmap buffer now key off the new helper.
- ggml-decoder.cpp: the raw-cache checks, including is_host_gather_rows(), use
the new helper.
- utils.{h,cpp}: drop the embedded-weight (self-contained) blob path, the
in-process keep-alive and the shared-bank sc-prefill/sc-decode branch;
remove the self_contained field from static_build_args and
ov_compiled_graph. model_cache_dir is left empty for NPU graphs without a KV
cache; weightless_bank = NPU && cache dir set. Import with skipped weights
always uses ov::weights_path + enable_weightless; compile enables weightless
export whenever the weightless bank is in use.
- model-cache.h: comments updated for the single cache layout.
- Docs: OPENVINO.md and OpenVINO-ENV-VARS.md drop the removed variables and
describe the automatic weightless bank.
Port notes
----------
Cherry-picked from d97d7fb52 (refact-cache-v0) onto xuejun/gemma4-e2b-v1.
Conflicts in ggml-openvino-extra.cpp, utils.h and utils.cpp were resolved by
keeping this branch's newer features and only removing SC/WB/SHARED:
- GGML_OPENVINO_KV_ONLY_PREFILL and GGML_OPENVINO_NPU_HOST_GATHER (env entries
and helpers) are kept;
- ggml_openvino_npu_decode_bucket() keeps this branch's
"BLOB_PREBUILD ? ggml_openvino_kv_slice_base() : 0";
- ov_compiled_graph keeps prefill_fp / decode_fp;
- a leftover ggml_openvino_npu_raw_weight_cache_enabled() call in
ggml-decoder.cpp (from a branch-only commit) was switched to the new helper.
Verification
------------
phi-4-mini Q4_0 llama-server on NPU (c=8192, chunk 1024, KV_SLICE=1,
BLOB_PREBUILD=1, LAZY_HOST_THRESHOLD_MB=128, no bank env var set):
- cold export: weightless bank selected automatically, 8 blobs (prefill +
decode for KV windows 1024/2048/4096/8192, 3.6-10.8 MB each) + one
2125 MB weights.bin; load 67.3 s, prefill 1119 t/s, decode 22.09 t/s;
- 3 imports with SELF_CONTAINED_MMAP=1, all blobs cache HIT, no recompile:
avg of 3 imports baseline(lazy128) this commit delta
LoadMs 3822 3686 -3.6%
InUseDeltaMB 3398 3470 +2.1%
Prefill t/s 1260 1253 -0.6%
Decode t/s 22.45 22.67 +1.0%
compare_baseline.ps1 -Variant lazy128: within tolerance.
- llama-simple smoke test on NPU passes.
* ggml-openvino: remove GGML_OPENVINO_NPU_PARALLEL_COMPILE
Drop the opt-in switch that compiled the NPU prefill and decode models
concurrently. Prefill and decode are now always compiled one after the
other, which was already the default behaviour.
Why
---
- It was off by default and not used by any preset, launch config or
bench script.
- It only applied when the weightless bank was off. Since the weightless
bank is now automatic whenever GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR is
set on NPU, it could only take effect for uncached runs.
- Compiling both models at the same time raises the host memory peak
during load, which works against the memory-reduction work on NPU.
- It added a second, rarely tested code path around build_static_model().
Code changes
------------
- ggml-openvino-extra.{h,cpp}: remove the GGML_OPENVINO_NPU_PARALLEL_COMPILE
env table entry and ggml_openvino_npu_parallel_compile_enabled().
- utils.cpp: remove the parallel_compile flag and the std::async branch in
the static (NPU) compile path; keep the sequential prefill -> decode
compile, including the no-KV-cache and shared decode_source cases,
unchanged. Update the comments that mentioned parallel compilation and
drop the now unused <future> include.
- dev_doc/OpenVINO-ENV-VARS.md: remove the variable from the table.
A leftover GGML_OPENVINO_NPU_PARALLEL_COMPILE in the environment is now
reported as an unknown variable and ignored.
Verification
------------
- llama-server and llama-simple build with GGML_OPENVINO (MSVC Release).
- llama-simple granite-4.0-1b Q4_0 on NPU decodes 20 tokens correctly.
* ggml-openvino: apply clang-format
* docs : add a gemma-4 E2B NPU example with the model cache
* docs : update docs
* ggml-openvino: remove dead code and simplify env handling
* ggml-openvino: add GGML_OPENVINO_DEBUG_DYNAMIC_DIMS
* ggml-openvino: one compiled-model cache per static (NPU) graph
Replace the static-path cache bookkeeping with a single cache per cgraph
entry. The key is the cgraph; the value is a map of compiled models, one
per static variant (prefill/decode, KV window, SWA window, output length),
each holding its own infer request.
Why
---
The static (NPU) path kept compiled models in several places that had to
be kept in sync:
- a prefill/decode "compiled pair" in ov_compiled_graph shared across
backends through compiled_cache->graphs;
- per-KV-window decode and prefill models plus their requests and I/O name
caches in ov_runtime_context;
- a process-wide table of imported blobs (g_imported_blobs /
import_cached_blob / ov_clear_imported_blobs).
Export, import, KV-window switching and fallback each walked a different
subset of these, which made the logic hard to follow and to change.
New structure
-------------
- utils.h:
- ov_static_variant_key {prefill, attention_size, attention_size_swa,
output_len}, ordered and comparable.
- ov_static_variant {compiled model, lazily created infer request,
input/output names}.
- decoder_runtime_ctx owns std::map<key, variant> variants plus the
per-graph state shared by all variants (kv_only_prefill,
decode_unfold, cache_base_extra, prefill/decode prepared flags and the
weights path/bank/layout).
- ov_compiled_graph is reduced to the fields used by the dynamic path;
the prefill request/name caches are removed from ov_runtime_context.
- utils.cpp (static path):
- Small helpers before ov_graph_compute_static: variant key list,
fingerprint, weights selection, blob usability check, decoder build,
compile config, conversion, weights layout and
static_load_variants().
- static_load_variants() imports every usable blob and compiles the rest
in one place. The first prefill and decode models are still converted
before any compile (Bonsai-8B ordering). Each model logs
"<prefill|decode> model of KV window N imported/compiled in X ms".
- ov_graph_compute_static() now: looks up the entry, resets it when the
graph cannot be reused, picks the needed prefill key and the decode
key, loads what is missing, then takes the request from the variant
(created on first use). The KV-only output step and KV growth use the
same variant map; the separate decode-window request switching is gone.
- Removed g_imported_blobs, import_cached_blob() and
ov_clear_imported_blobs().
- ggml-openvino.cpp: drop the ov_clear_imported_blobs() call in backend
free.
- model-cache.cpp is unchanged.
Cache behaviour (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR set on NPU)
-------------------------------------------------------------------
- GGML_OPENVINO_SELF_CONTAINED_MMAP=0: models with a usable blob are
imported, all missing ones (every prefill/decode KV window) are compiled
and exported as weightless-bank blobs plus the shared weights file.
- GGML_OPENVINO_SELF_CONTAINED_MMAP=1: every model is imported from the
cache. A missing blob now fails immediately with
"GGML_OPENVINO_SELF_CONTAINED_MMAP: no usable cached <prefill|decode>
model of KV window N in <dir>; run once with
GGML_OPENVINO_SELF_CONTAINED_MMAP=0 to build the cache".
- Compiling after the host weights were released still fails fast.
- The fingerprint formula (cache_base_extra and per-variant salt) is
unchanged, so existing caches stay valid: a fresh phi-4-mini export
produces the same 8 blob names as a cache from the previous commit.
Behaviour changes
-----------------
- Compiled models belong to their backend entry and are no longer shared
across backends through compiled_cache->graphs.
- Without head-major KV, an export compiles all prefill KV windows but
keeps only the needed one resident; the others are imported from the
cache on first use. With SELF_CONTAINED_MMAP=1 or head-major KV all
variants are kept.
Verification
------------
- llama-server and llama-simple build with GGML_OPENVINO (MSVC Release);
llama-simple granite-4.0-1b Q4_0 on NPU decodes 20 tokens correctly.
- phi-4-mini Q4_0 llama-server on NPU (c=8192, chunk 1024, KV_SLICE=1,
BLOB_PREBUILD=1, KV_ON_DEMAND=1, HFA_PREFILL=1, DECODE_UNFOLD=1,
LAZY_HOST_THRESHOLD_MB=128):
- export: 8 models compiled and exported (blob names identical to the
previous cache), load 64.7 s, prefill 1152 t/s, decode 21.8 t/s;
- 3 imports with SELF_CONTAINED_MMAP=1, no recompile:
avg of 3 imports baseline(lazy128) this commit delta
LoadMs 3822 3725 -2.5%
InUseDeltaMB 3398 3386 -0.4%
Prefill t/s 1260 1266 +0.4%
Decode t/s 22.45 22.48 +0.1%
compare_baseline.ps1 -Variant lazy128: within tolerance.
- gemma-4-E2B Q4_0 llama-server on NPU (c=8192, ub 1024, chunk 512,
KV-only prefill path): export compiles 8 models (load 404 s); 2 imports
with SELF_CONTAINED_MMAP=1, no recompile, no errors: avg load 4452 ms,
InUse 2534 MB, prefill 2315 t/s, decode 21.55 t/s.
- SELF_CONTAINED_MMAP=1 with an empty cache dir (granite llama-simple)
exits with the error message above.
* docs : update docs
* ggml-openvino: check the conv state cache feature size in CPY
* ggml-openvino: apply clang-format
* ggml-openvino: fix SSM_CONV_CONCAT_FUSION test on GPU
- ssm_conv: use a 2D GroupConvolution (unit H dim) instead of 1D. The OV 2026.4 GPU plugin fails to compile the 1D form in ACCURACY mode (Weights/ifm mismatch) when the input comes from RMSNorm -> Transpose -> Concat.
- cpy: handle CPY into a contiguous view of a plain (non-KV, non-recurrent) tensor at a static offset via op_case 4, and splice on the flattened base so offsets spanning rows are written correctly.
* ggml-openvino: fix GATED_DELTA_NET_CACHE_FUSION test
* ggml-openvino: fix SHORT_CONV test
---------
Co-authored-by: Anisha Kulkarni <anisha.dattatraya.kulkarni@intel.com>
Co-authored-by: ravi9 <ravi.panchumarthy@intel.com>
diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md
index 27c17c3ef..f645f25d3 100644
--- a/docs/backend/OPENVINO.md
+++ b/docs/backend/OPENVINO.md
@@ -110,7 +110,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin
**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.
+- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding.
- The validated models use `Q4_K_M` files.
**Layout names:**
@@ -882,7 +882,9 @@ The defaults fit most models. The variables below trade one property for another
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_PREFILL_CHUNK_SIZE` | NPU | Integer | `256` | Number of tokens that the NPU processes in one prefill step. A larger value can make long prompts faster, and makes the first load longer. Zero or a negative value means the default. Example: `GGML_OPENVINO_PREFILL_CHUNK_SIZE=512`. |
-| `GGML_OPENVINO_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_KV_ONLY_PREFILL` | NPU | Boolean | `1` | For models whose last layers reuse the KV cache of an earlier layer (Gemma 3n and Gemma 4 E2B/E4B): compile the prefill with only the KV-cache writes as outputs, which drops those layers and the output layer from it, and compute the output token of a batch with one decode step. Takes effect only without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state; with decode KV windows (`GGML_OPENVINO_NPU_BLOB_PREBUILD=1`) the output step runs the decode graph of the window that covers the output token. A batch that needs more than one output token switches to the full prefill. `0` turns it off. |
+| `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` | NPU | String | `q8_0_c` | How a `Q6_K` `token_embd.weight` is stored for the NPU: `q8_0_c` (8-bit, one scale per row), `f16`, `q4_0_128` (4-bit, one scale per 128 weights) or `q4_0_c` (4-bit, one scale per row). The 4-bit layouts use less memory at some cost in accuracy; `f16` uses more memory. Keep the default unless memory is tight. When set, it also applies to a `Q4_K` or `Q5_K` `token_embd.weight`, which otherwise keeps the 8-bit layout of the other weights; with a tied output layer (Gemma 4 E2B) `q4_0_128` stores it in about half the memory. |
+| `GGML_OPENVINO_NPU_HOST_GATHER` | NPU | Boolean | `0` | Look up the rows of large embedding tables (64 MiB or more) on the host, from the GGUF data, and pass them to the NPU graph as an input, instead of binding the whole table to the NPU. A table used only for such lookups, such as the per-layer embedding table of Gemma 3n and Gemma 4 E2B/E4B, is then not converted for the NPU at all. Lowers memory and decode time for such models. |
| `GGML_OPENVINO_GDN_DECOMPOSE` | all | Boolean | auto | Translate `GATED_DELTA_NET` (Qwen3.5) into MatMul operations instead of the OpenVINO `GatedDeltaNet` op. Unset: on for the Lunar Lake NPU, off elsewhere. `0` turns it off, `1` turns it on for any device. Try `1` for Qwen3.5 on the Panther Lake NPU. |
| `GGML_OPENVINO_MANUAL_GQA_ATTN` | CPU, GPU | Boolean | on for GPU | Build grouped-query attention from separate MatMul operations. Unset: on for GPU, off for CPU and NPU. `1` turns it on, `0` turns it off. Try `1` on the CPU for faster decode. |
| `GGML_OPENVINO_REQUANT_KQUANT` | CPU, GPU | String | `not set` | Requantize `Q6_K` and `Q5_K` weights to a 4-bit layout instead of `Q8_0_C`: faster decode for lower accuracy. One of `q4_asym64`, `q4_asym64_all` (also `Q4_K`), `q4_sym128`, `q4_sym128_all` (also `Q4_K`) or `native` (no requantization). On GPU with `Q4_K_M` files use `q4_asym64_all`, because `q4_asym64` does not compile there. |
@@ -903,10 +905,10 @@ export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
# 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.
+# NPU: valid cached models are imported. Otherwise the run compiles them, writes them without weights plus one
+# shared weights file, and logs a warning.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-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.
@@ -919,12 +921,11 @@ export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
| `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY` | CPU, GPU | Boolean | `0` | Require an existing cached model and skip the weight upload and the compilation. Needs mmap model loading (the default on Linux and Windows) and a model that runs fully on OpenVINO. |
-| `GGML_OPENVINO_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_SELF_CONTAINED_MMAP` | NPU | Boolean | `0` | Later runs only. Requires `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` with an existing cache. Use the memory-mapped GGUF file as the model buffer, which lowers the host memory peak. Fails if a cached model is missing, for example after a change of the model, `-c` or another setting; run once without it to build the cache. |
| `GGML_OPENVINO_CACHE_DIR` | all | String | `not set` | Directory for the cache of the OpenVINO plugin itself. `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` is the recommended cache. |
- One directory can hold the cached models of different models and settings.
-- NPU: each prefill length enters the cache in a run without `GGML_OPENVINO_SELF_CONTAINED_MMAP`.
+- NPU, with the default settings: the first prompt writes the prefill model of every KV window up to `-c`, so later runs with the same `-c` find a cached model for any prompt length.
- See [Compiled model cache](../../ggml/src/ggml-openvino/README.md#compiled-model-cache) for the workflow and the restrictions.
</details>
diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt
index 3ed43b9fa..250593a38 100644
--- a/ggml/src/ggml-openvino/CMakeLists.txt
+++ b/ggml/src/ggml-openvino/CMakeLists.txt
@@ -1,3 +1,7 @@
+if (NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|amd64|AMD64|aarch64)$")
+ message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}")
+endif()
+
find_package(OpenVINO REQUIRED COMPONENTS Runtime Threading)
find_package(OpenCL REQUIRED)
@@ -24,17 +28,11 @@ if (WIN32)
target_link_libraries(ggml-openvino PRIVATE psapi)
endif()
-if (GGML_OPENVINO)
- if (CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
- elseif (CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64" OR CMAKE_SYSTEM_PROCESSOR STREQUAL "AMD64")
- else()
- 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)
+include(CMakePushCheckState)
unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE)
+cmake_push_check_state(RESET)
set(CMAKE_REQUIRED_LIBRARIES openvino::runtime)
set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op")
check_cxx_source_compiles("#include <recurrent_cache_update.hpp>
@@ -43,8 +41,7 @@ int main() {
auto gdn = std::make_shared<ov::op::internal::RecurrentGatedDeltaNetUpdate>(ov::OutputVector{});
}"
GGML_OPENVINO_HAS_CACHE_UPDATE)
-unset(CMAKE_REQUIRED_LIBRARIES)
-unset(CMAKE_REQUIRED_INCLUDES)
+cmake_pop_check_state()
if(GGML_OPENVINO_HAS_CACHE_UPDATE)
target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1)
endif()
diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md
index 0b4f31291..497cf46df 100644
--- a/ggml/src/ggml-openvino/README.md
+++ b/ggml/src/ggml-openvino/README.md
@@ -87,3 +87,11 @@ The generic recurrent-cache translation invalidates blobs made with the former s
- File identity, size, modification/change timestamps, tensor offsets, graph structure, settings, and OpenVINO version identify cache entries. Linux uses device/inode and Windows uses volume serial/file index. Replacing, copying, or modifying a GGUF invalidates its entries. This avoids reading weight bytes and ties the cache to the local source files. Keep those files unchanged throughout loading and inference.
- Use the same target device and compatible OpenVINO/plugin installation. Import support depends on the plugin; the tested CPU plugin cannot import MoE graphs containing `GatherMatmulCompressed`. GPU MoE and CPU dense graph imports were tested.
- Blobs contain weights and can approach model size for each compiled graph. Import still reads those blobs and initializes the device.
+
+# KV-only prefill
+
+On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), models whose tail layers read an earlier layer's KV get a KV-only prefill by default; `GGML_OPENVINO_KV_ONLY_PREFILL=0` turns it off. It compiles the static prefill graph with only the KV-cache writes as outputs (`openvino/pass/keep_cache_results.cpp`). Everything that only feeds the logits is dropped from it: for models whose tail layers read an earlier layer's KV (Gemma 3n/4 E-series) that is every KV-shared layer, plus the LM head. When the batch needs logits, the decode graph is then run once on the output token; it rewrites that token's KV rows and computes the dropped layers against the complete cache. It is used only when attention ops of the graph share a KV cache tensor and the graph has no recurrent state. If a batch needs more than one output token, or the output step fails, the backend logs a warning and uses the full prefill from then on.
+
+# NPU host gather
+
+`GGML_OPENVINO_NPU_HOST_GATHER=1` (NPU, opt-in) gathers the rows of large host-resident embedding tables (at least 64 MiB, raw GGUF data) on the host. The static graph gets the gathered rows through an `ggml_host_rows_<node>` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all.
diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
index 9d72ceacb..57deb264e 100644
--- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
+++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
@@ -11,6 +11,7 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
| `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_DEBUG_DYNAMIC_DIMS` | all | Boolean | `0` | Print each graph node and its sources with their shapes when a graph is decoded. `*` marks the dynamic (token) dimension. |
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
@@ -28,6 +29,9 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+# Shapes of each graph node, with * at the dynamic (token) dimension. Printed to stdout.
+GGML_OPENVINO_DEBUG_DYNAMIC_DIMS=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 4 -no-cnv -p "Hello" > dims.txt
+
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
@@ -50,8 +54,8 @@ Each variable turns off an optimization that is on by default, or sets its stren
| Variable | Device | Type | Default | Description |
|---|---|---|---|---|
-| `GGML_OPENVINO_KV_SLICE` | all | 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_KV_SLICE` | all | Integer | `1` | Bind the KV cache, and size the KQ masks, at the attended length instead of the full context. `0`: off. `1`: on, KV window base 1024. `N` (a multiple of 256): on, KV window base `N`. CPU and GPU: a view over the cache (any non-zero value just turns it on). Static path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); the decode KV windows of `GGML_OPENVINO_NPU_BLOB_PREBUILD` use the same base. With `0`, `llama-bench -d` fails on the NPU. Use the same value in the run that writes the cache and in the runs that read it. |
+| `GGML_OPENVINO_NPU_BLOB_PREBUILD` | NPU | Boolean | `1` | With `GGML_OPENVINO_KV_SLICE` on, decode attends the smallest `N * 2^k` rows (`N` from `GGML_OPENVINO_KV_SLICE`) that cover the next position, with one decode graph for each window, and the prefill windows are aligned to them. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `0`, or `GGML_OPENVINO_KV_SLICE=0`: one decode graph attends the whole context, and prefill graphs are built on first use. Use the same value in the run that writes the cache and in the runs that read it. |
| `GGML_OPENVINO_NPU_FAST_MASK` | NPU | Boolean | `1` | Write the prefill attention mask directly into the input tensor, without an intermediate copy. The result is identical. |
| `GGML_OPENVINO_NPU_L0_HOST_TENSORS` | NPU | Boolean | `1` | Keep the KV cache and the compute buffers in Level Zero host memory, so the plugin reads them without an extra copy. Falls back to plain host memory if the allocation is not available. |
| `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`. |
@@ -75,7 +79,6 @@ These options are off by default. They are not validated for general use: some h
| 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`. |
@@ -90,16 +93,13 @@ These options are off by default. They are not validated for general use: some h
| `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.
+# NPU cache: weightless blobs plus one shared weights file. Keep all other NPU settings the same in both runs.
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=/tmp/ov_cache
-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"
+./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # first run: warns "no usable cached blobs", exports
export GGML_OPENVINO_SELF_CONTAINED_MMAP=1
./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512 -lv 4 # later runs: log shows "model cache HIT"
@@ -141,7 +141,6 @@ export GGML_OPENVINO_REDUCE_COMPILE_MEM=1
# 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
@@ -182,11 +181,15 @@ Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend do
| `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`. |
+Set properties with `GGML_OPENVINO_NPU_CONFIG`:
+
```bash
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_NPU_CONFIG="NPU_COMPILER_TYPE=PLUGIN,COMPILATION_NUM_THREADS=1,LOG_LEVEL=LOG_INFO"
```
+List the properties of the installed NPU plugin:
+
```cpp
// List the properties of the installed NPU plugin with their current values
ov::Core core;
@@ -199,6 +202,35 @@ for (const auto & name : core.get_property("NPU", ov::supported_properties)) {
- `NPUW_*` options, with type and default: `src/plugins/intel_npu/src/al/include/intel_npu/config/npuw_option_defs.inc` in the OpenVINO source.
- Graphs without a KV cache compile without NPUW: the backend removes `NPU_USE_NPUW` and the `NPUW_*` keys for them.
+### Example: gemma-4 E2B with the model cache
+
+`GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR` saves the model compiled for the NPU, so only the first start compiles it. Run step 1 once, then start the model as in step 2 every later time.
+
+#### Step 1: first run, compile and save the model
+
+```bash
+# This start takes longer: the backend compiles the model for the NPU and saves it in the cache directory
+# (with -lv 4 the log shows "no usable cached blobs ... compiling and exporting").
+# Use the model as usual, then exit with /exit.
+export GGML_OPENVINO_DEVICE=NPU
+export GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR=$HOME/ov_cache
+export GGML_OPENVINO_NPU_HOST_GATHER=1 # optional: faster generation, less memory and disk; the output can differ slightly
+export GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT=q4_0_128 # optional: slightly less memory; may lower accuracy
+export GGML_OPENVINO_PREFILL_CHUNK_SIZE=512 # optional: can make long prompts faster; makes the first run longer
+./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
+```
+
+#### Step 2: later runs, load the model from the cache
+
+```bash
+# Use the same exports as in step 1 (repeat them in a new shell) and the same command.
+# The backend loads the compiled model instead of compiling it, so the model starts much faster
+# (with -lv 4 the log shows "model cache HIT"). A changed setting or -c value compiles and saves again,
+# or stops with an error when GGML_OPENVINO_SELF_CONTAINED_MMAP=1 is set.
+export GGML_OPENVINO_SELF_CONTAINED_MMAP=1 # optional, later runs only: slightly shorter start; fails without the cache of step 1
+./build/ReleaseOV/bin/llama-cli -m google_gemma-4-E2B-it-Q4_K_M.gguf -c 4096
+```
+
## 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.
diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
index d29175ab0..d3dd8942e 100644
--- a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
+++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
@@ -20,8 +20,12 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() {
std::optional<ExtraQuantType> 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) {
+ // before dequantizing them (see gather_compressed_rows). Other K-quant tables default to the channel-wise
+ // int8 of ggml_openvino_get_requant_type() and follow this setting only when it is set explicitly
+ // (Gemma 4 E2B: a tied Q4_K table is 384 MiB as int8, 198 MiB as q4_0_128).
+ if (tensor->type != GGML_TYPE_Q6_K &&
+ !((tensor->type == GGML_TYPE_Q4_K || tensor->type == GGML_TYPE_Q5_K) &&
+ ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT") != nullptr)) {
return std::nullopt;
}
const std::string quant = ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT", "q8_0_c");
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index 13272f298..1eb7ae9fc 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -12,7 +12,6 @@
#include <cctype>
#include <cstddef>
#include <cstdint>
-#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
@@ -313,6 +312,17 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
return "embd";
}
+ const auto & model_params = decoder->get_model_params();
+ if (tensor == model_params.prune_ids) {
+ return "inp_prune_ids";
+ }
+ if (tensor == model_params.prune_keep) {
+ return "inp_prune_keep";
+ }
+ if (auto it = model_params.pruned_masks.find(tensor); it != model_params.pruned_masks.end()) {
+ // not a graph input: get_kq_mask_input() gathers the rows from the input mask of this name
+ return get_tensor_graph_input_ov_name(decoder, cgraph, it->second, op) + "_pruned";
+ }
// 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)) {
@@ -796,8 +806,14 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
} else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
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) {
+ } else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW &&
+ node->src[1]->view_src == node->view_src &&
+ (is_conv_states_all_tensor(node->view_src) ||
+ (node->view_src->op == GGML_OP_NONE && ggml_is_contiguous(node->src[1]) &&
+ !is_recurrent_cache(node->view_src) &&
+ strncmp(node->view_src->name, "cache_", strlen("cache_")) != 0))) {
+ // View writeback into a contiguous block of a plain (non-KV, non-recurrent) tensor at
+ // a static offset, e.g. the mamba-style conv state copy into its cache row.
op_case = 4;
break;
} else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
@@ -1075,7 +1091,32 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
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);
+ const ggml_tensor * layer_input_mask = layer_mask[layer.value()];
+ if (layer_input_mask != mask && layer_input_mask->op == GGML_OP_NONE) {
+ // a second input mask on the cache of a layer: the mask rows of gemma-4's KV-shared layers
+ model_params.pruned_masks.emplace(mask, layer_input_mask);
+ } else {
+ model_params.kq_masks.insert(mask);
+ }
+ }
+ }
+
+ if (!model_params.pruned_masks.empty()) {
+ // The first output row index list gathers the rows of the KV-shared layers, a later one the output rows
+ // among them
+ for (int i = 0; i < cgraph->n_nodes; i++) {
+ const ggml_tensor * node = cgraph->nodes[i];
+ if (node->op != GGML_OP_GET_ROWS || !is_output_idx(node->src[1], node)) {
+ continue;
+ }
+ if (model_params.prune_ids == nullptr) {
+ model_params.prune_ids = node->src[1];
+ } else if (node->src[1] != model_params.prune_ids) {
+ model_params.prune_keep = node->src[1];
+ }
+ }
+ if (model_params.prune_ids == nullptr) {
+ throw std::runtime_error("OpenVINO: masks of KV-shared layers without their row index list");
}
}
@@ -1210,7 +1251,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
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() :
+ const std::string mask_name = mask->op != GGML_OP_NONE || model_params.pruned_masks.count(mask) ?
+ 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
@@ -1229,7 +1271,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
}
}
if (is_static) {
- const bool slice_prefill = ggml_openvino_kv_slice_enabled() && compute_params.input_len > 1;
+ 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;
}
@@ -1261,10 +1304,8 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
}
- // When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
- // mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
- // share a single precomputed rope_sin/rope_cos. Track divergence so the
- // translator falls back to per-op make_sin_cos in that case.
+ // Multiple ROPE ops can disagree on op_params (e.g. gemma4's mixed SWA/non-SWA layers with different
+ // n_dims or freq_base). Track divergence for the graph key and for decoder reuse.
static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
if (!rope_seen) {
memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
@@ -1402,13 +1443,13 @@ std::pair<ModelParams, ComputeParams> 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.
+ // A sliced static prefill attends base*2^k KV rows (base from GGML_OPENVINO_KV_SLICE): 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 window.
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);
+ compute_params.attention_size = ggml_openvino_static_kv_window(
+ compute_params.attention_size, model_params.ctx_per_seq, ggml_openvino_kv_slice_base());
}
// The GPU plugin keeps device memory for each KV length it sees, and llama.cpp grows the KV length in steps of
// 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step.
@@ -1478,8 +1519,8 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
// 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;
+ 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;
}
@@ -1613,8 +1654,44 @@ bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
return false;
}
+bool GgmlOvDecoder::is_host_gather_rows(const ggml_tensor * node) {
+ if (!ggml_openvino_npu_host_gather_enabled() || node == nullptr || node->op != GGML_OP_GET_ROWS) {
+ return false;
+ }
+ const ggml_tensor * table = node->src[0];
+ const ggml_tensor * ids = node->src[1];
+ // The table must hold raw ggml rows in host memory. OpenVINO buffers store weights in the extracted layout, except
+ // with the NPU weightless cache, where they keep (or, with SELF_CONTAINED_MMAP, wrap) the raw GGUF bytes.
+ constexpr size_t min_table_bytes = 64ull * 1024 * 1024;
+ if (table == nullptr || ids == nullptr || table->view_src != nullptr || table->buffer == nullptr) {
+ return false;
+ }
+ const bool raw_cache = ggml_openvino_npu_weightless_cache_enabled();
+ const bool raw_rows = ggml_backend_buffer_is_openvino(table->buffer) ? raw_cache :
+ ggml_backend_buffer_is_host(table->buffer);
+ return table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && raw_rows &&
+ ggml_get_type_traits(table->type)->to_float != nullptr &&
+ ggml_nbytes(table) >= min_table_bytes && ids->type == GGML_TYPE_I32 && ids->op == GGML_OP_NONE &&
+ ggml_nelements(ids) == ids->ne[0] && node->ne[1] == ids->ne[0];
+}
+
void GgmlOvDecoder::add_extra_inputs() {
m_model_extra_inputs.clear();
+ m_host_gather_rows.clear();
+ if (m_is_static) {
+ for (const auto & info : m_node_info_list) {
+ if (is_host_gather_rows(info.node)) {
+ const std::string name = std::string(host_rows_prefix) + info.node_name;
+ m_host_gather_rows[name] = info.node;
+ m_model_extra_inputs[name] = {ov::element::f32,
+ ov::Shape{1, 1, (size_t) get_static_n_tokens(), (size_t) info.node->ne[0]},
+ 0,
+ true,
+ {},
+ -1};
+ }
+ }
+ }
// Extra inputs:
// 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
@@ -1679,7 +1756,6 @@ void GgmlOvDecoder::add_extra_inputs() {
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);
// 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
@@ -1885,6 +1961,9 @@ void GgmlOvDecoder::compute_model_inputs() {
if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
continue;
}
+ if (is_pruned_mask(src)) {
+ continue;
+ }
m_inputs[src_name] = src;
@@ -2087,22 +2166,6 @@ bool GgmlOvDecoder::is_kvcache_token_rows(const ggml_tensor * cache) const {
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];
- for (int j = 0; j < GGML_MAX_SRC; j++) {
- const auto * src = node->src[j];
- if (src == nullptr) {
- break;
- }
- if (get_tensor_ov_name(m_cgraph, src) == name) {
- return src;
- }
- }
- }
- 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);
@@ -2143,6 +2206,10 @@ std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_no
continue;
}
+ // A table whose rows are gathered on the host needs no OV weight for that use.
+ if (i == 0 && is_host_gather_rows(node)) {
+ continue;
+ }
// A view over a weight is served by the base tensor's Constant.
ggml_tensor * base = src->view_src ? src->view_src : src;
std::string src_name = get_tensor_ov_name(cgraph, base);
@@ -2242,9 +2309,9 @@ std::shared_ptr<ov::Node> 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.
- // Self-contained decode-window models are built after the pair; reusing the node keeps e.g. the
+ // Cached 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 keep_for_windows = ggml_openvino_npu_weightless_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) {
@@ -2273,10 +2340,10 @@ std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor
if (ggml_is_quantized(tensor->type)) {
auto use_bias = naive;
if (is_ov_buffer) {
- const bool preserve_raw = ggml_openvino_npu_raw_weight_cache_enabled();
+ const bool preserve_raw = ggml_openvino_npu_weightless_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.
+ // cached 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
@@ -2689,7 +2756,10 @@ std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
// the written state block plus the full updated cache (see translate_cpy op_case 13)
return {m_node_info_list[node_idx].node_name, get_tensor_ov_name(m_cgraph, node->view_src)};
}
- if (node->op == GGML_OP_GATED_DELTA_NET && (!m_model_params.has_rs_rollback || node->op_params[0] > 1)) {
+ // Naive (op test) graphs have no runtime slot inputs for the native state writeback, so they keep the packed
+ // [attention | state] output, which the consumers slice through the generic view path.
+ if (!m_naive && 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++) {
@@ -2824,43 +2894,29 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
if (src == nullptr) {
continue;
}
- struct ggml_tensor * root_src = nullptr;
- // if (src->org_src) {
- // root_src = src->org_src;
- // }
- if (root_src) {
- 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;
- }
- 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_get_rows_input_idx(src, node)) {
- m_node_dynamic_dims[src] = 0;
- continue;
- }
- if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
- m_node_dynamic_dims[src] = 1;
- continue;
- }
- 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;
- }
- if (is_inp_embd_2d(src, node)) {
- m_node_dynamic_dims[src] = 1;
- continue;
- }
- self(self, src);
+ 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;
+ }
+ if (is_inp_scale_rows(src, node) || is_inp_embd_leaf(src, node)) {
+ m_node_dynamic_dims[src] = 1;
+ continue;
}
+ 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;
+ }
+ if (is_inp_embd_2d(src, node)) {
+ m_node_dynamic_dims[src] = 1;
+ continue;
+ }
+ self(self, src);
}
switch (node->op) {
case GGML_OP_NONE:
@@ -2885,9 +2941,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
}
}
}
- // OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
- // "Dynamic dim value mismatch for node: " + std::string(node->name) +
- // " and its src[1]: " + std::string(node->src[1]->name));
}
break;
case GGML_OP_MUL:
@@ -2904,7 +2957,6 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
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];
// 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];
@@ -3229,8 +3281,8 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
visit_node(visit_node, node);
}
- // print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
- if (0) {
+ // GGML_OPENVINO_DEBUG_DYNAMIC_DIMS: print each node and its sources with their shapes, '*' marking the dynamic dim
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_DYNAMIC_DIMS")) {
for (int i = 0; i < m_cgraph->n_nodes; i++) {
ggml_tensor * node = m_cgraph->nodes[i];
int dynamic_dim = m_node_dynamic_dims[node];
diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h
index 39b3496e5..4c2106df9 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.h
+++ b/ggml/src/ggml-openvino/ggml-decoder.h
@@ -47,6 +47,15 @@ struct ModelParams {
// The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through
// GET_ROWS, which must resolve to the same OV parameter as the attention ops
std::set<const ggml_tensor *> kq_masks;
+ // gemma-4's KV-shared layers attend for the output rows only (prune_shared in src/models/gemma4.cpp): llama.cpp
+ // copies their mask rows from the input masks on the host into separate inputs (out_mask, out_mask_swa), and
+ // gathers their activations, positions and per-layer embeddings with an index list (inp_prune_ids). The static
+ // models bind the input masks per prefill chunk, so these masks are not graph inputs: each maps to the input
+ // mask it copies, and the OV model gathers its rows from that mask with inp_prune_ids instead.
+ std::map<const ggml_tensor *, const ggml_tensor *> pruned_masks;
+ const ggml_tensor * prune_ids = nullptr;
+ // the output rows among the gathered rows (inp_prune_keep)
+ const ggml_tensor * prune_keep = nullptr;
std::vector<std::string> kv_names;
size_t kv_buffer_ctx_id = 0;
@@ -86,7 +95,6 @@ struct ComputeParams {
int swa_window = -1;
int input_len = -1;
int token_len_per_seq = -1;
- int past_kv_len = -1;
int output_len = 1;
int cache_rs_reset_idx = -1;
@@ -288,16 +296,38 @@ public:
virtual std::set<std::string> get_model_output_names() const override { return m_model_output_names; }
+ virtual std::set<std::string> get_cache_output_names() const override {
+ std::set<std::string> names;
+ for (const auto & name : m_model_output_names) {
+ const ggml_tensor * tensor = m_model_outputs.at(name);
+ if (is_kvcache(tensor, nullptr) || is_recurrent_cache(tensor)) {
+ names.insert(name);
+ }
+ }
+ return names;
+ }
+
+ virtual bool is_kv_only_outputs() const override { return m_kv_only_outputs; }
+
+ // Convert the model with only the cache writes as outputs (GGML_OPENVINO_KV_ONLY_PREFILL); the conversion pipeline
+ // then drops everything that only feeds the other outputs, see pass::KeepCacheResults.
+ void set_kv_only_outputs(bool kv_only) { m_kv_only_outputs = kv_only; }
+
+ // GET_ROWS of a large host-resident weight table by graph-input ids (GGML_OPENVINO_NPU_HOST_GATHER): its rows
+ // are gathered on the host and fed through the "ggml_host_rows_<node>" input instead of an OV Gather.
+ static bool is_host_gather_rows(const ggml_tensor * node);
+ static constexpr const char * host_rows_prefix = "ggml_host_rows_";
+ const ggml_tensor * get_host_gather_rows(const std::string & input_name) const {
+ auto it = m_host_gather_rows.find(input_name);
+ return it == m_host_gather_rows.end() ? nullptr : it->second;
+ }
+
const std::map<std::string, ggml_tensor *> & get_model_outputs() const { return m_model_outputs; }
virtual int get_ctx_size() const { return m_model_params.ctx; }
virtual int get_ctx_per_seq() const { return m_model_params.ctx_per_seq; }
- virtual int get_ctx_per_seq_swa() const { return m_model_params.ctx_per_seq_swa; }
-
- virtual int get_n_seq() const { return m_model_params.n_seq; }
-
virtual int is_swa_layer(int layer) const override {
return std::find(m_model_params.swa_layers.begin(), m_model_params.swa_layers.end(), layer) !=
m_model_params.swa_layers.end();
@@ -318,14 +348,10 @@ public:
return m_model_params.n_heads_kv;
}
- int get_past_kv_len() const { return m_compute_params.past_kv_len; }
-
int get_input_len() const { return m_compute_params.input_len; }
virtual int32_t * get_rope_params() const override { return const_cast<int32_t *>(m_model_params.rope_params); }
- virtual bool has_mixed_rope_params() const override { return m_model_params.mixed_rope_params; }
-
virtual int get_ssm_state_size() const override { return m_model_params.state_size; }
virtual std::map<std::string, std::string> get_kv_param_res_names() const override;
@@ -417,8 +443,6 @@ public:
return v;
}
- const ggml_tensor * get_tensor_from_name(const std::string & name) const;
-
std::string get_hfa_history_input_name() const;
void clear_model_weights() { m_model_weights.clear(); }
@@ -608,10 +632,6 @@ public:
bool is_direct_gdn_view(const ggml_tensor * node) const;
- static bool is_cache(const ggml_tensor * tensor, const ggml_tensor * op) {
- return is_recurrent_cache(tensor) || is_kvcache(tensor, op);
- }
-
static bool is_kvcache(const ggml_tensor * tensor, const ggml_tensor * op) {
if (tensor == nullptr || is_recurrent_cache(tensor)) {
return false;
@@ -697,6 +717,8 @@ public:
bool is_kq_mask(const ggml_tensor * tensor) const { return m_model_params.kq_masks.count(tensor) != 0; }
+ bool is_pruned_mask(const ggml_tensor * tensor) const { return m_model_params.pruned_masks.count(tensor) != 0; }
+
// A graph-input index list of GET_ROWS: out_ids, or the inp->s_copy leaf when build_rs gathers
// every recurrent state at once.
static bool is_get_rows_input_idx(const ggml_tensor * tensor, const ggml_tensor * op) {
@@ -722,33 +744,6 @@ public:
op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY;
}
- std::string get_graph_input_ov_name(const ggml_tensor * tensor, const ggml_tensor * op) const {
- if (is_inp_pos(tensor, op)) {
- return "inp_pos";
- }
- if (is_inp_emb(tensor, op)) {
- return "embd";
- }
- if (is_inp_mask(tensor, op)) {
- // Give the two attention masks distinct OV parameter names.
- //
- // An interleaved-SWA model builds one full-attention mask and one sliding-window mask,
- // but build_attn_inp_kq_mask() names them identically, so keying a parameter off
- // tensor->name alone makes the second mask OVERWRITE the first in m_model_inputs: both
- // attention types then read a single parameter, and the windowed layers silently run
- // against an unbanded mask. Disambiguate using the SWA layer set computed in
- // compute_llm_params(), which classifies by mask tensor identity rather than by name.
- //
- // When no SWA layer was found there is only one mask in play, so the plain name is
- // correct and no _swa parameter is created.
- if (m_model_params.swa_layers.empty()) {
- return "self_kq_mask";
- }
- return is_swa_mask(tensor) ? "self_kq_mask_swa" : "self_kq_mask";
- }
- return tensor->name;
- }
-
private:
void set_input_output();
int compute_op_case(const ggml_tensor * node) const;
@@ -776,6 +771,8 @@ private:
std::set<std::string> m_model_output_names;
// The output set the compiled model was built from, for has_same_graph_io().
std::set<std::string> m_built_output_names;
+ bool m_kv_only_outputs = false;
+ std::map<std::string, const ggml_tensor *> m_host_gather_rows;
std::vector<NodeInfo> m_node_info_list;
std::map<ggml_tensor *, int> m_node_dynamic_dims;
std::set<const ggml_tensor *> m_kvcache_4d;
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
index 0e99ff194..054d78c31 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
@@ -162,6 +162,7 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_DUMP_IR", env_type::BOOL},
{"GGML_OPENVINO_DEBUG_INPUT", env_type::BOOL},
{"GGML_OPENVINO_DEBUG_OUTPUT", env_type::BOOL},
+ {"GGML_OPENVINO_DEBUG_DYNAMIC_DIMS", env_type::BOOL},
// Force the static (NPU-shape) compute path on any device, e.g. GGML_OPENVINO_DEVICE=CPU,
// to test the static-shape translation without NPUW/real NPU hardware in the loop.
{"GGML_OPENVINO_FORCE_STATIC", env_type::BOOL},
@@ -191,14 +192,12 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_GDN_NATIVE_STATE", env_type::BOOL},
{"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL},
{"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL},
- {"GGML_OPENVINO_KV_SLICE", env_type::BOOL},
+ {"GGML_OPENVINO_KV_SLICE", env_type::INT},
{"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL},
{"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL},
- {"GGML_OPENVINO_NPU_PARALLEL_COMPILE", env_type::BOOL},
- {"GGML_OPENVINO_SELF_CONTAINED_BLOB", env_type::BOOL},
{"GGML_OPENVINO_SELF_CONTAINED_MMAP", env_type::BOOL},
- {"GGML_OPENVINO_NPU_SHARED_BANK", env_type::BOOL},
- {"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", env_type::BOOL},
+ {"GGML_OPENVINO_KV_ONLY_PREFILL", env_type::BOOL},
+ {"GGML_OPENVINO_NPU_HOST_GATHER", env_type::BOOL},
// Build the precise (but O(n_nodes)) graph cache key. Needed by op tests.
{"GGML_OPENVINO_FULL_GRAPH_KEY", env_type::BOOL},
};
@@ -260,6 +259,12 @@ std::string checked_env_value(const env_var & var, const char * value) {
if (!parse_env_int(value, number)) {
GGML_ABORT("ggml-openvino: %s=%s is not valid, use a whole number", var.name, value);
}
+ if (std::strcmp(var.name, "GGML_OPENVINO_KV_SLICE") == 0 && number != 0 && number != 1 &&
+ (number < 0 || number % 256 != 0)) {
+ GGML_ABORT("ggml-openvino: %s=%s is not valid, use 0 (off), 1 (on) or a KV window size that is a multiple "
+ "of 256",
+ var.name, value);
+ }
return std::to_string(number);
case env_type::FLOAT: {
char * end = nullptr;
@@ -548,10 +553,7 @@ std::string ggml_openvino_config_overrides_in_use() {
bool ggml_openvino_manual_gqa_enabled() {
// set: a positive value enables it, 0 disables it; unset: on GPU only
- if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
- return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
- }
- return ggml_openvino_is_gpu();
+ return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN", ggml_openvino_is_gpu() ? 1 : 0) > 0;
}
bool ggml_openvino_gdn_prescale_enabled() {
@@ -580,10 +582,7 @@ bool ggml_openvino_npu_is_4000() {
}
bool ggml_openvino_gdn_decompose_enabled() {
- if (ggml_openvino_getenv_str("GGML_OPENVINO_GDN_DECOMPOSE") != nullptr) {
- return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE") > 0;
- }
- return ggml_openvino_npu_is_4000();
+ return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0;
}
int ggml_openvino_gdn_decompose_chunk() {
@@ -607,19 +606,14 @@ float ggml_openvino_gdn_q_scale() {
}
bool ggml_openvino_reduce_compile_mem_enabled() {
- const char * reduce_compile_mem = ggml_openvino_getenv_str("GGML_OPENVINO_REDUCE_COMPILE_MEM");
- if (reduce_compile_mem != nullptr) {
- return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM") != 0;
- }
- return ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
+ return ggml_openvino_getenv_int("GGML_OPENVINO_REDUCE_COMPILE_MEM",
+ ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
}
bool ggml_openvino_release_weights_enabled() {
- const char * release_weights = ggml_openvino_getenv_str("GGML_OPENVINO_RELEASE_WEIGHTS");
- if (release_weights != nullptr) {
- return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS") != 0;
- }
- return ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE") != 0;
+ return ggml_openvino_is_gpu() &&
+ ggml_openvino_getenv_int("GGML_OPENVINO_RELEASE_WEIGHTS",
+ ggml_openvino_getenv_int("GGML_OPENVINO_MEMORY_OPTIMIZE")) != 0;
}
// Check if running on NPU
@@ -635,8 +629,13 @@ bool ggml_openvino_is_gpu() {
return has_prefix(ggml_openvino_get_device_name(), "GPU");
}
+int ggml_openvino_kv_slice_base() {
+ const int value = ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1);
+ return value <= 0 ? 0 : value == 1 ? 1024 : value;
+}
+
bool ggml_openvino_kv_slice_enabled() {
- return ggml_openvino_getenv_int("GGML_OPENVINO_KV_SLICE", 1) != 0;
+ return ggml_openvino_kv_slice_base() > 0;
}
bool ggml_openvino_npu_fast_mask_enabled() {
@@ -655,26 +654,15 @@ bool ggml_openvino_npu_decode_unfold_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_DECODE_UNFOLD") != 0;
}
-bool ggml_openvino_npu_parallel_compile_enabled() {
- return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_PARALLEL_COMPILE") != 0;
-}
-
int ggml_openvino_npu_decode_bucket() {
if (!ggml_openvino_is_npu()) {
return 0;
}
- // A self-contained blob embeds its weights bank, and NPUW cannot load a blob into a bank that already holds
- // weights, so a decode model per KV window cannot be imported next to the decode model of the pair.
- if (ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") &&
- ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 &&
- !ggml_openvino_npu_weightless_bank_enabled()) {
- return 0;
- }
- return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? 1024 : 0;
+ return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_BLOB_PREBUILD", 1) != 0 ? ggml_openvino_kv_slice_base() : 0;
}
-int ggml_openvino_static_kv_window(int rows, int ctx) {
- int window = 1;
+int ggml_openvino_static_kv_window(int rows, int ctx, int base) {
+ int window = std::max(base, 1);
while (window < rows && window < ctx) {
window *= 2;
}
@@ -683,7 +671,7 @@ int ggml_openvino_static_kv_window(int rows, int ctx) {
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens) {
if (n_tokens > 16) {
- return ggml_openvino_static_kv_window(rows, ctx);
+ return ggml_openvino_static_kv_window(rows, ctx, 1);
}
// a multiple of 256 and of 2^k / 4, where 2^k <= rows < 2^(k+1)
int step = 256;
@@ -702,13 +690,22 @@ bool ggml_openvino_npu_kv_head_major_enabled() {
ggml_openvino_kv_slice_enabled();
}
-bool ggml_openvino_npu_raw_weight_cache_enabled() {
- return ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 ||
- ggml_openvino_npu_weightless_bank_enabled();
+bool ggml_openvino_npu_host_gather_enabled() {
+ return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0;
+}
+
+bool ggml_openvino_kv_only_prefill_enabled() {
+ // On by default; it only takes effect for graphs with KV-shared layers.
+ return ggml_openvino_getenv_int("GGML_OPENVINO_KV_ONLY_PREFILL", 1) != 0;
+}
+
+bool ggml_openvino_npu_weightless_cache_enabled() {
+ return ggml_openvino_is_npu() && ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") != nullptr;
}
-bool ggml_openvino_npu_weightless_bank_enabled() {
- return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_WEIGHTLESS_BANK") != 0;
+bool ggml_openvino_self_contained_mmap_enabled() {
+ return ggml_openvino_npu_weightless_cache_enabled() &&
+ ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0;
}
namespace {
@@ -768,8 +765,8 @@ bool kv_grow_locked(kv_storage_entry & e, size_t rows, size_t heads) {
if (rows <= e.cap_rows) {
return false;
}
- const int bucket = ggml_openvino_npu_decode_bucket();
- size_t cap = bucket > 0 ? static_cast<size_t>(bucket) : 1024;
+ const int base = ggml_openvino_kv_slice_base();
+ size_t cap = base > 0 ? static_cast<size_t>(base) : 1024;
while (cap < rows) {
cap *= 2;
}
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h
index 61d2a2f88..7c4d1bdb6 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.h
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h
@@ -6,7 +6,6 @@
#define CL_TARGET_OPENCL_VERSION 300
#include <CL/cl.h>
-#include <cstdlib>
#include <map>
#include <memory>
#include <openvino/core/node.hpp>
@@ -140,10 +139,14 @@ bool ggml_openvino_is_static();
// KV-cache slicing: bind the KV cache, and size the KQ masks, at the attended length instead of the full context.
// One mechanism, two modes:
// dynamic graphs (CPU/GPU): the KV input is a view over the cache; the graph is not recompiled.
-// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at the aligned
-// attended length and recompiled when it changes; decode keeps the full context.
-// On by default for all devices; GGML_OPENVINO_KV_SLICE=0 turns it off.
+// static graphs (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): the prefill graph is compiled at a KV window of
+// base*2^k rows (clamped to ctx) covering the attended length and recompiled when it changes; decode keeps the
+// full context unless NPU decode KV windows are on (see ggml_openvino_npu_decode_bucket).
+// GGML_OPENVINO_KV_SLICE: unset or 1 = on with window base 1024, N (a multiple of 256) = on with window base N,
+// 0 = off. CPU/GPU dynamic graphs only use it as on/off.
bool ggml_openvino_kv_slice_enabled();
+// Static KV window base of GGML_OPENVINO_KV_SLICE, 0 = off.
+int ggml_openvino_kv_slice_base();
// On by default: back NPU buffers with Level Zero host memory; GGML_OPENVINO_NPU_L0_HOST_TENSORS=0 turns it off.
bool ggml_openvino_npu_l0_host_tensors_enabled();
@@ -155,17 +158,28 @@ bool ggml_openvino_npu_fast_mask_enabled();
// env-var name lives in one place; see docs/backend/OPENVINO.md for semantics.
bool ggml_openvino_npu_hfa_prefill_enabled();
bool ggml_openvino_npu_decode_unfold_enabled();
-bool ggml_openvino_npu_parallel_compile_enabled();
-
-// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1): static NPU graphs attend a KV window of 1024*2^k rows (clamped to ctx)
-// instead of the whole ctx, with one decode model per window, all built/imported with the prefill/decode pair;
-// with head-major KV the prefill models of every window are also exported and preloaded.
-// Returns the window base (1024), 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0).
+// Static path (NPU, or any device with GGML_OPENVINO_FORCE_STATIC): prefill only the KV-writing part of the model
+// and compute the logits with one decode step. Pays off for models whose tail layers share earlier layers' KV
+// (Gemma 3n/4 E-series), where it skips those layers for prompt tokens. On by default (it only applies to graphs
+// with KV-shared attention, at most one output token per batch, and no HFA prefill);
+// GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off.
+bool ggml_openvino_kv_only_prefill_enabled();
+// Gather the rows of large embedding tables on the host and feed them to the static graph as an input, instead of
+// binding the whole table to the NPU (NPUW lifts it to a function input, and gathering from an input that large
+// costs about as much as streaming the table).
+bool ggml_openvino_npu_host_gather_enabled();
+
+// GGML_OPENVINO_NPU_BLOB_PREBUILD (default 1), with GGML_OPENVINO_KV_SLICE on: static NPU decode also attends a KV
+// window of base*2^k rows (clamped to ctx, base from GGML_OPENVINO_KV_SLICE) instead of the whole ctx, with one
+// decode model per window, all built/imported with the prefill/decode pair.
+// The prefill windows are aligned to the decode windows, and with the weightless bank the prefill models of every
+// window are exported too (and preloaded with head-major KV).
+// Returns the window base, 0 = off (GGML_OPENVINO_NPU_BLOB_PREBUILD=0 or GGML_OPENVINO_KV_SLICE=0: decode attends
+// the full ctx).
int ggml_openvino_npu_decode_bucket();
-// Rows a static prefill attends with GGML_OPENVINO_KV_SLICE: the attended length rounded up to a power of two,
-// clamped to ctx.
-int ggml_openvino_static_kv_window(int rows, int ctx);
+// Smallest base*2^k covering rows, clamped to ctx.
+int ggml_openvino_static_kv_window(int rows, int ctx, int base);
// Rows the dynamic GPU graph attends for a batch of n_tokens tokens per sequence, clamped to ctx. The GPU plugin keeps
// memory for each attended length, so a long context should use a few lengths:
@@ -176,18 +190,19 @@ int ggml_openvino_static_kv_window(int rows, int ctx);
int ggml_openvino_gpu_kv_window(int rows, int ctx, int n_tokens);
// On-demand NPU KV cache (GGML_OPENVINO_NPU_KV_ON_DEMAND): the ggml KV buffer stays non-resident and the
-// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = decode bucket or 1024) with the rows in use.
+// NPU binds per-tensor L0 storage that grows (base*2^k rows, base = KV_SLICE window base or 1024) with the rows in use.
bool ggml_openvino_npu_kv_on_demand_enabled();
// On-demand KV with BLOB_PREBUILD and KV_SLICE: K storage is [heads][rows][head_size] and V storage is
// [heads][head_size][rows] (head-major with heads * head_size channels); every static graph binds the whole storage
// as [1, heads, rows, head_size] / [1, heads, head_size, rows], and attention uses V^T.
bool ggml_openvino_npu_kv_head_major_enabled();
-// NPU blob cache modes that keep the raw GGUF weights and skip requantization on a warm hit:
-// GGML_OPENVINO_SELF_CONTAINED_BLOB (weights embedded in each blob) or
-// GGML_OPENVINO_NPU_WEIGHTLESS_BANK (weightless blobs plus one shared weights file).
-bool ggml_openvino_npu_raw_weight_cache_enabled();
-bool ggml_openvino_npu_weightless_bank_enabled();
+// NPU with GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR: graphs with a KV cache are cached as weightless blobs plus one
+// shared weights file. Valid blobs are imported; otherwise the models are compiled and exported. The raw GGUF
+// weights are kept, and requantization is skipped on a warm hit.
+bool ggml_openvino_npu_weightless_cache_enabled();
+// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 with the NPU weightless cache
+bool ggml_openvino_self_contained_mmap_enabled();
void ggml_openvino_kv_storage_register(void * data, size_t row_bytes, size_t rows);
void ggml_openvino_kv_storage_unregister(const void * base, size_t size);
// Storage address backing ggml address `ptr` with at least `bytes` valid (grown if needed);
diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp
index 634301ee8..f34a4b77c 100644
--- a/ggml/src/ggml-openvino/ggml-openvino.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp
@@ -31,9 +31,6 @@
#include <openvino/runtime/intel_npu/level_zero/level_zero.hpp>
#include <openvino/runtime/properties.hpp>
#include <openvino/runtime/tensor.hpp>
-#include <algorithm>
-#include <map>
-#include <set>
#include <string>
#include <tuple>
#include <vector>
@@ -98,8 +95,6 @@ struct ggml_backend_openvino_buffer_context {
std::map<const void *, uint64_t> weight_fingerprints;
std::vector<ggml_openvino_source_mapping> source_mappings;
- // Used for re-allocation on device for kvcache
- void * data_prev = nullptr;
// data is in the weight buffer registry
bool weight_registered = false;
@@ -149,10 +144,7 @@ struct ggml_backend_openvino_buffer_context {
// commits/zeroes it eagerly (fully resident). For such large buffers, reserve
// demand-zero pages instead (no L0, no memset) so they stay non-resident. KV and small
// I/O buffers keep the L0 host tensor for zero-copy import (decode throughput).
- const bool strict_mmap = device_name == "NPU" &&
- ggml_openvino_npu_raw_weight_cache_enabled() &&
- ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
- ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
+ const bool strict_mmap = device_name == "NPU" && ggml_openvino_self_contained_mmap_enabled();
// 2 GiB keeps a large-context KV cache (~1 GiB at ctx 8K) on L0 while the bigger prefill
// compute buffer still goes lazy.
const size_t lazy_host_threshold =
@@ -391,12 +383,6 @@ static bool is_stateful_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") != 0;
}
-static bool is_self_contained_mmap_enabled() {
- return ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
- ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") &&
- ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
-}
-
// Stores extra as the tensor's extra, deleting the one it replaces
static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
ggml_tensor * tensor,
@@ -431,7 +417,6 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer,
}
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
- // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
// Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
@@ -505,7 +490,6 @@ static void ggml_backend_openvino_buffer_memset_tensor(ggml_backend_buffer_t buf
uint8_t value,
size_t offset,
size_t size) {
- // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -617,7 +601,6 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
const void * data,
size_t offset,
size_t size) {
- // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -642,10 +625,9 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
bool is_supported_weight_shape = is_2d || (tensor->ne[3] == 1 && ggml_is_quantized(tensor->type));
if (is_weight_buffer && is_full_tensor_set && is_supported_weight_shape) {
- if (ggml_openvino_is_npu() && ggml_openvino_npu_raw_weight_cache_enabled() &&
- ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR")) {
+ if (ggml_openvino_npu_weightless_cache_enabled()) {
// Keep raw bytes for cache fingerprint validation and compile fallback; the imported
- // self-contained blob supplies the runtime weights, so eager requant is unnecessary.
+ // blob supplies the runtime weights, so eager requant is unnecessary.
memcpy(tensor->data, data, size);
return;
}
@@ -653,32 +635,15 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
auto result = process_weight_tensor(tensor, data, tensor->data);
result.weight_node->set_friendly_name(tensor->name);
- // const auto & layout = result.layout;
ggml_openvino_extra_base * extra;
// Quantized path with extracted weight/scale/zp tensors
if (result.is_quantized()) {
extra = new ggml_openvino_quantized_weight_extra(std::move(result.weights), std::move(result.scales),
std::move(result.zp), result.weight_node);
-
- // if (layout.is_requant) {
- // GGML_LOG_DEBUG("%s: requantized %s to %s (u%d, block_size=%ld)\n", __func__, tensor->name,
- // extra_quant_type_name(layout.requant_type.value()), layout.is_u4 ? 4 : 8,
- // layout.weights_per_block);
- // } else {
- // int64_t n_blocks = ggml_nelements(tensor) / layout.weights_per_block;
- // GGML_LOG_DEBUG("%s: extracted quantized weight node for %s (u%d, %zu weights, %ld blocks)\n",
- // __func__, tensor->name, layout.is_u4 ? 4 : 8, layout.weights_size, n_blocks);
- // }
} else {
// F16/F32/BF16 weight or F16-requant
extra = new ggml_openvino_weight_extra(std::move(result.weights), result.weight_node);
-
- // if (layout.total_size > 0) {
- // GGML_LOG_DEBUG("%s: requantized %s to F16\n", __func__, tensor->name);
- // } else {
- // GGML_LOG_DEBUG("%s: created shared-memory weight node for %s\n", __func__, tensor->name);
- // }
}
ggml_openvino_set_extra(ctx, tensor, extra);
@@ -804,7 +769,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
void * data,
size_t offset,
size_t size) {
- // GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
GGML_ASSERT(tensor != nullptr && tensor->data != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -843,7 +807,6 @@ static void ggml_backend_openvino_buffer_get_tensor(ggml_backend_buffer_t buffer
static bool ggml_backend_openvino_buffer_cpy_tensor(ggml_backend_buffer_t buffer,
const ggml_tensor * src,
ggml_tensor * dst) {
- // GGML_LOG_DEBUG("%s: src tensor name=%s, dst tensor name=%s\n", __func__, src->name, dst->name);
GGML_ASSERT(src != nullptr && dst != nullptr);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
@@ -978,7 +941,7 @@ static size_t ggml_backend_openvino_buffer_type_get_alloc_size(ggml_backend_buff
const ggml_tensor * tensor) {
GGML_UNUSED(buft);
- if (is_self_contained_mmap_enabled()) {
+ if (ggml_openvino_self_contained_mmap_enabled()) {
return ggml_nbytes(tensor);
}
@@ -1178,7 +1141,6 @@ static void ggml_backend_openvino_free(ggml_backend_t backend) {
// reuses it instead of recompiling against zeroed weights.
if (!ggml_openvino_weight_buffers_released()) {
cache->graphs.clear();
- ov_clear_imported_blobs();
std::lock_guard<std::mutex> fingerprints_lock(g_fallback_fingerprints_mutex);
g_fallback_fingerprints.clear();
}
@@ -1455,7 +1417,7 @@ static void ggml_backend_openvino_device_get_props(ggml_backend_dev_t dev, ggml_
props->caps = {
/* .async = */ false,
/* .host_buffer = */ false,
- /* .buffer_from_host_ptr = */ is_self_contained_mmap_enabled(),
+ /* .buffer_from_host_ptr = */ ggml_openvino_self_contained_mmap_enabled(),
/* .events = */ false,
/* .mmap_support = */ true,
/* .fast_async_host_input = */ false,
@@ -1685,6 +1647,13 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) {
GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op);
}
+// SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a
+// state tensor) are supported only for the recognized cache writes.
+static bool set_rows_output_view_is_supported(const ggml_tensor * op) {
+ return op->view_src == nullptr || ggml_nbytes(op) == 0 || ggml_is_contiguous(op) ||
+ GgmlOvDecoder::is_column_set_rows(op) || GgmlOvDecoder::is_conv_state_snapshot_writeback(op);
+}
+
static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) {
const ggml_tensor * as = op->src[0];
const ggml_tensor * ids = op->src[2];
@@ -1795,6 +1764,9 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
if (op->op == GGML_OP_SET_ROWS && op->src[0]->type == GGML_TYPE_BF16) {
return {false, "SET_ROWS with BF16 src0 is not supported"};
}
+ if (op->op == GGML_OP_SET_ROWS && !set_rows_output_view_is_supported(op)) {
+ return {false, "SET_ROWS with non-contiguous output view is not supported"};
+ }
if (op->ne[0] == 256 && (op->src[0]->type == GGML_TYPE_Q4_K || op->src[0]->type == GGML_TYPE_Q5_K ||
op->src[0]->type == GGML_TYPE_Q4_1 || op->src[0]->type == GGML_TYPE_Q5_1)) {
// These are all f16-arithmetic dequant rounding errors that intermittently exceed the
@@ -2335,10 +2307,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
if (!supported) {
return {false, "op " + std::string(ggml_op_name(op->op)) + " has no op translator"};
}
- static std::set<ggml_op> ops_not_support_view_input{};
- if (ops_not_support_view_input.find(op->op) != ops_not_support_view_input.end() && has_view_op_input(op)) {
- return {false, "op " + std::string(ggml_op_name(op->op)) + " with VIEW input is not supported"};
- }
}
}
diff --git a/ggml/src/ggml-openvino/ggml-quants.h b/ggml/src/ggml-openvino/ggml-quants.h
index 04fe0218a..912805fbf 100644
--- a/ggml/src/ggml-openvino/ggml-quants.h
+++ b/ggml/src/ggml-openvino/ggml-quants.h
@@ -8,29 +8,6 @@
static constexpr size_t GGML_QUANTIZATION_GROUP_SIZE = 32;
-inline const char * extra_quant_type_name(ExtraQuantType t) {
- switch (t) {
- case ExtraQuantType::F16:
- return "F16";
- case ExtraQuantType::Q4_0_C:
- return "Q4_0_C";
- case ExtraQuantType::Q4_0_128:
- return "Q4_0_128";
- case ExtraQuantType::Q8_0_C:
- return "Q8_0_C";
- case ExtraQuantType::Q8_0_32:
- return "Q8_0_32";
- case ExtraQuantType::Q8_1_C:
- return "Q8_1_C";
- case ExtraQuantType::Q4_0_64:
- return "Q4_0_64";
- case ExtraQuantType::Q4_1_64:
- return "Q4_1_64";
- default:
- return "unknown";
- }
-}
-
// Result from process_weight_tensor containing the weight node and tensors.
// For quantized weights, also contains the extracted layout and scale/zp tensors.
struct OvWeight {
diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp
index d35168750..74ba8a1ce 100644
--- a/ggml/src/ggml-openvino/model-cache.cpp
+++ b/ggml/src/ggml-openvino/model-cache.cpp
@@ -7,20 +7,21 @@
#include "ggml-openvino-extra.h"
#include "openvino/rt_info/weightless_caching_attributes.hpp"
-#include <cerrno>
+#include <sys/stat.h>
+#include <sys/types.h>
+
#include <algorithm>
#include <cstdio>
#include <cstring>
+#include <filesystem>
#include <fstream>
#include <iomanip>
#include <limits>
-#include <sstream>
#include <openvino/core/model.hpp>
#include <openvino/core/version.hpp>
#include <openvino/op/constant.hpp>
#include <string>
-#include <sys/stat.h>
-#include <sys/types.h>
+#include <system_error>
#include <unordered_map>
#include <unordered_set>
#include <vector>
@@ -113,50 +114,12 @@ std::string hex64(uint64_t v) {
return std::string(buf);
}
-// Portable mkdir for a single path component. Returns true if the directory
-// exists after the call (created now or already present).
-bool make_dir(const std::string & path) {
-#if defined(_WIN32)
- int rc = _mkdir(path.c_str());
-#else
- int rc = ::mkdir(path.c_str(), 0755);
-#endif
- if (rc == 0 || errno == EEXIST) {
- return true;
- }
- return false;
-}
-
-// Create `path` and any missing parents (like `mkdir -p`). Best-effort:
-// returns true only if the full directory exists afterwards.
-bool make_dirs(const std::string & path) {
- if (path.empty()) {
- return false;
- }
- std::string acc;
- for (size_t i = 0; i < path.size(); ++i) {
- const char c = path[i];
- acc.push_back(c);
- const bool sep = (c == '/'
-#if defined(_WIN32)
- || c == '\\'
-#endif
- );
- // Create each intermediate component (skip a leading "/" root).
- if (sep && acc.size() > 1) {
- std::string component = acc.substr(0, acc.size() - 1);
-#if defined(_WIN32)
- // A drive root such as "D:" cannot be mkdir'ed (EACCES, not EEXIST).
- if (component.size() == 2 && component[1] == ':') {
- continue;
- }
-#endif
- if (!make_dir(component)) {
- return false;
- }
- }
- }
- return make_dir(path);
+// Create `path` and any missing parents (like `mkdir -p`). True if the directory exists afterwards.
+bool make_dirs(const std::string & path, std::error_code & ec) {
+ const auto fs_path = std::filesystem::u8path(path);
+ std::filesystem::create_directories(fs_path, ec);
+ std::error_code ec_dir;
+ return std::filesystem::is_directory(fs_path, ec_dir);
}
} // namespace
@@ -179,10 +142,8 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_EXACT_ZERO_POINT",
"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",
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
@@ -337,9 +298,10 @@ std::string ggml_openvino_model_cache_dir() {
// Create the cache directory (and parents) on first use so callers don't
// have to pre-create it; a missing dir would otherwise silently disable the
// cache (manifest/blob writes fail with no directory to write into).
- if (!make_dirs(path)) {
- GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (errno=%d); caching disabled\n",
- path.c_str(), errno);
+ std::error_code ec;
+ if (!make_dirs(path, ec)) {
+ GGML_LOG_WARN("ggml-openvino: could not create model cache dir '%s' (%s); caching disabled\n", path.c_str(),
+ ec.message().c_str());
return std::string();
}
return path;
@@ -370,13 +332,16 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
// Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
- h = fnv1a_u64(h, 9);
+ // Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling),
+ // and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings.
+ h = fnv1a_u64(h, 10);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
h = fnv1a(h, value, strlen(value) + 1);
}
h = fnv1a_u64(h, ggml_openvino_gdn_decompose_enabled() ? ggml_openvino_gdn_decompose_chunk() : 0);
+ h = fnv1a_u64(h, ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1 : 0);
if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
h = fnv1a(h, "GGML_OPENVINO_DEBUG_NODE", sizeof("GGML_OPENVINO_DEBUG_NODE"));
h = fnv1a(h, debug_nodes, strlen(debug_nodes) + 1);
diff --git a/ggml/src/ggml-openvino/model-cache.h b/ggml/src/ggml-openvino/model-cache.h
index 25acadeee..355f8feeb 100644
--- a/ggml/src/ggml-openvino/model-cache.h
+++ b/ggml/src/ggml-openvino/model-cache.h
@@ -1,17 +1,13 @@
#pragma once
// Compiled blobs include weights. Cache-only execution skips weight uploads and graph compilation.
-// On NPU, GGML_OPENVINO_SELF_CONTAINED_BLOB=1 exports embedded-weight prefill/decode
-// blobs. A warm hit skips weight requantization, graph conversion, and compilation,
-// at the cost of roughly model-size storage per blob and separate NPUW weight banks.
-// After both blobs exist, GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the
-// GGUF mmap instead of allocating the private OpenVINO model buffer. This mode is
-// import-only and fails clearly if either required blob is missing or invalid.
-// GGML_OPENVINO_NPU_WEIGHTLESS_BANK=1 is the same raw-weight flow, but exports weightless
-// prefill/decode blobs plus ONE <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair
-// of the model (pairs differ only in KV window). Warm import reads the weights from that file
-// (ov::weights_path) and NPUW deduplicates all models into one bank
-// (no OpenVINO patch needed), so the weights are stored once on disk and resident once.
+// On NPU, GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR imports the cached prefill/decode blobs when they are
+// valid; otherwise it compiles them and exports weightless blobs plus ONE
+// <weights_fp>-<weights_fp>.weights.bin shared by every prefill/decode pair of the model (pairs differ
+// only in KV window), with a warning. Import reads the weights from that file (ov::weights_path) and NPUW
+// deduplicates all models into one bank, so the weights are stored once on disk and resident once.
+// GGML_OPENVINO_SELF_CONTAINED_MMAP=1 additionally wraps the GGUF mmap instead of allocating the private
+// OpenVINO model buffer. This mode is import-only and fails clearly if a required blob is missing.
#include "ggml.h"
@@ -84,7 +80,7 @@ bool ggml_openvino_model_cache_verify_manifest(const std::string & path,
std::vector<std::string> & inputs,
std::vector<std::string> & outputs);
-// GGML_OPENVINO_NPU_WEIGHTLESS_BANK: a weights file shared by weightless blobs. Every weightless-tagged
+// NPU cache: a weights file shared by weightless blobs. Every weightless-tagged
// Constant is one region keyed by its data pointer (NPUW maps a Constant to its file offset by pointer).
struct ggml_openvino_weights_layout {
std::string path;
diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h
index 980f0b88d..3a05c8b43 100644
--- a/ggml/src/ggml-openvino/openvino/decoder.h
+++ b/ggml/src/ggml-openvino/openvino/decoder.h
@@ -111,11 +111,14 @@ public:
virtual const std::map<std::string, ModelExtraInputInfo> & get_model_extra_inputs() const = 0;
virtual const std::map<std::string, std::shared_ptr<ov::Node>> & get_model_weights() const = 0;
virtual std::set<std::string> get_model_output_names() const = 0;
+ // KV-only prefill (GGML_OPENVINO_KV_ONLY_PREFILL): the model keeps only the cache outputs, see
+ // pass::KeepCacheResults.
+ virtual bool is_kv_only_outputs() const { return false; }
+ // The outputs that write a KV or recurrent cache.
+ virtual std::set<std::string> get_cache_output_names() const { return {}; }
virtual int32_t * get_rope_params() const = 0;
- virtual bool has_mixed_rope_params() const = 0;
-
virtual int get_ssm_state_size() const = 0;
virtual std::map<std::string, std::string> get_kv_param_res_names() const = 0;
diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h
index faa019681..51f7f6352 100644
--- a/ggml/src/ggml-openvino/openvino/node_context.h
+++ b/ggml/src/ggml-openvino/openvino/node_context.h
@@ -16,21 +16,15 @@ typedef std::map<std::string, Output<Node>> TensorMap;
class NodeContext : public frontend::NodeContext {
public:
- NodeContext(const std::shared_ptr<GgmlDecoder> & decoder,
- std::shared_ptr<TensorMap> & tensor_map,
- int node_idx,
- TranslateSession * translate_session = nullptr) :
+ NodeContext(const std::shared_ptr<GgmlDecoder> & decoder, std::shared_ptr<TensorMap> & tensor_map, int node_idx) :
ov::frontend::NodeContext(decoder->get_op_type(node_idx)),
m_decoder(decoder),
m_tensor_map(tensor_map),
- m_node_idx(node_idx),
- m_translate_session(translate_session) {
+ m_node_idx(node_idx) {
m_input_names = decoder->get_input_names(m_node_idx);
m_output_names = decoder->get_output_names(m_node_idx);
}
- TranslateSession * get_translate_session() const { return m_translate_session; }
-
const std::vector<std::string> & get_input_names() const { return m_input_names; }
const std::vector<std::string> & get_output_names() const { return m_output_names; }
@@ -172,7 +166,6 @@ private:
std::shared_ptr<GgmlDecoder> m_decoder;
std::shared_ptr<TensorMap> & m_tensor_map;
int m_node_idx;
- TranslateSession * m_translate_session;
std::vector<std::string> m_input_names;
std::vector<std::string> m_output_names;
};
diff --git a/ggml/src/ggml-openvino/openvino/op/argsort.cpp b/ggml/src/ggml-openvino/openvino/op/argsort.cpp
index a3ae09fbd..2d4c2d7bb 100644
--- a/ggml/src/ggml-openvino/openvino/op/argsort.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/argsort.cpp
@@ -1,10 +1,9 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
-#include "ggml.h"
#include "ggml-openvino/ggml-openvino-extra.h"
+#include "ggml.h"
-#include <climits>
#include <cstdint>
#include <openvino/frontend/exception.hpp>
#include <openvino/op/add.hpp>
diff --git a/ggml/src/ggml-openvino/openvino/op/cpy.cpp b/ggml/src/ggml-openvino/openvino/op/cpy.cpp
index e0d63ac95..aa3565966 100644
--- a/ggml/src/ggml-openvino/openvino/op/cpy.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/cpy.cpp
@@ -1,9 +1,9 @@
#include "../node_context.h"
#include "../op_table.h"
#include "../utils.h"
+
#include <climits>
#include <cstdint>
-#include <cstdio>
#include <memory>
#include <numeric>
#include <openvino/frontend/exception.hpp>
@@ -126,9 +126,13 @@ OutputVector translate_cpy(const NodeContext & context) {
auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
- auto head_part = std::make_shared<ov::op::v8::Slice>(base, zero, begin, one, axis);
- auto tail_part = std::make_shared<ov::op::v8::Slice>(base, end, int_max, one, axis);
- auto res = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
+ // The view offset is relative to the whole base buffer, so splice on the flattened base.
+ auto flat_base = std::make_shared<ov::op::v1::Reshape>(base, flat_shape, false);
+ auto head_part = std::make_shared<ov::op::v8::Slice>(flat_base, zero, begin, one, axis);
+ auto tail_part = std::make_shared<ov::op::v8::Slice>(flat_base, end, int_max, one, axis);
+ auto spliced = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head_part, src, tail_part}, 3);
+ auto res = std::make_shared<ov::op::v1::Reshape>(
+ spliced, std::make_shared<ov::op::v3::ShapeOf>(base, ov::element::i64), false);
return rename_outputs_with_suffix({res}, context.get_name());
}
@@ -221,6 +225,8 @@ OutputVector translate_cpy(const NodeContext & context) {
"CPY conv state cache update requires static source feature view");
const int64_t full_feature_size = base_shape[3].get_length();
+ FRONT_END_OP_CONVERSION_CHECK(full_feature_size > 0,
+ "CPY conv state cache update requires a non-empty base cache feature size");
const int64_t update_feature_size = input_shape[2].get_length() * input_shape[3].get_length();
const auto output_stride = context.get_output_stride();
const size_t elem_size = output_stride.empty() ? context.get_output_type().size() : output_stride.back();
diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
index b83c6de3a..ea223973f 100644
--- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
@@ -139,7 +139,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
float * params = reinterpret_cast<float *>(context.get_output_op_params());
float scale = params[0];
- // float max_bias = params[1];
const float logit_softcap = params[2];
auto q = std::make_shared<ov::op::v0::Convert>(q_f32, ov::element::f16);
@@ -168,9 +167,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
false);
}
- //auto tile_kv = [&](int64_t num_heads, int64_t num_heads_kv, int64_t head_size, ov::Output<Node> kv) {
- // int64_t factor = num_heads / num_heads_kv;
- // if (factor > 1 && num_heads_kv > 1) {
auto q_shape = context.get_input_shape(0).to_shape();
auto k_shape = context.get_input_shape(1).to_shape();
auto v_shape = context.get_input_shape(2).to_shape();
@@ -279,9 +275,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
new_kv_shape = ov::op::v0::Constant::create(
ov::element::i64, {4},
transposed ? std::vector<int64_t>{0, n_heads, hs, -1} : std::vector<int64_t>{0, n_heads, -1, hs});
- // ov::element::i64, {5}, {(int64_t) 1, (int64_t) 1, factor, (int64_t) 1, (int64_t) 1});
- //new_kv_shape =
- // ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 0, num_heads, (int64_t) -1, head_size});
kv = std::make_shared<ov::op::v3::Broadcast>(kv_unsqueezed, kv_broadcast_shape,
ov::op::BroadcastType::BIDIRECTIONAL);
@@ -294,9 +287,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
const bool v_transposed = ggml_openvino_npu_kv_head_major_enabled() && context.is_static() &&
context.get_input_names()[2].find("cache_v_l") != std::string::npos;
- // the HFA prefill path has no sinks
- const bool use_hfa_gate =
- ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() && has_mask && !has_sink;
+ // the HFA prefill path has no sinks, and attends the rows of a whole chunk (not those of gemma-4's KV-shared layers)
+ const bool use_hfa_gate = ggml_openvino_npu_hfa_prefill_enabled() && context.is_static() && context.is_prefill() &&
+ has_mask && !has_sink && !is_pruned_mask_name(context.get_input_names()[3]);
if (use_hfa_gate) {
const int layer = extract_layer(context.get_input_names()[1]);
auto past_k = context.get_input("ggml_hfa_past_cache_k_l" + std::to_string(layer));
@@ -350,10 +343,6 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
return rename_outputs_with_suffix({res}, context.get_name());
}
- //auto q_shape = context.get_input_shape(0).to_shape();
- //auto k_shape = context.get_input_shape(1).to_shape();
- //k = tile_kv(q_shape[1], k_shape[1], q_shape[3], k);
- //v = tile_kv(q_shape[1], k_shape[1], q_shape[3], v);
k = tile_kv(num_heads, num_heads_kv, head_size, k);
v = tile_kv(num_heads, num_heads_kv, head_size, v, v_transposed);
diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
index 6caafeb4f..eef3874fa 100644
--- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
@@ -514,10 +514,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}
- // std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
- // << ", v=" << v.get_partial_shape() << ", g=" << g.get_partial_shape()
- // << ", beta=" << beta.get_partial_shape() << ", state=" << state.get_partial_shape() << std::endl;
-
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
if (cache_inputs) {
OutputVector args{q, k, v, (*cache_inputs)[0], g, beta};
diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
index 89a75570c..59c0fb094 100644
--- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp
@@ -24,6 +24,13 @@ namespace op {
OutputVector translate_get_rows(const NodeContext & context) {
num_inputs_check(context, 2, 2);
+ // Rows gathered on the host (GGML_OPENVINO_NPU_HOST_GATHER) arrive as a [1, 1, n_tokens, row] input.
+ const std::string host_rows = "ggml_host_rows_" + context.get_name();
+ if (context.has_input(host_rows)) {
+ // Not renamed: the output is the Parameter itself, whose name binds the input at runtime.
+ return {context.get_input(host_rows)};
+ }
+
Output<Node> res;
Output<Node> data;
int64_t row_offset = 0;
diff --git a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
index 0cfe44960..45fc1a547 100644
--- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp
@@ -2,7 +2,6 @@
#include "../op_table.h"
#include "../utils.h"
-#include <climits>
#include <cstdint>
#include <memory>
#include <openvino/core/node.hpp>
diff --git a/ggml/src/ggml-openvino/openvino/op/permute.cpp b/ggml/src/ggml-openvino/openvino/op/permute.cpp
index 7a65a0b01..b6232e970 100644
--- a/ggml/src/ggml-openvino/openvino/op/permute.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/permute.cpp
@@ -3,7 +3,6 @@
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
-#include <climits>
#include <cstdint>
#include <memory>
#include <openvino/core/node.hpp>
@@ -113,10 +112,6 @@ OutputVector translate_permute(const NodeContext & context) {
auto new_shape =
std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, n_heads, head_size}, 0);
- // // Alternative
- // auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
- // auto new_shape = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{n_seq_active, neg_one, zero, zero}, 0);
-
auto reshaped = std::make_shared<ov::op::v1::Reshape>(src, new_shape, true);
res = std::make_shared<ov::op::v1::Transpose>(reshaped, perm);
} else if ((op_case == 3 || op_case == 4) && is_kvcache_4d_shape(src.get_partial_shape())) {
diff --git a/ggml/src/ggml-openvino/openvino/op/rope.cpp b/ggml/src/ggml-openvino/openvino/op/rope.cpp
index a01cd0128..c8703747c 100644
--- a/ggml/src/ggml-openvino/openvino/op/rope.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/rope.cpp
@@ -49,34 +49,29 @@ OutputVector translate_rope(const NodeContext & context) {
Output<Node> cos_theta_node;
Output<Node> sin_theta_node;
- if (context.has_input("rope_cos")) {
- cos_theta_node = context.get_input("rope_cos");
- sin_theta_node = context.get_input("rope_sin");
+ std::string cache_key = "rope_sin_cos";
+ for (int i = 0; i < 15; i++) {
+ cache_key += "_" + std::to_string(op_params[i]);
+ }
+ if (context.get_input_size() == 3) {
+ cache_key += "_ff_" + context.get_input_names()[2];
+ }
+ // Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
+ cache_key += "_pos_" + context.get_input_names()[1];
+ if (context.has_input(cache_key + "_cos")) {
+ cos_theta_node = context.get_input(cache_key + "_cos");
+ sin_theta_node = context.get_input(cache_key + "_sin");
} else {
- std::string cache_key = "rope_sin_cos";
- for (int i = 0; i < 15; i++) {
- cache_key += "_" + std::to_string(op_params[i]);
- }
+ auto inp_pos = context.get_input(1).get_node_shared_ptr();
+ std::shared_ptr<ov::Node> rope_freqs_weight;
if (context.get_input_size() == 3) {
- cache_key += "_ff_" + context.get_input_names()[2];
- }
- // Not every ROPE takes inp_pos: gemma-4 rotates its KV-shared layers at the positions of the output rows only
- cache_key += "_pos_" + context.get_input_names()[1];
- if (context.has_input(cache_key + "_cos")) {
- cos_theta_node = context.get_input(cache_key + "_cos");
- sin_theta_node = context.get_input(cache_key + "_sin");
- } else {
- auto inp_pos = context.get_input(1).get_node_shared_ptr();
- std::shared_ptr<ov::Node> rope_freqs_weight;
- if (context.get_input_size() == 3) {
- rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
- }
- auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
- sin_theta_node = sin_cos.first;
- cos_theta_node = sin_cos.second;
- context.put_shared(cache_key + "_cos", cos_theta_node);
- context.put_shared(cache_key + "_sin", sin_theta_node);
+ rope_freqs_weight = context.get_input(2).get_node_shared_ptr();
}
+ auto sin_cos = make_sin_cos(op_params, inp_pos, rope_freqs_weight, mode, false, head_dim);
+ sin_theta_node = sin_cos.first;
+ cos_theta_node = sin_cos.second;
+ context.put_shared(cache_key + "_cos", cos_theta_node);
+ context.put_shared(cache_key + "_sin", sin_theta_node);
}
auto output_type = context.get_output_type();
diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
index 24cbeac35..385dc8c00 100644
--- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
@@ -3,7 +3,6 @@
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
-#include <cassert>
#include <cstdint>
#include <memory>
#include <numeric>
diff --git a/ggml/src/ggml-openvino/openvino/op/ssm_conv.cpp b/ggml/src/ggml-openvino/openvino/op/ssm_conv.cpp
index 352fd9056..7d36ab7c2 100644
--- a/ggml/src/ggml-openvino/openvino/op/ssm_conv.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/ssm_conv.cpp
@@ -5,9 +5,7 @@
#include <openvino/op/constant.hpp>
#include <openvino/op/group_conv.hpp>
#include <openvino/op/reshape.hpp>
-#include <openvino/op/squeeze.hpp>
#include <openvino/op/transpose.hpp>
-#include <openvino/op/unsqueeze.hpp>
namespace ov {
namespace frontend {
@@ -23,34 +21,32 @@ OutputVector translate_ssm_conv(const NodeContext & context) {
auto sx_shape = context.get_input_shape(0).to_shape(); // [1, n_s, d_inner, ncs]
auto c_shape = context.get_input_shape(1).to_shape(); // [1, 1, d_inner, d_conv]
- // int64_t n_s = sx_shape[1];
int64_t d_inner = sx_shape[2];
- // int64_t ncs = sx_shape[3]; // d_conv - 1 + n_t
- int64_t d_conv = c_shape[3];
- // int64_t n_t = ncs - d_conv + 1;
-
- // Reshape sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, ncs] for 1D GroupConvolution
- auto sx_reshaped =
- std::make_shared<ov::op::v0::Squeeze>(sx, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
-
- // Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, d_conv]
- // GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kernel_size]
- auto c_new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{d_inner, 1, 1, d_conv});
+ int64_t d_conv = c_shape[3];
+
+ // The depthwise conv is expressed as a 2D GroupConvolution with a unit H dim: the GPU plugin
+ // (OV 2026.4, ACCURACY mode) fails to compile the 1D form ("Weights/ifm mismatch") when its
+ // input comes from RMSNorm -> Transpose -> Concat.
+ // Transpose sx from [1, n_s, d_inner, ncs] to [n_s, d_inner, 1, ncs]
+ auto sx_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 2, 0, 3});
+ auto sx_reshaped = std::make_shared<ov::op::v1::Transpose>(sx, sx_perm);
+
+ // Reshape c from [1, 1, d_inner, d_conv] to [d_inner, 1, 1, 1, d_conv]
+ // GroupConvolution filter: [groups, out_channels/groups, in_channels/groups, kH, kW]
+ auto c_new_shape =
+ ov::op::v0::Constant::create(ov::element::i64, {5}, std::vector<int64_t>{d_inner, 1, 1, 1, d_conv});
auto c_reshaped = std::make_shared<ov::op::v1::Reshape>(c, c_new_shape, false);
- // Depthwise 1D convolution: groups=d_inner, stride=1, no padding, no dilation
- // Input: [n_s, d_inner, ncs], Filter: [d_inner, 1, 1, d_conv]
- // Output: [n_s, d_inner, n_t]
- auto conv = std::make_shared<ov::op::v1::GroupConvolution>(
- sx_reshaped, c_reshaped, ov::Strides{1}, ov::CoordinateDiff{0}, ov::CoordinateDiff{0}, ov::Strides{1});
-
- // Transpose from [n_s, d_inner, n_t] to [n_s, n_t, d_inner]
- auto perm = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{0, 2, 1});
- auto transposed = std::make_shared<ov::op::v1::Transpose>(conv, perm);
+ // Depthwise convolution: groups=d_inner, stride=1, no padding, no dilation
+ // Input: [n_s, d_inner, 1, ncs], Filter: [d_inner, 1, 1, 1, d_conv]
+ // Output: [n_s, d_inner, 1, n_t]
+ auto conv = std::make_shared<ov::op::v1::GroupConvolution>(sx_reshaped, c_reshaped, ov::Strides{1, 1},
+ ov::CoordinateDiff{0, 0}, ov::CoordinateDiff{0, 0},
+ ov::Strides{1, 1});
- // Reshape to output shape [1, n_s, n_t, d_inner]
- auto res =
- std::make_shared<ov::op::v0::Unsqueeze>(transposed, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
+ // Transpose from [n_s, d_inner, 1, n_t] to output shape [1, n_s, n_t, d_inner]
+ auto perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{2, 0, 3, 1});
+ auto res = std::make_shared<ov::op::v1::Transpose>(conv, perm);
return rename_outputs_with_suffix({res}, context.get_name());
}
diff --git a/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp
new file mode 100644
index 000000000..d69123295
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp
@@ -0,0 +1,53 @@
+#include "keep_cache_results.h"
+
+#include <openvino/core/model.hpp>
+#include <openvino/op/parameter.hpp>
+#include <openvino/op/result.hpp>
+
+#include <unordered_set>
+
+namespace ov {
+namespace frontend {
+namespace ggml {
+namespace pass {
+
+bool KeepCacheResults::run_on_model(const std::shared_ptr<ov::Model> & model) {
+ bool changed = false;
+ // Copies: remove_result()/remove_parameter() modify the vectors these accessors return.
+ const ov::ResultVector results = model->get_results();
+ for (const auto & result : results) {
+ if (m_cache_outputs.count(result->get_friendly_name()) == 0) {
+ model->remove_result(result);
+ changed = true;
+ }
+ }
+ if (!changed) {
+ return false;
+ }
+
+ // Removed Results leave their producers unreachable, but those nodes still hold their inputs, so a Parameter
+ // is unused when none of its consumers is still part of the model.
+ std::unordered_set<const ov::Node *> live;
+ for (const auto & op : model->get_ordered_ops()) {
+ live.insert(op.get());
+ }
+ const ov::ParameterVector params = model->get_parameters();
+ for (const auto & param : params) {
+ bool used = false;
+ for (const auto & input : param->output(0).get_target_inputs()) {
+ if (live.count(input.get_node()) != 0) {
+ used = true;
+ break;
+ }
+ }
+ if (!used) {
+ model->remove_parameter(param);
+ }
+ }
+ return true;
+}
+
+} // namespace pass
+} // namespace ggml
+} // namespace frontend
+} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h
new file mode 100644
index 000000000..711fa0703
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h
@@ -0,0 +1,30 @@
+#include "openvino/pass/pass.hpp"
+
+#include <set>
+#include <string>
+
+namespace ov {
+namespace frontend {
+namespace ggml {
+namespace pass {
+
+// Keeps only the Results named in |cache_outputs| (the KV / recurrent cache writes) and drops every other Result,
+// so that everything that only feeds them -- for models whose tail layers read an earlier layer's KV (Gemma 3n/4
+// E-series) the KV-shared layers and the LM head -- leaves the model. Parameters that nothing reads afterwards are
+// removed too. Used for KV-only prefill on the static path (GGML_OPENVINO_KV_ONLY_PREFILL); the outputs of the
+// batch then come from one step of the decode model.
+class KeepCacheResults : public ov::pass::ModelPass {
+public:
+ OPENVINO_MODEL_PASS_RTTI("ov::frontend::ggml::pass::KeepCacheResults")
+ explicit KeepCacheResults(std::set<std::string> cache_outputs) : m_cache_outputs(std::move(cache_outputs)) {}
+
+ bool run_on_model(const std::shared_ptr<ov::Model> & model) override;
+
+private:
+ std::set<std::string> m_cache_outputs;
+};
+
+} // namespace pass
+} // namespace ggml
+} // namespace frontend
+} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h b/ggml/src/ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h
index c229e25fb..eb4f92a8f 100644
--- a/ggml/src/ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h
+++ b/ggml/src/ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h
@@ -1,6 +1,5 @@
#pragma once
-#include "mark_decompression_convert_constant_folding.h"
#include "openvino/core/visibility.hpp"
#include "openvino/pass/matcher_pass.hpp"
diff --git a/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp b/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp
index 0b64fa1e9..7f9be6d91 100644
--- a/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp
+++ b/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp
@@ -4,6 +4,7 @@
#include "ggml-openvino/openvino/decoder.h"
#include "ggml-openvino/openvino/pass/fuse_argsort_topk.h"
#include "ggml-openvino/openvino/pass/fuse_to_conv.h"
+#include "ggml-openvino/openvino/pass/keep_cache_results.h"
#include "ggml-openvino/openvino/pass/kv_state_seq_axis.h"
#include "ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h"
#include "ggml-openvino/openvino/pass/mark_dequantization_subgraph.h"
@@ -21,11 +22,18 @@ GraphTraits analyze_graph(const GgmlDecoder & decoder) {
traits.device = ggml_openvino_is_npu() ? Device::NPU : ggml_openvino_is_gpu() ? Device::GPU : Device::CPU;
traits.is_static = decoder.is_static();
traits.is_stateful = decoder.is_stateful();
+ traits.kv_only_outputs = decoder.is_kv_only_outputs();
+ if (traits.kv_only_outputs) {
+ traits.cache_output_names = decoder.get_cache_output_names();
+ }
return traits;
}
void register_common_passes(ov::pass::Manager & manager, const GraphTraits & traits) {
- (void) traits;
+ // First, so the other passes do not work on the layers it removes.
+ if (traits.kv_only_outputs) {
+ manager.register_pass<pass::KeepCacheResults>(traits.cache_output_names);
+ }
manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
// Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain
// (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding,
diff --git a/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h b/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h
index 8db8ebfd6..44b372fad 100644
--- a/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h
+++ b/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h
@@ -16,6 +16,9 @@
#include <openvino/pass/make_stateful.hpp>
#include <openvino/pass/manager.hpp>
+#include <set>
+#include <string>
+
namespace ov {
namespace frontend {
namespace ggml {
@@ -31,6 +34,8 @@ struct GraphTraits {
Device device = Device::CPU;
bool is_static = false; // static shapes (NPU, or GGML_OPENVINO_FORCE_STATIC)
bool is_stateful = false; // KV cache kept inside the model (GGML_OPENVINO_STATEFUL_EXECUTION)
+ bool kv_only_outputs = false; // static KV-only prefill: keep only the cache outputs (GGML_OPENVINO_KV_ONLY_PREFILL)
+ std::set<std::string> cache_output_names;
};
GraphTraits analyze_graph(const GgmlDecoder & decoder);
diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp
index 8d0ac026d..a3b56bb5e 100644
--- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp
+++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp
@@ -3,10 +3,8 @@
# include "../ggml-openvino-extra.h"
# include "ggml-impl.h"
+# include "op/recurrent_cache_update.hpp"
# include "op_table.h"
-# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
-# include "op/recurrent_cache_update.hpp"
-# endif
# include "utils.h"
# include <openvino/op/concat.hpp>
diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp
index eddebd901..1c43c8ae0 100644
--- a/ggml/src/ggml-openvino/openvino/translate_session.cpp
+++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp
@@ -15,11 +15,9 @@
#include <algorithm>
#include <cstdint>
-#include <cstdlib>
#include <limits>
#include <map>
#include <memory>
-#include <set>
#include <openvino/core/node.hpp>
#include <openvino/core/preprocess/pre_post_process.hpp>
#include <openvino/core/shape.hpp>
@@ -53,6 +51,7 @@
#include <openvino/op/unsqueeze.hpp>
#include <openvino/pass/constant_folding.hpp>
#include <openvino/pass/make_stateful.hpp>
+#include <set>
#include <sstream>
#include <unordered_map>
#include <vector>
@@ -325,7 +324,7 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
auto it = m_translator_map.find(operation_type);
FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type,
" is not implemented.");
- NodeContext node_context(decoder, tensor_map, node_idx, this);
+ NodeContext node_context(decoder, tensor_map, node_idx);
ov::OutputVector converted_outputs;
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
converted_outputs = recurrent_fusion.translate(node_idx, node_context);
@@ -451,9 +450,6 @@ std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputMo
used_params.push_back(param);
}
}
- // if (auto diff = params.size() - used_params.size()) {
- // GGML_LOG_INFO("%zu parameters are not used in the model.", diff);
- // }
resulting_model = std::make_shared<Model>(results, used_params);
apply_transformations(resulting_model);
diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp
index 7094cb733..0a5d5b8c0 100644
--- a/ggml/src/ggml-openvino/openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/openvino/utils.cpp
@@ -496,15 +496,37 @@ std::shared_ptr<ov::Node> gather_compressed_rows(const ov::Output<ov::Node> & we
return saw_compressed ? gathered : nullptr;
}
+bool is_pruned_mask_name(const std::string & name) {
+ static const std::string suffix = "_pruned";
+ return name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0;
+}
+
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index) {
- const auto & name = context.get_input_names()[input_index];
+ const auto & input_name = context.get_input_names()[input_index];
+ const bool pruned = is_pruned_mask_name(input_name);
+ const std::string name = pruned ? input_name.substr(0, input_name.size() - std::string("_pruned").size()) : input_name;
const std::string sliced = name == "self_kq_mask_swa" ? "KQ_mask_swa_sliced" :
name == "self_kq_mask" || name == "KQ_mask" ? "KQ_mask_sliced" :
std::string();
+ ov::Output<ov::Node> mask;
if (!sliced.empty() && context.has_input(sliced)) {
- return context.get_input(sliced);
+ mask = context.get_input(sliced);
+ } else if (pruned) {
+ mask = context.get_input(name);
+ } else {
+ return context.get_input(input_index);
+ }
+ if (!pruned) {
+ return mask;
}
- return context.get_input(input_index);
+ // gemma-4's KV-shared layers: the rows of their output tokens, gathered from the input mask (see
+ // ModelParams::pruned_masks)
+ auto ids = std::make_shared<ov::op::v1::Reshape>(context.get_input("inp_prune_ids"),
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false);
+ const auto rank = mask.get_partial_shape().rank();
+ FRONT_END_OP_CONVERSION_CHECK(rank.is_static() && rank.get_length() >= 2, "Expected a static mask rank");
+ auto axis = ov::op::v0::Constant::create(ov::element::i64, {}, {rank.get_length() - 2});
+ return std::make_shared<ov::op::v8::Gather>(mask, ids, axis);
}
ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int input_index) {
diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h
index 3fe3b60f9..499596e6f 100644
--- a/ggml/src/ggml-openvino/openvino/utils.h
+++ b/ggml/src/ggml-openvino/openvino/utils.h
@@ -49,6 +49,9 @@ OutputVector translate_recurrent_cache_reset(const NodeContext & context);
// add_sliced_mask_stateful); any other input, e.g. the mask rows gemma-4 gathers for its KV-shared layers, as is.
ov::Output<ov::Node> get_kq_mask_input(const NodeContext & context, size_t input_index);
+// The mask of gemma-4's KV-shared layers, whose rows get_kq_mask_input() gathers from an input mask
+bool is_pruned_mask_name(const std::string & name);
+
// A stateless KV cache in the [1, ctx, n_heads_kv, head_size] layout (GgmlOvDecoder::is_kvcache_4d), as opposed to
// [1, n_seq, ctx, n_heads_kv * head_size]
inline bool is_kvcache_4d_shape(const ov::PartialShape & shape) {
diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp
index 03479f35e..29f7f4041 100644
--- a/ggml/src/ggml-openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/utils.cpp
@@ -12,16 +12,14 @@
#include "openvino/input_model.h"
#include <algorithm>
-#include <cassert>
+#include <atomic>
#include <cmath>
#include <cstddef>
#include <cstdint>
-#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <functional>
-#include <future>
#include <iomanip>
#include <iostream>
#include <memory>
@@ -200,7 +198,8 @@ std::optional<ov::Tensor> try_make_kv_4d_tensor(const std::shared_ptr<GgmlOvDeco
// Column count of a static KQ mask input; must match GgmlOvDecoder::get_graph_input_shape().
static size_t get_static_attention_size(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & name) {
const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name));
- if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) {
+ if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() :
+ ggml_openvino_npu_decode_bucket() > 0) {
const auto & params = ggml_decoder->get_compute_params();
const int attention_size = is_swa ? params.attention_size_swa : params.attention_size;
if (attention_size > 0) {
@@ -230,6 +229,7 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren
extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u);
extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_hfa_prefill_enabled() ? 4u : 0u); // HFA input ABI v4.
+ extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_host_gather_enabled() ? 1u : 0u);
if (ggml_openvino_is_npu()) {
extra_cfg = extra_cfg * 131 + static_cast<uint64_t>(ggml_openvino_get_npu_requant_type());
}
@@ -459,6 +459,12 @@ static std::string ov_profiling_csv_field(const std::string & value) {
return escaped;
}
+// GGML_OPENVINO_DEBUG_OUTPUT, or GGML_OPENVINO_DEBUG_NODE (its extra outputs)
+static bool debug_output_enabled() {
+ return ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
+ ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE");
+}
+
static void dump_ov_profiling_info(const ov::InferRequest & infer_request) {
if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") < 2) {
return;
@@ -701,13 +707,11 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr<GgmlOvDecoder> & ggml_
if (ggml_tensor->extra != nullptr && !ggml_decoder->is_splited_model()) {
auto * extra_base = static_cast<ggml_openvino_extra_base *>(ggml_tensor->extra);
if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) {
- // GGML_LOG_DEBUG("Using ggml_tensor->extra as ov::Tensor for input: %s\n", name.c_str());
auto * tensor_extra = static_cast<ggml_openvino_tensor_extra *>(extra_base);
return *tensor_extra->tensor;
}
}
- // GGML_LOG_DEBUG("Converting ggml tensor to ov::Tensor for input: %s\n", name.c_str());
auto * input_data = ggml_tensor->data;
ov::Shape input_shape;
if (ggml_tensor->op == GGML_OP_VIEW && !ggml_decoder->is_splited_model()) {
@@ -788,8 +792,31 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_decod
return input_tensor;
}
+// Rows |first|..|first + count| of a host-gathered table (GGML_OPENVINO_NPU_HOST_GATHER), dequantized from the raw
+// ggml table into a [1, 1, padded, row] f32 tensor. Padded rows repeat the last valid row; their outputs are unused.
+static ov::Tensor make_host_rows_tensor(const ggml_tensor * node, size_t first, size_t count, size_t padded) {
+ const ggml_tensor * table = node->src[0];
+ const auto * ids = static_cast<const int32_t *>(node->src[1]->data);
+ const size_t row = table->ne[0];
+ const auto to_float = ggml_get_type_traits(table->type)->to_float;
+ ov::Tensor rows(ov::element::f32, ov::Shape{1, 1, padded, row});
+ auto * dst = rows.data<float>();
+ for (size_t i = 0; i < padded; i++) {
+ const int64_t id = ids[first + std::min(i, count - 1)];
+ to_float(static_cast<const char *>(table->data) + id * table->nb[1], dst + i * row, static_cast<int64_t>(row));
+ }
+ return rows;
+}
+
+// Input of the static decode model for token |row| of the graph: row 0 of a decode graph, or a row of a prefill graph
+// whose outputs a KV-only prefill computes with the decode model (the decoder is then in decode mode, so that the KV
+// cache and the masks bind at full context).
ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder,
- const std::string & param_name) {
+ const std::string & param_name,
+ int64_t row = 0) {
+ if (const auto * node = ggml_decoder->get_host_gather_rows(param_name)) {
+ return make_host_rows_tensor(node, row, 1, 1);
+ }
// NPU decoding stage
if (ggml_decoder->get_model_extra_inputs().count(param_name)) {
return get_ov_input_tensor(ggml_decoder, param_name);
@@ -799,38 +826,49 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder
if (GgmlOvDecoder::is_inp_tok(ggml_tensor, op) || GgmlOvDecoder::is_inp_pos(ggml_tensor, op) ||
GgmlOvDecoder::is_kv_idx(ggml_tensor, op)) {
- // IMROPE's inp_pos holds one value per t/h/w/e plane instead of a single position;
- // with a single decode token the planes are still contiguous, so a flat copy works.
+ // IMROPE's inp_pos holds one plane per t/h/w/e, each as long as the graph has tokens; take the row of each plane.
const int n_planes = GgmlOvDecoder::is_inp_pos(ggml_tensor, op) ? GgmlOvDecoder::get_inp_pos_n_planes(op) : 1;
- assert(ggml_tensor->ne[0] == n_planes);
- ov::Shape input_shape = {1, 1, 1, (size_t) n_planes};
- ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
- std::memcpy(input_tensor.data(), ggml_tensor->data, n_planes * ggml_type_size(ggml_tensor->type));
+ const int64_t n_rows = ggml_tensor->ne[0] / n_planes;
+ const size_t element_size = ggml_type_size(ggml_tensor->type);
+ ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), ov::Shape{1, 1, 1, (size_t) n_planes});
+ for (int p = 0; p < n_planes; p++) {
+ std::memcpy(static_cast<char *>(input_tensor.data()) + p * element_size,
+ static_cast<const char *>(ggml_tensor->data) + (p * n_rows + row) * element_size, element_size);
+ }
return input_tensor;
}
if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
- ov::Shape input_shape = {1, 1, 1, 1};
- ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
- // The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read.
+ // The decode model computes the outputs of its one token. out_ids is empty when the graph has no output, so it
+ // is not read.
+ ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), ov::Shape{1, 1, 1, 1});
*input_tensor.data<int32_t>() = 0;
return input_tensor;
}
+ if (GgmlOvDecoder::is_inp_scale_rows(ggml_tensor, op) && ggml_nelements(ggml_tensor) > 1) {
+ // One scale per token of the graph.
+ ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, 1, 1});
+ *input_tensor.data<float>() = static_cast<const float *>(ggml_tensor->data)[row];
+ return input_tensor;
+ }
+
if (GgmlOvDecoder::is_inp_mask(ggml_tensor, op)) {
- size_t context_size = get_static_attention_size(ggml_decoder, param_name);
+ const size_t context_size = get_static_attention_size(ggml_decoder, param_name);
+ const size_t cols = ggml_tensor->ne[0];
if (ggml_tensor->type == GGML_TYPE_F16) {
+ const auto * src = static_cast<const ggml_fp16_t *>(ggml_tensor->data) + row * cols;
std::vector<ggml_fp16_t> padded_data =
- pad_input<ggml_fp16_t>(ggml_tensor, 1, context_size, GGML_FP32_TO_FP16(-INFINITY));
+ pad_input<ggml_fp16_t>(src, 1, cols, 1, context_size, GGML_FP32_TO_FP16(-INFINITY));
ov::Tensor input_tensor(ov::element::f16, ov::Shape{1, 1, 1, context_size});
std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(ggml_fp16_t));
return input_tensor;
}
- std::vector<float> padded_data = pad_input<float>(ggml_tensor, 1, context_size, -INFINITY);
+ const auto * src = static_cast<const float *>(ggml_tensor->data) + row * cols;
+ std::vector<float> padded_data = pad_input<float>(src, 1, cols, 1, context_size, -INFINITY);
ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, 1, context_size});
- auto * data_ptr = input_tensor.data<float>();
- std::copy(padded_data.begin(), padded_data.begin() + context_size, data_ptr);
+ std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(float));
return input_tensor;
}
@@ -908,6 +946,9 @@ ov::Tensor get_ov_input_tensor_static_prefill(const std::shared_ptr<GgmlOvDecode
}
return input_tensor;
}
+ if (const auto * node = ggml_decoder->get_host_gather_rows(param_name)) {
+ return make_host_rows_tensor(node, chunk_index * chunk_size, chunk_valid_size, chunk_size);
+ }
if (chunk_index > 0 && param_name == "cache_rs_reset_len") {
// The recurrent-state clear belongs to the start of the sequence. Re-applying it on every
// chunk would wipe the state accumulated by the preceding chunks, so disable it (a zero
@@ -1127,8 +1168,7 @@ enum ggml_status naive_compute(ggml_cgraph * cgraph,
auto model_output_it = model_outputs.find(output_names[i]);
if (model_output_it == model_outputs.end()) {
// Debug-only output added via GGML_OPENVINO_DEBUG_NODE; nothing to copy into.
- if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
- ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
+ if (debug_output_enabled()) {
print_output_tensor_info(output_names[i], output_tensor, nullptr);
}
continue;
@@ -1200,7 +1240,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
auto & core = ov_singleton_core();
const auto & config = ggml_openvino_get_compile_config();
const auto & device = r_ctx->device;
- static auto is_static = false;
+ constexpr bool is_static = false;
static const bool cache_disabled = ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE");
@@ -1875,8 +1915,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
}
dump_ov_profiling_info(*infer_request);
- if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
- ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
+ if (debug_output_enabled()) {
for (size_t i = 0; i < ov_output_names.size(); i++) {
const auto output_tensor = infer_request->get_output_tensor(i);
print_output_tensor_info(ov_output_names[i], output_tensor, nullptr);
@@ -1944,43 +1983,12 @@ struct static_build_args {
long long dump_ir_timestamp;
std::string model_cache_dir;
ggml_cgraph * cgraph;
- bool self_contained;
- bool skip_weights;
- // GGML_OPENVINO_NPU_WEIGHTLESS_BANK: weightless blob whose weights live in weights_path.
- bool weightless_bank = false;
+ // NPU with GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR: weightless blob whose weights live in weights_path.
+ bool weightless_bank;
+ bool skip_weights;
std::string weights_path;
};
-// Cached blobs imported in this process, keyed by fingerprint, so a pair or window switch reuses them. Self-contained
-// models compiled in this process are kept here too. Cleared with the shared compiled-model cache when the last
-// backend is freed.
-static std::mutex g_imported_blobs_mutex;
-static std::unordered_map<uint64_t, ov::CompiledModel> g_imported_blobs;
-
-static ov::CompiledModel import_cached_blob(ov::Core & core,
- const std::string & device,
- const std::string & blob_path,
- uint64_t fp,
- const ov::AnyMap & import_config,
- const char * tag) {
- {
- std::lock_guard<std::mutex> lock(g_imported_blobs_mutex);
- auto it = g_imported_blobs.find(fp);
- if (it != g_imported_blobs.end()) {
- return it->second;
- }
- }
- std::ifstream blob_in(blob_path, std::ios::binary);
- const int64_t import_start_time = ggml_time_us();
- ov::CompiledModel compiled = core.import_model(blob_in, device, import_config);
- if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
- fprintf(stderr, "ggml-openvino: model cache IMPORT %s: %.3f ms\n", tag,
- (ggml_time_us() - import_start_time) / 1000.0);
- }
- std::lock_guard<std::mutex> lock(g_imported_blobs_mutex);
- return g_imported_blobs.emplace(fp, std::move(compiled)).first->second;
-}
-
static std::shared_ptr<ov::Model> convert_static_model(const static_build_args & a,
const std::shared_ptr<GgmlOvDecoder> & decoder,
const char * tag,
@@ -2008,7 +2016,6 @@ static void build_static_model(const static_build_args & a,
const ov::AnyMap & model_config,
uint64_t model_fp,
ov::CompiledModel & compiled_model,
- std::shared_ptr<ov::InferRequest> & infer_request,
std::vector<std::string> & names_in,
std::vector<std::string> & names_out,
int64_t & local_conversion_end_time,
@@ -2027,77 +2034,66 @@ static void build_static_model(const static_build_args & a,
if (a.skip_weights) {
try {
ov::AnyMap import_config = model_config;
- if (a.weightless_bank) {
- import_config[ov::weights_path.name()] = a.weights_path;
- import_config[ov::enable_weightless.name()] = true;
+ import_config[ov::weights_path.name()] = a.weights_path;
+ import_config[ov::enable_weightless.name()] = true;
+ std::ifstream blob_in(blob_path, std::ios::binary);
+ const int64_t import_start_time = ggml_time_us();
+ compiled_model = core.import_model(blob_in, device, import_config);
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
+ fprintf(stderr, "ggml-openvino: model cache IMPORT %s: %.3f ms\n", tag,
+ (ggml_time_us() - import_start_time) / 1000.0);
}
- compiled_model = import_cached_blob(core, device, blob_path, model_fp, import_config, tag);
} catch (const std::exception & e) {
std::remove(blob_path.c_str());
std::remove(manifest_path.c_str());
- throw std::runtime_error(std::string(a.weightless_bank ? "weightless-bank" : "self-contained") +
- " cache import failed for " + std::string(tag) +
+ throw std::runtime_error("weightless-bank cache import failed for " + std::string(tag) +
"; removed the invalid entry, rerun to rebuild it: " + e.what());
}
- infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
std::set<std::string> compiled_input_names;
for (const auto & input : compiled_model.inputs()) {
compiled_input_names.insert(input.get_node()->get_friendly_name());
}
+ // The frontend drops inputs nothing reads: HFA prefill, KV-only prefill (out_ids) and host gather (token
+ // ids) can leave decoder inputs out of the compiled model. Keep the decoder order.
for (const auto & [name, _] : decoder->get_model_inputs()) {
- if (!ggml_openvino_npu_hfa_prefill_enabled() || std::string(tag) != "prefill" ||
- compiled_input_names.count(name) != 0) {
+ if (compiled_input_names.count(name) != 0) {
names_in.push_back(name);
}
}
for (const auto & [name, info] : decoder->get_model_extra_inputs()) {
- if (info.is_parameter) {
+ if (info.is_parameter && compiled_input_names.count(name) != 0) {
names_in.push_back(name);
}
}
- for (const auto & name : decoder->get_model_output_names()) {
+ // A KV-only prefill model keeps only the cache outputs (pass::KeepCacheResults), in decoder order.
+ for (const auto & name : decoder->is_kv_only_outputs() ? decoder->get_cache_output_names() :
+ decoder->get_model_output_names()) {
names_out.push_back(name);
}
if (names_in.size() != compiled_model.inputs().size() || names_out.size() != compiled_model.outputs().size()) {
- throw std::runtime_error(
- "self-contained cache port count mismatch for " + std::string(tag) +
- ": decoder inputs=" + std::to_string(names_in.size()) +
- ", compiled inputs=" + std::to_string(compiled_model.inputs().size()) +
- ", decoder outputs=" + std::to_string(names_out.size()) +
- ", compiled outputs=" + std::to_string(compiled_model.outputs().size()));
+ throw std::runtime_error("weightless-bank cache port count mismatch for " + std::string(tag) +
+ ": decoder inputs=" + std::to_string(names_in.size()) +
+ ", compiled inputs=" + std::to_string(compiled_model.inputs().size()) +
+ ", decoder outputs=" + std::to_string(names_out.size()) +
+ ", compiled outputs=" + std::to_string(compiled_model.outputs().size()));
}
decoder->clear_model_weights();
local_conversion_end_time = local_compile_end_time = ggml_time_us();
- GGML_LOG_INFO("ggml-openvino: model cache HIT (%s) %s (%s)\n",
- a.weightless_bank ? "weightless bank" : "self-contained", blob_path.c_str(), tag);
+ GGML_LOG_INFO("ggml-openvino: model cache HIT (weightless bank) %s (%s)\n", blob_path.c_str(), tag);
return;
}
bool imported = false;
- // A self-contained blob embeds its weights bank, and NPUW cannot load a blob into a bank that already holds
- // weights. Pairs that differ only in the prefill model share the decode model and its bank, so build each model
- // once per process.
- const bool keep_in_process = a.self_contained && !a.weightless_bank && model_fp != 0;
- if (keep_in_process) {
- std::lock_guard<std::mutex> lock(g_imported_blobs_mutex);
- auto it = g_imported_blobs.find(model_fp);
- if (it != g_imported_blobs.end()) {
- compiled_model = it->second;
- imported = true;
- }
- }
// A weightless-bank blob is only valid with the weights file it was exported with, which is rewritten whenever
// the blob is rebuilt, so never import a leftover blob here.
- if (!imported && !model_cache_dir.empty() && model_fp != 0 && !a.weightless_bank) {
+ if (!model_cache_dir.empty() && model_fp != 0 && !a.weightless_bank) {
std::ifstream blob_in(blob_path, std::ios::binary);
std::vector<std::string> cached_inputs, cached_outputs;
if (blob_in.is_open() &&
ggml_openvino_model_cache_verify_manifest(manifest_path, cgraph, model_fp, cached_inputs, cached_outputs)) {
try {
ov::AnyMap import_config = model_config;
- if (!a.self_contained) {
- import_config[ov::hint::model.name()] = std::shared_ptr<const ov::Model>(model);
- }
+ import_config[ov::hint::model.name()] = std::shared_ptr<const ov::Model>(model);
const int64_t import_start_time = ggml_time_us();
compiled_model = core.import_model(blob_in, device, import_config);
const int64_t import_end_time = ggml_time_us();
@@ -2116,16 +2112,11 @@ static void build_static_model(const static_build_args & a,
if (!imported) {
ov::AnyMap compile_config = model_config;
- if (a.self_contained) {
- compile_config[ov::enable_weightless.name()] = a.weightless_bank;
+ if (a.weightless_bank) {
+ compile_config[ov::enable_weightless.name()] = true;
}
compiled_model = core.compile_model(model, device, compile_config);
}
- if (keep_in_process) {
- std::lock_guard<std::mutex> lock(g_imported_blobs_mutex);
- g_imported_blobs.emplace(model_fp, compiled_model);
- }
- infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
local_compile_end_time = ggml_time_us();
for (const auto & ov_param : model->get_parameters()) {
@@ -2140,11 +2131,10 @@ static void build_static_model(const static_build_args & a,
const std::string blob_tmp = blob_path + ".tmp";
const std::string manifest_tmp = manifest_path + ".tmp";
const std::string source_manifest_tmp = manifest_path + ".source.tmp";
- const bool manifest_ready =
- a.self_contained ?
- std::ifstream(source_manifest_tmp).good() :
- ggml_openvino_model_cache_write_manifest(manifest_tmp, cgraph, model_fp, names_in, names_out);
- const std::string & manifest_publish = a.self_contained ? source_manifest_tmp : manifest_tmp;
+ const bool manifest_ready = a.weightless_bank ? std::ifstream(source_manifest_tmp).good() :
+ ggml_openvino_model_cache_write_manifest(
+ manifest_tmp, cgraph, model_fp, names_in, names_out);
+ const std::string & manifest_publish = a.weightless_bank ? source_manifest_tmp : manifest_tmp;
if (manifest_ready) {
std::ofstream blob_out(blob_tmp, std::ios::binary | std::ios::trunc);
if (blob_out.is_open()) {
@@ -2172,6 +2162,374 @@ static void build_static_model(const static_build_args & a,
}
}
+// A layer that reuses the KV cache of an earlier layer (Gemma 3n/4 E-series) reads a KV cache tensor that another
+// attention op also reads. Every other layer reads its own cache, whichever caches it writes (MLA has no V cache).
+static bool has_kv_shared_attention(const ggml_cgraph * cgraph) {
+ std::unordered_map<const ggml_tensor *, int> readers;
+ for (int i = 0; i < cgraph->n_nodes; i++) {
+ const ggml_tensor * node = cgraph->nodes[i];
+ if (node->op != GGML_OP_FLASH_ATTN_EXT || node->src[1] == nullptr) {
+ continue;
+ }
+ const ggml_tensor * k = node->src[1];
+ while (k->view_src != nullptr) {
+ k = k->view_src;
+ }
+ if (GgmlOvDecoder::is_kvcache(k, nullptr) && ++readers[k] > 1) {
+ return true;
+ }
+ }
+ return false;
+}
+
+// The output step runs a token of the batch through the decode model again. That rewrites the token's KV rows with the
+// same values, but would apply a recurrent state update twice.
+static bool has_recurrent_state(const ggml_cgraph * cgraph) {
+ for (int i = 0; i < cgraph->n_nodes; i++) {
+ const ggml_tensor * node = cgraph->nodes[i];
+ if (GgmlOvDecoder::is_recurrent_cache(node->view_src)) {
+ return true;
+ }
+ for (int j = 0; j < GGML_MAX_SRC; j++) {
+ if (GgmlOvDecoder::is_recurrent_cache(node->src[j])) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// Set when a KV-only prefill could not compute the outputs of a batch; later graphs use the full prefill.
+static std::atomic<bool> g_kv_only_prefill_failed{false};
+
+// What a static graph call builds its compiled models with. A model takes the call's compute params with the
+// attention sizes and output count of its key.
+struct static_graph_args {
+ ov::Core & core;
+ const std::string & device;
+ ggml_cgraph * cgraph;
+ const ModelParams & m_params;
+ const ComputeParams & c_params;
+ int chunk;
+ int decode_bucket;
+ const ov::AnyMap & compile_config;
+ std::string model_cache_dir;
+ // NPU with a model cache: weightless blobs sharing one weights file.
+ bool weightless_bank;
+ // GGML_OPENVINO_SELF_CONTAINED_MMAP: import every model, never compile.
+ bool self_contained_mmap;
+ bool no_kv_cache;
+ bool dump_ir;
+ long long dump_ir_timestamp;
+};
+
+struct static_converted {
+ std::shared_ptr<GgmlOvDecoder> decoder;
+ std::shared_ptr<ov::Model> model;
+ int64_t t_conv = 0;
+};
+
+// KV windows base*2^k below the context, then the context.
+static std::vector<int> static_kv_windows(int ctx, int base) {
+ if (base <= 0 || ctx <= 0) {
+ return {ctx};
+ }
+ std::vector<int> windows;
+ for (int window = base;; window *= 2) {
+ window = std::min(window, ctx);
+ windows.push_back(window);
+ if (window >= ctx) {
+ break;
+ }
+ }
+ return windows;
+}
+
+// Every compiled model a phase of the graph can run: a prefill model per sliced KV window, a decode model per decode
+// KV window (GGML_OPENVINO_NPU_BLOB_PREBUILD), otherwise one model of the full context.
+static std::vector<ov_static_variant_key> static_variant_keys(const static_graph_args & a, bool prefill) {
+ const int ctx = a.m_params.ctx_per_seq;
+ std::vector<int> windows;
+ if (prefill) {
+ windows = ggml_openvino_kv_slice_enabled() && !a.m_params.is_cacheless_attn ?
+ static_kv_windows(ctx, ggml_openvino_kv_slice_base()) :
+ std::vector<int>{a.c_params.attention_size};
+ } else {
+ windows = a.decode_bucket > 0 ? static_kv_windows(ctx, a.decode_bucket) : std::vector<int>{ctx};
+ }
+ std::vector<ov_static_variant_key> keys;
+ for (const int window : windows) {
+ keys.push_back({prefill, window, a.c_params.attention_size_swa, prefill ? a.c_params.output_len : 1});
+ }
+ return keys;
+}
+
+// Fingerprint salt of every compiled model of a static graph. It names the cached blobs: keep the formula.
+static uint64_t static_cache_base_extra(bool weightless_bank, bool kv_only_prefill) {
+ uint64_t base_extra = ggml_openvino_model_cache_extra_cfg(/*stateful=*/false, /*recurrent=*/false);
+ base_extra = base_extra * 131 + (weightless_bank ? 3u : 0u);
+ base_extra = ggml_openvino_model_cache_mix_string(base_extra,
+ ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT"));
+ // KV slice window base; the default base (1024) keeps the fingerprint of the former on/off flag.
+ const int kv_slice_base = ggml_openvino_kv_slice_base();
+ base_extra = base_extra * 131 + static_cast<uint64_t>(kv_slice_base == 1024 ? 1 : kv_slice_base);
+ base_extra = base_extra * 131 + (ggml_openvino_npu_kv_head_major_enabled() ? 1u : 0u);
+ base_extra = base_extra * 131 + (kv_only_prefill ? 1u : 0u);
+ for (const char * name : {"GGML_OPENVINO_NPU_CONFIG", "GGML_OPENVINO_NPU_COMPILE_CONFIG",
+ "GGML_OPENVINO_NPU_COMPILER_TYPE", "GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL",
+ "GGML_OPENVINO_NPUW_UNFOLD_IREQS", "GGML_OPENVINO_COMPILATION_NUM_THREADS"}) {
+ base_extra = ggml_openvino_model_cache_mix_string(base_extra, ggml_openvino_getenv_str(name));
+ }
+ return base_extra;
+}
+
+static uint64_t static_variant_fp(const static_graph_args & a,
+ const decoder_runtime_ctx & e,
+ const ov_static_variant_key & k) {
+ // out_ids is bound at a fixed length, so the output count is part of the static shape
+ return ggml_openvino_model_fingerprint(a.cgraph, a.device, true, a.m_params.rope_params, 16,
+ static_model_salt(e.cache_base_extra, k.prefill, a.chunk, k.attention_size,
+ k.attention_size_swa, !k.prefill && e.decode_unfold),
+ "static-1 out=" + std::to_string(k.output_len));
+}
+
+// The weights file and NPUW bank of a graph's blobs: one per model, or the graph's own when its weights differ from
+// the model file (static_layout_weights). NPUW matches weights by the LazyTensor hash recorded at compile time and
+// keeps one resident copy per bank.
+static void static_select_weights(const static_graph_args & a, decoder_runtime_ctx & e, bool own) {
+ char bank[96];
+ if (own) {
+ const uint64_t prefill_fp = static_variant_fp(a, e, static_variant_keys(a, true).front());
+ const uint64_t decode_fp = static_variant_fp(a, e, static_variant_keys(a, false).front());
+ snprintf(bank, sizeof(bank), "ggml-wl-shared-%016llx-%016llx", static_cast<unsigned long long>(prefill_fp),
+ static_cast<unsigned long long>(decode_fp));
+ e.weights_path = ggml_openvino_model_cache_weights_path(a.model_cache_dir, prefill_fp, decode_fp);
+ } else {
+ const uint64_t weights_fp = ggml_openvino_model_fingerprint(a.cgraph, a.device, true, a.m_params.rope_params,
+ 16, e.cache_base_extra, "weights");
+ snprintf(bank, sizeof(bank), "ggml-wl-model-%016llx", static_cast<unsigned long long>(weights_fp));
+ e.weights_path = ggml_openvino_model_cache_weights_path(a.model_cache_dir, weights_fp, weights_fp);
+ }
+ e.weights_bank = bank;
+}
+
+// A cached blob is usable if its manifest matches the graph and, for a weightless blob, its weights file is complete
+// and not newer than the blob (a rewritten file invalidates the blobs exported against the former one).
+static bool static_blob_usable(const static_graph_args & a, const decoder_runtime_ctx & e, uint64_t fp) {
+ if (!static_blob_valid(a.model_cache_dir, fp, a.cgraph)) {
+ return false;
+ }
+ if (!a.weightless_bank) {
+ return true;
+ }
+ std::error_code ec1, ec2;
+ const auto blob_time = std::filesystem::last_write_time(
+ std::filesystem::u8path(ggml_openvino_model_cache_blob_path(a.model_cache_dir, fp)), ec1);
+ const auto weights_time = std::filesystem::last_write_time(std::filesystem::u8path(e.weights_path), ec2);
+ return !ec1 && !ec2 && blob_time >= weights_time && ggml_openvino_model_cache_weights_valid(e.weights_path);
+}
+
+static static_build_args static_build_args_of(const static_graph_args & a,
+ const decoder_runtime_ctx & e,
+ bool skip_weights) {
+ return {&a.core, a.device, a.dump_ir, a.dump_ir_timestamp, a.model_cache_dir,
+ a.cgraph, a.weightless_bank, skip_weights, e.weights_path};
+}
+
+static std::shared_ptr<GgmlOvDecoder> static_build_decoder(const static_graph_args & a,
+ const decoder_runtime_ctx & e,
+ const ov_static_variant_key & k,
+ bool with_weights) {
+ auto weights = with_weights ? GgmlOvDecoder::create_weight_nodes(a.cgraph) : get_weight_names(a.cgraph);
+ auto m_params = a.m_params;
+ auto c_params = a.c_params;
+ c_params.attention_size = k.attention_size;
+ c_params.attention_size_swa = k.attention_size_swa;
+ c_params.output_len = k.output_len;
+ auto decoder = std::make_shared<GgmlOvDecoder>(a.cgraph, m_params, c_params, weights, /*is_static=*/true,
+ /*stateful=*/false, false, k.prefill, a.chunk);
+ decoder->set_kv_only_outputs(k.prefill && e.kv_only_prefill);
+ decoder->device = a.device;
+ return decoder;
+}
+
+static ov::AnyMap static_variant_config(const static_graph_args & a,
+ const decoder_runtime_ctx & e,
+ const GgmlOvDecoder & decoder,
+ bool prefill) {
+ ov::AnyMap config = prefill ? ggml_openvino_npu_prefill_config(a.compile_config, decoder) :
+ ggml_openvino_npu_decode_config(a.compile_config, a.device);
+ if (!a.model_cache_dir.empty()) {
+ config.erase("CACHE_DIR");
+ config.erase("CACHE_MODE");
+ }
+ if (a.weightless_bank) {
+ config["NPUW_WEIGHTS_BANK"] = e.weights_bank;
+ }
+ return config;
+}
+
+static void static_convert(const static_graph_args & a,
+ const decoder_runtime_ctx & e,
+ const ov_static_variant_key & k,
+ static_converted & c) {
+ c.decoder = static_build_decoder(a, e, k, /*with_weights=*/true);
+ c.model =
+ convert_static_model(static_build_args_of(a, e, false), c.decoder, k.prefill ? "prefill" : "decode", c.t_conv);
+ if (e.weights_layout) {
+ // weights outside the file (none for a model of the same graph) are embedded in the blob
+ ggml_openvino_model_cache_retag_weights(c.model, *e.weights_layout);
+ }
+}
+
+// Lays the graph's weights out in its weights file before the first compile, reusing a valid file of the same
+// weights. The layout comes from the first prefill and decode models, converted here and returned for compiling.
+// |rewritten|: the file was (re)written, so none of its former blobs is usable.
+static std::map<ov_static_variant_key, static_converted> static_layout_weights(const static_graph_args & a,
+ decoder_runtime_ctx & e,
+ bool & rewritten) {
+ std::map<ov_static_variant_key, static_converted> converted;
+ std::vector<std::shared_ptr<ov::Model>> models;
+ for (const bool prefill : {true, false}) {
+ if (!prefill && a.no_kv_cache) {
+ continue;
+ }
+ const auto k = static_variant_keys(a, prefill).front();
+ auto & c = converted[k];
+ static_convert(a, e, k, c);
+ models.push_back(c.model);
+ }
+ auto status = ggml_openvino_weights_status::written;
+ e.weights_layout = ggml_openvino_model_cache_write_weights(e.weights_path, models, /*keep_existing=*/true, &status);
+ if (status == ggml_openvino_weights_status::mismatch) {
+ GGML_LOG_WARN("ggml-openvino: weights differ from %s, using a per-graph weights file\n",
+ e.weights_path.c_str());
+ static_select_weights(a, e, /*own=*/true);
+ ggml_openvino_model_cache_remove_weights(e.weights_path);
+ e.weights_layout = ggml_openvino_model_cache_write_weights(e.weights_path, models);
+ }
+ if (!e.weights_layout) {
+ // E.g. a full disk. The models still compile and run, without a cached blob.
+ GGML_LOG_WARN("ggml-openvino: could not write the NPU weights file %s; not caching this graph\n",
+ e.weights_path.c_str());
+ }
+ rewritten = status != ggml_openvino_weights_status::reused;
+ return converted;
+}
+
+// Loads the models |keys| of a static graph: imports each usable cached blob, converts and compiles (and exports) the
+// others. Every decode model stays loaded, as a growing sequence switches between them; another prefill model than
+// |needed| is only exported, and imported on first use, unless every model is imported (self-contained mmap) or the
+// prompt length picks the prefill KV window (head-major KV), where a prompt would otherwise import one mid-request.
+// Caller holds the compile mutex.
+static void static_load_variants(const static_graph_args & a,
+ decoder_runtime_ctx & e,
+ const std::vector<ov_static_variant_key> & keys,
+ const ov_static_variant_key & needed) {
+ struct pending_model {
+ ov_static_variant_key key;
+ uint64_t fp;
+ bool import;
+ static_converted conv;
+ };
+
+ const bool keep_all = a.self_contained_mmap || ggml_openvino_npu_kv_head_major_enabled();
+ auto keep = [&](const ov_static_variant_key & k) {
+ return keep_all || !k.prefill || k == needed;
+ };
+ std::vector<pending_model> pending;
+ for (const auto & k : keys) {
+ if (e.variants.count(k) != 0) {
+ continue;
+ }
+ const uint64_t fp = a.model_cache_dir.empty() ? 0 : static_variant_fp(a, e, k);
+ const bool import = a.weightless_bank && static_blob_usable(a, e, fp);
+ if (!import && a.self_contained_mmap) {
+ throw std::runtime_error("GGML_OPENVINO_SELF_CONTAINED_MMAP: no usable cached " +
+ std::string(k.prefill ? "prefill" : "decode") + " model of KV window " +
+ std::to_string(k.attention_size) + " in " + a.model_cache_dir +
+ "; run once with GGML_OPENVINO_SELF_CONTAINED_MMAP=0 to build the cache");
+ }
+ if (!import || keep(k)) {
+ pending.push_back({k, fp, import, {}});
+ }
+ }
+ const size_t n_compile = std::count_if(pending.begin(), pending.end(), [](const auto & p) { return !p.import; });
+ if (n_compile != 0) {
+ // Same fail-fast as the dynamic path: once the host weight pages have been dropped they read as zeros, so a
+ // compile here would bake garbage into the new model.
+ if (ggml_openvino_weight_buffers_released()) {
+ throw std::runtime_error("ggml-openvino: cannot compile a new graph after releasing host weights");
+ }
+ std::map<ov_static_variant_key, static_converted> converted;
+ if (a.weightless_bank && !e.weights_layout) {
+ bool rewritten = false;
+ converted = static_layout_weights(a, e, rewritten);
+ if (rewritten) {
+ pending.clear();
+ for (const auto & k : keys) {
+ if (e.variants.count(k) == 0) {
+ pending.push_back({k, static_variant_fp(a, e, k), false, {}});
+ }
+ }
+ }
+ }
+ if (a.weightless_bank) {
+ GGML_LOG_WARN(
+ "ggml-openvino: no usable cached blobs in %s for %zu model(s); compiling and exporting them "
+ "as weightless-bank blobs\n",
+ a.model_cache_dir.c_str(),
+ static_cast<size_t>(
+ std::count_if(pending.begin(), pending.end(), [](const auto & p) { return !p.import; })));
+ }
+ // Convert the first prefill and decode models before compiling either: a decode model converted after the
+ // prefill compile gives wrong output on some NPU models (Bonsai-8B).
+ bool prefill_converted = false;
+ bool decode_converted = false;
+ for (auto & p : pending) {
+ bool & done = p.key.prefill ? prefill_converted : decode_converted;
+ if (p.import || done) {
+ continue;
+ }
+ auto it = converted.find(p.key);
+ if (it != converted.end()) {
+ p.conv = std::move(it->second);
+ } else {
+ static_convert(a, e, p.key, p.conv);
+ }
+ done = true;
+ }
+ }
+
+ for (auto & p : pending) {
+ const char * tag = p.key.prefill ? "prefill" : "decode";
+ // Without a weights file (it could not be written), compile without caching.
+ const uint64_t fp = a.weightless_bank && !p.import && !e.weights_layout ? 0 : p.fp;
+ if (!p.import && !p.conv.model) {
+ static_convert(a, e, p.key, p.conv);
+ }
+ if (!p.conv.decoder) {
+ p.conv.decoder = static_build_decoder(a, e, p.key, /*with_weights=*/false);
+ }
+ if (!p.import && a.weightless_bank && fp != 0) {
+ ggml_openvino_model_cache_write_manifest(
+ ggml_openvino_model_cache_manifest_path(a.model_cache_dir, fp) + ".source.tmp", a.cgraph, fp, {}, {});
+ }
+ const int64_t t0 = ggml_time_us();
+ ov_static_variant v;
+ int64_t t_compile = 0;
+ build_static_model(static_build_args_of(a, e, p.import), p.conv.decoder, tag, std::move(p.conv.model),
+ static_variant_config(a, e, *p.conv.decoder, p.key.prefill), fp, v.model, v.input_names,
+ v.output_names, p.conv.t_conv, t_compile);
+ GGML_LOG_INFO("ggml-openvino: %s model of KV window %d %s in %.1f ms\n", tag, p.key.attention_size,
+ p.import ? "imported" : "compiled", (ggml_time_us() - t0) / 1000.0);
+ p.conv = {};
+ if (keep(p.key)) {
+ e.variants.emplace(p.key, std::move(v));
+ }
+ }
+}
+
enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared_ptr<ov_runtime_context> & r_ctx) {
auto & core = ov_singleton_core();
@@ -2186,8 +2544,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
// Normally NPU, but honors GGML_OPENVINO_DEVICE so GGML_OPENVINO_FORCE_STATIC can run the
// static-shape path on CPU/GPU to isolate translation bugs from NPUW/NPU-driver issues.
const auto & device = r_ctx->device;
- static auto is_static = true;
- static auto stateful = false;
+ constexpr bool is_static = true;
+ constexpr bool stateful = false;
auto prefill_chunk_size = get_prefill_chunk_size();
const auto & config = ggml_openvino_get_compile_config();
@@ -2215,6 +2573,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
const ov::AnyMap compile_config = no_kv_cache ? ggml_openvino_npu_without_npuw(config) :
m_params.state_size >= 0 ? ggml_openvino_npu_gdn_config(config) :
config;
+ // Decided by the first call of a graph; later calls follow entry->kv_only_prefill.
+ // The output step runs the decode model of the KV window covering the output token (the full context without
+ // decode KV windows).
+ const bool kv_only_prefill = !no_kv_cache && ggml_openvino_kv_only_prefill_enabled() && !g_kv_only_prefill_failed &&
+ !ggml_openvino_npu_hfa_prefill_enabled() && c_params.output_len <= 1 &&
+ has_kv_shared_attention(cgraph) && !has_recurrent_state(cgraph);
if (m_params.n_heads_kv == -1) {
prefill_chunk_size = inp_pos->ne[0];
}
@@ -2223,11 +2587,13 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
bool cache_hit = false;
// Decode KV window: smallest base*2^k covering the next decode position, clamped to ctx. Prefill
- // calls pick the window the decode model of the compiled pair is built with.
+ // calls pick the decode model their KV-only output step runs.
const int decode_bucket = (!no_kv_cache && cache_enabled && inp_pos != nullptr && inp_pos->type == GGML_TYPE_I32) ?
ggml_openvino_npu_decode_bucket() :
0;
int decode_window = m_params.ctx_per_seq;
+ // With decode KV windows and sliced (not head-major) KV, prefill sizes follow the decode KV windows.
+ const bool prefill_window_aligned = decode_bucket > 0 && !ggml_openvino_npu_kv_head_major_enabled();
if (decode_bucket > 0 && m_params.ctx_per_seq > 0) {
const int last_pos = static_cast<const int32_t *>(inp_pos->data)[std::max<int64_t>(input_tokens, 1) - 1];
const int needed = last_pos + (is_prefill ? 2 : 1);
@@ -2240,6 +2606,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
// Head-major KV is bound whole, so prefill and decode both use the window of the storage capacity.
decode_window = std::min(std::max(decode_window, kv_storage_rows(cgraph)), m_params.ctx_per_seq);
c_params.attention_size = decode_window;
+ } else if (is_prefill && prefill_window_aligned && c_params.attention_size > 0) {
+ // A prefill attends at least the decode KV window, so the prefill sizes are the window sizes and the
+ // weightless-bank export can build them all up front.
+ c_params.attention_size = std::min(std::max(c_params.attention_size, decode_window), m_params.ctx_per_seq);
}
if (!is_prefill) {
c_params.attention_size = decode_window;
@@ -2254,758 +2624,166 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
int64_t ov_raw_infer_total = 0;
std::shared_ptr<decoder_runtime_ctx> entry;
- ModelParams old_m_params;
-
if (cache_enabled) {
std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
auto it = r_ctx->decoder_cache.find(key);
- cache_hit = it != r_ctx->decoder_cache.end();
- if (cache_hit) {
+ if (it != r_ctx->decoder_cache.end()) {
entry = it->second;
r_ctx->touch_locked(key);
} else {
- auto mutex = std::make_shared<std::mutex>();
- entry = std::make_shared<decoder_runtime_ctx>(mutex);
+ entry = std::make_shared<decoder_runtime_ctx>(std::make_shared<std::mutex>());
r_ctx->decoder_cache[key] = entry;
r_ctx->admit_locked(key);
}
} else {
- auto mutex = std::make_shared<std::mutex>();
- entry = std::make_shared<decoder_runtime_ctx>(mutex);
- cache_hit = false;
+ entry = std::make_shared<decoder_runtime_ctx>(std::make_shared<std::mutex>());
}
std::lock_guard<std::mutex> lock(*(entry->mutex));
- cache_hit = cache_hit && entry->ptr;
- if (cache_hit) {
- cache_hit = r_ctx->infer_request_cache.count(key) != 0 &&
- r_ctx->infer_request_cache_prefill.count(key) != 0;
- }
-
- // Same model, only the prefill attention size differs from the entry's pair.
- bool prefill_size_changed = false;
- if (cache_hit) {
- ggml_decoder = entry->ptr;
- old_m_params = ggml_decoder->get_model_params();
- cache_hit = old_m_params.can_reuse_statically(m_params);
- if (cache_hit && is_prefill && ggml_openvino_kv_slice_enabled()) {
- // A larger compiled prefill also serves a smaller attended length: the extra KV rows are masked, as with
- // the power-of-two rounding. Without this, a new prompt walks up the sizes again, and since only one
- // prefill model is kept, every prompt longer than one chunk recompiles. Head-major KV is bound at the
- // storage size, so it keeps the exact match.
- // The output count is part of the static prefill shape (more than 1 only for llama-perplexity).
- const bool reuse_larger = !ggml_openvino_npu_kv_head_major_enabled();
- cache_hit = entry->prefill_output_len == c_params.output_len &&
- (reuse_larger ? entry->prefill_attention_size >= c_params.attention_size &&
- entry->prefill_attention_size_swa >= c_params.attention_size_swa :
- entry->prefill_attention_size == c_params.attention_size &&
- entry->prefill_attention_size_swa == c_params.attention_size_swa);
- if (cache_hit) {
- c_params.attention_size = entry->prefill_attention_size;
- c_params.attention_size_swa = entry->prefill_attention_size_swa;
+ ModelParams old_m_params;
+ if (entry->ptr) {
+ old_m_params = entry->ptr->get_model_params();
+ if (!old_m_params.can_reuse_statically(m_params)) {
+ // Another model with the same graph: none of the compiled models applies.
+ *entry = decoder_runtime_ctx(entry->mutex);
+ }
+ }
+
+ // NPU: weightless blobs plus one shared weights file. Needs NPUW, which cacheless graphs compile without, so
+ // those are not cached on the NPU.
+ const std::string model_cache_dir =
+ device == "NPU" && no_kv_cache ? std::string() : ggml_openvino_model_cache_dir();
+ const bool weightless_bank = device == "NPU" && !model_cache_dir.empty();
+ const static_graph_args args{core,
+ device,
+ cgraph,
+ m_params,
+ c_params,
+ prefill_chunk_size,
+ decode_bucket,
+ compile_config,
+ model_cache_dir,
+ weightless_bank,
+ weightless_bank && ggml_openvino_self_contained_mmap_enabled(),
+ no_kv_cache,
+ ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_IR") != 0,
+ static_cast<long long>(ggml_time_us())};
+ if (!entry->ptr && entry->variants.empty()) {
+ entry->kv_only_prefill = kv_only_prefill;
+ entry->decode_unfold = ggml_openvino_npu_decode_config(compile_config, device).count("NPUW_UNFOLD_IREQS") != 0;
+ if (!model_cache_dir.empty()) {
+ entry->cache_base_extra = static_cache_base_extra(weightless_bank, kv_only_prefill);
+ }
+ if (weightless_bank) {
+ // Only a graph exported with weights differing from the model file has its own file.
+ static_select_weights(args, *entry, /*own=*/true);
+ if (!ggml_openvino_model_cache_weights_valid(entry->weights_path)) {
+ static_select_weights(args, *entry, /*own=*/false);
+ }
+ }
+ }
+
+ // The model this call runs. Decode: the KV window of the next decode position (the full context without decode
+ // KV windows).
+ const ov_static_variant_key decode_key{false, decode_bucket > 0 ? decode_window : m_params.ctx_per_seq,
+ c_params.attention_size_swa, 1};
+ ov_static_variant_key needed = decode_key;
+ if (is_prefill) {
+ // The output count is part of the static prefill shape (more than 1 only for llama-perplexity).
+ needed = {true, c_params.attention_size, c_params.attention_size_swa, c_params.output_len};
+ if (ggml_openvino_kv_slice_enabled() && !ggml_openvino_npu_kv_head_major_enabled()) {
+ // A larger loaded prefill model also serves a smaller attended length: the extra KV rows are masked, as
+ // with the power-of-two rounding. Head-major KV is bound at the storage size, so it keeps the exact
+ // match. The map order makes the first match the smallest.
+ for (const auto & [k, v] : entry->variants) {
+ if (k.prefill && k.output_len == needed.output_len && k.attention_size >= needed.attention_size &&
+ k.attention_size_swa >= needed.attention_size_swa) {
+ needed = k;
+ break;
+ }
}
- prefill_size_changed = !cache_hit;
}
}
- std::vector<std::string> ov_input_names_local;
- bool pair_built = false;
- std::vector<std::string> ov_output_names_local;
-
- if (cache_hit) {
- std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
- ggml_decoder->m_is_prefill = is_prefill;
- ggml_decoder->set_model_params(m_params);
- ggml_decoder->set_compute_params(c_params);
- if (old_m_params.kv_buffer_changed(m_params) || !ggml_decoder->is_bound_to(cgraph)) {
- ggml_decoder->update_io(cgraph);
+ // With a model cache and decode KV windows, the first prefill call exports (or imports) the prefill model of every
+ // KV window; the first call loads every decode model, as a growing sequence switches between them.
+ const bool prepare_prefill = is_prefill && weightless_bank && decode_bucket > 0 && !entry->prefill_prepared;
+ const bool prepare_decode = !no_kv_cache && !entry->decode_prepared;
+ std::vector<ov_static_variant_key> keys;
+ if (prepare_prefill) {
+ keys = static_variant_keys(args, true);
+ }
+ if (prepare_decode) {
+ for (const auto & k : static_variant_keys(args, false)) {
+ keys.push_back(k);
}
- ggml_decoder->add_extra_inputs();
- {
- std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
- infer_request =
- is_prefill ? r_ctx->infer_request_cache_prefill.at(key) : r_ctx->infer_request_cache.at(key);
- ov_input_names_local = is_prefill ? r_ctx->ov_input_names_cache_prefill.at(key) :
- r_ctx->ov_input_names_cache.at(key);
- ov_output_names_local = is_prefill ? r_ctx->ov_output_names_cache_prefill.at(key) :
- r_ctx->ov_output_names_cache.at(key);
+ }
+ for (const auto & k : {needed, decode_key}) {
+ if ((k.prefill || !no_kv_cache) && std::find(keys.begin(), keys.end(), k) == keys.end()) {
+ keys.push_back(k);
}
-
- decoder_end_time = ggml_time_us();
- conversion_end_time = decoder_end_time;
- compile_end_time = decoder_end_time;
- } else {
- // Same fail-fast as the dynamic path: once the host weight pages have been dropped
- // they read as zeros, so a recompile here would bake garbage into the new model.
- if (ggml_openvino_weight_buffers_released()) {
- GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
- return GGML_STATUS_FAILED;
+ }
+ decoder_end_time = ggml_time_us();
+ if (std::any_of(keys.begin(), keys.end(), [&](const auto & k) { return entry->variants.count(k) == 0; })) {
+ if (!weightless_bank && is_prefill && entry->variants.count(needed) == 0) {
+ // Without a model cache, keep one prefill model: each loaded prefill model keeps NPU memory for its
+ // inferences, and next to a second one the NPU can run out
+ // (pfnAppendGraphExecute: ZE_RESULT_ERROR_UNINITIALIZED).
+ for (auto it = entry->variants.begin(); it != entry->variants.end();) {
+ it = it->first.prefill ? entry->variants.erase(it) : std::next(it);
+ }
}
- if (cache_enabled) {
- std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
- r_ctx->infer_request_cache.erase(key);
- r_ctx->infer_request_cache_prefill.erase(key);
+ std::lock_guard<std::mutex> compile_lock(r_ctx->compiled_cache->mutex);
+ static_load_variants(args, *entry, keys, needed);
+ if (entry->kv_only_prefill && is_prefill) {
+ GGML_LOG_INFO("ggml-openvino: KV-only prefill model (outputs via one decode step)\n");
}
-
- // Static execution shares a compiled prefill/decode pair. Each backend
- // creates and retains its own requests for both phases.
- auto shared_cache = r_ctx->compiled_cache;
- std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
- auto weight_names = get_weight_names(cgraph);
- auto local_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, weight_names, is_static,
- stateful, false, is_prefill, prefill_chunk_size);
- local_decoder->device = device;
- const std::string shared_key =
- cache_enabled ? compiled_graph_key(cgraph, *local_decoder, device, prefill_chunk_size) : "";
- auto shared_it = shared_cache->graphs.find(shared_key);
- if (!shared_key.empty() && shared_it != shared_cache->graphs.end()) {
- auto & compiled = shared_it->second;
- auto prefill_request = std::make_shared<ov::InferRequest>(compiled.prefill.create_infer_request());
- auto decode_request = no_kv_cache ?
- prefill_request :
- std::make_shared<ov::InferRequest>(compiled.decode.create_infer_request());
- ggml_decoder = local_decoder;
- entry->ptr = ggml_decoder;
- entry->prefill_attention_size = c_params.attention_size;
- entry->prefill_attention_size_swa = c_params.attention_size_swa;
- entry->prefill_output_len = c_params.output_len;
- entry->decode_attention_size = compiled.decode_attention_size;
- entry->shared_key = shared_key;
- entry->decode_window_requests.clear();
- infer_request = is_prefill ? prefill_request : decode_request;
- ov_input_names_local = is_prefill ? compiled.prefill_input_names : compiled.input_names;
- ov_output_names_local = is_prefill ? compiled.prefill_output_names : compiled.output_names;
- r_ctx->infer_request_cache_prefill[key] = prefill_request;
- r_ctx->infer_request_cache[key] = decode_request;
- r_ctx->ov_input_names_cache[key] = compiled.input_names;
- r_ctx->ov_output_names_cache[key] = compiled.output_names;
- r_ctx->ov_input_names_cache_prefill[key] = compiled.prefill_input_names;
- r_ctx->ov_output_names_cache_prefill[key] = compiled.prefill_output_names;
- decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us();
- GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n");
- if (prefill_size_changed) {
- GGML_LOG_INFO("ggml-openvino: reuse the compiled prefill model of attention size %d\n",
- c_params.attention_size);
- }
- } else {
- auto decode_c_params = c_params;
- // A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the
- // decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows
- // than the graph has tokens.
- decode_c_params.output_len = 1;
- if (ggml_openvino_kv_slice_enabled()) {
- decode_c_params.attention_size = m_params.ctx_per_seq;
- decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa;
- }
- if (decode_bucket > 0) {
- decode_c_params.attention_size = decode_window;
- }
- const ov::AnyMap prefill_config = ggml_openvino_npu_prefill_config(compile_config, *local_decoder);
- const ov::AnyMap decode_config = ggml_openvino_npu_decode_config(compile_config, device);
-
- const std::string model_cache_dir = ggml_openvino_model_cache_dir();
- const bool self_contained = device == "NPU" && !model_cache_dir.empty() &&
- ggml_openvino_npu_raw_weight_cache_enabled();
- // Weightless prefill/decode blobs plus one shared weights file. Needs NPUW, which cacheless graphs
- // compile without, so those keep the embedded-weight blob.
- const bool weightless_bank =
- self_contained && !no_kv_cache && ggml_openvino_npu_weightless_bank_enabled();
- // Another prefill attention size of the entry's model. The decode models (base and KV windows) do not
- // depend on it, so the new pair takes them over from the entry's current pair, and that pair is dropped
- // before the new prefill model compiles: each loaded prefill model keeps NPU memory for its inferences, and
- // next to a second one the NPU can run out (pfnAppendGraphExecute: ZE_RESULT_ERROR_UNINITIALIZED). A pair
- // another backend may use stays cached. Self-contained pairs are exported together, so they keep their own
- // decode.
- std::optional<ov_compiled_graph> decode_source;
- if (prefill_size_changed && !self_contained && !no_kv_cache) {
- auto source_it = shared_cache->graphs.find(entry->shared_key);
- if (source_it != shared_cache->graphs.end()) {
- decode_source = source_it->second;
- decode_source->prefill = {};
- decode_c_params = decode_source->decode_c_params;
- // Make the KV window of the next decode step the base decode model, as a newly built pair has
- // it, so that step does not switch to a window request it has to create first.
- auto window_it = decode_source->decode_windows.find(decode_window);
- if (decode_bucket > 0 && window_it != decode_source->decode_windows.end()) {
- ov::CompiledModel window_model = window_it->second;
- decode_source->decode_windows.erase(window_it);
- decode_source->decode_windows.emplace(decode_c_params.attention_size, decode_source->decode);
- decode_source->decode = window_model;
- decode_c_params.attention_size = decode_window;
- }
- if (shared_cache->backend_count == 1) {
- shared_cache->graphs.erase(source_it);
+ } else {
+ cache_hit = true;
+ }
+ entry->prefill_prepared |= prepare_prefill;
+ entry->decode_prepared |= prepare_decode;
+ conversion_end_time = compile_end_time = ggml_time_us();
+
+ // A request is created on first use. One prefill request at a time: each holds NPU memory for its inferences.
+ auto variant_with_request = [&](const ov_static_variant_key & k) -> ov_static_variant & {
+ auto & v = entry->variants.at(k);
+ if (!v.request) {
+ if (k.prefill) {
+ for (auto & [other_key, other] : entry->variants) {
+ if (other_key.prefill) {
+ other.request.reset();
}
}
}
- ov::AnyMap mc_config = prefill_config;
- ov::AnyMap mc_decode_config = decode_config;
- if (!model_cache_dir.empty()) {
- mc_config.erase("CACHE_DIR");
- mc_config.erase("CACHE_MODE");
- mc_decode_config.erase("CACHE_DIR");
- mc_decode_config.erase("CACHE_MODE");
- }
-
- uint64_t prefill_fp = 0;
- uint64_t decode_fp = 0;
- uint64_t base_extra = 0;
- const bool decode_unfold = mc_decode_config.find("NPUW_UNFOLD_IREQS") != mc_decode_config.end();
- if (!model_cache_dir.empty()) {
- base_extra = ggml_openvino_model_cache_extra_cfg(stateful, /*recurrent=*/false);
- base_extra = base_extra * 131 + (weightless_bank ? 3u : (self_contained ? 1u : 0u));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT"));
- base_extra = base_extra * 131 + (ggml_openvino_kv_slice_enabled() ? 1u : 0u);
- base_extra = base_extra * 131 + (ggml_openvino_npu_kv_head_major_enabled() ? 1u : 0u);
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_CONFIG"));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_COMPILE_CONFIG"));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_COMPILER_TYPE"));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPUW_FUNCALL_FOR_ALL"));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPUW_UNFOLD_IREQS"));
- base_extra = ggml_openvino_model_cache_mix_string(
- base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_COMPILATION_NUM_THREADS"));
- // out_ids is bound at a fixed length, so the output count is part of the static shape
- const std::string prefill_signature = "static-1 out=" + std::to_string(c_params.output_len);
- const std::string decode_signature = "static-1 out=1";
- prefill_fp = ggml_openvino_model_fingerprint(
- cgraph, device, true, m_params.rope_params, 16,
- static_model_salt(base_extra, true, prefill_chunk_size, c_params.attention_size,
- c_params.attention_size_swa, false),
- prefill_signature);
- decode_fp = ggml_openvino_model_fingerprint(
- cgraph, device, true, m_params.rope_params, 16,
- static_model_salt(base_extra, false, prefill_chunk_size, decode_c_params.attention_size,
- decode_c_params.attention_size_swa, decode_unfold),
- decode_signature);
- }
-
- std::string weights_path;
- std::string pair_weights_path;
- std::string model_weights_path;
- std::string pair_bank;
- std::string model_bank;
- if (weightless_bank) {
- // One weights file and NPUW bank for every pair of this model (pairs differ only in KV window):
- // NPUW matches weights by the LazyTensor hash recorded at compile time and keeps one resident copy.
- // A pair whose weights differ from the model file falls back to its own file and bank.
- const uint64_t weights_fp = ggml_openvino_model_fingerprint(cgraph, device, true, m_params.rope_params,
- 16, base_extra, "weights");
- char model_bank_name[64];
- char shared_bank[96];
- snprintf(model_bank_name, sizeof(model_bank_name), "ggml-wl-model-%016llx",
- static_cast<unsigned long long>(weights_fp));
- snprintf(shared_bank, sizeof(shared_bank), "ggml-wl-shared-%016llx-%016llx",
- static_cast<unsigned long long>(prefill_fp), static_cast<unsigned long long>(decode_fp));
- pair_bank = shared_bank;
- model_bank = model_bank_name;
- pair_weights_path = ggml_openvino_model_cache_weights_path(model_cache_dir, prefill_fp, decode_fp);
- model_weights_path = ggml_openvino_model_cache_weights_path(model_cache_dir, weights_fp, weights_fp);
- // Only a pair exported with differing weights has its own file.
- const bool pair_own = ggml_openvino_model_cache_weights_valid(pair_weights_path);
- weights_path = pair_own ? pair_weights_path : model_weights_path;
- mc_config["NPUW_WEIGHTS_BANK"] = pair_own ? pair_bank : model_bank;
- mc_decode_config["NPUW_WEIGHTS_BANK"] = mc_config["NPUW_WEIGHTS_BANK"];
- } else if (self_contained) {
- char prefill_bank[64];
- char decode_bank[64];
- snprintf(prefill_bank, sizeof(prefill_bank), "ggml-sc-prefill-%016llx",
- static_cast<unsigned long long>(prefill_fp));
- snprintf(decode_bank, sizeof(decode_bank), "ggml-sc-decode-%016llx",
- static_cast<unsigned long long>(decode_fp));
- if (ggml_openvino_getenv_int("GGML_OPENVINO_NPU_SHARED_BANK")) {
- // Share ONE weights bank between prefill and decode. Both decoders are built
- // from the same model_weights map, so NPUW dedups them into a single in-process
- // bank; on warm import the shared blob's identical (uid,tensor) pairs are
- // content-verified and reused (patched NPUW weights_bank). Halves the resident
- // compiled-weight footprint (~2 GiB) at the cost of larger per-graph blobs.
- char shared_bank[96];
- snprintf(shared_bank, sizeof(shared_bank), "ggml-sc-shared-%016llx-%016llx",
- static_cast<unsigned long long>(prefill_fp),
- static_cast<unsigned long long>(decode_fp));
- mc_config["NPUW_WEIGHTS_BANK"] = std::string(shared_bank);
- mc_decode_config["NPUW_WEIGHTS_BANK"] = std::string(shared_bank);
- } else {
- mc_config["NPUW_WEIGHTS_BANK"] = std::string(prefill_bank);
- mc_decode_config["NPUW_WEIGHTS_BANK"] = std::string(decode_bank);
- }
- }
-
- auto blob_valid = [&](uint64_t fp) {
- if (model_cache_dir.empty() || fp == 0) {
- return false;
- }
- std::ifstream blob_in(ggml_openvino_model_cache_blob_path(model_cache_dir, fp), std::ios::binary);
- std::vector<std::string> inputs, outputs; // ports are bound in frontend order, see below
- return blob_in.is_open() &&
- ggml_openvino_model_cache_verify_manifest(
- ggml_openvino_model_cache_manifest_path(model_cache_dir, fp), cgraph, fp, inputs, outputs);
- };
- const bool self_contained_mmap =
- self_contained && ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0;
- const bool skip_weights = self_contained && blob_valid(prefill_fp) && blob_valid(decode_fp) &&
- (!weightless_bank || ggml_openvino_model_cache_weights_valid(weights_path));
- if (self_contained_mmap && !skip_weights) {
- throw std::runtime_error(
- "GGML_OPENVINO_SELF_CONTAINED_MMAP requires valid self-contained blob(s); "
- "run once with GGML_OPENVINO_SELF_CONTAINED_MMAP=0 to build the cache");
- }
-
- if (self_contained && !skip_weights && !model_cache_dir.empty()) {
- if (prefill_fp != 0) {
- ggml_openvino_model_cache_write_manifest(
- ggml_openvino_model_cache_manifest_path(model_cache_dir, prefill_fp) + ".source.tmp",
- cgraph, prefill_fp, {}, {});
- }
- if (decode_fp != 0) {
- ggml_openvino_model_cache_write_manifest(
- ggml_openvino_model_cache_manifest_path(model_cache_dir, decode_fp) + ".source.tmp",
- cgraph, decode_fp, {}, {});
- }
- }
-
- std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
- if (skip_weights) {
- for (const auto & name : GgmlOvDecoder::collect_weight_names(cgraph)) {
- model_weights[name] = nullptr;
- }
- } else {
- model_weights = GgmlOvDecoder::create_weight_nodes(cgraph);
- }
-
- auto ggml_decoder_prefill = std::make_shared<GgmlOvDecoder>(
- cgraph, m_params, c_params, model_weights, is_static, stateful, false, true, prefill_chunk_size);
- auto ggml_decoder_decode =
- no_kv_cache ? ggml_decoder_prefill :
- std::make_shared<GgmlOvDecoder>(cgraph, m_params, decode_c_params, model_weights,
- is_static, stateful, false, false, prefill_chunk_size);
- ggml_decoder_prefill->device = device;
- ggml_decoder_decode->device = device;
- decoder_end_time = ggml_time_us();
-
- const bool dump_ir = ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_IR");
- const auto dump_ir_timestamp = static_cast<long long>(ggml_time_us());
-
- // Both decoders share the weight nodes, and converting attaches each new graph to them. ov::Node is not
- // thread-safe, so the models are always converted one at a time; only compilation can run in parallel.
- const static_build_args build_args{&core, device, dump_ir, dump_ir_timestamp,
- model_cache_dir, cgraph, self_contained, skip_weights,
- weightless_bank, weights_path};
- auto convert_static_model = [&build_args](std::shared_ptr<GgmlOvDecoder> decoder, const char * tag,
- int64_t & local_conversion_end_time) {
- return ::convert_static_model(build_args, decoder, tag, local_conversion_end_time);
- };
- auto build_static_model = [&build_args](std::shared_ptr<GgmlOvDecoder> decoder,
- const char * tag,
- std::shared_ptr<ov::Model> model,
- const ov::AnyMap & model_config,
- uint64_t model_fp,
- ov::CompiledModel & compiled_model,
- std::shared_ptr<ov::InferRequest> & infer_request,
- std::vector<std::string> & names_in,
- std::vector<std::string> & names_out,
- int64_t & local_conversion_end_time,
- int64_t & local_compile_end_time) {
- ::build_static_model(build_args, std::move(decoder), tag, std::move(model), model_config, model_fp,
- compiled_model, infer_request, names_in, names_out, local_conversion_end_time,
- local_compile_end_time);
- };
- ov::CompiledModel compiled_model_prefill;
- ov::CompiledModel compiled_model_decode;
- std::shared_ptr<ov::InferRequest> infer_request_prefill;
- std::shared_ptr<ov::InferRequest> infer_request_decode;
- std::vector<std::string> names_in_prefill, names_out_prefill;
- std::vector<std::string> names_in_decode, names_out_decode;
- int64_t prefill_conversion_end_time = 0;
- int64_t decode_conversion_end_time = 0;
- int64_t prefill_compile_end_time = 0;
- int64_t decode_compile_end_time = 0;
-
- // Convert decode before compiling prefill: a decode model converted after the prefill compile gives
- // wrong output on some NPU models (Bonsai-8B). Compiling both in parallel raises the host memory peak,
- // so it is opt-in.
- const bool parallel_compile =
- !self_contained && !no_kv_cache && !decode_source && ggml_openvino_npu_parallel_compile_enabled();
- auto model_prefill = convert_static_model(ggml_decoder_prefill, "prefill", prefill_conversion_end_time);
- std::shared_ptr<ov::Model> model_decode;
- if (!no_kv_cache && !decode_source) {
- model_decode = convert_static_model(ggml_decoder_decode, "decode", decode_conversion_end_time);
- }
- std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
- if (weightless_bank && !skip_weights) {
- // Lay both models' weights out in one file before compiling, so both blobs reference the same file.
- // Old blobs reference the old layout, so drop them first in case the export does not complete.
- for (const uint64_t fp : { prefill_fp, decode_fp }) {
- std::remove(ggml_openvino_model_cache_blob_path(model_cache_dir, fp).c_str());
- std::remove(ggml_openvino_model_cache_manifest_path(model_cache_dir, fp).c_str());
- // A decode window built earlier on its own may have left a weights file for this fingerprint.
- ggml_openvino_model_cache_remove_weights(
- ggml_openvino_model_cache_weights_path(model_cache_dir, fp, fp));
- }
- ggml_openvino_model_cache_remove_weights(pair_weights_path);
- ggml_openvino_weights_status status = ggml_openvino_weights_status::written;
- weights_path = model_weights_path;
- mc_config["NPUW_WEIGHTS_BANK"] = model_bank;
- mc_decode_config["NPUW_WEIGHTS_BANK"] = model_bank;
- weights_layout = ggml_openvino_model_cache_write_weights(weights_path, {model_prefill, model_decode},
- /*keep_existing=*/true, &status);
- if (status == ggml_openvino_weights_status::mismatch) {
- GGML_LOG_WARN("ggml-openvino: weights differ from %s, using a per-pair weights file\n",
- model_weights_path.c_str());
- weights_path = pair_weights_path;
- mc_config["NPUW_WEIGHTS_BANK"] = pair_bank;
- mc_decode_config["NPUW_WEIGHTS_BANK"] = pair_bank;
- weights_layout =
- ggml_openvino_model_cache_write_weights(weights_path, {model_prefill, model_decode});
- }
- if (!weights_layout) {
- throw std::runtime_error("ggml-openvino: failed to write NPU weights file " + weights_path);
- }
- }
- if (parallel_compile) {
- auto prefill_future = std::async(std::launch::async, build_static_model, ggml_decoder_prefill, "prefill",
- std::move(model_prefill), std::cref(mc_config), prefill_fp,
- std::ref(compiled_model_prefill), std::ref(infer_request_prefill),
- std::ref(names_in_prefill), std::ref(names_out_prefill),
- std::ref(prefill_conversion_end_time),
- std::ref(prefill_compile_end_time));
- auto decode_future = std::async(std::launch::async, build_static_model, ggml_decoder_decode, "decode",
- std::move(model_decode), std::cref(mc_decode_config), decode_fp,
- std::ref(compiled_model_decode), std::ref(infer_request_decode),
- std::ref(names_in_decode), std::ref(names_out_decode),
- std::ref(decode_conversion_end_time),
- std::ref(decode_compile_end_time));
- prefill_future.get();
- decode_future.get();
- } else {
- build_static_model(ggml_decoder_prefill, "prefill", std::move(model_prefill), mc_config, prefill_fp,
- compiled_model_prefill, infer_request_prefill, names_in_prefill, names_out_prefill,
- prefill_conversion_end_time, prefill_compile_end_time);
- if (no_kv_cache) {
- compiled_model_decode = compiled_model_prefill;
- infer_request_decode = infer_request_prefill;
- names_in_decode = names_in_prefill;
- names_out_decode = names_out_prefill;
- decode_conversion_end_time = prefill_conversion_end_time;
- decode_compile_end_time = prefill_compile_end_time;
- } else if (decode_source) {
- compiled_model_decode = decode_source->decode;
- infer_request_decode =
- std::make_shared<ov::InferRequest>(compiled_model_decode.create_infer_request());
- names_in_decode = decode_source->input_names;
- names_out_decode = decode_source->output_names;
- decode_conversion_end_time = prefill_conversion_end_time;
- decode_compile_end_time = prefill_compile_end_time;
- } else {
- build_static_model(ggml_decoder_decode, "decode", std::move(model_decode), mc_decode_config,
- decode_fp, compiled_model_decode, infer_request_decode, names_in_decode,
- names_out_decode, decode_conversion_end_time, decode_compile_end_time);
- }
- }
- conversion_end_time = std::max(prefill_conversion_end_time, decode_conversion_end_time);
- compile_end_time = std::max(prefill_compile_end_time, decode_compile_end_time);
-
- ggml_decoder = is_prefill ? ggml_decoder_prefill : ggml_decoder_decode;
- infer_request = is_prefill ? infer_request_prefill : infer_request_decode;
- ov_input_names_local = is_prefill ? names_in_prefill : names_in_decode;
- ov_output_names_local = is_prefill ? names_out_prefill : names_out_decode;
- entry->ptr = ggml_decoder;
- entry->prefill_attention_size = c_params.attention_size;
- entry->prefill_attention_size_swa = c_params.attention_size_swa;
- entry->prefill_output_len = c_params.output_len;
- entry->decode_attention_size = decode_c_params.attention_size;
- entry->shared_key = shared_key;
- entry->decode_window_requests.clear();
-
- if (!shared_key.empty()) {
- ov_compiled_graph graph;
- graph.decode = compiled_model_decode;
- graph.prefill = compiled_model_prefill;
- graph.input_names = names_in_decode;
- graph.output_names = names_out_decode;
- graph.prefill_input_names = names_in_prefill;
- graph.prefill_output_names = names_out_prefill;
- graph.decode_attention_size = decode_c_params.attention_size;
- if (decode_source) {
- graph.decode_windows = decode_source->decode_windows;
- }
- graph.decode_config = mc_decode_config;
- graph.cache_base_extra = base_extra;
- graph.self_contained = self_contained;
- graph.decode_unfold = decode_unfold;
- graph.weightless_bank = weightless_bank;
- graph.weights_path = weights_path;
- graph.weights_layout = decode_bucket > 0 ? std::move(weights_layout) : nullptr;
- graph.decode_c_params = decode_c_params;
- shared_cache->graphs.emplace(shared_key, std::move(graph));
- pair_built = !decode_source;
- }
-
- if (cache_enabled) {
- std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
- r_ctx->infer_request_cache_prefill[key] = infer_request_prefill;
- r_ctx->infer_request_cache[key] = infer_request_decode;
- r_ctx->ov_input_names_cache[key] = names_in_decode;
- r_ctx->ov_output_names_cache[key] = names_out_decode;
- r_ctx->ov_input_names_cache_prefill[key] = names_in_prefill;
- r_ctx->ov_output_names_cache_prefill[key] = names_out_prefill;
- }
- }
- }
-
- // Decode model for another KV window than the pair's; built/imported once per window with the pair's
- // settings and weights bank, then cached in the shared compiled cache. Caller holds the shared cache mutex.
- auto build_decode_window = [&](ov_compiled_graph & graph, const ComputeParams & base_c_params,
- int window) -> ov::CompiledModel & {
- auto window_it = graph.decode_windows.find(window);
- if (window_it != graph.decode_windows.end()) {
- return window_it->second;
- }
- auto window_c_params = base_c_params;
- window_c_params.attention_size = window;
- const std::string model_cache_dir = ggml_openvino_model_cache_dir();
- const uint64_t fp = model_cache_dir.empty() ?
- 0 :
- ggml_openvino_model_fingerprint(
- cgraph, device, true, m_params.rope_params, 16,
- static_model_salt(graph.cache_base_extra, false, prefill_chunk_size, window,
- window_c_params.attention_size_swa, graph.decode_unfold),
- "static-1 out=1");
- if (fp != 0) {
- std::lock_guard<std::mutex> blobs_lock(g_imported_blobs_mutex);
- auto cached = g_imported_blobs.find(fp);
- if (cached != g_imported_blobs.end()) {
- return graph.decode_windows.emplace(window, cached->second).first->second;
- }
- }
- // Weightless bank: a window compiled with the pair resolves the shared weights through the pair's file
- // (the rest is embedded in its blob); otherwise it gets its own weights file.
- const std::string own_weights_path =
- graph.weightless_bank ? ggml_openvino_model_cache_weights_path(model_cache_dir, fp, fp) : "";
- const bool own_weights_valid =
- graph.weightless_bank && ggml_openvino_model_cache_weights_valid(own_weights_path);
- // A window blob resolved through the pair's file must not predate it (the pair may have been re-exported).
- auto pair_weights_usable = [&]() {
- std::error_code ec1, ec2;
- const auto blob_time = std::filesystem::last_write_time(
- std::filesystem::u8path(ggml_openvino_model_cache_blob_path(model_cache_dir, fp)), ec1);
- const auto weights_time =
- std::filesystem::last_write_time(std::filesystem::u8path(graph.weights_path), ec2);
- return !ec1 && !ec2 && blob_time >= weights_time &&
- ggml_openvino_model_cache_weights_valid(graph.weights_path);
- };
- const bool skip_weights = graph.self_contained && static_blob_valid(model_cache_dir, fp, cgraph) &&
- (!graph.weightless_bank || own_weights_valid || pair_weights_usable());
- if (graph.self_contained && !skip_weights &&
- ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") != 0) {
- throw std::runtime_error("GGML_OPENVINO_SELF_CONTAINED_MMAP: no cached decode model for KV window " +
- std::to_string(window) + "; rerun with GGML_OPENVINO_SELF_CONTAINED_MMAP=0");
- }
- std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
- if (skip_weights) {
- for (const auto & name : GgmlOvDecoder::collect_weight_names(cgraph)) {
- model_weights[name] = nullptr;
- }
- } else {
- if (graph.self_contained && fp != 0) {
- ggml_openvino_model_cache_write_manifest(
- ggml_openvino_model_cache_manifest_path(model_cache_dir, fp) + ".source.tmp", cgraph, fp, {}, {});
- }
- model_weights = GgmlOvDecoder::create_weight_nodes(cgraph);
- }
- auto window_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, window_c_params, model_weights,
- is_static, stateful, false, false, prefill_chunk_size);
- window_decoder->device = device;
- static_build_args args{&core, device, false, 0, model_cache_dir, cgraph, graph.self_contained,
- skip_weights, graph.weightless_bank, {}};
- ov::CompiledModel compiled;
- std::shared_ptr<ov::InferRequest> built_request;
- std::vector<std::string> names_in, names_out;
- int64_t t_conv = 0, t_compile = 0;
- const int64_t t0 = ggml_time_us();
- auto model = convert_static_model(args, window_decoder, "decode", t_conv);
- if (graph.weightless_bank) {
- args.weights_path = own_weights_valid ? own_weights_path : graph.weights_path;
- if (model && graph.weights_layout) {
- const size_t resolved = ggml_openvino_model_cache_retag_weights(model, *graph.weights_layout);
- GGML_LOG_INFO("ggml-openvino: decode KV window %d resolves %zu weights through %s\n", window,
- resolved, graph.weights_path.c_str());
- ggml_openvino_model_cache_remove_weights(own_weights_path);
- args.weights_path = graph.weights_path;
- } else if (model) {
- if (!ggml_openvino_model_cache_write_weights(own_weights_path, { model })) {
- throw std::runtime_error("ggml-openvino: failed to write NPU weights file " + own_weights_path);
- }
- args.weights_path = own_weights_path;
- }
- }
- build_static_model(args, window_decoder, "decode", std::move(model), graph.decode_config, fp, compiled,
- built_request, names_in, names_out, t_conv, t_compile);
- if (names_in != graph.input_names || names_out != graph.output_names) {
- throw std::runtime_error("ggml-openvino: decode window model ports differ from the base decode model");
- }
- GGML_LOG_INFO("ggml-openvino: decode KV window %d model ready in %.1f ms\n", window,
- (ggml_time_us() - t0) / 1000.0);
- return graph.decode_windows.emplace(window, std::move(compiled)).first->second;
- };
-
- auto get_decode_window_request = [&](int window) -> std::shared_ptr<ov::InferRequest> {
- auto & request = entry->decode_window_requests[window];
- if (request) {
- return request;
- }
- auto shared_cache = r_ctx->compiled_cache;
- std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
- auto graph_it = shared_cache->graphs.find(entry->shared_key);
- if (graph_it == shared_cache->graphs.end()) {
- throw std::runtime_error("ggml-openvino: decode window requested without a shared compiled graph");
+ v.request = std::make_shared<ov::InferRequest>(v.model.create_infer_request());
}
- auto & compiled = build_decode_window(graph_it->second, c_params, window);
- request = std::make_shared<ov::InferRequest>(compiled.create_infer_request());
- return request;
+ return v;
};
+ const auto & variant = variant_with_request(needed);
+ infer_request = variant.request;
+ const std::vector<std::string> ov_input_names_local = variant.input_names;
+ const std::vector<std::string> ov_output_names_local = variant.output_names;
- // Build or import every other decode window right after the pair, from the pair's own graph and params,
- // so a growing sequence only switches requests.
- if (pair_built && decode_bucket > 0) {
- auto shared_cache = r_ctx->compiled_cache;
- std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
- auto graph_it = shared_cache->graphs.find(entry->shared_key);
- if (graph_it != shared_cache->graphs.end()) {
- auto & graph = graph_it->second;
- const int64_t t0 = ggml_time_us();
- for (int window = decode_bucket;; window *= 2) {
- window = std::min(window, m_params.ctx_per_seq);
- if (window != graph.decode_attention_size) {
- build_decode_window(graph, graph.decode_c_params, window);
- }
- if (window >= m_params.ctx_per_seq) {
- break;
- }
- }
- GGML_LOG_INFO("ggml-openvino: prebuilt %zu decode KV window model(s) in %.1f ms\n",
- graph.decode_windows.size(), (ggml_time_us() - t0) / 1000.0);
-
- // With head-major KV a prefill also runs at a KV window, picked by prompt length. Export the prefill
- // model of every other window too, so an import-only run has a pair for any prompt length.
- const std::string model_cache_dir = ggml_openvino_model_cache_dir();
- if (graph.weightless_bank && graph.weights_layout && ggml_openvino_npu_kv_head_major_enabled() &&
- ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") == 0) {
- const int64_t t1 = ggml_time_us();
- size_t exported = 0;
- for (int window = decode_bucket;; window *= 2) {
- window = std::min(window, m_params.ctx_per_seq);
- if (window != entry->prefill_attention_size) {
- auto window_c_params = c_params;
- window_c_params.attention_size = window;
- const uint64_t fp = ggml_openvino_model_fingerprint(
- cgraph, device, true, m_params.rope_params, 16,
- static_model_salt(graph.cache_base_extra, true, prefill_chunk_size, window,
- window_c_params.attention_size_swa, false),
- "static-1 out=" + std::to_string(window_c_params.output_len));
- std::error_code ec1, ec2;
- const auto blob_time = std::filesystem::last_write_time(
- std::filesystem::u8path(ggml_openvino_model_cache_blob_path(model_cache_dir, fp)), ec1);
- const auto weights_time =
- std::filesystem::last_write_time(std::filesystem::u8path(graph.weights_path), ec2);
- const bool cached =
- !ec1 && !ec2 && blob_time >= weights_time && static_blob_valid(model_cache_dir, fp, cgraph);
- if (!cached) {
- ggml_openvino_model_cache_write_manifest(
- ggml_openvino_model_cache_manifest_path(model_cache_dir, fp) + ".source.tmp", cgraph,
- fp, {}, {});
- auto model_weights = GgmlOvDecoder::create_weight_nodes(cgraph);
- auto window_decoder =
- std::make_shared<GgmlOvDecoder>(cgraph, m_params, window_c_params, model_weights,
- is_static, stateful, false, true, prefill_chunk_size);
- ov::AnyMap window_config =
- ggml_openvino_npu_prefill_config(compile_config, *window_decoder);
- window_config.erase("CACHE_DIR");
- window_config.erase("CACHE_MODE");
- window_config["NPUW_WEIGHTS_BANK"] = graph.decode_config.at("NPUW_WEIGHTS_BANK");
- static_build_args args{&core, device, false, 0, model_cache_dir,
- cgraph, true, false, true, graph.weights_path};
- int64_t t_conv = 0, t_compile = 0;
- auto model = convert_static_model(args, window_decoder, "prefill", t_conv);
- ggml_openvino_model_cache_retag_weights(model, *graph.weights_layout);
- ov::CompiledModel compiled;
- std::shared_ptr<ov::InferRequest> built_request;
- std::vector<std::string> names_in, names_out;
- build_static_model(args, window_decoder, "prefill", std::move(model), window_config, fp,
- compiled, built_request, names_in, names_out, t_conv, t_compile);
- ++exported;
- }
- }
- if (window >= m_params.ctx_per_seq) {
- break;
- }
- }
- GGML_LOG_INFO("ggml-openvino: exported %zu prefill KV window model(s) in %.1f ms\n", exported,
- (ggml_time_us() - t1) / 1000.0);
- }
-
- // Import the prefill model of every other window now, so a prompt that needs another window builds its
- // pair from already imported models instead of importing them mid-request.
- if (graph.weightless_bank && ggml_openvino_npu_kv_head_major_enabled() &&
- ggml_openvino_model_cache_weights_valid(graph.weights_path)) {
- const int64_t t2 = ggml_time_us();
- size_t imported = 0;
- for (int window = decode_bucket;; window *= 2) {
- window = std::min(window, m_params.ctx_per_seq);
- if (window != entry->prefill_attention_size) {
- auto window_c_params = c_params;
- window_c_params.attention_size = window;
- const uint64_t fp = ggml_openvino_model_fingerprint(
- cgraph, device, true, m_params.rope_params, 16,
- static_model_salt(graph.cache_base_extra, true, prefill_chunk_size, window,
- window_c_params.attention_size_swa, false),
- "static-1 out=" + std::to_string(window_c_params.output_len));
- bool already_imported;
- {
- std::lock_guard<std::mutex> blobs_lock(g_imported_blobs_mutex);
- already_imported = g_imported_blobs.count(fp) != 0;
- }
- if (!already_imported && static_blob_valid(model_cache_dir, fp, cgraph)) {
- std::map<std::string, std::shared_ptr<ov::Node>> weight_names;
- for (const auto & name : GgmlOvDecoder::collect_weight_names(cgraph)) {
- weight_names[name] = nullptr;
- }
- GgmlOvDecoder window_decoder(cgraph, m_params, window_c_params, weight_names, is_static,
- stateful, false, true, prefill_chunk_size);
- ov::AnyMap import_config = ggml_openvino_npu_prefill_config(compile_config, window_decoder);
- import_config.erase("CACHE_DIR");
- import_config.erase("CACHE_MODE");
- import_config["NPUW_WEIGHTS_BANK"] = graph.decode_config.at("NPUW_WEIGHTS_BANK");
- import_config[ov::weights_path.name()] = graph.weights_path;
- import_config[ov::enable_weightless.name()] = true;
- const std::string blob_path = ggml_openvino_model_cache_blob_path(model_cache_dir, fp);
- try {
- import_cached_blob(core, device, blob_path, fp, import_config, "prefill");
- ++imported;
- } catch (const std::exception & e) {
- // Drop the invalid entry, as the pair import does; the window is then built
- // when a prompt first needs it.
- std::remove(blob_path.c_str());
- std::remove(ggml_openvino_model_cache_manifest_path(model_cache_dir, fp).c_str());
- GGML_LOG_WARN(
- "ggml-openvino: removed the invalid cached prefill model of KV window %d: %s\n",
- window, e.what());
- }
- }
- }
- if (window >= m_params.ctx_per_seq) {
- break;
- }
- }
- GGML_LOG_INFO("ggml-openvino: preloaded %zu prefill KV window model(s) in %.1f ms\n", imported,
- (ggml_time_us() - t2) / 1000.0);
- }
+ if (is_prefill) {
+ c_params.attention_size = needed.attention_size;
+ c_params.attention_size_swa = needed.attention_size_swa;
+ }
+ if (!entry->ptr) {
+ auto weight_names = get_weight_names(cgraph);
+ entry->ptr = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, weight_names, is_static, stateful,
+ false, is_prefill, prefill_chunk_size);
+ entry->ptr->device = device;
+ ggml_decoder = entry->ptr;
+ } else {
+ ggml_decoder = entry->ptr;
+ ggml_decoder->m_is_prefill = is_prefill;
+ ggml_decoder->set_model_params(m_params);
+ ggml_decoder->set_compute_params(c_params);
+ if (old_m_params.kv_buffer_changed(m_params) || !ggml_decoder->is_bound_to(cgraph)) {
+ ggml_decoder->update_io(cgraph);
}
+ ggml_decoder->add_extra_inputs();
}
// On-demand KV: grow the storage to this call's KV window before binding, so every view of the call
@@ -3133,20 +2911,101 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
static_cast<long long>(chunk_start), chunk_infer_us / 1000.0);
}
- if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
- ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
+ if (debug_output_enabled()) {
for (size_t i = 0; i < ov_output_names_local.size(); i++) {
const auto output_tensor = infer_request->get_output_tensor(i);
print_output_tensor_info(ov_output_names_local[i], output_tensor, nullptr);
}
}
}
+
+ if (entry->kv_only_prefill) {
+ // The prefill model only filled the KV cache. Compute the outputs of the requested token by running the
+ // decode model on it: it rewrites that token's KV rows with the same values and runs the layers the
+ // prefill model dropped, reading the now complete cache.
+ const ggml_tensor * out_ids = nullptr;
+ for (const auto & [name, info] : ggml_decoder->get_model_inputs()) {
+ const ggml_tensor * tensor = ggml_decoder->get_input_ggml_tensor(name);
+ // gemma-4's inp_prune_keep indexes the gathered rows, not the rows of the graph
+ if (tensor != nullptr && tensor != ggml_decoder->get_model_params().prune_keep &&
+ GgmlOvDecoder::is_output_idx(tensor, ggml_decoder->get_tensor_used_op(tensor))) {
+ out_ids = tensor;
+ break;
+ }
+ }
+ const int64_t n_outputs = out_ids != nullptr ? out_ids->ne[0] : 0;
+ std::string kv_only_error;
+ if (n_outputs > 1) {
+ kv_only_error = "the batch needs " + std::to_string(n_outputs) + " output tokens";
+ } else if (n_outputs == 1) {
+ const int64_t row = static_cast<const int32_t *>(out_ids->data)[0];
+ const ComputeParams prefill_c_params = ggml_decoder->get_compute_params();
+ ggml_decoder->m_is_prefill = false;
+ try {
+ // Run the decode model of the KV window the next decode step uses (it covers the output
+ // token); its inputs are sized by the decoder's attention size.
+ auto & step = variant_with_request(decode_key);
+ auto step_request = step.request;
+ auto step_c_params = prefill_c_params;
+ step_c_params.attention_size = decode_key.attention_size;
+ step_c_params.attention_size_swa = decode_key.attention_size_swa;
+ ggml_decoder->set_compute_params(step_c_params);
+ const auto & compiled_inputs = step.model.inputs();
+ for (size_t i = 0; i < step.input_names.size(); i++) {
+ const auto & name = step.input_names[i];
+ auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, name, row);
+ if (input_tensor.get_shape() != compiled_inputs[i].get_shape()) {
+ throw std::runtime_error("decode input " + name + " has shape " +
+ input_tensor.get_shape().to_string() + ", expected " +
+ compiled_inputs[i].get_shape().to_string());
+ }
+ step_request->set_input_tensor(i, input_tensor);
+ }
+ const auto & model_outputs = ggml_decoder->get_model_outputs();
+ for (size_t i = 0; i < step.output_names.size(); i++) {
+ auto it = model_outputs.find(step.output_names[i]);
+ if (it == model_outputs.end() || ggml_nbytes(it->second) == 0) {
+ continue;
+ }
+ step_request->set_output_tensor(
+ i, create_ov_output_tensor(ggml_decoder, step_request, i, it->second));
+ }
+ const int64_t decode_start = ggml_time_us();
+ step_request->infer();
+ const int64_t decode_us = ggml_time_us() - decode_start;
+ ov_raw_infer_total += decode_us;
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
+ fprintf(stderr,
+ "GGML OpenVINO profiling: KV-only prefill output step: row=%lld, kv_window=%d, raw "
+ "infer=%.3f ms\n",
+ static_cast<long long>(row), ggml_decoder->get_compute_params().attention_size,
+ decode_us / 1000.0);
+ }
+ } catch (const std::exception & e) {
+ kv_only_error = e.what();
+ }
+ ggml_decoder->set_compute_params(prefill_c_params);
+ ggml_decoder->m_is_prefill = true;
+ }
+ if (!kv_only_error.empty()) {
+ // Fall back to the full prefill: drop this backend's requests and run the graph again. The KV-only prefill
+ // has already written the batch's KV rows, and the full prefill writes the same values.
+ GGML_LOG_WARN("ggml-openvino: KV-only prefill cannot compute the outputs (%s); using the full prefill\n",
+ kv_only_error.c_str());
+ g_kv_only_prefill_failed = true;
+ {
+ std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
+ r_ctx->clear_caches_locked();
+ }
+ // Free the KV-only models before the full ones are built.
+ infer_request.reset();
+ entry->variants.clear();
+ entry->ptr.reset();
+ return ov_graph_compute_static(cgraph, r_ctx);
+ }
+ }
infer_end_time = ggml_time_us();
} else {
- if (decode_bucket > 0 && c_params.attention_size != entry->decode_attention_size) {
- infer_request = get_decode_window_request(c_params.attention_size);
- }
-
for (size_t i = 0; i < ov_input_names_local.size(); i++) {
const auto & param_name = ov_input_names_local[i];
auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, param_name);
@@ -3177,8 +3036,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
infer_end_time = ggml_time_us();
ov_raw_infer_total = infer_end_time - ov_raw_infer_start;
- if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
- ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
+ if (debug_output_enabled()) {
for (size_t i = 0; i < ov_output_names_local.size(); i++) {
const auto output_tensor = infer_request->get_output_tensor(i);
print_output_tensor_info(ov_output_names_local[i], output_tensor, nullptr);
@@ -3189,26 +3047,13 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
if (kv_grew) {
GGML_LOG_INFO("ggml-openvino: on-demand KV storage moved to cover a %zu-row window\n", kv_rows);
}
- if (kv_grew && cache_enabled && !entry->shared_key.empty()) {
- // Idle requests still bound to the previous KV storage keep it (and their own buffers) alive: drop the
- // other window requests and recreate the pair's idle requests.
- for (auto it = entry->decode_window_requests.begin(); it != entry->decode_window_requests.end();) {
- it = it->second == infer_request ? std::next(it) : entry->decode_window_requests.erase(it);
- }
- auto shared_cache = r_ctx->compiled_cache;
- std::lock_guard<std::mutex> compile_lock(shared_cache->mutex);
- auto graph_it = shared_cache->graphs.find(entry->shared_key);
- if (graph_it != shared_cache->graphs.end()) {
- std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
- auto renew = [&](auto & cache, ov::CompiledModel & compiled) {
- auto it = cache.find(key);
- if (it != cache.end() && it->second != infer_request) {
- it->second.reset();
- it->second = std::make_shared<ov::InferRequest>(compiled.create_infer_request());
- }
- };
- renew(r_ctx->infer_request_cache_prefill, graph_it->second.prefill);
- renew(r_ctx->infer_request_cache, graph_it->second.decode);
+ if (kv_grew) {
+ // Idle requests still bound to the previous KV storage keep it (and their own buffers) alive: drop them, they
+ // are recreated on next use.
+ for (auto & [k, v] : entry->variants) {
+ if (v.request != infer_request) {
+ v.request.reset();
+ }
}
}
@@ -3227,11 +3072,6 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
}
} // namespace
-void ov_clear_imported_blobs() {
- std::lock_guard<std::mutex> lock(g_imported_blobs_mutex);
- g_imported_blobs.clear();
-}
-
// Drop unselected branches except pure top-k sampling. Keeping those branches gives MTP a stable
// model interface as active slots change; inactive results use private output buffers.
static ggml_cgraph * get_compute_graph(ggml_cgraph * cgraph, ov_runtime_context & r_ctx, bool stable_sampling) {
@@ -3410,14 +3250,23 @@ bool is_model_splitted(ggml_cgraph * cgraph) {
}
bool is_naive(ggml_cgraph * cgraph) {
+ // Small graphs, and graphs without model weights (whole-graph op tests), are translated op by op; the model
+ // path relies on LLM graph patterns.
constexpr int naive_graph_size_threshold = 20;
int count = 0;
+ bool has_weights = false;
for (int i = 0; i < cgraph->n_nodes; i++) {
- if (cgraph->nodes[i]->op != GGML_OP_NONE) {
+ const ggml_tensor * node = cgraph->nodes[i];
+ if (node->op != GGML_OP_NONE) {
count++;
}
+ for (int j = 0; j < GGML_MAX_SRC && !has_weights; j++) {
+ const ggml_tensor * src = node->src[j];
+ has_weights =
+ src != nullptr && src->buffer != nullptr && src->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS;
+ }
}
- return count < naive_graph_size_threshold;
+ return count < naive_graph_size_threshold || !has_weights;
}
void print_input_tensor_info(const std::string & name, const ov::Tensor & input) {
diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h
index 270676b07..ee170a266 100644
--- a/ggml/src/ggml-openvino/utils.h
+++ b/ggml/src/ggml-openvino/utils.h
@@ -13,6 +13,7 @@
#include <openvino/runtime/core.hpp>
#include <openvino/runtime/infer_request.hpp>
#include <string>
+#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <utility>
@@ -96,43 +97,55 @@ struct graph_key_hash {
}
};
+// One compiled model of a static graph: its phase, KV window, SWA window and output count.
+struct ov_static_variant_key {
+ bool prefill = false;
+ int attention_size = -1;
+ int attention_size_swa = -1;
+ int output_len = 1;
+
+ bool operator<(const ov_static_variant_key & other) const {
+ return std::tie(prefill, output_len, attention_size_swa, attention_size) <
+ std::tie(other.prefill, other.output_len, other.attention_size_swa, other.attention_size);
+ }
+
+ bool operator==(const ov_static_variant_key & other) const { return !(*this < other) && !(other < *this); }
+};
+
+struct ov_static_variant {
+ ov::CompiledModel model;
+ // Created on first use, so only the requests a run needs hold NPU memory.
+ std::shared_ptr<ov::InferRequest> request;
+ std::vector<std::string> input_names;
+ std::vector<std::string> output_names;
+};
+
struct decoder_runtime_ctx {
decoder_runtime_ctx(std::shared_ptr<std::mutex> mutex) : mutex(std::move(mutex)) {}
std::shared_ptr<std::mutex> mutex;
std::shared_ptr<GgmlOvDecoder> ptr;
- // Attention sizes and output count the cached prefill model was built with; decode calls overwrite the
- // decoder's.
- int prefill_attention_size = -1;
- int prefill_attention_size_swa = -1;
- int prefill_output_len = -1;
- // KV window of the decode model in the compiled pair (GGML_OPENVINO_NPU_BLOB_PREBUILD).
- int decode_attention_size = -1;
- std::string shared_key;
- std::map<int, std::shared_ptr<ov::InferRequest>> decode_window_requests;
+
+ // Static path: the compiled models of this graph with their requests (ov_graph_compute_static).
+ std::map<ov_static_variant_key, ov_static_variant> variants;
+ // The prefill models only write the KV cache; logits come from one decode step (GGML_OPENVINO_KV_ONLY_PREFILL).
+ bool kv_only_prefill = false;
+ bool decode_unfold = false;
+ uint64_t cache_base_extra = 0;
+ // With a model cache, every window of a phase is exported (or imported) on the first call of that phase.
+ bool prefill_prepared = false;
+ bool decode_prepared = false;
+ // NPU weightless bank: the weights file and NPUW bank of every blob of this graph, and the file's layout once
+ // it is known in this process (new blobs resolve their weights through it).
+ std::string weights_path;
+ std::string weights_bank;
+ std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
};
struct ov_compiled_graph {
ov::CompiledModel decode;
- ov::CompiledModel prefill;
std::vector<std::string> input_names;
std::vector<std::string> output_names;
- std::vector<std::string> prefill_input_names;
- std::vector<std::string> prefill_output_names;
- // Extra decode models for other KV windows, built on first use with the pair's settings.
- int decode_attention_size = -1;
- std::map<int, ov::CompiledModel> decode_windows;
- ov::AnyMap decode_config;
- uint64_t cache_base_extra = 0;
- bool self_contained = false;
- bool decode_unfold = false;
- // GGML_OPENVINO_NPU_WEIGHTLESS_BANK: the pair's weights file, and its layout when the pair was compiled in
- // this process (window models then resolve the shared weights through the same file).
- bool weightless_bank = false;
- std::string weights_path;
- std::shared_ptr<ggml_openvino_weights_layout> weights_layout;
- // Compute params the pair's decode model was built with; window models derive from them.
- ComputeParams decode_c_params;
};
// Only compilation and cache publication use this mutex. Requests, decoders and
@@ -154,11 +167,8 @@ struct ov_runtime_context {
bool stateful;
std::unordered_map<graph_key, std::shared_ptr<decoder_runtime_ctx>, graph_key_hash> decoder_cache;
std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache;
- std::unordered_map<graph_key, std::shared_ptr<ov::InferRequest>, graph_key_hash> infer_request_cache_prefill;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
- std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
- std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
// LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
// that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
// injection graphs every round -- needs a slot per shape open at once; a single-entry cache
@@ -193,11 +203,8 @@ struct ov_runtime_context {
lru_keys.pop_front();
decoder_cache.erase(victim);
infer_request_cache.erase(victim);
- infer_request_cache_prefill.erase(victim);
ov_input_names_cache.erase(victim);
ov_output_names_cache.erase(victim);
- ov_input_names_cache_prefill.erase(victim);
- ov_output_names_cache_prefill.erase(victim);
}
// Make room for one more graph shape if the cache is at capacity, then mark `key` as most
@@ -212,11 +219,8 @@ struct ov_runtime_context {
void clear_caches_locked() {
decoder_cache.clear();
infer_request_cache.clear();
- infer_request_cache_prefill.clear();
ov_input_names_cache.clear();
ov_output_names_cache.clear();
- ov_input_names_cache_prefill.clear();
- ov_output_names_cache_prefill.clear();
lru_keys.clear();
kv_state_input_name_map.clear();
stateful_kv_size = 0;
@@ -230,9 +234,6 @@ struct ov_runtime_context {
enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t backend);
-// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
-void ov_clear_imported_blobs();
-
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);