Skip to content

Refactor compiled model caching for static NPU graphs - #460

Merged
ravi9 merged 4 commits into
ravi9:dev_backend_openvinofrom
zhaixuejun1993:xuejun/gemma4-e2b-v3
Nov 26, 2026
Merged

ravi9 merged 4 commits into
ravi9:dev_backend_openvinofrom
zhaixuejun1993:xuejun/gemma4-e2b-v3

Conversation

@zhaixuejun1993

@zhaixuejun1993 zhaixuejun1993 commented Nov 26, 2026 •

Copy link
Copy Markdown
Collaborator

ggml-openvino: one compiled-model cache per static (NPU) graph

Summary

The static (NPU) path now keeps one cache entry per cgraph. Each entry holds a map from a static variant to the compiled model for that variant and its infer request. A variant is prefill or decode, at a given KV window, SWA window and output length.

All importing and compiling happens in one function, static_load_variants(). Which cache directory to use, and whether to export or import, is still set by two environment variables, so no new variables are added.

Before and after

Before After
Where compiled models live Three places that had to stay 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, requests and I/O names in ov_runtime_context
• a process-wide imported-blob table (g_imported_blobs, import_cached_blob(), ov_clear_imported_blobs())
One place: decoder_runtime_ctx::variants, a std::map<ov_static_variant_key, ov_static_variant>
Variant key Implicit: a pair, plus separate window maps ov_static_variant_key {prefill, attention_size, attention_size_swa, output_len}, ordered
Infer requests Separate request and name caches for prefill, decode and each window Each ov_static_variant owns its request, created lazily on first use. Only one prefill request exists at a time.
Export / import / KV-window switch / fallback Each went through a different subset of the caches All go through static_load_variants(keys, needed)
Sharing across backends Compiled pair shared through compiled_cache->graphs Models belong to their own backend entry
SELF_CONTAINED_MMAP=1 with a missing blob Error surfaced late or indirectly Fails immediately: 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
Logging Mixed One line per model: <prefill|decode> model of KV window N imported/compiled in X ms
Cache fingerprint cache_base_extra + per-variant salt Unchanged, so existing caches stay valid and a new export gives the same blob names
Without head-major KV, during export All prefill windows kept resident All prefill windows are compiled and exported, but only the needed one stays resident. The others are imported on first use.
Code size — 530 lines added, 867 removed across utils.cpp, utils.h and ggml-openvino.cpp

Structure (utils.h)

struct ov_static_variant_key { bool prefill; int attention_size; int attention_size_swa; int output_len; };
struct ov_static_variant     { ov::CompiledModel model; std::shared_ptr<ov::InferRequest> request;
                               std::vector<std::string> input_names, output_names; };
struct decoder_runtime_ctx   { std::map<ov_static_variant_key, ov_static_variant> variants;
                               bool kv_only_prefill, decode_unfold, prefill_prepared, decode_prepared;
                               uint64_t cache_base_extra; /* weights path / bank / layout */ ... };

Helpers (utils.cpp, used by ov_graph_compute_static)

  • static_variant_keys: lists the variant keys to load.
  • static_cache_base_extra, static_variant_fp: compute the cache fingerprint.
  • static_select_weights: chooses the weights file (the graph's own file or the shared one).
  • static_blob_usable: checks that the blob, its manifest and the weights file are all valid.
  • static_build_decoder, static_convert, static_layout_weights, static_variant_config: build and convert the models.
  • static_load_variants: imports every model that has a usable blob, compiles and exports the rest, and enforces fail-fast.

Model cache workflow

Per-call flow (ov_graph_compute_static)

flowchart TD
    A[graph_compute cgraph] --> B{decoder_cache has graph_key?}
    B -- no --> B1[new decoder_runtime_ctx<br/>admit_locked, LRU max 8]
    B -- yes --> B2[touch_locked]
    B1 --> C
    B2 --> C{entry.ptr can_reuse_statically?}
    C -- no --> C1[reset entry: drop all variants]
    C -- yes --> D
    C1 --> D[first call: set kv_only_prefill, decode_unfold,<br/>cache_base_extra, select weights file]
    D --> E[compute decode_window from inp_pos and KV_SLICE base<br/>decode_key = decode, window]
    E --> F{is_prefill?}
    F -- yes --> F1[needed = prefill, attn, swa, out_len<br/>KV_SLICE and not head-major:<br/>reuse smallest loaded prefill with attn >= needed]
    F -- no --> F2[needed = decode_key]
    F1 --> G
    F2 --> G[keys = needed + decode_key<br/>+ all prefill windows if first prefill, cache dir set, decode_bucket > 0<br/>+ all decode windows if first call]
    G --> H{all keys in variants?}
    H -- yes --> I[cache hit]
    H -- no --> H1[no cache dir and prefill:<br/>erase other prefill variants, one prefill only]
    H1 --> J[static_load_variants keys, needed]
    J --> I
    I --> K[variant_with_request needed<br/>create request lazily, reset other prefill requests]
    K --> L[bind inputs, infer, copy outputs]
Loading

Inside static_load_variants

flowchart TD
    S[for each key not in variants] --> T[fp = static_variant_fp]
    T --> U{weightless bank and blob, manifest, weights valid?}
    U -- yes --> V[mark import]
    U -- no --> W{SELF_CONTAINED_MMAP=1?}
    W -- yes --> X[throw: no usable cached model of KV window N]
    W -- no --> Y[mark compile]
    V --> Z
    Y --> Z{anything to compile?}
    Z -- yes --> Z1[fail fast if host weights released<br/>first export: write shared weights.bin layout<br/>WARN: no usable cached blobs ... N models<br/>convert first prefill and first decode before compiling]
    Z1 --> R
    Z -- no --> R[for each pending model:<br/>import blob, or compile + export blob + manifest]
    R --> Q[LOG: model of KV window N imported/compiled in X ms]
    Q --> P{keep in memory?<br/>all decode; needed prefill;<br/>all if MMAP=1 or head-major}
    P -- yes --> P1[variants.emplace]
    P -- no --> P2[drop; reimported from cache on first use]
Loading

Cache modes

flowchart LR
    N0[COMPILED_MODEL_CACHE_DIR unset] --> M0[compile in memory only<br/>one prefill variant resident<br/>decode windows compiled once]
    N1[cache dir set + MMAP=0<br/>export run] --> M1[import usable blobs<br/>compile + export missing ones<br/>weightless blobs + one shared weights.bin]
    N2[cache dir set + MMAP=1<br/>import run] --> M2[import everything<br/>GGUF mmap as weight buffer<br/>missing blob means immediate error]
Loading

How to use

1. Export once (build the cache)

$env:GGML_OPENVINO_DEVICE = 'NPU'
$env:GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR = "$PWD\bench-cache\phi4"
$env:GGML_OPENVINO_SELF_CONTAINED_MMAP = '0'   # compile + export missing blobs
$env:GGML_OPENVINO_KV_SLICE = '1'              # 1 = base 1024; any other value is the base window
$env:GGML_OPENVINO_NPU_BLOB_PREBUILD = '1'     # export every prefill/decode KV window up front
llama-server.exe -m phi-4-mini-instruct-q4_0.gguf -c 8192 -fa 1 ...

Expected log:

W ggml-openvino: no usable cached blobs in <dir> for 8 model(s); compiling and exporting them as weightless-bank blobs
I ggml-openvino: prefill model of KV window 1024 compiled in ... ms
I ggml-openvino: decode model of KV window 1024 compiled in ... ms
...

2. Import on later runs

Use the same model, arguments and environment as the export run. The only change is setting SELF_CONTAINED_MMAP to 1.

$env:GGML_OPENVINO_SELF_CONTAINED_MMAP = '1'      # import only; GGUF mmap as weight buffer
$env:GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB = '128' # optional: lower resident memory
llama-server.exe -m phi-4-mini-instruct-q4_0.gguf -c 8192 -fa 1 ...

Expected log: only ... imported in X ms lines, with no compiled lines.

If the cache does not match, for example because the arguments or environment changed, the run stops with:

GGML_OPENVINO_SELF_CONTAINED_MMAP: no usable cached decode model of KV window 256 in <dir>; run once with GGML_OPENVINO_SELF_CONTAINED_MMAP=0 to build the cache

3. Without a cache dir (for example llama-bench)

If GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR is not set, models are compiled in memory. Every decode KV window is compiled on the first call, and only one prefill model is kept, because two resident prefill models can run the NPU out of memory. With KV slicing on, a larger loaded prefill model also serves smaller windows, so the timed reps do not recompile.

Notes

  • NPU_CACHE_MMAP is ignored. Use GGML_OPENVINO_SELF_CONTAINED_MMAP.
  • NPU graphs without a KV cache are never cached and always compile.
  • A cache built with the previous commit can still be imported, because the fingerprint formula did not change.

Verification

  • Build: MSVC Release build of llama-server, llama-simple and llama-bench passes. granite-4.0-1b llama-simple on NPU decodes 20 tokens correctly.

  • phi-4-mini Q4_0, llama-server on NPU (c=8192, chunk 1024, KV_SLICE=1):

    • Export compiled 8 models, with the same blob names as before.

    • 3 imports with 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%
  • gemma-4-E2B Q4_0, llama-server on NPU (KV-only prefill): export compiled 8 models. Imports with MMAP=1 had no recompile and no errors: load 4452 ms, prefill 2315 t/s, decode 21.55 t/s.

  • Qwen3.5-4B, llama-bench pp1024, KV_SLICE=512, no cache dir: 3 compiles in total (decode 512, decode 1024, prefill 1024), all during load and warmup. The 5 timed reps had no recompile; result 453.28 ± 0.35 t/s.

  • Fail-fast: MMAP=1 with an empty cache dir exits with the error message above.


To put this on GitHub as the PR description, tell me and I'll save it to a file.

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.
@ravi9
ravi9 merged commit a97d80a into ravi9:dev_backend_openvino Nov 26, 2026
0 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants