Compare commits

...
3 Commits
Author SHA1 Message Date
e0b9fd7d76 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>
2026-11-26 18:26:55 -08:00
Anant Shrivastava a07831a008 sycl: route BMG D=256 single-query decode to the FA vector kernel (#30606) 2026-11-26 18:47:37 -05:00
lhezandHongqiang Wang 9fa7a33cbb opencl: add multi token f32 GEMV for spec verify (#33098)
* opencl: add multi token F32 GEMV

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
Assisted-by: Codex

* opencl: let ne01 > 512 still use tiled GEMM

---------

Co-authored-by: Hongqiang Wang <wangh@qti.qualcomm.com>
2026-11-26 13:26:17 -08:00
43 changed files with 1503 additions and 1377 deletions
+8 -7
View File
@@ -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>
+1
View File
@@ -818,6 +818,7 @@ User can use the device management in [docs/multi-gpu.md](https://github.com/ggm
| GGML_SYCL_ENABLE_VMM | 0 or 1 (default) | Enable the virtual-memory device pool. |
| GGML_SYCL_ENABLE_MKL_FA | 1 (default) or 0 | Enable oneMKL GEMM flash attention for XMX-accelerated prompt processing with quantized KV cache. Automatically activates during prefill (prompt processing) when all conditions are met: (1) flash-attn enabled (`-fa` or `--flash-attn on`), (2) KV cache quantized (`--cache-type-k q8_0 --cache-type-v q8_0` or other `*_0/*_1` types), (3) batch size ≥ 1024 (`--batch-size 1024`), (4) prompt length ≥ 1024 tokens. Set to 0 to force the TILE kernel for A/B testing. Example minimum command: `llama-cli -m model.gguf -fa -ngl 99 --cache-type-k q8_0 --cache-type-v q8_0 --batch-size 1024 -p "your prompt"` |
| GGML_SYCL_MKL_FA_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for MKL flash attention: GEMM/softmax timings, interleaved-head detection, and buffer memory usage. |
| GGML_SYCL_FA_TILE_DEBUG | 0 (default) or 1 | Enable per-call diagnostic logging for the flash-attention TILE kernel dispatcher: head dims (DKQ/DV), GQA ratio, query rows, KV length, and whether the GQA-optimized variant is selected. |
| GGML_SYCL_MEMTRACE | 0 (default), 1, 2 | Enable record and output memory allocation diagnostics. Requires `-lv 4`. <br>0 - Disable<br>1 - Basic memory info, including current and peak allocations, as well allocations from other sources, and the device free memory before each model buffer allocation, around 50 lines per model load.<br>2 - More verbose, logging around 900 specific allocations and deallocations. |
| GGML_SYCL_MEMTRACE_STEP | 64 (default) or positive integer | With GGML_SYCL_MEMTRACE=1, the minimum growth in memory usage to trigger another log record. |
| GGML_SYCL_MKL_FA_DIAG | 0 (default) or 1 | Enable output fingerprinting for MKL flash attention. Dumps the first 64 float output values for the first 6 FA calls with n_kv ≥ 1024, labeled with kernel type (MKL/TILE/VEC) for cross-kernel comparison. |
+83 -2
View File
@@ -1249,6 +1249,7 @@ struct ggml_backend_opencl_context {
cl_kernel kernel_mul_mv_id_mxfp4_f32_flat;
cl_kernel kernel_mul_mm_f32_f32_l4_lm;
cl_kernel kernel_gemv_f32_f32_mc; // multi-column (small-N) f32 GEMV for spec/MTP verify
cl_kernel kernel_gemv_f32_f32_mcr = nullptr;
cl_kernel kernel_mul_mm_f16_f32_l4_lm;
cl_kernel kernel_mul_mm_f16_f32_l4_lm_n8;
cl_kernel kernel_mul_mm_q1_0_f32_l4_lm;
@@ -1571,6 +1572,7 @@ struct ggml_backend_opencl_context {
}
#endif
for (cl_kernel kernel : {
kernel_gemv_f32_f32_mcr,
kernel_xielu_f32,
kernel_xielu_f16,
kernel_mul_mm_f16_f32_kq_p8,
@@ -4282,6 +4284,16 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
CL_CHECK((backend_ctx->kernel_mul_mm_f32_f32_l4_lm = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_mul_mm_f32_f32_l4_lm", &err), err));
CL_CHECK((backend_ctx->kernel_gemv_f32_f32_mc = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mc", &err), err));
cl_kernel mcr = clCreateKernel(backend_ctx->program_mul_mm_f32_f32_l4_lm, "kernel_gemv_f32_f32_mcr", &err);
if (err == CL_SUCCESS) {
if (backend_ctx->get_kernel_workgroup_size(mcr) >= 64) {
backend_ctx->kernel_gemv_f32_f32_mcr = mcr;
} else {
CL_CHECK(clReleaseKernel(mcr));
}
}
GGML_LOG_CONT(".");
}
@@ -33076,6 +33088,20 @@ static void ggml_cl_fwht(ggml_backend_t backend, const ggml_tensor * src, ggml_t
backend_ctx->enqueue_ndrange_kernel(kernel, 2, global, local, dst);
}
// reduce lanes per row for short K, down to four lanes.
static int ggml_cl_mcr_lpr_log2(int ne00) {
int lpr_log2 = 6;
while (lpr_log2 > 2 && ((ne00 / 4) >> lpr_log2) < 4) {
lpr_log2--;
}
return lpr_log2;
}
static bool ggml_cl_mcr_wide_enough(int ne00, int ne01) {
const int rows_per_wg = 64 >> ggml_cl_mcr_lpr_log2(ne00);
return CEIL_DIV((size_t) ne01, rows_per_wg) >= 256;
}
static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_ASSERT(src0);
GGML_ASSERT(src0->extra);
@@ -33670,8 +33696,63 @@ static void ggml_cl_mul_mat(ggml_backend_t backend, const ggml_tensor * src0, co
// under-occupied WG at ~2.3% tile utilization. Route to a per-output
// (m,n) GEMV (64-thread WG, K-split + __local reduce) instead.
// 2D contiguous, small N + skinny M only. Default on for X2E, GGML_OPENCL_F32_MC=0/1 forces it.
static const char * f32_mc_env = getenv("GGML_OPENCL_F32_MC");
const bool f32_mc = f32_mc_env ? atoi(f32_mc_env) != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
static const int f32_mc_env = [] {
const char * env = getenv("GGML_OPENCL_F32_MC");
return env ? atoi(env) : -1;
}();
const bool f32_mc = f32_mc_env >= 0 ? f32_mc_env != 0 : backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E;
static const int f32_mcr_env = [] {
const char * env = getenv("GGML_OPENCL_F32_MCR");
return env && *env ? atoi(env) : -1;
}();
const bool f32_mcr = f32_mcr_env >= 0 ? f32_mcr_env != 0 :
(backend_ctx->adreno_gen == ADRENO_GPU_GEN::X2E || backend_ctx->adreno_gen == ADRENO_GPU_GEN::A8X);
const bool f32_mcr_allowed = f32_mc_env >= 0 ? f32_mc_env != 0 : !adreno_e17_compiler_quirks(backend_ctx);
if (f32_mcr && f32_mcr_allowed && backend_ctx->kernel_gemv_f32_f32_mcr != nullptr &&
ne11 >= 2 && ne11 <= 8 && ne00 > 0 && ne00 <= INT_MAX && ne01 > 0 && ne01 <= 512 &&
(size_t) ne01 <= SIZE_MAX / 64 && (ne00 % 4 == 0) &&
ne02 == 1 && ne03 == 1 && ne12 == 1 && ne13 == 1 &&
dst->ne[2] == 1 && dst->ne[3] == 1 &&
ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ggml_is_contiguous(dst) &&
offset0 % 16 == 0 && offset1 % 16 == 0 && offsetd % sizeof(float) == 0 &&
ggml_cl_mcr_wide_enough((int) ne00, (int) ne01)
) {
const int K = (int) ne00;
const int M = (int) ne01;
const int N = (int) ne11;
const int stride_a = K;
const int stride_b = K;
const int stride_d = M;
const int lpr_log2 = ggml_cl_mcr_lpr_log2(K);
const int rows_per_wg = 64 >> lpr_log2;
cl_kernel mcr = backend_ctx->kernel_gemv_f32_f32_mcr;
CL_CHECK(clSetKernelArg(mcr, 0, sizeof(cl_mem), &extra0->data_device));
CL_CHECK(clSetKernelArg(mcr, 1, sizeof(cl_ulong), &offset0));
CL_CHECK(clSetKernelArg(mcr, 2, sizeof(cl_mem), &extra1->data_device));
CL_CHECK(clSetKernelArg(mcr, 3, sizeof(cl_ulong), &offset1));
CL_CHECK(clSetKernelArg(mcr, 4, sizeof(cl_mem), &extrad->data_device));
CL_CHECK(clSetKernelArg(mcr, 5, sizeof(cl_ulong), &offsetd));
CL_CHECK(clSetKernelArg(mcr, 6, sizeof(int), &K));
CL_CHECK(clSetKernelArg(mcr, 7, sizeof(int), &M));
CL_CHECK(clSetKernelArg(mcr, 8, sizeof(int), &N));
CL_CHECK(clSetKernelArg(mcr, 9, sizeof(int), &stride_a));
CL_CHECK(clSetKernelArg(mcr, 10, sizeof(int), &stride_b));
CL_CHECK(clSetKernelArg(mcr, 11, sizeof(int), &stride_d));
CL_CHECK(clSetKernelArg(mcr, 12, sizeof(int), &lpr_log2));
size_t global[] = {CEIL_DIV((size_t) M, rows_per_wg) * 64, 1, 1};
size_t local[] = {64, 1, 1};
backend_ctx->enqueue_ndrange_kernel(mcr, 3, global, local, dst);
return;
}
if (f32_mc && ne11 >= 2 && ne11 <= 8 && ne01 <= 512 && (ne00 % 4 == 0) &&
ne02 == 1 && ne12 == 1 && ne13 == 1 &&
ggml_is_contiguous(src0) && ggml_is_contiguous(src1)) {
@@ -194,3 +194,64 @@ kernel void kernel_gemv_f32_f32_mc(
}
if (lane == 0) dst[(ulong)n * (uint)stride_d + m] = red[0];
}
// Reuse each weight row across the narrow batch, with one accumulator per column.
kernel void kernel_gemv_f32_f32_mcr(
global const float * src0, ulong offset0,
global const float * src1, ulong offset1,
global float * dst, ulong offsetd,
int ne00, // K
int ne01, // M
int ne11, // N, 2..8
int stride_a,
int stride_b,
int stride_d,
int lpr_log2 // lanes per row = 1 << lpr_log2
) {
src0 = (global const float*)((global const char*)src0 + offset0);
src1 = (global const float*)((global const char*)src1 + offset1);
dst = (global float*)((global char*)dst + offsetd);
const uint lane = get_local_id(0);
const uint lpr = 1u << lpr_log2;
const uint l = lane & (lpr - 1);
const uint mr = get_group_id(0) * (64u >> lpr_log2) + (lane >> lpr_log2);
const bool valid = mr < (uint)ne01;
// Keep padded rows in the local-memory barriers.
const uint m = valid ? mr : (uint)ne01 - 1;
global const float4 * wrow = (global const float4*)(src0 + (ulong)m * (uint)stride_a);
const uint k4 = (uint)ne00 >> 2;
float acc[8] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
for (uint k = l; k < k4; k += lpr) {
const float4 w = wrow[k];
#pragma unroll
for (int n = 0; n < 8; n++) {
if (n < ne11) {
acc[n] += dot(w, ((global const float4*)(src1 + (ulong)n * (uint)stride_b))[k]);
}
}
}
local float red[8 * 64];
#pragma unroll
for (int n = 0; n < 8; n++) {
red[n * 64 + lane] = acc[n];
}
barrier(CLK_LOCAL_MEM_FENCE);
for (uint s = lpr >> 1; s > 0; s >>= 1) {
if (l < s) {
#pragma unroll
for (int n = 0; n < 8; n++) {
red[n * 64 + lane] += red[n * 64 + lane + s];
}
}
barrier(CLK_LOCAL_MEM_FENCE);
}
if (l == 0 && valid) {
for (int n = 0; n < ne11; n++) {
dst[(ulong)n * (uint)stride_d + m] = red[n * 64 + lane];
}
}
}
+7 -10
View File
@@ -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()
+8
View File
@@ -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.
@@ -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.
@@ -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");
+133 -81
View File
@@ -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];
+39 -42
View File
@@ -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;
+43 -46
View File
@@ -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_npu_weightless_bank_enabled() {
return ggml_openvino_getenv_int("GGML_OPENVINO_NPU_WEIGHTLESS_BANK") != 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_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;
}
+33 -18
View File
@@ -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();
// 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): 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).
// 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);
+15 -47
View File
@@ -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"};
}
}
}
-23
View File
@@ -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 {
+19 -54
View File
@@ -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);
+8 -12
View File
@@ -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;
+5 -2
View File
@@ -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;
@@ -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;
};
@@ -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>
+10 -4
View File
@@ -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();
@@ -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);
@@ -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};
@@ -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;
@@ -2,7 +2,6 @@
#include "../op_table.h"
#include "../utils.h"
#include <climits>
#include <cstdint>
#include <memory>
#include <openvino/core/node.hpp>
@@ -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())) {
+20 -25
View File
@@ -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();
@@ -3,7 +3,6 @@
#include "../utils.h"
#include "ggml-openvino/ggml-openvino-extra.h"
#include <cassert>
#include <cstdint>
#include <memory>
#include <numeric>
+20 -24
View File
@@ -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;
int64_t d_conv = c_shape[3];
// 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}));
// 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, 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});
// 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});
// 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});
// 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);
// 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());
}
@@ -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
@@ -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
@@ -1,6 +1,5 @@
#pragma once
#include "mark_decompression_convert_constant_folding.h"
#include "openvino/core/visibility.hpp"
#include "openvino/pass/matcher_pass.hpp"
@@ -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,
@@ -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);
@@ -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>
@@ -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);
+25 -3
View File
@@ -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);
}
return context.get_input(input_index);
if (!pruned) {
return mask;
}
// 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) {
+3
View File
@@ -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) {
File diff suppressed because it is too large Load Diff
+39 -38
View File
@@ -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);
+7
View File
@@ -18,6 +18,7 @@
extern int g_ggml_sycl_debug;
extern int g_ggml_sycl_dev_debug;
extern int g_ggml_sycl_fa_tile_debug;
#if defined(__clang__) && __has_builtin(__builtin_expect)
// Hint the optimizer to pipeline the more likely following instruction in branches
@@ -40,4 +41,10 @@ extern int g_ggml_sycl_dev_debug;
fprintf(stderr, __VA_ARGS__); \
} while (0)
#define GGML_SYCL_FA_TILE_DEBUG(...) \
do { \
if (UNLIKELY(g_ggml_sycl_fa_tile_debug)) \
fprintf(stderr, __VA_ARGS__); \
} while (0)
#endif // GGML_SYCL_BASE_HPP
+18 -5
View File
@@ -880,15 +880,24 @@ static void flash_attn_tile(const char * Q,
KQ_max_new_shared);
}
} else {
// Branch without out-of-bounds checks.
for (int k_VKQ_0 = item_ct1.get_group(1) * nbatch_fa; k_VKQ_0 < k_VKQ_max;
k_VKQ_0 += item_ct1.get_group_range(1) * nbatch_fa) {
// Branch without out-of-bounds checks for full chunks; the trailing partial
// chunk (n_kv not a multiple of nbatch_fa) takes the checked iteration, so
// the GQA-optimized variants no longer require K->ne[1] % FATTN_KQ_STRIDE == 0.
int k_VKQ_0 = item_ct1.get_group(1) * nbatch_fa;
while (k_VKQ_0 < k_VKQ_max - nbatch_fa) {
constexpr bool oob_check = false;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap,
oob_check>(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, stride_K2,
stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0,
KQ_max_new_shared);
k_VKQ_0 += item_ct1.get_group_range(1) * nbatch_fa;
}
if (k_VKQ_0 < k_VKQ_max) {
constexpr bool oob_check = true;
flash_attn_tile_iter<warp_size, nwarps, ncols1, ncols2, DKQ, DV, nbatch_fa, nbatch_K, use_logit_softcap,
oob_check>(Q_tmp, K_h2, V_h2, maskh, ne01, logit_softcap, slope, KQ, KV_tmp, stride_K2,
stride_V2, stride_mask, KQ_max, KQ_sum, VKQ, k_VKQ_0, k_VKQ_max, col_Q_0,
KQ_max_new_shared);
}
}
@@ -1166,7 +1175,11 @@ static void launch_fattn_tile_switch_ncols2(ggml_backend_sycl_context & ctx, ggm
// However, for DKQ == 576, DV == 512 only the kernel variant with GQA optimizations is implemented.
//const bool nvidia = GGML_SYCL_CC_IS_NVIDIA(ggml_sycl_info().devices[ggml_sycl_get_device()].cc);
const int gqa_limit = gqa_ratio <= 4 && DV <= 256 ? 16 : INT_MAX;
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit && K->ne[1] % FATTN_KQ_STRIDE == 0;
// n_kv need not be a multiple of FATTN_KQ_STRIDE: the kernel handles the trailing
// partial chunk with the out-of-bounds checked iteration.
const bool use_gqa_opt = mask && max_bias == 0.0f && Q->ne[1] <= gqa_limit;
GGML_SYCL_FA_TILE_DEBUG("[FA-TILE] DKQ=%d DV=%d gqa=%d q=%lld n_kv=%lld gqa_opt=%d\n",
DKQ, DV, gqa_ratio, (long long) Q->ne[1], (long long) K->ne[1], (int) use_gqa_opt);
if constexpr (DV == 512) {
if (use_gqa_opt && gqa_ratio % 16 == 0) {
+12 -2
View File
@@ -129,7 +129,9 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
float logit_softcap = 0.0f;
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f && K->ne[1] % FATTN_KQ_STRIDE == 0;
// The GQA-optimized TILE variant handles a trailing partial chunk (out-of-bounds
// checked iteration), so n_kv no longer needs to be a multiple of FATTN_KQ_STRIDE.
bool gqa_opt_applies = gqa_ratio >= 2 && mask && max_bias == 0.0f;
// XMX-accelerated path: oneDNN SDPA (native F16 and dequant+non-F16).
// ONEDNN requires min 32 query tokens — short-circuit decode to avoid
@@ -267,7 +269,15 @@ static best_fattn_kernel ggml_sycl_get_best_fattn_kernel(const int device, const
if (can_use_vector_kernel) {
if (!ggml_is_quantized(K->type) && !ggml_is_quantized(V->type)) {
if (Q->ne[1] == 1) {
if (!gqa_opt_applies) {
// BMG, D=256: single-query decode runs materially faster on the vector
// kernel than on the GQA-optimized tile config (832 vs 1150 us at
// kv=65536, GQA4, B70-measured; +4..+18% end-to-end tg at 8k..64k
// context on spark2_5/qwen35 D=256 models). Other archs and head sizes
// keep the tile dispatcher's original preference.
const gpu_arch arch = ggml_sycl_info().devices[device].hw_info.arch;
const bool vec_decode = (arch == gpu_arch::intel_gpu_bmg_g21 ||
arch == gpu_arch::intel_gpu_bmg_g31) && Q->ne[0] == 256;
if (vec_decode || !gqa_opt_applies) {
return BEST_FATTN_KERNEL_VEC;
}
}
+3
View File
@@ -99,6 +99,7 @@
static bool g_sycl_loaded = false;
int g_ggml_sycl_debug = 0;
int g_ggml_sycl_dev_debug = 0;
int g_ggml_sycl_fa_tile_debug = 0;
int g_ggml_sycl_enable_optimize = 1;
int g_ggml_sycl_enable_graph = 0;
int g_ggml_sycl_enable_dnn = 1;
@@ -434,6 +435,7 @@ static void ggml_check_sycl() try {
g_ggml_sycl_debug = ggml_sycl_get_env("GGML_SYCL_DEBUG", 0);
g_ggml_sycl_dev_debug = ggml_sycl_get_env("GGML_SYCL_DEV_DEBUG", 0);
g_ggml_sycl_fa_tile_debug = ggml_sycl_get_env("GGML_SYCL_FA_TILE_DEBUG", 0);
g_ggml_sycl_enable_optimize = ggml_sycl_get_env("GGML_SYCL_ENABLE_OPT", 1);
g_ggml_sycl_enable_graph = ggml_sycl_get_env("GGML_SYCL_ENABLE_GRAPH", 0);
g_ggml_sycl_enable_dnn = ggml_sycl_get_env("GGML_SYCL_ENABLE_DNN", 1);
@@ -542,6 +544,7 @@ static void ggml_check_sycl() try {
GGML_LOG_INFO("Running with Environment Variables:\n");
GGML_LOG_INFO(" GGML_SYCL_DEBUG: %d\n", g_ggml_sycl_debug);
GGML_LOG_INFO(" GGML_SYCL_DEV_DEBUG: %d\n", g_ggml_sycl_dev_debug);
GGML_LOG_INFO(" GGML_SYCL_FA_TILE_DEBUG: %d\n", g_ggml_sycl_fa_tile_debug);
#ifdef GGML_SYCL_SUPPORT_LEVEL_ZERO_API
GGML_LOG_INFO(" GGML_SYCL_DEV2DEV_MEMCPY: %d (%s)\n", g_ggml_sycl_dev2dev_memcpy, dev2dev_int2str(g_ggml_sycl_dev2dev_memcpy));