Skip to content

gemma4: Optimized prompt processing for multi-seq queries - #32342

Merged
am17an merged 2 commits into
ggml-org:masterfrom
Meet91721:optim/multi-seq-pp-g4
Nov 20, 2026
Merged

am17an merged 2 commits into
ggml-org:masterfrom
Meet91721:optim/multi-seq-pp-g4

Conversation

@Meet91721

@Meet91721 Meet91721 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR is in continuation to #31356 from @max-krasnyansky .
This PR enables Gemma 4 E4B and E2B models to skip calculation for prompt rows which do not requires logits to be calculated when processing multiple sequences.

The commit: dd099a6 in the master branch has the following benchmarks:

PP TG B N_KV T_PP s S_PP t/s T_TG s S_TG t/s T s S t/s
512 32 1 544 0.760 673.93 0.633 50.55 1.393 390.58
512 32 2 1088 1.487 688.75 0.774 82.65 2.261 481.19
512 32 4 2176 2.941 696.28 0.841 152.25 3.782 575.34
512 32 8 4352 5.864 698.53 0.945 270.85 6.809 639.16
2048 32 1 2080 3.139 652.34 0.642 49.81 3.782 549.98
2048 32 2 4160 6.572 623.27 0.793 80.71 7.365 564.86
2048 32 4 8320 13.907 589.06 0.918 139.36 14.825 561.20
2048 32 8 16640 63.753 256.99 4.293 59.64 68.045 244.54

Current PR's changes has the following benchmarks:

PP TG B N_KV T_PP s S_PP t/s T_TG s S_TG t/s T s S t/s
512 32 1 544 0.301 1700.60 0.633 50.55 0.934 582.40
512 32 2 1088 0.543 1885.77 0.774 82.70 1.317 826.19
512 32 4 2176 1.027 1994.67 0.836 153.18 1.862 1168.43
512 32 8 4352 1.994 2054.57 0.963 265.83 2.957 1471.94
2048 32 1 2080 1.088 1882.30 0.650 49.24 1.738 1196.85
2048 32 2 4160 2.131 1922.50 0.793 80.69 2.924 1422.84
2048 32 4 8320 4.221 1940.66 0.876 146.11 5.097 1632.23
2048 32 8 16640 8.494 1928.93 1.030 248.50 9.524 1747.16

The prompt processing rate is being improved by ~3x.

The above benchmarks were obtained using the following command:

llama-batched-bench \
  -m gemma-4-E2B-it-Q4_0.gguf \
  -c 20000  -b 2048  -ub 512 \
  -npp 512,2048 \
  -ntg 32 \
  -npl 1,2,4,8 \
  -fa on 

Additional information

I am testing this on the MacBook Air M3, 16GB RAM.
I have used the following model: ggml-org/gemma-4-E2B-it-GGUF

Requirements

  • I have read and agree with the contributing guidelines
  • AI usage disclosure: Yes, AI was used for reviewing the changes and it performed tests to check the correctness of these changes.

@Meet91721
Meet91721 requested a review from a team as a code owner November 15, 2026 13:36
@github-actions github-actions Bot added the model Model specific label Nov 15, 2026
@Meet91721

Copy link
Copy Markdown
Contributor Author

Hi @max-krasnyansky , @am17an

Please review these changes, it resolves the TODOs mentioned in the #31356 (comment) related to supporting the optimizations for multi sequence queries.
Let me know if there is something that needs to be addressed.

@am17an

am17an commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Does it work with spec-dec too?

@Meet91721

Copy link
Copy Markdown
Contributor Author

Yes, it works with speculative decoding too.

Comment thread src/models/gemma4.cpp Resolved
@am17an

am17an commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

BTW, even dsv4.1 has something like this, I think after the 20th layer we don't need to compute more than the SWA window. If you're willing to take that up let me know

@am17an

am17an commented Nov 15, 2026

Copy link
Copy Markdown
Contributor

Thanks, this looks correct to me. Automated review below.

Tested on an RTX PRO 6000 (sm_120, CUDA) with gemma-4-E2B-it Q4_0.

The masks and the row selection hold up in both layouts. With split KV the pruned mask is [n_kv, M, 1, n_stream]. With -kvu and FA, kv_rows gives [n_kv_rows, M, 1, n_slices]. In both cases build_attn_mha splits q into S groups of M rows, so the padding per slice lines up. The rows tensor is copied unchanged, which is correct because it is per slice. inp_prune_keep produces rows in ascending batch order, the same order as inp_out_ids. Graph reuse is covered: allow_reuse checks n_outputs, the attn input checks S, and the new input checks M.

Tests:

  • I wrote a small libllama harness. It puts 4 sequences in one batch, requests 3/1/2/1 outputs per sequence, then runs 4 decode steps. I ran it with split KV and with -kvu (kv_rows), with FA on and off, and once with all four prompts trimmed to the same length so they share one ubatch. Each pruned row was compared against the same sequence run alone with all outputs on. Max KL per row is 6e-5 to 4e-3. Master's own single-sequence pruning, measured the same way, gives 9e-4 to 1.1e-3, so the difference is numerical noise. Argmax matched on 23/23 rows in every config. With a single sequence the PR is bit-identical to master.
  • Spec decoding (re: my question above): with gemma4-assistant --spec-type draft-mtp, the draft shares memory with the target, so the target extracts masked nextn and pruning stays on for the verify batches. I ran llama-server -np 4 with both split KV and -kvu, with GGML_SCHED_DEBUG_REALLOC=1. There were 0 reallocs, and draft acceptance matched master. A 19k-token prompt sent after the short requests also went through.

llama-batched-bench with the command from the description (-ngl 99), 2 interleaved rounds:

PP B master S_PP t/s PR S_PP t/s
512 2 31.8k / 32.8k 58.6k / 60.6k
512 8 33.6k / 34.9k 69.1k / 65.6k
2048 1 30.9k / 32.7k 61.4k / 63.1k
2048 8 33.8k / 34.1k 69.0k / 73.1k

S_TG is unchanged. Note that the B=1 rows also speed up only because batched-bench creates the context with n_seq_max = 8, and master turns pruning off for any n_seq_max > 1. So the gain applies to every multi-slot context, including server -np N with a single active request. It would help to say that in the description, since it can read as if single-sequence runs were slow before.

Smaller things:

  • set_input copies inp_prune_keep without checking its size. take is asserted, so please also add GGML_ASSERT(keep.size() == size_t(inp_prune_keep->ne[0])). If n_outputs and the count of ubatch->output ever disagree, this turns a silent garbage row into a clear failure.
  • The out mask is built by reading full_mask->data on the host. That only works because inp_attn is added to res->inputs before this input, so its mask is already filled. Please add a comment saying so. Otherwise a later reordering, or a mask that stops being host-resident, breaks this without any warning.
  • Reserve: when n_outputs_max < n_tokens, ubatch_prepare_reserve spreads the outputs round-robin over the sequences, which reserves the smallest M. A real batch with its outputs concentrated in one stream then needs S*M rows, more than were reserved. The default (n_outputs_max = n_batch) reserves M = T and is fine. This only affects contexts that lower the cap.
  • Style: the S/T/M members aren't indented, and short descriptive names (or a one-line comment) would help. The std::vector<std::vector<int32_t>> built on every ubatch could be a flat pass over ubatch->output.

@Meet91721

Copy link
Copy Markdown
Contributor Author

I have renamed the variables.

BTW, even dsv4.1 has something like this, I think after the 20th layer we don't need to compute more than the SWA window. If you're willing to take that up let me know

Yes, I will work on that.

@Meet91721

Copy link
Copy Markdown
Contributor Author

@ggerganov , @max-krasnyansky

This PR requires one more approval, can you please review it?

@Meet91721

Copy link
Copy Markdown
Contributor Author

Hi @am17an ,

I cannot add reviewers to this PR.
Can you please add them?

@am17an am17an left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@max-krasnyansky @ggerganov please review.

@ggerganov ggerganov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! Haven't done tests, but based on the detailed review #32342 (comment) this should be good to merge.

@am17an
am17an merged commit 1848628 into ggml-org:master Nov 20, 2026
23 checks passed
Kidplayer666 pushed a commit to Kidplayer666/llama.cpp that referenced this pull request Nov 20, 2026
@max-krasnyansky

Copy link
Copy Markdown
Member

Ah. Missed this earlier (email notifications still busted for me).
Just tested on my setups with hexagon and everything looks great.

someaka pushed a commit to someaka/llama.cpp that referenced this pull request Nov 22, 2026
Upstream ggml-org#32342 (1848628) generalized the KV-shared-layer prune: it no
longer requires crop_before_nextn(inp_out_ids) or n_seq_max == 1, so on
gemma4 E2B it pruned intermediate layer rows to the output set even for
extraction contexts. The hidden-states ladder captures every layer and
asserts equal token counts (llama-context.cpp hidden state layer token
count mismatch) -> SIGABRT on the first decode of every gate scenario.

Guard prune_shared with !cparams.extract_hidden_states, mirroring the
existing embeddings_layer_inp guard loop (same full-row requirement).
Graph reuse already compares extract_hidden_states (llama-graph.h
allow_reuse), so the runtime toggle cannot reuse a pruned graph.

Receipts: hs-extract one-liner repro went SIGABRT -> clean JSON exit 0;
gate_batch.py check runs all 5 scenarios to completion with resume parity
(fullrun_equals_resumed true); self-test 33/33. Byte delta vs the
2026-08-18 anchor is upstream numerics evolution (e.g. 2cbfc3c SKU-aware
FP16/BF16 accumulation gating), attributed separately.

Assisted-by: Hermes Agent
Annieren pushed a commit to Annieren/llama.cpp-upstream that referenced this pull request Nov 23, 2026
@wanghqc

wanghqc commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Looks like this has hurt the perf of our OpenCL Adreno GPU backend .

@max-krasnyansky

Copy link
Copy Markdown
Member

Looks like this has hurt the perf of our OpenCL Adreno GPU backend .

Oh. We should double check. Big regression?

Cinderella-Man added a commit to Cinderella-Man/miner-llama that referenced this pull request Nov 24, 2026
Upstream's newest tag, 191 commits past b12483, merged on pascal-p106-v5 af00bb1 (the 14 landed branches).
26 files conflicted. Each kept both sides' intent; the list with reasons is the public data folder
docs/data/2026-11-24_c912_upstream_b12674/conflicts.tsv. The ones that change code:

- ggml.h, ggml.c, ggml-rpc.h: upstream's GGML_OP_SLEEP and GGML_OP_SIGMOID_BACK go after the fork's three ops after
  GLU, so the fork's op numbers stay; GGML_OP_COUNT 105, RPC patch version 6 (fork 4 + upstream 2).
- ggml-rpc.cpp: upstream's single validation step (ggml-org#32651) already rejects unknown ops, so the fork's own check goes;
  the client's FREE_BUFFER that forgets dropped graphs (C929) sends with upstream's typed call<>.
- mmid.cu: upstream's helper with duplicate expert ids (ggml-org#32505) dumps its store in pieces; the legacy tile layout
  (GGML_CUDA_MMQ_MOE_LEGACY) reads the expert's column count from n_dumped.
- mmq.cuh: the kernel takes kq_fp32 (C861) before upstream's force_tiling (GCN only); the force_tiling launch passes
  kq_fp32 through.
- ggml-cuda.cu: ggml-org#32239 (no matrix-vector fusion on any Pascal card) merged without a conflict; the fork keeps the
  fusion on compute 6.1 as v5 measured it per file, and GGML_CUDA_MMID_GLU_UNFUSE=2 gives upstream's rule (C893).
- llama-graph.cpp: upstream's automatic "<name>.scale" lookup (ggml-org#32669) replaces the explicit scale arguments, the cold
  tier's included (its scales carry their tensors' names); the down projection's rescale is upstream's use_amax rule
  (ggml-org#32677) and the fork's LLAMA_NO_MOE_DOWN_RESCALE condition; route-once's histogram before upstream's random routing
  (ggml-org#29539); the device-built KQ mask (LLAMA_GPU_KQ_MASK) moves into upstream's build_attn_iswa_impl (ggml-org#32429) and
  replaces only the default mask.
- llama-memory-hybrid-idx.cpp: ggml-org#32519 scores only the ubatch's sequences' k-pools; with the k-pool tables on the devices
  (LLAMA_QSA_KPOOL_DEV) the list keeps every sequence's pools, as the tables hold them (get_n_kpool); the pads avoid
  every pool's rep in both layouts (LLAMA_QSA_PAD_LINEAR's bound kept).
- llama-quant.cpp: N2P and N3P's fallbacks go into upstream's fallback_type_for (ggml-org#15550), with the row width; Q4_1_64
  in upstream's moved llama_ftype_get_default_type.
- glm5-next.cpp, qwen4exp.cpp: the fused lightning indexer is always on (ggml-org#32650): the in-place row variant
  (LLAMA_QSA_INDEXER_ROWS) without the removed switch.
- flint.cpp, qwen4exp.cpp, gemma4.cpp, test-llama-archs.cpp, test-backend-ops.cpp, server-context.cpp: the fork's
  code with upstream's signature changes, model-name helper, decision groups and label outputs (ggml-org#32553), gemma4's
  multi-sequence prune (ggml-org#32342) without device-built masks.

Carried upstream fixes now merged upstream: ggml-org#32434 (6026911: upstream's version taken, the fork's change kept is only
--ctx-checkpoints-share's copy and get_reuse's two trim arguments) and ggml-org#31913 (2b2da8a: upstream's fill, the same
change).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
zhaixuejun1993 added a commit to zhaixuejun1993/llama.cpp that referenced this pull request Nov 25, 2026
… 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 ggml-org#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.
Mr-J-369 pushed a commit to Mr-J-369/llama.cpp-Android that referenced this pull request Nov 25, 2026
ravi9 pushed a commit to ravi9/llama.cpp that referenced this pull request Nov 26, 2026
… 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 ggml-org#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.
Nindaleth pushed a commit to Nindaleth/llama.cpp that referenced this pull request Nov 26, 2026
ravi9 pushed a commit to ravi9/llama.cpp that referenced this pull request Nov 27, 2026
… 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 ggml-org#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.
ravi9 added a commit that referenced this pull request Nov 27, 2026
* 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 d97d7fb (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 <[email protected]>
Co-authored-by: ravi9 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model Model specific

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants