From 825de80755393c3e31e89b3ad32f9805c8728348 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Wed, 25 Nov 2026 00:31:44 +0530 Subject: [PATCH 01/21] ggml-openvino: write back consumed in-place nodes of op-test graphs On the naive path every node of an op-test graph is a model output, except an in-place node that another node reads: it got no output, so its destination buffer was never written. GATED_DELTA_NET_CACHE_FUSION copies the final state into the cache and then reads the copy, so the cache kept its old contents. Write such a node back through its view_src, as is already done when nothing reads it. Model graphs are unchanged. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index a9fac74b1ea1..33fbac78e267 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1976,9 +1976,15 @@ void GgmlOvDecoder::compute_model_outputs() { } } // op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused - // ADD + RMS_NORM + MUL, so every non-in-place node is a model output there - if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) { - cur_node = nullptr; + // ADD + RMS_NORM + MUL, so every node is a model output there. An in-place node is written back + // through its view_src, as when it has no consumer. + if (input_use_count == cur_node_use_count) { + if (!m_naive) { + cur_node = nullptr; + } else if (::is_inplace_op(cur_node)) { + cur_node = + cur_node->view_src != nullptr && ggml_nbytes(cur_node) > 0 ? cur_node->view_src : nullptr; + } } } if (cur_node != nullptr) { From 1e5d24b57cfb12a8b4c7460795bccb7d5f1e1826 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Wed, 25 Nov 2026 00:31:44 +0530 Subject: [PATCH 02/21] ggml-openvino: keep the rest of the buffer in a partial in-place FILL An in-place FILL on a view into part of a larger buffer produced only the filled values. Its output stands for the whole in-place source, so the write-back put those values at the start of the buffer and not at the view's offset. For a contiguous view with a static shape, build the whole buffer: the elements before the view, the filled values, then the elements after it. Add NodeContext::get_inplace_op_src() to detect the in-place case. --- .../src/ggml-openvino/openvino/node_context.h | 2 ++ ggml/src/ggml-openvino/openvino/op/fill.cpp | 36 ++++++++++++++++++- 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h index 948405745b95..faa01968156c 100644 --- a/ggml/src/ggml-openvino/openvino/node_context.h +++ b/ggml/src/ggml-openvino/openvino/node_context.h @@ -107,6 +107,8 @@ class NodeContext : public frontend::NodeContext { size_t get_output_op_offset() const { return m_decoder->get_output_op_offset(m_node_idx); } + std::string get_inplace_op_src() const { return m_decoder->get_inplace_op_src(m_node_idx); } + ov::element::Type get_output_type() const { return m_decoder->get_output_type(m_node_idx); } std::vector get_output_stride() const { return m_decoder->get_output_stride(m_node_idx); } diff --git a/ggml/src/ggml-openvino/openvino/op/fill.cpp b/ggml/src/ggml-openvino/openvino/op/fill.cpp index 8f0689510bd1..d04dc2a1ee97 100644 --- a/ggml/src/ggml-openvino/openvino/op/fill.cpp +++ b/ggml/src/ggml-openvino/openvino/op/fill.cpp @@ -2,9 +2,13 @@ #include "../op_table.h" #include "../utils.h" +#include #include +#include #include +#include #include +#include namespace ov { namespace frontend { @@ -26,7 +30,37 @@ OutputVector translate_fill(const NodeContext & context) { // the shape of the input, which keeps its dynamic token dim auto target_shape = std::make_shared(process_view_input_new(context, 0), ov::element::i64); auto val = ov::op::v0::Constant::create(context.get_output_type(), {}, {c}); - auto res = std::make_shared(val, target_shape); + ov::Output res = std::make_shared(val, target_shape); + + // In place on a contiguous part of a larger buffer: the result stands for the whole buffer (the in-place + // source), so keep the elements outside the filled range. + const auto base = context.get_input(0); + const auto & base_ps = base.get_partial_shape(); + const auto out_ps = context.get_output_shape(); + if (!context.get_inplace_op_src().empty() && base_ps.is_static() && out_ps.is_static()) { + const auto out_shape = out_ps.to_shape(); + const auto stride = context.get_output_stride(); + const size_t elem = context.get_output_type().size(); + bool contiguous = stride.size() == out_shape.size(); + size_t expected = elem; + for (size_t i = out_shape.size(); contiguous && i-- > 0;) { + contiguous = out_shape[i] == 1 || stride[i] == expected; + expected *= out_shape[i]; + } + const size_t total = ov::shape_size(base_ps.to_shape()); + const size_t count = ov::shape_size(out_shape); + const size_t begin = context.get_output_op_offset() / elem; + if (contiguous && count < total && begin <= total - count) { + auto i64 = [](int64_t v) { return ov::op::v0::Constant::create(ov::element::i64, {1}, {v}); }; + auto flat = std::make_shared(base, i64(-1), false); + auto head = std::make_shared(flat, i64(0), i64(begin), i64(1), i64(0)); + auto body = std::make_shared(res, i64(-1), false); + auto tail = std::make_shared(flat, i64(begin + count), i64(INT64_MAX), i64(1), i64(0)); + auto full = std::make_shared(ov::OutputVector{head, body, tail}, 0); + res = std::make_shared( + full, std::make_shared(base, ov::element::i64), false); + } + } return rename_outputs_with_suffix({res}, context.get_name()); } From 21ae03fae4cb0960aaaa1429a4def9d8117904e9 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Wed, 25 Nov 2026 02:29:53 +0530 Subject: [PATCH 03/21] ggml-openvino: fix softplus precision for large negative inputs softplus was computed as relu(x) + log(1 + exp(-|x|)). When exp(-|x|) is below the precision of 1 + exp(-|x|), the log returns 0 or one ulp, so for x below about -16 in f32 the result was 0 or far off. The SOFTPLUS test case with inputs in [-16.6, -16] fails on CPU and GPU. Compute log1p(y) for y = exp(-|x|) with the series y - y^2/2 + y^3/3 - y^4/4 when y < 0.01, where its relative error is below 2e-9, and keep log(1 + y) above that. --- ggml/src/ggml-openvino/openvino/op/unary.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/op/unary.cpp b/ggml/src/ggml-openvino/openvino/op/unary.cpp index 1bb7aa2c8e56..8e9307012484 100644 --- a/ggml/src/ggml-openvino/openvino/op/unary.cpp +++ b/ggml/src/ggml-openvino/openvino/op/unary.cpp @@ -14,11 +14,13 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include #include @@ -125,8 +127,18 @@ OutputVector translate_unary_softplus(const NodeContext & context) { auto positive = std::make_shared(input); auto abs = std::make_shared(input); auto neg_abs = std::make_shared(abs); - auto exp_neg_abs = std::make_shared(neg_abs); - auto log_term = std::make_shared(std::make_shared(one, exp_neg_abs)); + auto y = std::make_shared(neg_abs); + // log1p(y) for y in (0, 1]. log(1 + y) loses a small y to rounding in 1 + y (all of it below x = -16 in f32), + // so y < 0.01 takes the series y - y^2/2 + y^3/3 - y^4/4, whose relative error there is below 2e-9. + auto c = [&](float v) { return ov::op::v0::Constant::create(element_type, ov::Shape{}, {v}); }; + std::shared_ptr series = std::make_shared(y, c(0.25f)); + series = std::make_shared(c(1.0f / 3), series); + series = std::make_shared(c(0.5f), std::make_shared(y, series)); + series = std::make_shared(one, std::make_shared(y, series)); + series = std::make_shared(y, series); + auto log_direct = std::make_shared(std::make_shared(one, y)); + auto small = std::make_shared(y, c(0.01f)); + auto log_term = std::make_shared(small, series, log_direct); auto res = std::make_shared(positive, log_term); return rename_outputs_with_suffix({res}, context.get_name()); From 3d0ae550ca81f0d2e587f8fa218b2cf15d519d87 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Wed, 25 Nov 2026 05:10:18 +0530 Subject: [PATCH 04/21] ggml-openvino: finer GPU KV rounding for decode batches Rounding the GPU KV length up to a power of two makes a batch attend up to twice the rows that hold data right after each power of two. Decode reads every attended row, so long contexts lose decode speed. The GPU plugin keeps memory for each attended length: several large buffers for a prompt batch, about one copy of K and V for a decode batch. Keep the power of two for prompt batches (more than 16 tokens per sequence), and round decode batches up to a multiple of 2^k / 4 and of 256. That is four lengths per power of two, with at most 25% masked rows. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 8 ++++---- ggml/src/ggml-openvino/ggml-openvino-extra.cpp | 12 ++++++++++++ ggml/src/ggml-openvino/ggml-openvino-extra.h | 8 ++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 33fbac78e267..62ce06e3ac58 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1411,12 +1411,12 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr ggml_openvino_static_kv_window(compute_params.attention_size, model_params.ctx_per_seq); } // 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 to a power of two the same way, so that a long context uses a few lengths and not one per - // step. The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). + // 256. Round it up (ggml_openvino_gpu_kv_window), so that a long context uses a few lengths and not one per step. + // The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && !compute_params.mask_name.empty() && 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_gpu_kv_window(compute_params.attention_size, + model_params.ctx_per_seq, compute_params.input_len); } model_params.ctx = model_params.ctx_per_seq * model_params.n_seq; return {model_params, compute_params}; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 7e6711dd88a0..0e99ff194176 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -681,6 +681,18 @@ int ggml_openvino_static_kv_window(int rows, int ctx) { return std::min(window, 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); + } + // a multiple of 256 and of 2^k / 4, where 2^k <= rows < 2^(k+1) + int step = 256; + while (step * 8 <= rows) { + step *= 2; + } + return std::min((rows + step - 1) / step * step, ctx); +} + bool ggml_openvino_npu_kv_on_demand_enabled() { return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_KV_ON_DEMAND") != 0; } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index ca3227a41aab..61d2a2f88a10 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -167,6 +167,14 @@ int ggml_openvino_npu_decode_bucket(); // clamped to ctx. int ggml_openvino_static_kv_window(int rows, int ctx); +// 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: +// prompt batches (more than 16 tokens): the next power of two, as ggml_openvino_static_kv_window(). The memory kept +// per length grows with the batch size. +// decode batches: the next multiple of 2^k / 4 (2^k <= rows < 2^(k+1)) and of 256, four lengths per power of two. +// Decode reads every attended row, so it keeps the masked rows to at most 25% instead of up to 100%. +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. bool ggml_openvino_npu_kv_on_demand_enabled(); From 5ec63542d152472f61ca1e124991ccdfdecaa80d Mon Sep 17 00:00:00 2001 From: Mustafa Cavus Date: Wed, 25 Nov 2026 03:22:31 +0530 Subject: [PATCH 05/21] ggml-openvino : keep the head axis of the 4-D KV cache static --- ggml/src/ggml-openvino/ggml-decoder.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 62ce06e3ac58..13272f298781 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1445,6 +1445,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, } const std::string name = input != nullptr ? std::string(input->name) : std::string(); ov::PartialShape input_shape; + bool kv_layout_4d = false; if (is_inp_tok(input, op) || is_inp_pos(input, op)) { // tokens or positions @@ -1539,6 +1540,7 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, const int64_t combined_dim = input_shape[3].get_length(); // n_heads_kv * head_size const int64_t head_size = combined_dim / n_heads_kv; input_shape = {input_shape[0], ov::Dimension::dynamic(), n_heads_kv, head_size}; + kv_layout_4d = true; } } else if (is_kv_idx(input, op)) { @@ -1563,7 +1565,8 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, // A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are // fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes // dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails). - if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) { + // the 4-D KV layout already has its ctx axis (1) dynamic; 3 - dynamic_dim_index would hit the head axis + if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted) && !kv_layout_4d) { input_shape[3 - dynamic_dim_index] = -1; } if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE && From 0f769418a311130b66758ded22c622f842aff111 Mon Sep 17 00:00:00 2001 From: ravi9 Date: Wed, 25 Nov 2026 08:38:07 +0530 Subject: [PATCH 06/21] ggml-openvino: split two one-line lambdas per clang-format The backend's .clang-format keeps a lambda on one line only when it is a function argument (AllowShortLambdasOnASingleLine: Inline). The constant helpers in the softplus and FILL translators are assigned to variables, so clang-format splits them. Formatting only. --- ggml/src/ggml-openvino/openvino/op/fill.cpp | 4 +++- ggml/src/ggml-openvino/openvino/op/unary.cpp | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ggml/src/ggml-openvino/openvino/op/fill.cpp b/ggml/src/ggml-openvino/openvino/op/fill.cpp index d04dc2a1ee97..acdf50d3c9ad 100644 --- a/ggml/src/ggml-openvino/openvino/op/fill.cpp +++ b/ggml/src/ggml-openvino/openvino/op/fill.cpp @@ -51,7 +51,9 @@ OutputVector translate_fill(const NodeContext & context) { const size_t count = ov::shape_size(out_shape); const size_t begin = context.get_output_op_offset() / elem; if (contiguous && count < total && begin <= total - count) { - auto i64 = [](int64_t v) { return ov::op::v0::Constant::create(ov::element::i64, {1}, {v}); }; + auto i64 = [](int64_t v) { + return ov::op::v0::Constant::create(ov::element::i64, {1}, {v}); + }; auto flat = std::make_shared(base, i64(-1), false); auto head = std::make_shared(flat, i64(0), i64(begin), i64(1), i64(0)); auto body = std::make_shared(res, i64(-1), false); diff --git a/ggml/src/ggml-openvino/openvino/op/unary.cpp b/ggml/src/ggml-openvino/openvino/op/unary.cpp index 8e9307012484..5c338ec56b54 100644 --- a/ggml/src/ggml-openvino/openvino/op/unary.cpp +++ b/ggml/src/ggml-openvino/openvino/op/unary.cpp @@ -130,7 +130,9 @@ OutputVector translate_unary_softplus(const NodeContext & context) { auto y = std::make_shared(neg_abs); // log1p(y) for y in (0, 1]. log(1 + y) loses a small y to rounding in 1 + y (all of it below x = -16 in f32), // so y < 0.01 takes the series y - y^2/2 + y^3/3 - y^4/4, whose relative error there is below 2e-9. - auto c = [&](float v) { return ov::op::v0::Constant::create(element_type, ov::Shape{}, {v}); }; + auto c = [&](float v) { + return ov::op::v0::Constant::create(element_type, ov::Shape{}, {v}); + }; std::shared_ptr series = std::make_shared(y, c(0.25f)); series = std::make_shared(c(1.0f / 3), series); series = std::make_shared(c(0.5f), std::make_shared(y, series)); From 3042519e888138d9b123cf16609af1e24d2f5f3f Mon Sep 17 00:00:00 2001 From: Anisha Kulkarni Date: Mon, 2 Nov 2026 16:01:33 -0700 Subject: [PATCH 07/21] 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. --- docs/backend/OPENVINO.md | 1 + ggml/src/ggml-openvino/README.md | 4 + ggml/src/ggml-openvino/ggml-decoder.h | 18 ++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 6 + ggml/src/ggml-openvino/ggml-openvino-extra.h | 6 + ggml/src/ggml-openvino/openvino/decoder.h | 5 + .../openvino/pass/keep_cache_results.cpp | 53 +++++ .../openvino/pass/keep_cache_results.h | 30 +++ .../openvino/pass_registry/common.cpp | 10 +- .../openvino/pass_registry/pipeline.h | 5 + ggml/src/ggml-openvino/utils.cpp | 204 ++++++++++++++++-- ggml/src/ggml-openvino/utils.h | 6 + 12 files changed, 330 insertions(+), 18 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp create mode 100644 ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 27c17c3eff8b..26f007508978 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -882,6 +882,7 @@ 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_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 with full-context decode (`GGML_OPENVINO_NPU_BLOB_PREBUILD=0`), without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state. 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. | | `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. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 0b4f31291ac6..b2eeaf82cf1c 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -87,3 +87,7 @@ 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. diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 39b3496e5669..20a9d5397bb6 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -288,6 +288,23 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { virtual std::set get_model_output_names() const override { return m_model_output_names; } + virtual std::set get_cache_output_names() const override { + std::set 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; } + const std::map & get_model_outputs() const { return m_model_outputs; } virtual int get_ctx_size() const { return m_model_params.ctx; } @@ -776,6 +793,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { std::set m_model_output_names; // The output set the compiled model was built from, for has_same_graph_io(). std::set m_built_output_names; + bool m_kv_only_outputs = false; std::vector m_node_info_list; std::map m_node_dynamic_dims; std::set m_kvcache_4d; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 0e99ff194176..de0027544436 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -198,6 +198,7 @@ constexpr env_var env_vars[] = { {"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_KV_ONLY_PREFILL", env_type::BOOL}, {"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", 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}, @@ -702,6 +703,11 @@ bool ggml_openvino_npu_kv_head_major_enabled() { ggml_openvino_kv_slice_enabled(); } +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_raw_weight_cache_enabled() { return ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_BLOB") != 0 || ggml_openvino_npu_weightless_bank_enabled(); diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 61d2a2f88a10..1a5fc63d71cc 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -156,6 +156,12 @@ bool ggml_openvino_npu_fast_mask_enabled(); 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 or decode KV windows); +// GGML_OPENVINO_KV_ONLY_PREFILL=0 turns it off. +bool ggml_openvino_kv_only_prefill_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; diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 980f0b88dc86..879e574413bf 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -111,6 +111,11 @@ class GgmlDecoder : public DecoderBase { virtual const std::map & get_model_extra_inputs() const = 0; virtual const std::map> & get_model_weights() const = 0; virtual std::set 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 get_cache_output_names() const { return {}; } virtual int32_t * get_rope_params() const = 0; diff --git a/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp new file mode 100644 index 000000000000..d69123295095 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.cpp @@ -0,0 +1,53 @@ +#include "keep_cache_results.h" + +#include +#include +#include + +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace pass { + +bool KeepCacheResults::run_on_model(const std::shared_ptr & 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 live; + for (const auto & op : model->get_ordered_ops()) { + live.insert(op.get()); + } + const ov::ParameterVector params = model->get_parameters(); + for (const auto & param : params) { + bool used = false; + for (const auto & input : param->output(0).get_target_inputs()) { + if (live.count(input.get_node()) != 0) { + used = true; + break; + } + } + if (!used) { + model->remove_parameter(param); + } + } + return true; +} + +} // namespace pass +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h new file mode 100644 index 000000000000..711fa0703477 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/pass/keep_cache_results.h @@ -0,0 +1,30 @@ +#include "openvino/pass/pass.hpp" + +#include +#include + +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 cache_outputs) : m_cache_outputs(std::move(cache_outputs)) {} + + bool run_on_model(const std::shared_ptr & model) override; + +private: + std::set m_cache_outputs; +}; + +} // namespace pass +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp b/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp index 0b64fa1e9d0b..7f9be6d91115 100644 --- a/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp +++ b/ggml/src/ggml-openvino/openvino/pass_registry/common.cpp @@ -4,6 +4,7 @@ #include "ggml-openvino/openvino/decoder.h" #include "ggml-openvino/openvino/pass/fuse_argsort_topk.h" #include "ggml-openvino/openvino/pass/fuse_to_conv.h" +#include "ggml-openvino/openvino/pass/keep_cache_results.h" #include "ggml-openvino/openvino/pass/kv_state_seq_axis.h" #include "ggml-openvino/openvino/pass/mark_decompression_convert_constant_folding.h" #include "ggml-openvino/openvino/pass/mark_dequantization_subgraph.h" @@ -21,11 +22,18 @@ GraphTraits analyze_graph(const GgmlDecoder & decoder) { traits.device = ggml_openvino_is_npu() ? Device::NPU : ggml_openvino_is_gpu() ? Device::GPU : Device::CPU; traits.is_static = decoder.is_static(); traits.is_stateful = decoder.is_stateful(); + traits.kv_only_outputs = decoder.is_kv_only_outputs(); + if (traits.kv_only_outputs) { + traits.cache_output_names = decoder.get_cache_output_names(); + } return traits; } void register_common_passes(ov::pass::Manager & manager, const GraphTraits & traits) { - (void) traits; + // First, so the other passes do not work on the layers it removes. + if (traits.kv_only_outputs) { + manager.register_pass(traits.cache_output_names); + } manager.register_pass(); // Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain // (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding, diff --git a/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h b/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h index 8db8ebfd611f..44b372fad202 100644 --- a/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h +++ b/ggml/src/ggml-openvino/openvino/pass_registry/pipeline.h @@ -16,6 +16,9 @@ #include #include +#include +#include + 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 cache_output_names; }; GraphTraits analyze_graph(const GgmlDecoder & decoder); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 03479f35edd3..77f55760a8e2 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -12,6 +12,7 @@ #include "openvino/input_model.h" #include +#include #include #include #include @@ -788,8 +789,12 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod return input_tensor; } +// Input of the static decode model for token |row| of the graph: row 0 of a decode graph, or a row of a prefill graph +// whose outputs a KV-only prefill computes with the decode model (the decoder is then in decode mode, so that the KV +// cache and the masks bind at full context). ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr & ggml_decoder, - const std::string & param_name) { + const std::string & param_name, + int64_t row = 0) { // NPU decoding stage if (ggml_decoder->get_model_extra_inputs().count(param_name)) { return get_ov_input_tensor(ggml_decoder, param_name); @@ -799,38 +804,49 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptrne[0] == n_planes); - ov::Shape input_shape = {1, 1, 1, (size_t) n_planes}; - ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape); - std::memcpy(input_tensor.data(), ggml_tensor->data, n_planes * ggml_type_size(ggml_tensor->type)); + const int64_t n_rows = ggml_tensor->ne[0] / n_planes; + const size_t element_size = ggml_type_size(ggml_tensor->type); + ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), ov::Shape{1, 1, 1, (size_t) n_planes}); + for (int p = 0; p < n_planes; p++) { + std::memcpy(static_cast(input_tensor.data()) + p * element_size, + static_cast(ggml_tensor->data) + (p * n_rows + row) * element_size, element_size); + } return input_tensor; } if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) { - ov::Shape input_shape = {1, 1, 1, 1}; - ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape); - // The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read. + // The decode model computes the outputs of its one token. out_ids is empty when the graph has no output, so it + // is not read. + ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), ov::Shape{1, 1, 1, 1}); *input_tensor.data() = 0; return input_tensor; } + if (GgmlOvDecoder::is_inp_scale_rows(ggml_tensor, op) && ggml_nelements(ggml_tensor) > 1) { + // One scale per token of the graph. + ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, 1, 1}); + *input_tensor.data() = static_cast(ggml_tensor->data)[row]; + return input_tensor; + } + if (GgmlOvDecoder::is_inp_mask(ggml_tensor, op)) { - size_t context_size = get_static_attention_size(ggml_decoder, param_name); + const size_t context_size = get_static_attention_size(ggml_decoder, param_name); + const size_t cols = ggml_tensor->ne[0]; if (ggml_tensor->type == GGML_TYPE_F16) { + const auto * src = static_cast(ggml_tensor->data) + row * cols; std::vector padded_data = - pad_input(ggml_tensor, 1, context_size, GGML_FP32_TO_FP16(-INFINITY)); + pad_input(src, 1, cols, 1, context_size, GGML_FP32_TO_FP16(-INFINITY)); ov::Tensor input_tensor(ov::element::f16, ov::Shape{1, 1, 1, context_size}); std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(ggml_fp16_t)); return input_tensor; } - std::vector padded_data = pad_input(ggml_tensor, 1, context_size, -INFINITY); + const auto * src = static_cast(ggml_tensor->data) + row * cols; + std::vector padded_data = pad_input(src, 1, cols, 1, context_size, -INFINITY); ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, 1, context_size}); - auto * data_ptr = input_tensor.data(); - std::copy(padded_data.begin(), padded_data.begin() + context_size, data_ptr); + std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(float)); return input_tensor; } @@ -2055,7 +2071,9 @@ static void build_static_model(const static_build_args & a, names_in.push_back(name); } } - for (const auto & name : decoder->get_model_output_names()) { + // A KV-only prefill model keeps only the cache outputs (pass::KeepCacheResults), in decoder order. + for (const auto & name : decoder->is_kv_only_outputs() ? decoder->get_cache_output_names() : + decoder->get_model_output_names()) { names_out.push_back(name); } if (names_in.size() != compiled_model.inputs().size() || names_out.size() != compiled_model.outputs().size()) { @@ -2172,6 +2190,46 @@ static void build_static_model(const static_build_args & a, } } +// A layer that reuses the KV cache of an earlier layer (Gemma 3n/4 E-series) reads a KV cache tensor that another +// attention op also reads. Every other layer reads its own cache, whichever caches it writes (MLA has no V cache). +static bool has_kv_shared_attention(const ggml_cgraph * cgraph) { + std::unordered_map readers; + for (int i = 0; i < cgraph->n_nodes; i++) { + const ggml_tensor * node = cgraph->nodes[i]; + if (node->op != GGML_OP_FLASH_ATTN_EXT || node->src[1] == nullptr) { + continue; + } + const ggml_tensor * k = node->src[1]; + while (k->view_src != nullptr) { + k = k->view_src; + } + if (GgmlOvDecoder::is_kvcache(k, nullptr) && ++readers[k] > 1) { + return true; + } + } + return false; +} + +// The output step runs a token of the batch through the decode model again. That rewrites the token's KV rows with the +// same values, but would apply a recurrent state update twice. +static bool has_recurrent_state(const ggml_cgraph * cgraph) { + for (int i = 0; i < cgraph->n_nodes; i++) { + const ggml_tensor * node = cgraph->nodes[i]; + if (GgmlOvDecoder::is_recurrent_cache(node->view_src)) { + return true; + } + for (int j = 0; j < GGML_MAX_SRC; j++) { + if (GgmlOvDecoder::is_recurrent_cache(node->src[j])) { + return true; + } + } + } + return false; +} + +// Set when a KV-only prefill could not compute the outputs of a batch; later graphs use the full prefill. +static std::atomic g_kv_only_prefill_failed{false}; + enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared_ptr & r_ctx) { auto & core = ov_singleton_core(); @@ -2215,6 +2273,15 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared const ov::AnyMap compile_config = no_kv_cache ? ggml_openvino_npu_without_npuw(config) : m_params.state_size >= 0 ? ggml_openvino_npu_gdn_config(config) : config; + // Decided per compiled pair from the graph that triggers the compile; later calls follow entry->kv_only_prefill. + // The output step binds the full KV cache to the pair's decode model, so it needs a full-context decode window. + const bool kv_only_prefill = !no_kv_cache && ggml_openvino_kv_only_prefill_enabled() && !g_kv_only_prefill_failed && + !ggml_openvino_npu_hfa_prefill_enabled() && ggml_openvino_npu_decode_bucket() == 0 && + c_params.output_len <= 1 && has_kv_shared_attention(cgraph) && + !has_recurrent_state(cgraph); + std::shared_ptr decode_request_for_outputs; + std::vector decode_input_names_for_outputs; + std::vector decode_output_names_for_outputs; if (m_params.n_heads_kv == -1) { prefill_chunk_size = inp_pos->ne[0]; } @@ -2329,6 +2396,9 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared r_ctx->ov_input_names_cache.at(key); ov_output_names_local = is_prefill ? r_ctx->ov_output_names_cache_prefill.at(key) : r_ctx->ov_output_names_cache.at(key); + decode_request_for_outputs = r_ctx->infer_request_cache.at(key); + decode_input_names_for_outputs = r_ctx->ov_input_names_cache.at(key); + decode_output_names_for_outputs = r_ctx->ov_output_names_cache.at(key); } decoder_end_time = ggml_time_us(); @@ -2356,7 +2426,9 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared stateful, false, is_prefill, prefill_chunk_size); local_decoder->device = device; const std::string shared_key = - cache_enabled ? compiled_graph_key(cgraph, *local_decoder, device, prefill_chunk_size) : ""; + cache_enabled ? compiled_graph_key(cgraph, *local_decoder, device, prefill_chunk_size) + + (kv_only_prefill ? "|kv-only-prefill" : "") : + ""; auto shared_it = shared_cache->graphs.find(shared_key); if (!shared_key.empty() && shared_it != shared_cache->graphs.end()) { auto & compiled = shared_it->second; @@ -2381,6 +2453,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared r_ctx->ov_output_names_cache[key] = compiled.output_names; r_ctx->ov_input_names_cache_prefill[key] = compiled.prefill_input_names; r_ctx->ov_output_names_cache_prefill[key] = compiled.prefill_output_names; + entry->kv_only_prefill = compiled.kv_only_prefill; + decode_request_for_outputs = decode_request; + decode_input_names_for_outputs = compiled.input_names; + decode_output_names_for_outputs = compiled.output_names; decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us(); GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n"); if (prefill_size_changed) { @@ -2458,6 +2534,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT")); base_extra = base_extra * 131 + (ggml_openvino_kv_slice_enabled() ? 1u : 0u); base_extra = base_extra * 131 + (ggml_openvino_npu_kv_head_major_enabled() ? 1u : 0u); + base_extra = base_extra * 131 + (kv_only_prefill ? 1u : 0u); base_extra = ggml_openvino_model_cache_mix_string( base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_CONFIG")); base_extra = ggml_openvino_model_cache_mix_string( @@ -2580,6 +2657,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared auto ggml_decoder_prefill = std::make_shared( cgraph, m_params, c_params, model_weights, is_static, stateful, false, true, prefill_chunk_size); + ggml_decoder_prefill->set_kv_only_outputs(kv_only_prefill); auto ggml_decoder_decode = no_kv_cache ? ggml_decoder_prefill : std::make_shared(cgraph, m_params, decode_c_params, model_weights, @@ -2721,6 +2799,13 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared entry->decode_attention_size = decode_c_params.attention_size; entry->shared_key = shared_key; entry->decode_window_requests.clear(); + entry->kv_only_prefill = kv_only_prefill; + decode_request_for_outputs = infer_request_decode; + decode_input_names_for_outputs = names_in_decode; + decode_output_names_for_outputs = names_out_decode; + if (kv_only_prefill) { + GGML_LOG_INFO("ggml-openvino: KV-only prefill model (outputs via one decode step)\n"); + } if (!shared_key.empty()) { ov_compiled_graph graph; @@ -2736,12 +2821,15 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } graph.decode_config = mc_decode_config; graph.cache_base_extra = base_extra; + graph.prefill_fp = prefill_fp; + graph.decode_fp = decode_fp; graph.self_contained = self_contained; graph.decode_unfold = decode_unfold; graph.weightless_bank = weightless_bank; graph.weights_path = weights_path; graph.weights_layout = decode_bucket > 0 ? std::move(weights_layout) : nullptr; graph.decode_c_params = decode_c_params; + graph.kv_only_prefill = kv_only_prefill; shared_cache->graphs.emplace(shared_key, std::move(graph)); pair_built = !decode_source; } @@ -3141,6 +3229,88 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } } } + + if (entry->kv_only_prefill) { + // The prefill model only filled the KV cache. Compute the outputs of the requested token by running the + // decode model on it: it rewrites that token's KV rows with the same values and runs the layers the + // prefill model dropped, reading the now complete cache. + const ggml_tensor * out_ids = nullptr; + for (const auto & [name, info] : ggml_decoder->get_model_inputs()) { + const ggml_tensor * tensor = ggml_decoder->get_input_ggml_tensor(name); + if (tensor != nullptr && + GgmlOvDecoder::is_output_idx(tensor, ggml_decoder->get_tensor_used_op(tensor))) { + out_ids = tensor; + break; + } + } + const int64_t n_outputs = out_ids != nullptr ? out_ids->ne[0] : 0; + std::string kv_only_error; + if (n_outputs > 1) { + kv_only_error = "the batch needs " + std::to_string(n_outputs) + " output tokens"; + } else if (n_outputs == 1) { + const int64_t row = static_cast(out_ids->data)[0]; + ggml_decoder->m_is_prefill = false; + try { + const auto & compiled_inputs = decode_request_for_outputs->get_compiled_model().inputs(); + for (size_t i = 0; i < decode_input_names_for_outputs.size(); i++) { + const auto & name = decode_input_names_for_outputs[i]; + auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, name, row); + if (input_tensor.get_shape() != compiled_inputs[i].get_shape()) { + throw std::runtime_error("decode input " + name + " has shape " + + input_tensor.get_shape().to_string() + ", expected " + + compiled_inputs[i].get_shape().to_string()); + } + decode_request_for_outputs->set_input_tensor(i, input_tensor); + } + const auto & model_outputs = ggml_decoder->get_model_outputs(); + for (size_t i = 0; i < decode_output_names_for_outputs.size(); i++) { + auto it = model_outputs.find(decode_output_names_for_outputs[i]); + if (it == model_outputs.end() || ggml_nbytes(it->second) == 0) { + continue; + } + decode_request_for_outputs->set_output_tensor( + i, create_ov_output_tensor(ggml_decoder, decode_request_for_outputs, i, it->second)); + } + const int64_t decode_start = ggml_time_us(); + decode_request_for_outputs->infer(); + const int64_t decode_us = ggml_time_us() - decode_start; + ov_raw_infer_total += decode_us; + if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) { + fprintf(stderr, "GGML OpenVINO profiling: KV-only prefill output step: row=%lld, raw infer=%.3f ms\n", + static_cast(row), decode_us / 1000.0); + } + } catch (const std::exception & e) { + kv_only_error = e.what(); + } + ggml_decoder->m_is_prefill = true; + } + if (!kv_only_error.empty()) { + // Fall back to the full prefill: drop this backend's requests and run the graph again. The KV-only prefill + // has already written the batch's KV rows, and the full prefill writes the same values. + GGML_LOG_WARN("ggml-openvino: KV-only prefill cannot compute the outputs (%s); using the full prefill\n", + kv_only_error.c_str()); + g_kv_only_prefill_failed = true; + { + std::lock_guard map_lock(r_ctx->ctx_mutex); + r_ctx->clear_caches_locked(); + } + { + // Free the KV-only pair, including its models in the process-wide blob cache; a backend that still + // uses it keeps its own requests alive. + std::lock_guard cache_lock(r_ctx->compiled_cache->mutex); + auto it = r_ctx->compiled_cache->graphs.find(entry->shared_key); + if (it != r_ctx->compiled_cache->graphs.end()) { + std::lock_guard blobs_lock(g_imported_blobs_mutex); + g_imported_blobs.erase(it->second.prefill_fp); + g_imported_blobs.erase(it->second.decode_fp); + r_ctx->compiled_cache->graphs.erase(it); + } + } + infer_request.reset(); + decode_request_for_outputs.reset(); + return ov_graph_compute_static(cgraph, r_ctx); + } + } infer_end_time = ggml_time_us(); } else { if (decode_bucket > 0 && c_params.attention_size != entry->decode_attention_size) { diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 270676b07dca..c95e94de2def 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -110,6 +110,8 @@ struct decoder_runtime_ctx { int decode_attention_size = -1; std::string shared_key; std::map> decode_window_requests; + // The prefill model only writes the KV cache; logits come from one decode step (GGML_OPENVINO_KV_ONLY_PREFILL). + bool kv_only_prefill = false; }; struct ov_compiled_graph { @@ -124,6 +126,9 @@ struct ov_compiled_graph { std::map decode_windows; ov::AnyMap decode_config; uint64_t cache_base_extra = 0; + // Model cache fingerprints of the pair's prefill and decode models (0 without a model cache). + uint64_t prefill_fp = 0; + uint64_t decode_fp = 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 @@ -133,6 +138,7 @@ struct ov_compiled_graph { std::shared_ptr weights_layout; // Compute params the pair's decode model was built with; window models derive from them. ComputeParams decode_c_params; + bool kv_only_prefill = false; }; // Only compilation and cache publication use this mutex. Requests, decoders and From 82f18e54b5c3c9fe5017a5e9cdf3fa62c5891622 Mon Sep 17 00:00:00 2001 From: Anisha Kulkarni Date: Tue, 3 Nov 2026 14:31:26 -0700 Subject: [PATCH 08/21] 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_ 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. --- docs/backend/OPENVINO.md | 1 + ggml/src/ggml-openvino/README.md | 4 +++ ggml/src/ggml-openvino/ggml-decoder.cpp | 34 +++++++++++++++++++ ggml/src/ggml-openvino/ggml-decoder.h | 10 ++++++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 5 +++ ggml/src/ggml-openvino/ggml-openvino-extra.h | 4 +++ .../ggml-openvino/openvino/op/get_rows.cpp | 7 ++++ ggml/src/ggml-openvino/utils.cpp | 23 +++++++++++++ 8 files changed, 88 insertions(+) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 26f007508978..25db5015b0d7 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -884,6 +884,7 @@ The defaults fit most models. The variables below trade one property for another | `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_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 with full-context decode (`GGML_OPENVINO_NPU_BLOB_PREBUILD=0`), without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state. 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. | +| `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. | diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index b2eeaf82cf1c..497cf46df47c 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -91,3 +91,7 @@ The generic recurrent-cache translation invalidates blobs made with the former s # 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_` input instead of an OpenVINO Gather over the table. NPUW otherwise lifts the table to a function input, and gathering from an input that large costs about as much as streaming the whole table every call (21.6 ms of Gemma 4 E2B decode). A table used only for such lookups (the Gemma 3n/4 per-layer embedding table) is not converted or bound to the NPU at all. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 13272f298781..b03909c337ad 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1613,8 +1613,38 @@ 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 on the host: weights in an OpenVINO buffer are stored in the extracted layout. + constexpr size_t min_table_bytes = 64ull * 1024 * 1024; + return table != nullptr && ids != nullptr && table->view_src == nullptr && table->buffer != nullptr && + table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && ggml_backend_buffer_is_host(table->buffer) && + !ggml_backend_buffer_is_openvino(table->buffer) && 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, @@ -2143,6 +2173,10 @@ std::map> 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); diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 20a9d5397bb6..77e0f7fce45e 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -305,6 +305,15 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // 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_" 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 & get_model_outputs() const { return m_model_outputs; } virtual int get_ctx_size() const { return m_model_params.ctx; } @@ -794,6 +803,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // The output set the compiled model was built from, for has_same_graph_io(). std::set m_built_output_names; bool m_kv_only_outputs = false; + std::map m_host_gather_rows; std::vector m_node_info_list; std::map m_node_dynamic_dims; std::set m_kvcache_4d; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index de0027544436..ae97f6dff029 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -200,6 +200,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_NPU_SHARED_BANK", env_type::BOOL}, {"GGML_OPENVINO_KV_ONLY_PREFILL", env_type::BOOL}, {"GGML_OPENVINO_NPU_WEIGHTLESS_BANK", 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}, }; @@ -703,6 +704,10 @@ bool ggml_openvino_npu_kv_head_major_enabled() { ggml_openvino_kv_slice_enabled(); } +bool ggml_openvino_npu_host_gather_enabled() { + return ggml_openvino_is_npu() && ggml_openvino_getenv_int("GGML_OPENVINO_NPU_HOST_GATHER") != 0; +} + bool ggml_openvino_kv_only_prefill_enabled() { // On by default; it only takes effect for graphs with KV-shared layers. return ggml_openvino_getenv_int("GGML_OPENVINO_KV_ONLY_PREFILL", 1) != 0; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 1a5fc63d71cc..b4a7419479c5 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -162,6 +162,10 @@ bool ggml_openvino_npu_parallel_compile_enabled(); // 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. 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; diff --git a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp index 89a75570c427..59c0fb09431f 100644 --- a/ggml/src/ggml-openvino/openvino/op/get_rows.cpp +++ b/ggml/src/ggml-openvino/openvino/op/get_rows.cpp @@ -24,6 +24,13 @@ namespace op { OutputVector translate_get_rows(const NodeContext & context) { num_inputs_check(context, 2, 2); + // Rows gathered on the host (GGML_OPENVINO_NPU_HOST_GATHER) arrive as a [1, 1, n_tokens, row] input. + const std::string host_rows = "ggml_host_rows_" + context.get_name(); + if (context.has_input(host_rows)) { + // Not renamed: the output is the Parameter itself, whose name binds the input at runtime. + return {context.get_input(host_rows)}; + } + Output res; Output data; int64_t row_offset = 0; diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 77f55760a8e2..197e69e8c141 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -231,6 +231,7 @@ static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurren extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_shape_from_mask_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_hfa_prefill_enabled() ? 4u : 0u); // HFA input ABI v4. + extra_cfg = extra_cfg * 131 + (ggml_openvino_npu_host_gather_enabled() ? 1u : 0u); if (ggml_openvino_is_npu()) { extra_cfg = extra_cfg * 131 + static_cast(ggml_openvino_get_npu_requant_type()); } @@ -789,12 +790,31 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod return input_tensor; } +// Rows |first|..|first + count| of a host-gathered table (GGML_OPENVINO_NPU_HOST_GATHER), dequantized from the raw +// ggml table into a [1, 1, padded, row] f32 tensor. Padded rows repeat the last valid row; their outputs are unused. +static ov::Tensor make_host_rows_tensor(const ggml_tensor * node, size_t first, size_t count, size_t padded) { + const ggml_tensor * table = node->src[0]; + const auto * ids = static_cast(node->src[1]->data); + const size_t row = table->ne[0]; + const auto to_float = ggml_get_type_traits(table->type)->to_float; + ov::Tensor rows(ov::element::f32, ov::Shape{1, 1, padded, row}); + auto * dst = rows.data(); + for (size_t i = 0; i < padded; i++) { + const int64_t id = ids[first + std::min(i, count - 1)]; + to_float(static_cast(table->data) + id * table->nb[1], dst + i * row, static_cast(row)); + } + return rows; +} + // Input of the static decode model for token |row| of the graph: row 0 of a decode graph, or a row of a prefill graph // whose outputs a KV-only prefill computes with the decode model (the decoder is then in decode mode, so that the KV // cache and the masks bind at full context). ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr & ggml_decoder, const std::string & param_name, int64_t row = 0) { + if (const auto * node = ggml_decoder->get_host_gather_rows(param_name)) { + return make_host_rows_tensor(node, row, 1, 1); + } // NPU decoding stage if (ggml_decoder->get_model_extra_inputs().count(param_name)) { return get_ov_input_tensor(ggml_decoder, param_name); @@ -924,6 +944,9 @@ ov::Tensor get_ov_input_tensor_static_prefill(const std::shared_ptrget_host_gather_rows(param_name)) { + return make_host_rows_tensor(node, chunk_index * chunk_size, chunk_valid_size, chunk_size); + } if (chunk_index > 0 && param_name == "cache_rs_reset_len") { // The recurrent-state clear belongs to the start of the sequence. Re-applying it on every // chunk would wipe the state accumulated by the preceding chunks, so disable it (a zero From a95ce6742b839fa3467324eb2d67efddda634492 Mon Sep 17 00:00:00 2001 From: Anisha Kulkarni Date: Tue, 3 Nov 2026 14:48:10 -0700 Subject: [PATCH 09/21] 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/src/ggml-openvino/ggml-decoder.cpp | 15 +++++++++++---- ggml/src/ggml-openvino/utils.cpp | 16 ++++++++++++---- 2 files changed, 23 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index b03909c337ad..9546f8560418 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1619,11 +1619,18 @@ bool GgmlOvDecoder::is_host_gather_rows(const ggml_tensor * node) { } const ggml_tensor * table = node->src[0]; const ggml_tensor * ids = node->src[1]; - // The table must hold raw ggml rows on the host: weights in an OpenVINO buffer are stored in the extracted layout. + // The table must hold raw ggml rows in host memory. OpenVINO buffers store weights in the extracted layout, except + // in the raw-weight cache modes, where they keep (or, with SELF_CONTAINED_MMAP, wrap) the raw GGUF bytes. constexpr size_t min_table_bytes = 64ull * 1024 * 1024; - return table != nullptr && ids != nullptr && table->view_src == nullptr && table->buffer != nullptr && - table->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && ggml_backend_buffer_is_host(table->buffer) && - !ggml_backend_buffer_is_openvino(table->buffer) && ggml_get_type_traits(table->type)->to_float != nullptr && + if (table == nullptr || ids == nullptr || table->view_src != nullptr || table->buffer == nullptr) { + return false; + } + const bool raw_cache = ggml_openvino_npu_raw_weight_cache_enabled() && + ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR") != nullptr; + 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]; } diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 197e69e8c141..2003c3a3e89c 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -2083,14 +2083,15 @@ static void build_static_model(const static_build_args & a, for (const auto & input : compiled_model.inputs()) { compiled_input_names.insert(input.get_node()->get_friendly_name()); } + // The frontend drops inputs nothing reads: HFA prefill, KV-only prefill (out_ids) and host gather (token + // ids) can leave decoder inputs out of the compiled model. Keep the decoder order. for (const auto & [name, _] : decoder->get_model_inputs()) { - if (!ggml_openvino_npu_hfa_prefill_enabled() || std::string(tag) != "prefill" || - compiled_input_names.count(name) != 0) { + if (compiled_input_names.count(name) != 0) { names_in.push_back(name); } } for (const auto & [name, info] : decoder->get_model_extra_inputs()) { - if (info.is_parameter) { + if (info.is_parameter && compiled_input_names.count(name) != 0) { names_in.push_back(name); } } @@ -2765,7 +2766,14 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared ggml_openvino_model_cache_write_weights(weights_path, {model_prefill, model_decode}); } if (!weights_layout) { - throw std::runtime_error("ggml-openvino: failed to write NPU weights file " + weights_path); + // E.g. a full disk. The models still compile and run; only this pair is left uncached, since its + // blobs would reference a missing weights file. + GGML_LOG_WARN("ggml-openvino: could not write the NPU weights file %s; not caching this graph\n", + weights_path.c_str()); + for (const uint64_t fp : { prefill_fp, decode_fp }) { + std::remove((ggml_openvino_model_cache_manifest_path(model_cache_dir, fp) + ".source.tmp").c_str()); + } + prefill_fp = decode_fp = 0; } } if (parallel_compile) { From f8d3e4e1a1d3709e368d3975b52acdc0378765a1 Mon Sep 17 00:00:00 2001 From: Anisha Kulkarni Date: Fri, 6 Nov 2026 16:07:22 -0700 Subject: [PATCH 10/21] 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). --- docs/backend/OPENVINO.md | 4 ++-- ggml/src/ggml-openvino/device/npu_quant_policy.cpp | 8 ++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index 25db5015b0d7..e012d8bb38f8 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -110,7 +110,7 @@ Although OpenVINO supports a wide range of [Intel hardware](https://docs.openvin **NPU:** - All other quantized tensors are requantized to `Q4_0_128`. -- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. +- For a `Q6_K` token embedding, `GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT` selects another layout. When it is set, it also applies to a `Q4_K` or `Q5_K` token embedding. - The validated models use `Q4_K_M` files. **Layout names:** @@ -883,7 +883,7 @@ The defaults fit most models. The variables below trade one property for another |---|---|---|---|---| | `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_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 with full-context decode (`GGML_OPENVINO_NPU_BLOB_PREBUILD=0`), without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state. 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. | +| `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. | diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp index d29175ab0524..d3dd8942ea34 100644 --- a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp +++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp @@ -20,8 +20,12 @@ ExtraQuantType ggml_openvino_get_npu_requant_type() { std::optional 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"); From 5cae3e14183eb958bcdc59a273b6f6cd3a6e9605 Mon Sep 17 00:00:00 2001 From: xuejun Date: Mon, 23 Nov 2026 11:36:53 +0530 Subject: [PATCH 11/21] 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/src/ggml-openvino/utils.cpp | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 2003c3a3e89c..e3eb6f4fd22c 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -2319,6 +2319,11 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared ggml_openvino_npu_decode_bucket() : 0; int decode_window = m_params.ctx_per_seq; + // Weightless-bank model cache with sliced (not head-major) KV: prefill sizes follow the decode KV windows. + const bool prefill_window_aligned = decode_bucket > 0 && ggml_openvino_kv_slice_enabled() && + !ggml_openvino_npu_kv_head_major_enabled() && + ggml_openvino_npu_weightless_bank_enabled() && + !ggml_openvino_model_cache_dir().empty(); if (decode_bucket > 0 && m_params.ctx_per_seq > 0) { const int last_pos = static_cast(inp_pos->data)[std::max(input_tokens, 1) - 1]; const int needed = last_pos + (is_prefill ? 2 : 1); @@ -2331,6 +2336,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared // Head-major KV is bound whole, so prefill and decode both use the window of the storage capacity. decode_window = std::min(std::max(decode_window, kv_storage_rows(cgraph)), m_params.ctx_per_seq); c_params.attention_size = decode_window; + } else if (is_prefill && prefill_window_aligned && c_params.attention_size > 0) { + // Weightless-bank cache: a prefill attends at least the decode KV window, so the prefill sizes are + // the window sizes and the export can build them all up front (see the prefill window export below). + c_params.attention_size = std::min(std::max(c_params.attention_size, decode_window), m_params.ctx_per_seq); } if (!is_prefill) { c_params.attention_size = decode_window; @@ -3010,10 +3019,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared GGML_LOG_INFO("ggml-openvino: prebuilt %zu decode KV window model(s) in %.1f ms\n", graph.decode_windows.size(), (ggml_time_us() - t0) / 1000.0); - // With head-major KV a prefill also runs at a KV window, picked by prompt length. Export the prefill - // model of every other window too, so an import-only run has a pair for any prompt length. + // With head-major KV (or window-aligned prefill) a prefill also runs at a KV window, picked by prompt + // length. Export the prefill model of every other window too, so an import-only run has a pair for any + // prompt length. const std::string model_cache_dir = ggml_openvino_model_cache_dir(); - if (graph.weightless_bank && graph.weights_layout && ggml_openvino_npu_kv_head_major_enabled() && + if (graph.weightless_bank && graph.weights_layout && + (ggml_openvino_npu_kv_head_major_enabled() || prefill_window_aligned) && ggml_openvino_getenv_int("GGML_OPENVINO_SELF_CONTAINED_MMAP") == 0) { const int64_t t1 = ggml_time_us(); size_t exported = 0; From e767f19b44fb97836dec33c474e659b6799ff42e Mon Sep 17 00:00:00 2001 From: xuejun Date: Wed, 25 Nov 2026 10:36:04 +0530 Subject: [PATCH 12/21] 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. --- docs/backend/OPENVINO.md | 2 +- .../dev_doc/OpenVINO-ENV-VARS.md | 4 +- ggml/src/ggml-openvino/ggml-decoder.cpp | 61 ++++++++++++++++--- ggml/src/ggml-openvino/ggml-decoder.h | 11 ++++ .../src/ggml-openvino/ggml-openvino-extra.cpp | 27 +++++--- ggml/src/ggml-openvino/ggml-openvino-extra.h | 30 +++++---- .../openvino/op/flash_attn_ext.cpp | 6 +- ggml/src/ggml-openvino/openvino/utils.cpp | 28 ++++++++- ggml/src/ggml-openvino/openvino/utils.h | 3 + ggml/src/ggml-openvino/utils.cpp | 61 +++++++++++++------ 10 files changed, 174 insertions(+), 59 deletions(-) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index e012d8bb38f8..d8b1287f8060 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -882,7 +882,7 @@ 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_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 with full-context decode (`GGML_OPENVINO_NPU_BLOB_PREBUILD=0`), without `GGML_OPENVINO_NPU_HFA_PREFILL`, and not for models with recurrent state. A batch that needs more than one output token switches to the full prefill. `0` turns it off. | +| `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. | diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 9d72ceacb912..f939436e86e8 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -50,8 +50,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, and replaced when that size changes; 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. All windows are built, or read from the cache, together with the first prefill and decode pair (with the weightless bank the prefill graphs of every window are exported too). `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`. | diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 9546f8560418..161a54e3c187 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -313,6 +313,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)) { @@ -1075,7 +1086,32 @@ std::pair 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 +1246,8 @@ std::pair 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 +1266,8 @@ std::pair 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; } @@ -1402,13 +1440,13 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr if (is_static && compute_params.output_len == 0) { compute_params.output_len = 1; } - // A sliced static prefill attends a power-of-two number of KV rows: every attended size needs its own compiled - // prefill model, so a growing sequence compiles one when the attended length doubles, not for each ubatch. - // Rounding up adds masked rows, which cost prefill time, so it stops at the next power of two. + // 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 +1516,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; } @@ -1922,6 +1960,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; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 77e0f7fce45e..c0317ac311fb 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -47,6 +47,15 @@ struct ModelParams { // The attention masks that are graph inputs, by identity: gemma-4's KV-shared layers also read them through // GET_ROWS, which must resolve to the same OV parameter as the attention ops std::set 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 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 kv_names; size_t kv_buffer_ctx_id = 0; @@ -723,6 +732,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { 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) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index ae97f6dff029..91cb0233ead4 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -191,7 +191,7 @@ 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}, @@ -262,6 +262,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; @@ -637,8 +643,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() { @@ -672,11 +683,11 @@ int ggml_openvino_npu_decode_bucket() { !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; } @@ -685,7 +696,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; @@ -779,8 +790,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(bucket) : 1024; + const int base = ggml_openvino_kv_slice_base(); + size_t cap = base > 0 ? static_cast(base) : 1024; while (cap < rows) { cap *= 2; } diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index b4a7419479c5..8cae6bad8b20 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -140,10 +140,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(); @@ -159,7 +163,7 @@ 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 or decode KV windows); +// 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 @@ -167,15 +171,17 @@ bool ggml_openvino_kv_only_prefill_enabled(); // 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: @@ -186,7 +192,7 @@ 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 diff --git a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp index b83c6de3a1c4..98a021b5a37b 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -294,9 +294,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)); diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 7094cb7338ea..0a5d5b8c05cf 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -496,15 +496,37 @@ std::shared_ptr gather_compressed_rows(const ov::Output & 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 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 mask; if (!sliced.empty() && context.has_input(sliced)) { - return context.get_input(sliced); + mask = context.get_input(sliced); + } else if (pruned) { + mask = context.get_input(name); + } else { + return context.get_input(input_index); + } + if (!pruned) { + return mask; } - return context.get_input(input_index); + // gemma-4's KV-shared layers: the rows of their output tokens, gathered from the input mask (see + // ModelParams::pruned_masks) + auto ids = std::make_shared(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(mask, ids, axis); } ov::Output process_view_input_new(const NodeContext & context, int input_index) { diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 3fe3b60f918b..499596e6f14b 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -49,6 +49,9 @@ OutputVector translate_recurrent_cache_reset(const NodeContext & context); // add_sliced_mask_stateful); any other input, e.g. the mask rows gemma-4 gathers for its KV-shared layers, as is. ov::Output get_kq_mask_input(const NodeContext & context, size_t input_index); +// The mask of gemma-4's KV-shared layers, whose rows get_kq_mask_input() gathers from an input mask +bool is_pruned_mask_name(const std::string & name); + // A stateless KV cache in the [1, ctx, n_heads_kv, head_size] layout (GgmlOvDecoder::is_kvcache_4d), as opposed to // [1, n_seq, ctx, n_heads_kv * head_size] inline bool is_kvcache_4d_shape(const ov::PartialShape & shape) { diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index e3eb6f4fd22c..e155ebf0be52 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -201,7 +201,8 @@ std::optional try_make_kv_4d_tensor(const std::shared_ptr & ggml_decoder, const std::string & name) { const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name)); - if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) { + if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : + ggml_openvino_npu_decode_bucket() > 0) { const auto & params = ggml_decoder->get_compute_params(); const int attention_size = is_swa ? params.attention_size_swa : params.attention_size; if (attention_size > 0) { @@ -2298,9 +2299,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared m_params.state_size >= 0 ? ggml_openvino_npu_gdn_config(config) : config; // Decided per compiled pair from the graph that triggers the compile; later calls follow entry->kv_only_prefill. - // The output step binds the full KV cache to the pair's decode model, so it needs a full-context decode window. + // The output step runs the decode model of the KV window covering the output token (the full context without + // decode KV windows). const bool kv_only_prefill = !no_kv_cache && ggml_openvino_kv_only_prefill_enabled() && !g_kv_only_prefill_failed && - !ggml_openvino_npu_hfa_prefill_enabled() && ggml_openvino_npu_decode_bucket() == 0 && + !ggml_openvino_npu_hfa_prefill_enabled() && c_params.output_len <= 1 && has_kv_shared_attention(cgraph) && !has_recurrent_state(cgraph); std::shared_ptr decode_request_for_outputs; @@ -2319,11 +2321,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared ggml_openvino_npu_decode_bucket() : 0; int decode_window = m_params.ctx_per_seq; - // Weightless-bank model cache with sliced (not head-major) KV: prefill sizes follow the decode KV windows. - const bool prefill_window_aligned = decode_bucket > 0 && ggml_openvino_kv_slice_enabled() && - !ggml_openvino_npu_kv_head_major_enabled() && - ggml_openvino_npu_weightless_bank_enabled() && - !ggml_openvino_model_cache_dir().empty(); + // With decode KV windows and sliced (not head-major) KV, prefill sizes follow the decode KV windows. + const bool prefill_window_aligned = decode_bucket > 0 && !ggml_openvino_npu_kv_head_major_enabled(); if (decode_bucket > 0 && m_params.ctx_per_seq > 0) { const int last_pos = static_cast(inp_pos->data)[std::max(input_tokens, 1) - 1]; const int needed = last_pos + (is_prefill ? 2 : 1); @@ -2337,8 +2336,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared decode_window = std::min(std::max(decode_window, kv_storage_rows(cgraph)), m_params.ctx_per_seq); c_params.attention_size = decode_window; } else if (is_prefill && prefill_window_aligned && c_params.attention_size > 0) { - // Weightless-bank cache: a prefill attends at least the decode KV window, so the prefill sizes are - // the window sizes and the export can build them all up front (see the prefill window export below). + // A prefill attends at least the decode KV window, so the prefill sizes are the window sizes and the + // weightless-bank export can build them all up front (see the prefill window export below). c_params.attention_size = std::min(std::max(c_params.attention_size, decode_window), m_params.ctx_per_seq); } if (!is_prefill) { @@ -2565,7 +2564,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared base_extra = base_extra * 131 + (weightless_bank ? 3u : (self_contained ? 1u : 0u)); base_extra = ggml_openvino_model_cache_mix_string( base_extra, ggml_openvino_getenv_str("GGML_OPENVINO_NPU_TOKEN_EMBD_QUANT")); - base_extra = base_extra * 131 + (ggml_openvino_kv_slice_enabled() ? 1u : 0u); + // KV slice window base; the default base (1024) keeps the fingerprint of the former on/off flag. + const int kv_slice_base = ggml_openvino_kv_slice_base(); + base_extra = base_extra * 131 + + static_cast(kv_slice_base == 1024 ? 1 : kv_slice_base); base_extra = base_extra * 131 + (ggml_openvino_npu_kv_head_major_enabled() ? 1u : 0u); base_extra = base_extra * 131 + (kv_only_prefill ? 1u : 0u); base_extra = ggml_openvino_model_cache_mix_string( @@ -2993,7 +2995,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared if (graph_it == shared_cache->graphs.end()) { throw std::runtime_error("ggml-openvino: decode window requested without a shared compiled graph"); } - auto & compiled = build_decode_window(graph_it->second, c_params, window); + auto & compiled = build_decode_window(graph_it->second, graph_it->second.decode_c_params, window); request = std::make_shared(compiled.create_infer_request()); return request; }; @@ -3053,6 +3055,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared auto window_decoder = std::make_shared(cgraph, m_params, window_c_params, model_weights, is_static, stateful, false, true, prefill_chunk_size); + window_decoder->set_kv_only_outputs(graph.kv_only_prefill); ov::AnyMap window_config = ggml_openvino_npu_prefill_config(compile_config, *window_decoder); window_config.erase("CACHE_DIR"); @@ -3107,6 +3110,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } GgmlOvDecoder window_decoder(cgraph, m_params, window_c_params, weight_names, is_static, stateful, false, true, prefill_chunk_size); + window_decoder.set_kv_only_outputs(graph.kv_only_prefill); ov::AnyMap import_config = ggml_openvino_npu_prefill_config(compile_config, window_decoder); import_config.erase("CACHE_DIR"); import_config.erase("CACHE_MODE"); @@ -3279,7 +3283,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared const ggml_tensor * out_ids = nullptr; for (const auto & [name, info] : ggml_decoder->get_model_inputs()) { const ggml_tensor * tensor = ggml_decoder->get_input_ggml_tensor(name); - if (tensor != nullptr && + // gemma-4's inp_prune_keep indexes the gathered rows, not the rows of the graph + if (tensor != nullptr && tensor != ggml_decoder->get_model_params().prune_keep && GgmlOvDecoder::is_output_idx(tensor, ggml_decoder->get_tensor_used_op(tensor))) { out_ids = tensor; break; @@ -3291,9 +3296,21 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared kv_only_error = "the batch needs " + std::to_string(n_outputs) + " output tokens"; } else if (n_outputs == 1) { const int64_t row = static_cast(out_ids->data)[0]; + const ComputeParams prefill_c_params = ggml_decoder->get_compute_params(); ggml_decoder->m_is_prefill = false; try { - const auto & compiled_inputs = decode_request_for_outputs->get_compiled_model().inputs(); + // With decode KV windows, run the decode model of the window the next decode step uses (it + // covers the output token); its inputs are sized by the decoder's attention size. + auto step_request = decode_request_for_outputs; + if (decode_bucket > 0) { + auto step_c_params = prefill_c_params; + step_c_params.attention_size = decode_window; + ggml_decoder->set_compute_params(step_c_params); + if (decode_window != entry->decode_attention_size) { + step_request = get_decode_window_request(decode_window); + } + } + const auto & compiled_inputs = step_request->get_compiled_model().inputs(); for (size_t i = 0; i < decode_input_names_for_outputs.size(); i++) { const auto & name = decode_input_names_for_outputs[i]; auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, name, row); @@ -3302,7 +3319,7 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared input_tensor.get_shape().to_string() + ", expected " + compiled_inputs[i].get_shape().to_string()); } - decode_request_for_outputs->set_input_tensor(i, input_tensor); + step_request->set_input_tensor(i, input_tensor); } const auto & model_outputs = ggml_decoder->get_model_outputs(); for (size_t i = 0; i < decode_output_names_for_outputs.size(); i++) { @@ -3310,20 +3327,24 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared if (it == model_outputs.end() || ggml_nbytes(it->second) == 0) { continue; } - decode_request_for_outputs->set_output_tensor( - i, create_ov_output_tensor(ggml_decoder, decode_request_for_outputs, i, it->second)); + step_request->set_output_tensor( + i, create_ov_output_tensor(ggml_decoder, step_request, i, it->second)); } const int64_t decode_start = ggml_time_us(); - decode_request_for_outputs->infer(); + step_request->infer(); const int64_t decode_us = ggml_time_us() - decode_start; ov_raw_infer_total += decode_us; if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) { - fprintf(stderr, "GGML OpenVINO profiling: KV-only prefill output step: row=%lld, raw infer=%.3f ms\n", - static_cast(row), decode_us / 1000.0); + fprintf(stderr, + "GGML OpenVINO profiling: KV-only prefill output step: row=%lld, kv_window=%d, raw " + "infer=%.3f ms\n", + static_cast(row), ggml_decoder->get_compute_params().attention_size, + decode_us / 1000.0); } } catch (const std::exception & e) { kv_only_error = e.what(); } + ggml_decoder->set_compute_params(prefill_c_params); ggml_decoder->m_is_prefill = true; } if (!kv_only_error.empty()) { From 1550ef23a294a8fc2c03c7c53cb2158bc790755e Mon Sep 17 00:00:00 2001 From: xuejun Date: Wed, 25 Nov 2026 11:38:05 +0530 Subject: [PATCH 13/21] ggml-openvino: keep the compiled model alive while reading its inputs (-Wdangling-reference) --- ggml/src/ggml-openvino/utils.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index e155ebf0be52..d2a711e23307 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -3310,7 +3310,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared step_request = get_decode_window_request(decode_window); } } - const auto & compiled_inputs = step_request->get_compiled_model().inputs(); + const auto step_model = step_request->get_compiled_model(); + const auto & compiled_inputs = step_model.inputs(); for (size_t i = 0; i < decode_input_names_for_outputs.size(); i++) { const auto & name = decode_input_names_for_outputs[i]; auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, name, row); From 29f8c67075dd914d99962134381e711aae785b8a Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 09:22:52 +0100 Subject: [PATCH 14/21] ggml-openvino: translate recurrent cache replay graphs Assisted-by: Codex --- .../dev_doc/OpenVINO-ENV-VARS.md | 1 + ggml/src/ggml-openvino/ggml-decoder.cpp | 54 ++++- ggml/src/ggml-openvino/ggml-decoder.h | 3 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 1 + ggml/src/ggml-openvino/ggml-openvino.cpp | 31 ++- ggml/src/ggml-openvino/openvino/decoder.h | 1 + .../openvino/op/gated_delta_net.cpp | 29 +++ .../openvino/op/recurrent_replay_graph.hpp | 183 +++++++++++++++ ggml/src/ggml-openvino/openvino/op_table.h | 1 + .../openvino/recurrent_cache_fusion.cpp | 2 +- .../openvino/recurrent_replay_fusion.cpp | 217 ++++++++++++++++++ .../openvino/recurrent_replay_fusion.h | 30 +++ .../openvino/translate_session.cpp | 6 +- ggml/src/ggml-openvino/utils.cpp | 4 +- 14 files changed, 553 insertions(+), 10 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp create mode 100644 ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp create mode 100644 ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index f939436e86e8..b749da521daa 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -86,6 +86,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | | `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended KV length to a window on the dynamic stateless GPU path. Set to `0` to use the unrounded attended length while keeping KV slicing enabled. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | | `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. | diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 161a54e3c187..2008ac56a52e 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -486,6 +486,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { seq = node; } recurrent_sequence = seq == node; + } else if (concat->op == GGML_OP_CONT && concat->src[0]->op == GGML_OP_TRANSPOSE) { + const auto * cols = concat->src[0]->src[0]; + recurrent_sequence = cols->op == GGML_OP_CONCAT && cols->op_params[0] == 1 && cols->src[1] == node; } } else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) { const auto * biased = consumer->src[0]; @@ -1369,7 +1372,7 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr const bool is_extra_view = node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0]->op == GGML_OP_GET_ROWS; const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS || is_extra_view; - const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]); + const bool is_gdn_rollback = is_gdn && node->src[0]->src[0]->op_params[1] == 0 && is_same_shape(node->src[0], node->src[1]); const ggml_tensor * dest_view = node->src[1]; const ggml_tensor * cache = node->view_src; @@ -1451,7 +1454,8 @@ std::pair GgmlOvDecoder::compute_llm_params(ggml_cgr // 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. // The KQ mask input is padded to this length with -inf (convert_ggml_input_to_ov). - if (!is_static && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && + if (!is_static && ggml_openvino_is_gpu() && ggml_openvino_getenv_int("GGML_OPENVINO_GPU_KV_ROUND_UP", 1) && + !ggml_openvino_getenv_int("GGML_OPENVINO_STATEFUL_EXECUTION") && !compute_params.mask_name.empty() && compute_params.attention_size > 0 && model_params.ctx_per_seq > 0) { compute_params.attention_size = ggml_openvino_gpu_kv_window(compute_params.attention_size, model_params.ctx_per_seq, compute_params.input_len); @@ -1816,8 +1820,8 @@ void GgmlOvDecoder::add_extra_inputs() { create_1d_input("rs_window_count_" + node_name, writeback.window_count); } } -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE m_compute_params.recurrent_controls.clear(); +#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE // Naive graphs have no full-model cache fusion and node cases are not initialized here. if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { @@ -1872,6 +1876,50 @@ void GgmlOvDecoder::add_extra_inputs() { } } #endif + if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + const auto gdn = m_cgraph->nodes[i]; + if (gdn->op != GGML_OP_GATED_DELTA_NET || gdn->op_params[1] <= 0) continue; + const auto B = gdn->src[2]->ne[3]; + const ggml_tensor * rows = gdn->src[5]; + while (rows && (rows->op == GGML_OP_VIEW || rows->op == GGML_OP_RESHAPE)) rows = rows->src[0]; + if (!rows || rows->op != GGML_OP_GET_ROWS) continue; + rows = rows->src[1]; + while (rows && rows->op == GGML_OP_VIEW) rows = rows->src[0]; + if (!rows || rows->type != GGML_TYPE_I32 || !rows->data || !gdn->src[9]->data) continue; + const ggml_tensor * root = gdn->src[5]; + while (root && (root->op == GGML_OP_VIEW || root->op == GGML_OP_RESHAPE || root->op == GGML_OP_GET_ROWS)) root = root->src[0]; + int64_t head = -1, reset_begin = 0, reset_count = 0; + for (int j = 0; j < m_cgraph->n_nodes; ++j) { + const auto t = m_cgraph->nodes[j]; + if (t->view_src != root) continue; + if (t->op == GGML_OP_CPY && t->src[0]->op == GGML_OP_VIEW && t->src[0]->src[0] == gdn) + head = t->src[1]->view_offs / root->nb[1]; + if (is_recurrent_cache_reset(t)) { + reset_begin = t->src[0]->view_offs / root->nb[1]; + reset_count = ggml_nelements(t->src[0]) / root->ne[0]; + } + } + if (head < 0) continue; + auto & map = m_compute_params.recurrent_controls["rs_replay_rows"]; + auto & control = m_compute_params.recurrent_controls["rs_replay_control"]; + auto & resets = m_compute_params.recurrent_controls["rs_replay_reset"]; + map.clear(); control.clear(); resets.clear(); + const auto * copy = static_cast(rows->data); + for (int64_t j = 0; j < ggml_nelements(rows); ++j) { + if (j < B || head + j != copy[j]) { map.push_back(head + j); map.push_back(copy[j]); } + } + const auto * counts = static_cast(gdn->src[9]->data); + for (int64_t j = 0; j < B; ++j) control.push_back(counts[j]); + control.push_back(gdn->op_params[2]); + for (int64_t j = 0; j < reset_count; ++j) resets.push_back(reset_begin + j); + m_model_extra_inputs["rs_replay_rows"] = {ov::element::i64, ov::Shape{1, 1, map.size() / 2, 2}, 0, true, {}, -1, ov::PartialShape{1, 1, -1, 2}}; + m_model_extra_inputs["rs_replay_control"] = {ov::element::i64, ov::Shape{1, 1, 1, control.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}}; + m_model_extra_inputs["rs_replay_reset"] = {ov::element::i64, ov::Shape{1, 1, 1, resets.size()}, 0, true, {}, -1, ov::PartialShape{1, 1, 1, -1}}; + break; + } + } if (!m_is_static && !m_compute_params.sampling_rows.empty()) { m_model_extra_inputs["sampling_rows"] = {ov::element::i64, ov::Shape{m_compute_params.sampling_rows.size()}, 0, true, {}, -1}; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index c0317ac311fb..28d272d9dc45 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -574,7 +574,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { static bool is_recurrent_cache(const ggml_tensor * tensor) { return tensor != nullptr && (strncmp(tensor->name, "cache_r_l", strlen("cache_r_l")) == 0 || strncmp(tensor->name, "cache_s_l", strlen("cache_s_l")) == 0 || - strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0); + strncmp(tensor->name, "cache_ple_r_l", strlen("cache_ple_r_l")) == 0 || + strncmp(tensor->name, "cache_sp", strlen("cache_sp")) == 0); } static bool is_recurrent_cache_reset(const ggml_tensor * node) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 91cb0233ead4..14b175921edf 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -192,6 +192,7 @@ constexpr env_var env_vars[] = { {"GGML_OPENVINO_GDN_DECOMPOSE", env_type::BOOL}, {"GGML_OPENVINO_NPU_L0_HOST_TENSORS", env_type::BOOL}, {"GGML_OPENVINO_KV_SLICE", env_type::INT}, + {"GGML_OPENVINO_GPU_KV_ROUND_UP", env_type::BOOL}, {"GGML_OPENVINO_NPU_HFA_PREFILL", env_type::BOOL}, {"GGML_OPENVINO_NPU_DECODE_UNFOLD", env_type::BOOL}, {"GGML_OPENVINO_NPU_PARALLEL_COMPILE", env_type::BOOL}, diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index e1ba0baeb94b..e1dafa3b2346 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1671,6 +1671,25 @@ static bool tensor_view_fits_src_buffer(const ggml_tensor * tensor) { return tensor_nbytes <= src_nbytes - tensor->view_offs; } +static bool supports_replay_cache_banks() { + return ggml_openvino_is_gpu() && !ggml_openvino_is_static() && !is_stateful_enabled() && + !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE"); +} + +static bool is_replay_input_store(const ggml_tensor * op) { + if (op->op != GGML_OP_CPY || !op->view_src || strncmp(op->view_src->name, "cache_sp", 8) != 0 || + op->type != GGML_TYPE_F32 || op->src[0]->op != GGML_OP_VIEW || op->src[1]->op != GGML_OP_VIEW || + !supports_replay_cache_banks()) { + return false; + } + const auto dst = op->src[1]; + const auto base = dst->src[0]; + // Pending prefixes keep the full bank row stride; the complete replay fusion owns this store. + return base && base->op == GGML_OP_RESHAPE && base->src[0] == op->view_src && + dst->ne[0] <= base->ne[0] && dst->ne[1] == base->ne[1] && dst->ne[2] <= base->ne[2] && + dst->nb[0] == base->nb[0] && dst->nb[1] == base->nb[1] && dst->nb[2] == base->nb[2] && dst->nb[3] == base->nb[3]; +} + static bool cpy_output_view_is_supported(const ggml_tensor * op) { if (op->view_src == nullptr) { return true; @@ -1681,7 +1700,7 @@ static bool cpy_output_view_is_supported(const ggml_tensor * op) { } return ggml_nbytes(op) == 0 || ggml_is_contiguous(op) || GgmlOvDecoder::is_conv_state_writeback(op) || - GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op); + GgmlOvDecoder::is_gdn_snapshot_writeback(op) || GgmlOvDecoder::is_ssm_state_writeback(op) || is_replay_input_store(op); } static bool mul_mat_id_requires_large_tmp(const ggml_tensor * op) { @@ -2114,7 +2133,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { return {false, reason}; } if (((const int32_t *) op->op_params)[1] != 0) { - return {false, "GATED_DELTA_NET with replay of pending tokens is not supported"}; + bool banks = true; + for (int port : {5, 6, 7, 8}) { + const auto * source = op->src[port]; + while (source && (source->op == GGML_OP_VIEW || source->op == GGML_OP_RESHAPE || source->op == GGML_OP_GET_ROWS)) source = source->src[0]; + banks &= GgmlOvDecoder::is_recurrent_cache(source); + } + if (!banks || !supports_replay_cache_banks()) { + return {false, "GATED_DELTA_NET replay requires the dynamic stateless GPU cache-bank translation"}; + } } break; } diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 879e574413bf..a5a6444236bc 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -26,6 +26,7 @@ struct ModelExtraInputInfo { // when set, the value is read from dimension shape_axis of this model input instead of a Parameter std::string shape_source; int64_t shape_axis = -1; + PartialShape parameter_shape = PartialShape::dynamic(); }; class GgmlDecoder : public DecoderBase { diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 6caafeb4fde8..53625f5ab3f5 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -1,6 +1,7 @@ #include "gated_delta_net.hpp" #include "../node_context.h" +#include "recurrent_replay_graph.hpp" #include "../op_table.h" #include "../utils.h" #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE @@ -30,6 +31,7 @@ #include #include #include +#include #include #include #include @@ -575,6 +577,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto } OutputVector translate_gated_delta_net(const NodeContext & context) { + FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[1] == 0, "Replay requires a complete cache-bank fusion; functional replay translation is not implemented yet"); return translate_gdn(context, nullptr); } @@ -584,6 +587,32 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co } #endif +OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks) { + auto q = context.get_input(0), k = context.get_input(1); + const auto shape = context.get_input_shape(2); + auto v = process_view_input(context, 2, shape[2].get_length() * shape[3].get_length(), 3); + if (context.get_view_input_size(2)) { + v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0})); + v = std::make_shared(v, ov::op::v0::Constant::create(ov::element::i64, {4}, + std::vector{0, 0, shape[2].get_length(), shape[3].get_length()}), true); + } + if (context.get_op_case() == 1 && ggml_openvino_gdn_prescale_enabled()) { + q = std::make_shared(q, + ov::op::v0::Constant::create(ov::element::f32, {1}, {ggml_openvino_gdn_q_scale()})); + } else { + Output raw_q, raw_k; + float q_eps, k_eps; + if (match_gdn_l2_norm(q, raw_q, q_eps) && match_gdn_l2_norm(k, raw_k, k_eps)) { + auto axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}); + q = std::make_shared(raw_q, axis, q_eps, ov::op::EpsMode::ADD); + k = std::make_shared(raw_k, axis, k_eps, ov::op::EpsMode::ADD); + } + } + return ov::recurrent_replay::build({ + q, k, v, banks[0], context.get_input(3), context.get_input(4), + banks[1], banks[2], banks[3], banks[4], banks[5], banks[6]}, false); +} + static OutputVector translate_gated_delta_net_ref(const NodeContext & context) { num_inputs_check(context, 6, 6); FRONT_END_OP_CONVERSION_CHECK(!context.has_input("chunk_valid_len"), diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp new file mode 100644 index 000000000000..96086348d19a --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp @@ -0,0 +1,183 @@ +// Copyright (C) 2018-2026 Intel Corporation +// SPDX-License-Identifier: Apache-2.0 +#pragma once + +#include "openvino/opsets/opset13.hpp" +#include "openvino/core/model.hpp" +#include +#include + +namespace ov::recurrent_replay { +namespace ops = ov::opset13; +using Value = ov::Output; + +inline Value scalar(int64_t n) { return ops::Constant::create(element::i64, {}, {n}); } +inline Value vec(std::vector v) { return ops::Constant::create(element::i64, {v.size()}, v); } +inline Value fp(float x) { return ops::Constant::create(element::f32, {}, {x}); } +inline Value f32(Value x) { + return x.get_element_type() == element::f32 ? x : Value(std::make_shared(x, element::f32)); +} +inline Value gather(Value x, Value i, int axis, int batch = 0) { + return std::make_shared(x, i, scalar(axis), batch); +} +inline Value unsqueeze(Value x, int axis) { return std::make_shared(x, scalar(axis)); } +inline Value squeeze(Value x, int axis) { return std::make_shared(x, scalar(axis)); } +inline Value reshape(Value x, std::vector dims) { return std::make_shared(x, vec(dims), true); } +inline Value dim(Value x, int axis) { return gather(std::make_shared(x, element::i64), scalar(axis), 0); } +inline Value cat(OutputVector xs, int axis) { return std::make_shared(xs, axis); } +inline Value slice(Value x, Value begin, Value end, int axis) { + return std::make_shared(x, unsqueeze(begin, 0), unsqueeze(end, 0), vec({1}), vec({axis})); +} +inline Value slice_end() { return scalar(std::numeric_limits::max()); } +inline Value add(Value x, Value y) { return std::make_shared(x, y); } +inline Value mul(Value x, Value y) { return std::make_shared(x, y); } +inline Value swap_time_channels(Value x) { return std::make_shared(x, vec({0, 2, 1})); } +inline Value linear(Value count) { return std::make_shared(scalar(0), count, scalar(1), element::i64); } + +struct RowSelection { + Value sources, destinations, extra_src, extra_dst, resets, counts, keep; + RowSelection(Value rows, Value control, Value reset, Value batch) { + rows = reshape(rows, {-1, 2}); + auto src = gather(rows, scalar(1), 1); + auto dst = gather(rows, scalar(0), 1); + sources = slice(src, scalar(0), batch, 0); + destinations = slice(dst, scalar(0), batch, 0); + extra_src = slice(src, batch, slice_end(), 0); + extra_dst = slice(dst, batch, slice_end(), 0); + resets = reshape(reset, {-1}); + auto flags = reshape(control, {-1}); + counts = slice(flags, scalar(0), batch, 0); + keep = std::make_shared(gather(flags, scalar(-1), 0), scalar(0)); + } +}; + +// A bank is logically [slots, features]. Gather original rows before any stores; +// active stores only replace their written features in the destination row. +struct Bank { + Value cleared, sources, destinations, extra_values; + const RowSelection& rows; + Bank(Value input, const RowSelection& r) : rows(r) { + auto flat = squeeze(squeeze(input, 0), 0); + auto reset_shape = cat({unsqueeze(dim(r.resets, 0), 0), unsqueeze(dim(flat, 1), 0)}, 0); + auto zeros = std::make_shared(fp(0), reset_shape); + cleared = std::make_shared(flat, unsqueeze(r.resets, 1), zeros); + sources = gather(cleared, r.sources, 0); + destinations = gather(cleared, r.destinations, 0); + extra_values = gather(cleared, r.extra_src, 0); + } + Value write(Value active) const { + // One destination per row-map entry. GGML generates these in slot order, + // including the inactive rows that need a copy. + auto indices = unsqueeze(cat({rows.destinations, rows.extra_dst}, 0), 1); + auto values = cat({reshape(active, {0, -1}), extra_values}, 0); + auto result = std::make_shared(cleared, indices, values); + return unsqueeze(unsqueeze(result, 0), 0); + } +}; +inline Value store_prefix(Value original, Value prefix) { + return cat({prefix, slice(original, dim(prefix, 1), slice_end(), 1)}, 1); +} + +inline OutputVector conv_body(const OutputVector& a) { + auto x = squeeze(a[2], 0); + const auto channels = a[3].get_partial_shape()[2].get_length(); + const auto taps = a[3].get_partial_shape()[3].get_length(); + RowSelection rows(a[1], a[4], a[5], dim(x, 0)); + Bank bank(a[0], rows); + auto history = reshape(bank.sources, {0, -1, channels}); + auto indices = add(unsqueeze(rows.counts, 1), unsqueeze(linear(scalar(taps - 1)), 0)); + auto window = gather(history, indices, 1, 1); + auto columns = cat({window, f32(x)}, 1); + auto weights = reshape(f32(a[3]), {channels, 1, 1, taps}); + auto convolved = std::make_shared(swap_time_channels(columns), weights, Strides{1}, + CoordinateDiff{0}, CoordinateDiff{0}, Strides{1}); + Value result = unsqueeze(swap_time_channels(convolved), 0); + if (a[2].get_element_type() != element::f32) + result = std::make_shared(result, a[2].get_element_type()); + // Keep the history and pending tokens, or commit only the last history window. + auto begin = std::make_shared(rows.keep, scalar(0), dim(x, 1)); + auto update = slice(columns, begin, slice_end(), 1); + return {result, bank.write(store_prefix(reshape(bank.destinations, {0, -1, channels}), update))}; +} + +inline Value expand_heads(Value x, int64_t heads, int64_t expanded) { + if (heads == expanded) + return x; + std::vector indices(expanded); + for (int64_t h = 0; h < expanded; ++h) + indices[h] = h % heads; + return gather(x, vec(indices), 2); +} +inline Value dot(Value state, Value key) { + return std::make_shared(mul(state, unsqueeze(key, 2)), scalar(3), false); +} +inline Value step(Value state, Value key, Value value, Value gate, Value beta) { + auto decayed = mul(state, unsqueeze(std::make_shared(gate), 2)); + auto delta = mul(beta, std::make_shared(value, dot(decayed, key))); + return add(decayed, mul(unsqueeze(delta, 3), unsqueeze(key, 2))); +} +inline OutputVector current_tokens(Value state, Value q, Value k, Value v, Value g, Value beta, float scale) { + auto idx = std::make_shared(element::i64, PartialShape{}); + auto carried = std::make_shared(element::f32, state.get_partial_shape()); + ParameterVector params{idx, carried}; + OutputVector inputs{q, k, v, g, beta}, token; + for (const auto& input : inputs) { + auto p = std::make_shared(input.get_element_type(), input.get_partial_shape()); + params.push_back(p); + token.push_back(gather(p, idx, 1)); + } + auto next = step(carried, token[1], token[2], token[3], token[4]); + auto attention = unsqueeze(mul(dot(next, token[0]), fp(scale)), 1); + auto yes = ops::Constant::create(element::boolean, {}, {true}); + auto body = std::make_shared(OutputVector{yes, next, attention}, params); + auto loop = std::make_shared(dim(v, 1), yes); + loop->set_function(body); + loop->set_special_body_ports({0, 0}); + loop->set_merged_input(carried, state, next); + for (size_t i = 0; i < inputs.size(); ++i) + loop->set_invariant_input(params[i + 2], inputs[i]); + return {loop->get_concatenated_slices(attention, 0, 1, 1, -1, 1), loop->get_iter_value(next, -1)}; +} + +inline OutputVector gdn_body(const OutputVector& a) { + const auto qshape = a[0].get_partial_shape(), kshape = a[1].get_partial_shape(), vshape = a[2].get_partial_shape(); + const int64_t Hq = qshape[2].get_length(), Hk = kshape[2].get_length(), Hv = vshape[2].get_length(); + const int64_t K = kshape[3].get_length(), V = vshape[3].get_length(), G = a[4].get_partial_shape()[3].get_length(); + const int64_t P = a[6].get_partial_shape()[3].get_length() / (Hk * K); + RowSelection rows(a[9], a[10], a[11], dim(a[2], 0)); + Bank states(a[3], rows), keys(a[6], rows), values(a[7], rows), gates(a[8], rows); + Value state = reshape(states.sources, {0, Hv, V, K}); + auto pk = expand_heads(reshape(keys.sources, {0, P, Hk, K}), Hk, Hv); + auto pv = reshape(values.sources, {0, P, Hv, V}); + auto pgb = reshape(gates.sources, {0, 2 * P, Hv, G}); + for (int64_t t = 0; t < P; ++t) { + auto time = scalar(t); + auto b = slice(gather(pgb, scalar(P + t), 1), scalar(0), scalar(1), 2); + auto next = step(state, gather(pk, time, 1), gather(pv, time, 1), gather(pgb, time, 1), b); + auto active = reshape(std::make_shared(rows.counts, time), {-1, 1, 1, 1}); + state = std::make_shared(active, next, state); + } + auto q = expand_heads(f32(a[0]), Hq, Hv), k = expand_heads(f32(a[1]), Hk, Hv); + auto computed = current_tokens(state, q, k, f32(a[2]), f32(a[4]), f32(a[5]), 1.0f / std::sqrt(float(K))); + auto save = [&](Value x) { return slice(f32(x), scalar(0), scalar(P), 1); }; + auto saved_g = save(a[4]), saved_b = save(a[5]); + auto gb = reshape(gates.destinations, {0, 2 * P, Hv, G}); + auto gb_gate = slice(gb, scalar(0), scalar(P), 1), gb_beta = slice(gb, scalar(P), slice_end(), 1); + if (G > 1) { + auto old_prefix = slice(gb_beta, scalar(0), dim(saved_b, 1), 1); + saved_b = cat({saved_b, slice(old_prefix, scalar(1), slice_end(), 3)}, 3); + } + Value output = computed[0]; + if (a[0].get_element_type() != element::f32) + output = std::make_shared(output, a[0].get_element_type()); + auto committed = std::make_shared(rows.keep, state, computed[1]); + return {output, states.write(committed), + keys.write(store_prefix(reshape(keys.destinations, {0, P, Hk, K}), save(a[1]))), + values.write(store_prefix(reshape(values.destinations, {0, P, Hv, V}), save(a[2]))), + gates.write(cat({store_prefix(gb_gate, saved_g), store_prefix(gb_beta, saved_b)}, 1))}; +} + +inline OutputVector build(const OutputVector& args, bool conv) { + return conv ? conv_body(args) : gdn_body(args); +} +} // namespace ov::recurrent_replay diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 766ca4e6f76c..aed1ff7a895f 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -57,6 +57,7 @@ bool gdn_per_key_gate_supported(); #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); #endif +OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks); GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); GGML_OP_CONVERTER(translate_set); diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp index 8d0ac026dc62..160a7337fafa 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -117,7 +117,7 @@ RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & } else { for (int j = i + 1; j < graph->n_nodes; ++j) { const auto node = graph->nodes[j]; - if (node->op != GGML_OP_GATED_DELTA_NET || !node->src[5] || node->src[5]->op != GGML_OP_RESHAPE) { + if (node->op != GGML_OP_GATED_DELTA_NET || node->op_params[1] != 0 || !node->src[5] || node->src[5]->op != GGML_OP_RESHAPE) { continue; } const auto active = node->src[5]->src[0]; diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp new file mode 100644 index 000000000000..e387e1c77436 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.cpp @@ -0,0 +1,217 @@ +#include "recurrent_replay_fusion.h" + +#include "../ggml-openvino-extra.h" +#include "ggml-impl.h" +#include "op/recurrent_replay_graph.hpp" +#include "op_table.h" +#include "utils.h" + +#include +#include +#include + +namespace ov::frontend::ggml { +namespace { +const ggml_tensor * cache_root(const ggml_tensor * node) { + while (node && (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE || node->op == GGML_OP_GET_ROWS)) { + node = node->src[0]; + } + return node && node->op == GGML_OP_NONE && GgmlOvDecoder::is_recurrent_cache(node) ? node : nullptr; +} +} // namespace + +RecurrentReplayFusion::RecurrentReplayFusion(const std::shared_ptr & decoder, + const std::shared_ptr & tensors) : + m_decoder(decoder), + m_tensors(tensors) { + auto actual = std::dynamic_pointer_cast(decoder); + if (!actual || actual->m_naive || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() || + !ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") || + !tensors->count("rs_replay_rows")) { + return; + } + m_graph = actual->get_cgraph(); + for (int i = 0; i < m_graph->n_nodes; ++i) { + const auto node = m_graph->nodes[i]; + Group group; + group.compute = i; + if (node->op == GGML_OP_GATED_DELTA_NET && node->op_params[1] > 0) { + for (int port : {5, 6, 7, 8}) { + group.banks.push_back(cache_root(node->src[port])); + } + } else if (node->op == GGML_OP_SSM_CONV && node->src[0]->op == GGML_OP_CONT && + node->src[0]->src[0]->op == GGML_OP_TRANSPOSE) { + const auto cols = node->src[0]->src[0]->src[0]; + if (cols->op != GGML_OP_CONCAT || cols->op_params[0] != 1 || cols->src[0]->op != GGML_OP_GET_ROWS) { + continue; + } + group.conv = true; + group.current = cols->src[1]; + group.banks.push_back(cache_root(cols->src[0]->src[0])); + } else { + continue; + } + if (std::any_of(group.banks.begin(), group.banks.end(), [](const ggml_tensor * bank) { + return !bank || bank->type != GGML_TYPE_F32 || bank->ne[2] != 1 || bank->ne[3] != 1; + })) { + continue; + } + auto is_bank = [&](const ggml_tensor * t) { + return std::find(group.banks.begin(), group.banks.end(), t) != group.banks.end(); + }; + // Collect only cache-owned paths. Current-token producers remain outside this group. + std::function collect = [&](const ggml_tensor * t) { + if (!t || t->op == GGML_OP_NONE || t == group.current || is_bank(t) || !group.consumed.insert(t).second) { + return; + } + for (int port = 0; port < (t->op == GGML_OP_GET_ROWS ? 1 : GGML_MAX_SRC); ++port) { + if (t->src[port]) { + collect(t->src[port]); + } + } + }; + if (group.conv) { + collect(node->src[0]); + } else { + for (int port : {5, 6, 7, 8}) { + collect(node->src[port]); + } + } + std::map resets, writes; + for (int j = 0; j < m_graph->n_nodes; ++j) { + const auto t = m_graph->nodes[j]; + if (!is_bank(t->view_src)) { + continue; + } + if (GgmlOvDecoder::is_recurrent_cache_reset(t)) { + float value; + memcpy(&value, t->op_params, sizeof(value)); + if (value != 0) { + continue; + } + ++resets[t->view_src]; + collect(t); + } else if (t->op == GGML_OP_CPY) { + const auto src = t->src[0]; + const bool extra = + src->op == GGML_OP_VIEW && src->src[0]->op == GGML_OP_GET_ROWS && cache_root(src) == t->view_src; + bool update = false; + if (group.conv) { + update = src->op == GGML_OP_VIEW && src->src[0] == node->src[0]->src[0]->src[0]; + } else { + update = src->op == GGML_OP_VIEW && src->src[0] == node; + for (int port : {1, 2, 3, 4}) { + update |= src->op == GGML_OP_VIEW && src->src[0] == node->src[port]; + } + } + if (!extra && !update) { + continue; + } + if (update) { + ++writes[t->view_src]; + } + group.consumed.insert(t); + collect(t->src[1]); + group.consumed.insert(src); + if (extra) { + collect(src); + } + } + } + bool complete = true; + for (const auto bank : group.banks) { + complete &= resets[bank] == 1 && writes[bank] == (bank == group.banks.back() && !group.conv ? 2 : 1); + } + group.consumed.insert(node); + // A bank reader or writer outside this group would race with the implicit stores. + for (int j = 0; j < m_graph->n_nodes && complete; ++j) { + const auto t = m_graph->nodes[j]; + if (group.consumed.count(t)) { + continue; + } + if (is_bank(t->view_src) && t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) { + complete = false; + } + for (int port = 0; port < GGML_MAX_SRC; ++port) { + const auto src = t->src[port]; + if (!src || is_bank(src) == false) { + continue; + } + if (t->op != GGML_OP_VIEW && t->op != GGML_OP_RESHAPE) { + complete = false; + } + } + } + if (!complete) { + continue; + } + const auto id = m_groups.size(); + for (int j = 0; j < m_graph->n_nodes; ++j) { + if (group.consumed.count(m_graph->nodes[j])) { + m_nodes[j] = id; + } + } + m_groups.push_back(std::move(group)); + } + if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_CGRAPH")) { + const auto conv = + std::count_if(m_groups.begin(), m_groups.end(), [](const Group & group) { return group.conv; }); + GGML_LOG_INFO("ggml-openvino: replay fusion: %zu convolution, %zu GDN groups\n", size_t(conv), + m_groups.size() - conv); + } +} + +OutputVector RecurrentReplayFusion::translate(int index, const NodeContext & context) { + const auto found = m_nodes.find(index); + if (found == m_nodes.end()) { + return {}; + } + const auto & group = m_groups[found->second]; + using namespace ov::op; + auto bank_input = [&](const ggml_tensor * t) -> Output { + const auto name = GgmlOvDecoder::get_tensor_name(m_graph, t); + const auto found = m_tensors->find(name); + FRONT_END_OP_CONVERSION_CHECK(found != m_tensors->end(), "Replay input missing: ", name, " while translating ", + context.get_name()); + return found->second; + }; + if (index != group.compute) { + const auto node = m_graph->nodes[index]; + auto root = cache_root(node); + if (!root && node->view_src && + std::find(group.banks.begin(), group.banks.end(), node->view_src) != group.banks.end()) { + root = node->view_src; + } + return OutputVector(context.get_output_names().size(), bank_input(root ? root : group.banks[0])); + } + OutputVector banks; + for (const auto bank : group.banks) { + auto input = bank_input(bank); + auto source = input.get_node_shared_ptr(); + while (ov::is_type(source)) { + source = source->input_value(0).get_node_shared_ptr(); + } + FRONT_END_OP_CONVERSION_CHECK(ov::is_type(source), + "Replay banks require writable Parameter storage"); + banks.push_back(input); + } + auto rows = context.get_input("rs_replay_rows"), control = context.get_input("rs_replay_control"), + reset = context.get_input("rs_replay_reset"); + if (group.conv) { + auto x = bank_input(group.current); + const auto history = m_graph->nodes[index]->src[1]->ne[0] - 1; + auto pattern = + v0::Constant::create(element::i64, Shape{4}, std::vector{1, 1, group.current->ne[0], history + 1}); + auto weights = std::make_shared(context.get_input(1), pattern, false); + auto replay = ov::recurrent_replay::build({banks[0], rows, x, weights, control, reset}, true); + m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[0])] = replay[1]; + return {replay[0]}; + } + auto outputs = op::translate_recurrent_gated_delta_net_replay( + context, {banks[0], banks[1], banks[2], banks[3], rows, control, reset}); + for (size_t i = 0; i < group.banks.size(); ++i) { + m_updated_banks[GgmlOvDecoder::get_tensor_name(m_graph, group.banks[i])] = outputs[i + 1]; + } + return {outputs[0], outputs[1]}; +} +} // namespace ov::frontend::ggml diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h new file mode 100644 index 000000000000..f9ed2bb6f40a --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h @@ -0,0 +1,30 @@ +#pragma once +#include "../ggml-decoder.h" +#include "node_context.h" + +#include + +namespace ov::frontend::ggml { +class RecurrentReplayFusion { +public: + RecurrentReplayFusion(const std::shared_ptr &, const std::shared_ptr &); + OutputVector translate(int index, const NodeContext & context); + + const std::map> & updated_banks() const { return m_updated_banks; } +private: + struct Group { + int compute = -1; + bool conv = false; + const ggml_tensor * current = nullptr; + std::vector banks; + std::set consumed; + }; + + std::shared_ptr m_decoder; + std::shared_ptr m_tensors; + const ggml_cgraph * m_graph = nullptr; + std::vector m_groups; + std::map m_nodes; + std::map> m_updated_banks; +}; +} // namespace ov::frontend::ggml diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index eddebd901dab..8129b04a39dd 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -5,6 +5,7 @@ #include "ggml-openvino/openvino/node_context.h" #include "ggml-openvino/openvino/utils.h" #include "input_model.h" +#include "recurrent_replay_fusion.h" #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE #include "recurrent_cache_fusion.h" #endif @@ -75,7 +76,7 @@ std::shared_ptr create_parameter(const std::string & name std::shared_ptr create_extra_input(const std::string & name, const ModelExtraInputInfo & input_info) { if (input_info.is_parameter) { - ov::PartialShape shape(input_info.shape); + ov::PartialShape shape = input_info.parameter_shape.rank().is_static() ? input_info.parameter_shape : ov::PartialShape(input_info.shape); // One SET_ROWS emits min(tokens, snapshot capacity) windows on each batch. if (name.compare(0, 11, "rs_windows_") == 0) { shape[2] = ov::Dimension::dynamic(); @@ -306,6 +307,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); #endif + RecurrentReplayFusion replay_fusion(ggml_model_decoder, tensor_map); auto translate_node = [&](const std::shared_ptr & decoder, int node_idx) { auto operation_type = decoder->get_op_type(node_idx); if (operation_type == "GGML_OP_NONE") { @@ -330,6 +332,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE converted_outputs = recurrent_fusion.translate(node_idx, node_context); #endif + if (converted_outputs.empty()) converted_outputs = replay_fusion.translate(node_idx, node_context); if (converted_outputs.empty()) { converted_outputs = it->second(node_context); } @@ -391,6 +394,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } ggml_model_decoder->visit_subgraph(node_visitor); + for (const auto & updated : replay_fusion.updated_banks()) (*tensor_map)[updated.first] = updated.second; for (const auto & name : ggml_model_decoder->get_model_output_names()) { #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE if (recurrent_fusion.is_inplace_output(name)) { diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index d2a711e23307..6e223f3665c2 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -219,7 +219,7 @@ static size_t get_static_attention_size(const std::shared_ptr & g static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); - uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results. + uint64_t extra_cfg = 18; // Convolution replay uses a shared graph and a dynamic history slice. #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); #else @@ -765,7 +765,7 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) { *data++ = row.second; } - } else if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0) { + } else if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0 || param_name.compare(0, 10, "rs_replay_") == 0) { const auto & controls = ggml_decoder->get_compute_params(); const auto & values = controls.recurrent_controls.at(param_name); std::copy(values.begin(), values.end(), input_tensor.data()); From 575db27dd93e70e5ee5aa44edb49c6e8236d43cc Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 11:43:31 +0100 Subject: [PATCH 15/21] ggml-openvino: use host USM for 4-D KV on integrated GPUs Assisted-by: Codex --- .../dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 32 +++++++++++++++---- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index b749da521daa..5b6018205b22 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -85,7 +85,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. | | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | -| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | +| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Single-stream attention KV on integrated GPUs prefers host USM with device USM as a fallback. Requires an OpenVINO build newer than 2026.4.1. | | `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended KV length to a window on the dynamic stateless GPU path. Set to `0` to use the unrounded attended length while keeping KV slicing enabled. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index e1dafa3b2346..c726a6a86999 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -67,6 +67,8 @@ // - CPU repack buffer: tensor->extra stores tensor_traits with repacked data // ===================================================== +static bool ov_device_shares_system_memory(const std::string & device); + namespace { // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { @@ -121,7 +123,8 @@ struct ggml_backend_openvino_buffer_context { ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } - ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) : + ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false, + bool prefer_host_usm = false) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), id(next_buffer_id()), @@ -138,8 +141,18 @@ struct ggml_backend_openvino_buffer_context { GGML_ASSERT(ggml_openvino_is_gpu()); auto remote_context = ggml_openvino_get_remote_context(device_name); auto gpu_context = remote_context->as(); - ov::intel_gpu::ocl::USMTensor usm_tensor = - gpu_context.create_usm_device_tensor(ov::element::u8, ov::Shape{size}); + ov::intel_gpu::ocl::USMTensor usm_tensor; + if (prefer_host_usm) { + try { + usm_tensor = gpu_context.create_usm_host_tensor(ov::element::u8, ov::Shape{size}); + GGML_LOG_DEBUG("%s: allocated %zu bytes of USM host memory for attention KV\n", __func__, size); + } catch (const ov::Exception & e) { + GGML_LOG_DEBUG("%s: USM host KV allocation failed: %s\n", __func__, e.what()); + } + } + if (!usm_tensor) { + usm_tensor = gpu_context.create_usm_device_tensor(ov::element::u8, ov::Shape{size}); + } data = usm_tensor.get(); ov_buffer = std::make_shared(std::move(usm_tensor)); } else { @@ -416,12 +429,13 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer, ggml_backend_openvino_buffer_context *& ctx, ggml_tensor * tensor, bool is_remote, - bool lazy) { + bool lazy, + bool prefer_host_usm = false) { const int device = ctx->device; const size_t size = ctx->size; const size_t offset = (char *) tensor->data - (char *) ctx->data; delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy); + ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy, prefer_host_usm); buffer->context = ctx; if (ctx->data == nullptr) { return false; @@ -439,16 +453,20 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu // buffer, so in host memory the plugin copies it to the device and back on every inference. const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 || strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0; + const bool is_kv_tensor = strncmp(tensor->name, "cache_k_l", 9) == 0 || strncmp(tensor->name, "cache_v_l", 9) == 0; if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) { GGML_ASSERT(ctx->tensor_extras.empty()); - if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) { + // Large device USM allocations slowed attention reads on Arc B390. Host USM preserves remote KV bindings. + const bool prefer_host_usm = is_kv_tensor && tensor->ne[2] == 1 && tensor->ne[3] == 1 && !ggml_openvino_is_static() && + ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 && + ov_device_shares_system_memory(ggml_openvino_get_available_devices()[ctx->device]); + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false, prefer_host_usm)) { return GGML_STATUS_ALLOC_FAILED; } } // On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor // and register every KV tensor; the NPU binds grown L0 storage instead. - const bool is_kv_tensor = strncmp(tensor->name, "cache_k_l", 9) == 0 || strncmp(tensor->name, "cache_v_l", 9) == 0; if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() && tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) { if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) { From b549240d0cb700f48fb594bbe7a5297ccdeda05a Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 12:00:08 +0100 Subject: [PATCH 16/21] Revert "ggml-openvino: use host USM for 4-D KV on integrated GPUs" This reverts commit 575db27dd93e70e5ee5aa44edb49c6e8236d43cc. --- .../dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 32 ++++--------------- 2 files changed, 8 insertions(+), 26 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 5b6018205b22..b749da521daa 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -85,7 +85,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_ROPE_F32_ANGLE` | GPU | Boolean | `0` | Keep the RoPE angle in f32 under the f16 hint, for long prompts. Validated on one model. On CPU, `test-backend-ops -o ROPE` fails with it. | | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | -| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Single-stream attention KV on integrated GPUs prefers host USM with device USM as a fallback. Requires an OpenVINO build newer than 2026.4.1. | +| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | | `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended KV length to a window on the dynamic stateless GPU path. Set to `0` to use the unrounded attended length while keeping KV slicing enabled. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index c726a6a86999..e1dafa3b2346 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -67,8 +67,6 @@ // - CPU repack buffer: tensor->extra stores tensor_traits with repacked data // ===================================================== -static bool ov_device_shares_system_memory(const std::string & device); - namespace { // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { @@ -123,8 +121,7 @@ struct ggml_backend_openvino_buffer_context { ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } - ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false, - bool prefer_host_usm = false) : + ggml_backend_openvino_buffer_context(int device, size_t size, bool is_remote = false, bool lazy = false) : device(device), name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)), id(next_buffer_id()), @@ -141,18 +138,8 @@ struct ggml_backend_openvino_buffer_context { GGML_ASSERT(ggml_openvino_is_gpu()); auto remote_context = ggml_openvino_get_remote_context(device_name); auto gpu_context = remote_context->as(); - ov::intel_gpu::ocl::USMTensor usm_tensor; - if (prefer_host_usm) { - try { - usm_tensor = gpu_context.create_usm_host_tensor(ov::element::u8, ov::Shape{size}); - GGML_LOG_DEBUG("%s: allocated %zu bytes of USM host memory for attention KV\n", __func__, size); - } catch (const ov::Exception & e) { - GGML_LOG_DEBUG("%s: USM host KV allocation failed: %s\n", __func__, e.what()); - } - } - if (!usm_tensor) { - usm_tensor = gpu_context.create_usm_device_tensor(ov::element::u8, ov::Shape{size}); - } + ov::intel_gpu::ocl::USMTensor usm_tensor = + gpu_context.create_usm_device_tensor(ov::element::u8, ov::Shape{size}); data = usm_tensor.get(); ov_buffer = std::make_shared(std::move(usm_tensor)); } else { @@ -429,13 +416,12 @@ static bool ggml_openvino_swap_buffer_context(ggml_backend_buffer_t buffer, ggml_backend_openvino_buffer_context *& ctx, ggml_tensor * tensor, bool is_remote, - bool lazy, - bool prefer_host_usm = false) { + bool lazy) { const int device = ctx->device; const size_t size = ctx->size; const size_t offset = (char *) tensor->data - (char *) ctx->data; delete ctx; - ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy, prefer_host_usm); + ctx = new ggml_backend_openvino_buffer_context(device, size, is_remote, lazy); buffer->context = ctx; if (ctx->data == nullptr) { return false; @@ -453,20 +439,16 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu // buffer, so in host memory the plugin copies it to the device and back on every inference. const bool is_device_state = strncmp(tensor->name, "cache_", 6) == 0 || strcmp(tensor->name, "layer_inp_dev") == 0 || strcmp(tensor->name, "h_nextn_dev") == 0; - const bool is_kv_tensor = strncmp(tensor->name, "cache_k_l", 9) == 0 || strncmp(tensor->name, "cache_v_l", 9) == 0; if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) { GGML_ASSERT(ctx->tensor_extras.empty()); - // Large device USM allocations slowed attention reads on Arc B390. Host USM preserves remote KV bindings. - const bool prefer_host_usm = is_kv_tensor && tensor->ne[2] == 1 && tensor->ne[3] == 1 && !ggml_openvino_is_static() && - ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 && - ov_device_shares_system_memory(ggml_openvino_get_available_devices()[ctx->device]); - if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false, prefer_host_usm)) { + if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, true, false)) { return GGML_STATUS_ALLOC_FAILED; } } // On-demand NPU KV: swap the eagerly committed buffer for demand-zero memory at its first KV tensor // and register every KV tensor; the NPU binds grown L0 storage instead. + const bool is_kv_tensor = strncmp(tensor->name, "cache_k_l", 9) == 0 || strncmp(tensor->name, "cache_v_l", 9) == 0; if (is_kv_tensor && tensor->view_src == nullptr && !ctx->is_remote && ggml_openvino_npu_kv_on_demand_enabled() && tensor->ne[2] == 1 && tensor->ne[3] == 1 && tensor->nb[1] == ggml_row_size(tensor->type, tensor->ne[0])) { if (!ctx->kv_on_demand && ctx->tensor_extras.empty() && tensor->data == ctx->data) { From 7956c262e4aebcfe5fe8801c22047300f136fce3 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 12:12:13 +0100 Subject: [PATCH 17/21] ggml-openvino: key compiled replay graphs by declared control shapes Assisted-by: Codex --- ggml/src/ggml-openvino/utils.cpp | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 6e223f3665c2..c77550d3f0c6 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -371,9 +372,17 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph, for (const auto & [name, input] : decoder.get_model_extra_inputs()) { append_string(name); append_string(input.type.get_type_name()); - append(input.shape.size()); - for (auto dim : input.shape) { - append(dim); + // Replay control lengths change with the batch. The compiled graph uses the declared Parameter shape. + if (input.is_parameter && input.parameter_shape.rank().is_static() && input.parameter_shape.is_dynamic()) { + append(std::numeric_limits::max()); + append_string(input.parameter_shape.to_string()); + } else { + const auto shape = input.is_parameter && input.parameter_shape.is_static() ? + input.parameter_shape.to_shape() : input.shape; + append(shape.size()); + for (const auto dim : shape) { + append(dim); + } } append(input.is_parameter); if (!input.is_parameter) { From fed6548bb71e1d7128a76f4bb31786cd596fa0a8 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 05:26:19 +0100 Subject: [PATCH 18/21] ggml-openvino: represent replay writes with Assign sinks --- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 30 +++++-------- .../openvino/op/recurrent_replay_graph.hpp | 45 ++++++++++++++++++- .../openvino/recurrent_replay_fusion.h | 4 ++ .../openvino/translate_session.cpp | 17 ++++++- ggml/src/ggml-openvino/utils.cpp | 25 ++++++++++- ggml/src/ggml-openvino/utils.h | 1 + 6 files changed, 101 insertions(+), 21 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 7dfb742b141a..18a6aed6b0a7 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -1,39 +1,33 @@ # Current Qwen GPU implementation -The default Qwen3.5/Qwen3.6 path is dynamic stateless execution with `RecurrentConvCacheUpdate`, `RecurrentGatedDeltaNetUpdate`, and stable pure-top-k MTP translation. It supports one or multiple slots and rollback. The implementation applies to `qwen35` and `qwen35moe`; the reference model is the UD Qwen3.6-35B-A3B MTP GGUF. +The default Qwen3.5/Qwen3.6 MTP path uses pending-token replay, dynamic stateless execution, and stable pure-top-k sampling. When MTP discards a suffix, the next batch replays the retained tokens before processing new tokens. The implementation applies to `qwen35` and `qwen35moe` with one or multiple slots. The reference model is the UD Qwen3.6-35B-A3B MTP GGUF. -Build against the matching OpenVINO runtime/GPU plugin with single-output Update ops. Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The cache translation revision is 15. Historical measurements retain their original source revisions. - -The separate dynamic output-binding fix in OpenVINO PR #39354 remains required for cache-only MTP serving. Native cache-op export/import tests pass without it, but Qwen3.6 imported MTP graphs still trigger the missing-input-memory error without the fix. +Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requantization policy. The matching GPU plugin structurally fuses complete replay groups into its internal convolution and Gated Delta Net ops. Regenerate compiled blobs after switching to the writable-input replay interface. Historical measurements retain their original source revisions. ## Buffer ownership and operation boundaries | State | Storage and lifetime | Update path | |---|---|---| | Attention K/V | Full caller-owned USM allocation, sized by context and KV layout | Native stateless KV fusion when eligible; SDPA consumes the live prefix | -| Convolution `cache_r` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, convolution and ordered history/snapshot writes | -| GDN `cache_s` | Full caller-owned USM row bank, sized by slot/snapshot capacity | Fused reset, original-row gather/reorder, GDN and ordered final/snapshot writes | +| Convolution `cache_r` | Caller-owned USM row bank with history and pending columns | Fused reset, original-row gather/reorder, convolution and ordered history/pending writes | +| GDN `cache_s`, `cache_spk`, `cache_spv`, `cache_spgb` | Caller-owned USM row banks with committed state and pending token inputs | Fused reset, original-row gather/reorder, GDN and ordered state/pending writes | | Runtime controls | Reused USM host storage on GPU | Row maps, offsets and write controls remain runtime inputs | | Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps | | Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers | -Attention context capacity does not set recurrent-cache size. Each cache input Parameter binds a stable writable allocation; recurrent cache Results are omitted. There are no rotation banks or pointer swaps. +Recurrent-cache size depends on slot capacity and pending-token capacity. Each fused cache input Parameter binds a caller-owned writable allocation. llama.cpp represents writeback as standard `Assign` sinks. The GPU pass replaces matching sinks and their computation with one internal op, preserving the model's Results. The GPU plugin uses two stages: first preserve required original rows in scratch while applying logical reset and precision rounding; then compute and perform ordered writes. This avoids overwriting a source before another destination has read it. Identity reorder sources need no scratch writes. In-place execution removes the spare full output bank, not every cache read or internal memory transaction. -`RecurrentConvCacheUpdate` has nine inputs, including depthwise weights, and returns convolution `[1,B,T,C]`. `RecurrentGatedDeltaNetUpdate` returns attention and writes the newest `min(T,snapshot_count)` states into its cache input, newest first. Neither op returns a cache tensor. +`RecurrentConvCacheReplayUpdate` returns convolution `[1,B,T,C]` and writes history and pending columns. `RecurrentGatedDeltaNetReplayUpdate` returns attention and writes committed state and pending K, V, gate and beta. Both kernels write their cache inputs directly. ## Convolution cache stores -`build_conv_state_store` emits one CPY for the final history when rollback is disabled. With rollback enabled, it emits one SET_ROWS from overlapping `[history, window, channel, sequence]` views into strided snapshot planes. Window starts advance in time while destination planes descend, so plane zero holds the newest history. The fixed ARANGE/scale/cast chain supplies this descending slot order. - -The backend recognizes this structure and refreshes source starts, cache heads, sequence counts, window counts and plane strides on every batch. Native fusion passes runtime `[source column, destination slot]` pairs to the existing convolution op; the pair-count dimension is dynamic. Functional translation gathers the same windows, scatters them into the full cache, and preserves unwritten slots and features. The native op spec is unchanged. +The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution. A slice selects history and pending columns for the next batch, and ScatterNDUpdate produces the updated bank for the Assign sink. Row maps, replay counts and reset rows are runtime inputs. ## Generic fallback and restrictions -Writable cache inputs must be GPU RemoteTensors with exclusive graph readers, optionally through Reshape aliases. The GPU plugin rejects shared cache readers and computed cache banks. Other inputs and the computation output must not overlap the cache. The frontend skips fusion for unmatched cache reads and retains functional cache writeback. Restore or clear state after a failed inference before retrying. - -`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains ordinary cache decomposition. Naive graphs skip full-model recurrence fusion. Unmatched snapshot GDN uses ordinary GDN token prefixes to preserve state outputs. The fused path requires the matching native runtime; otherwise dynamic CPU and GPU execution uses ordinary GDN. Stateful and NPU MTP are outside this change. +Fusion requires direct writable GPU USM Parameters with exclusive bank readers. The GPU implementation checks that bank ranges do not overlap other inputs or the computation output. When the translated graph runs without a matching fusion, the Assign sinks retain the updated banks and llama.cpp copies their states into the GGML buffers after inference. Mixed-precision GPU execution of the unfused graph can round bank values. The GPU replay translator requires complete dynamic stateless groups. ## Attention KV layout @@ -45,18 +39,18 @@ Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). Live-prefix slicing applies The [graph walkthrough](MTP-SAMPLING-GRAPH.md) describes the fixed sampling interface. The backend keeps pure top-k branches for all configured slots, packs runtime row indices, and uses scratch for inactive outputs. It does not change the original cgraph or execute inactive stateful sampler chains. Only the small sampling branches stay at configured capacity; the expensive draft layer processes active rows. -One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare a compatible revision-15 cache once, then use cache-only mode. Exhaustive active-subset priming is no longer required, though first-use model import and runtime preparation still have a cost. +One compatible draft graph is shared across active subsets. Trunk and genuinely different graph stages/configurations remain separate. Prepare compatible blobs once, then use cache-only mode. The first import and runtime preparation still have a cost. ## Validation -Native OV tests cover shape/attribute serialization, reset, cycles, duplicates, overlapping writes, mixed precision, changing shapes, writable cache input rebinding, exclusive Reshapes, shared readers, host/device USM and export/import. Convolution is checked against a host reference; GDN uses an independent cache mapping around ordinary GDN. See `docs/dev/qwen35-llamacpp-recurrent-cache.md` and `recurrent_cache_update.cpp` in the OV checkout for contracts and tests. +Validation checks the caller's mutated convolution bank against the expected reset, reorder and history writes. The four-layer Qwen3.6 model exercises replay at one and four active sequences. ## Debugging and source map - `ggml-decoder.cpp`: dynamic dimensions, control inputs, output names and `cgraph_ov.txt` dump. - `utils.cpp`: compute-branch filtering, compiled reuse and input/output binding. -- `openvino/recurrent_cache_fusion.cpp`: structural pattern matching and native Update op translation. +- `openvino/recurrent_replay_fusion.cpp`: GGML group recognition and standard-op replay translation. - `openvino/translate_session.cpp`: runtime sampling aliases and model construction. -- OV `recurrent_cache_update` implementation: writable-input validation, source staging and GPU computation. +- OV `recurrent_replay_fusion.cpp` and `recurrent_cache_replay`: structural matching, writable-input validation, source staging and GPU computation. `GGML_OPENVINO_DUMP_CGRAPH=1` dumps the raw graph before filtering. It includes COMPUTE/OUTPUT flags and byte offsets and overwrites `cgraph_ov.txt` on each call. Enable dumps only for diagnosis; use the captured examples for a static view. GPU profiles and OpenCL copy traces add overhead, and lack of an explicit copy call does not prove zero traffic inside a kernel. diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp index 96086348d19a..8c5b166868bc 100644 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp @@ -4,8 +4,18 @@ #include "openvino/opsets/opset13.hpp" #include "openvino/core/model.hpp" +#include "openvino/core/visibility.hpp" #include #include +#include + +namespace ov { +// The runtime exports this transformation attribute even when its header is not installed. +#ifndef OPENVINO_STATIC_LIBRARY +OPENVINO_CORE_IMPORTS +#endif +void disable_conversion(const std::shared_ptr& node, const element::Type& to); +} namespace ov::recurrent_replay { namespace ops = ov::opset13; @@ -178,6 +188,39 @@ inline OutputVector gdn_body(const OutputVector& a) { } inline OutputVector build(const OutputVector& args, bool conv) { - return conv ? conv_body(args) : gdn_body(args); + auto outputs = conv ? conv_body(args) : gdn_body(args); + const auto bank_ports = conv ? std::vector{0} : std::vector{3, 6, 7, 8}; + for (const auto port : bank_ports) { + auto bank = args[port]; + while (ov::is_type(bank.get_node())) { + ov::disable_conversion(bank.get_node_shared_ptr(), element::f16); + bank = bank.get_node()->input_value(0); + } + ov::disable_conversion(bank.get_node_shared_ptr(), element::f16); + } + // Keep the functional replay state in FP32 under the GPU's mixed-precision + // policy. Stop at the replay inputs to preserve the upstream precision policy. + std::unordered_set visited; + for (const auto& arg : args) { + visited.insert(arg.get_node()); + } + auto pending = outputs; + while (!pending.empty()) { + const auto node = pending.back().get_node_shared_ptr(); + pending.pop_back(); + if (!visited.insert(node.get()).second) { + continue; + } + ov::disable_conversion(node, element::f16); + if (const auto loop = ov::as_type_ptr(node)) { + for (const auto& body_node : loop->get_function()->get_ordered_ops()) { + ov::disable_conversion(body_node, element::f16); + } + } + for (const auto& input : node->input_values()) { + pending.push_back(input); + } + } + return outputs; } } // namespace ov::recurrent_replay diff --git a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h index f9ed2bb6f40a..d02e9049c098 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h +++ b/ggml/src/ggml-openvino/openvino/recurrent_replay_fusion.h @@ -3,8 +3,12 @@ #include "node_context.h" #include +#include namespace ov::frontend::ggml { +// Assign variables with this prefix opt a caller-owned remote bank into writable-input fusion. +inline constexpr std::string_view replay_cache_state_prefix = "__ggml_replay_cache_"; + class RecurrentReplayFusion { public: RecurrentReplayFusion(const std::shared_ptr &, const std::shared_ptr &); diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index 8129b04a39dd..c23f3206288f 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -394,6 +395,8 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } ggml_model_decoder->visit_subgraph(node_visitor); + ov::SinkVector sinks; + const auto actual_decoder = std::dynamic_pointer_cast(ggml_model_decoder); for (const auto & updated : replay_fusion.updated_banks()) (*tensor_map)[updated.first] = updated.second; for (const auto & name : ggml_model_decoder->get_model_output_names()) { #ifdef GGML_OPENVINO_HAS_CACHE_UPDATE @@ -404,6 +407,18 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo #endif FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(), "Output name not found in tensor map: ", name); + if (const auto bank = replay_fusion.updated_banks().find(name); + bank != replay_fusion.updated_banks().end() && actual_decoder && + ggml_openvino_buffer_is_remote(actual_decoder->get_model_outputs().at(name))) { + const auto & update = bank->second; + // Let the Assign input determine the state type. GPU precision conversion can rewrite + // declared variable types even when the precision-sensitive input stays in FP32. + auto variable = std::make_shared(ov::op::util::VariableInfo{ + update.get_partial_shape(), element::dynamic, std::string(replay_cache_state_prefix) + name}); + auto assign = std::make_shared(update, variable); + sinks.push_back(assign); + continue; + } auto result = std::make_shared(tensor_map->at(name)); result->set_friendly_name(name); results.push_back(result); @@ -458,7 +473,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo // 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(results, used_params); + resulting_model = std::make_shared(results, sinks, used_params); apply_transformations(resulting_model); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index c77550d3f0c6..7f8a96198cf6 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -10,6 +10,7 @@ #include "model-cache.h" #include "openvino/frontend.h" #include "openvino/input_model.h" +#include "openvino/recurrent_replay_fusion.h" #include #include @@ -1496,8 +1497,12 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share uint64_t exact_fp = 0; std::string blob_path, manifest_path; if (!model_cache_dir.empty() && !model_is_splitted) { - const uint64_t extra_cfg = + uint64_t extra_cfg = ggml_openvino_model_cache_extra_cfg(r_ctx->stateful, stateful_recurrent); + if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) { + // The writable-input replay interface replaces bank Results with Assign sinks. + extra_cfg = extra_cfg * 131 + 1; + } model_fp = ggml_openvino_model_fingerprint(cgraph, device, /*fa=*/true, m_params.rope_params, 16, extra_cfg, dynamic_graph_signature(cgraph, *ggml_decoder, m_params)); @@ -1738,6 +1743,16 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share shared_model = compiled_model; } // end non-imported (compile) path + entry->replay_writebacks.clear(); + if (ggml_decoder->get_model_extra_inputs().count("rs_replay_rows")) { + constexpr auto prefix = ov::frontend::ggml::replay_cache_state_prefix; + for (auto state : infer_request->query_state()) { + const auto name = state.get_name(); + if (name.compare(0, prefix.size(), prefix) == 0) { + entry->replay_writebacks.emplace_back(name.substr(prefix.size()), std::move(state)); + } + } + } entry->ptr = ggml_decoder; if (!shared_key.empty() && shared_it == shared_cache->graphs.end()) { ov_compiled_graph graph; @@ -1913,6 +1928,14 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share } throw; } + for (const auto & [name, state] : entry->replay_writebacks) { + const auto bank = ggml_decoder->get_model_outputs().at(name); + const auto updated = state.get_state(); + OPENVINO_ASSERT(updated.get_element_type() == GgmlOvDecoder::get_ov_type(bank) && + updated.get_shape() == GgmlOvDecoder::get_shape(bank), + "Invalid replay cache writeback for ", name); + ggml_backend_tensor_set(bank, updated.data(), 0, ggml_nbytes(bank)); + } infer_end_time = ggml_time_us(); for (const auto & out : staged_outputs) { std::memcpy(out.dst, out.src, out.bytes); diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index c95e94de2def..62c3b59d3e9b 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -101,6 +101,7 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; + std::vector> replay_writebacks; // Attention sizes and output count the cached prefill model was built with; decode calls overwrite the // decoder's. int prefill_attention_size = -1; From b0fd84a153e6224dc7d128d17bf0e22dfe84f52f Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 06:09:21 +0100 Subject: [PATCH 19/21] ggml-openvino: document writable replay graph contract --- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 18 ++++++++++++++---- .../ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md | 4 ++-- .../openvino/op/recurrent_replay_graph.hpp | 2 ++ 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index 18a6aed6b0a7..f111e274bcf4 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -15,7 +15,7 @@ Configure `GGML_OPENVINO_DEVICE=GPU`, native softplus, and the documented requan | Protected source rows | Private device scratch | Staged before writes to protect cycles, duplicate sources and overlaps | | Inactive sampling results | Private device-USM scratch | Discarded without touching inactive GGML output buffers | -Recurrent-cache size depends on slot capacity and pending-token capacity. Each fused cache input Parameter binds a caller-owned writable allocation. llama.cpp represents writeback as standard `Assign` sinks. The GPU pass replaces matching sinks and their computation with one internal op, preserving the model's Results. +Recurrent-cache size depends on slot capacity and pending-token capacity. Each fused cache input Parameter binds a caller-owned writable allocation. The GPU plugin uses two stages: first preserve required original rows in scratch while applying logical reset and precision rounding; then compute and perform ordered writes. This avoids overwriting a source before another destination has read it. Identity reorder sources need no scratch writes. In-place execution removes the spare full output bank, not every cache read or internal memory transaction. @@ -25,15 +25,25 @@ The GPU plugin uses two stages: first preserve required original rows in scratch The structural replay graph gathers history using the retained-token count, concatenates live input, and uses one grouped convolution. A slice selects history and pending columns for the next batch, and ScatterNDUpdate produces the updated bank for the Assign sink. Row maps, replay counts and reset rows are runtime inputs. -## Generic fallback and restrictions +## Replay graph contract -Fusion requires direct writable GPU USM Parameters with exclusive bank readers. The GPU implementation checks that bank ranges do not overlap other inputs or the computation output. When the translated graph runs without a matching fusion, the Assign sinks retain the updated banks and llama.cpp copies their states into the GGML buffers after inference. Mixed-precision GPU execution of the unfused graph can round bank values. The GPU replay translator requires complete dynamic stateless groups. +The backend emits a standard-op graph for each complete dynamic stateless replay group. The computation feeds later layers and the updated banks feed standard `Assign` sinks. Fusion requires each bank to be a direct FP32 `Parameter` of shape `[1, 1, slots, features]` backed by caller-owned writable GPU USM. The backend opts each bank into in-place fusion by giving its sink the variable ID `__ggml_replay_cache_`. + +The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface. The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding, which avoids the GPU runtime changes that would be needed to alias a cache output to its input. + +The variable ID supplies the write permission. `RecurrentReplayFusion` still matches the computation, row controls, reset, reordering and writeback structure, and requires exclusive bank readers and a live computation output. The kernel checks for overlapping buffer ranges. When a sink remains, including on a GPU plugin without this pass, llama.cpp uses `query_state()` to find it and copies its state to the original GGML bank after inference. Mixed-precision execution of that graph can round bank values. + +The backend builds the graph in [`openvino/op/recurrent_replay_graph.hpp`](../openvino/op/recurrent_replay_graph.hpp). The GPU matcher in `src/plugins/intel_gpu/src/plugin/transformations/recurrent_replay_fusion.cpp` compares it to a reference built from the OpenVINO copy of `recurrent_replay_graph.hpp` in the same directory. When upstream modeling changes the GGML graph, adapt the backend recognition and check what it emits. If the emitted replay pattern or its semantics change, update the reference and the relevant matcher and kernel logic with the translation. Verify that the graph still fuses and that the standard-op writeback still works. ## Attention KV layout `GGML_OPENVINO_ENABLE_KV_4D=1` enables eligible native stateless in-place attention updates. The current eligibility covers one physical stream, including unified KV. Explicit split multi-slot KV retains the full-cache path and can be much slower even with only one active slot. Use `--kv-unified` for multi-slot OV GPU serving. -Leave `GGML_OPENVINO_KV_SLICE` at its default (`1`). Live-prefix slicing applies to eligible ordinary attention K/V roots, not recurrent caches. In-place KV fusion can bind the full allocation while exposing a live prefix internally. KV-slice on/off is a runtime binding choice and does not require different compiled blobs; incompatible graph layouts/capacities can still do so. +On dynamic CPU and GPU, `GGML_OPENVINO_KV_SLICE` is a binding switch and defaults to `1`. For an eligible contiguous ordinary attention K/V root with one active sequence at offset zero, it binds a view of the allocation sized to the attended prefix. Recurrent banks and sliding-window attention use the full binding. The 4-D in-place attention path binds the full allocation first and exposes the attended prefix inside the graph. Dynamic compiled blobs can accept either eligible binding. + +`GGML_OPENVINO_GPU_KV_ROUND_UP` controls the attended width separately on dynamic stateless GPU. With `0`, the decoder uses the GGML mask width, which ordinary GGML attention KV already pads in steps of 256 rows. The default `1` uses power-of-two windows when the graph input has more than 16 tokens and coarser aligned steps for smaller batches. The step starts at 256 rows and doubles whenever the width reaches eight times the current step. At 33,024 GGML rows, the added rounding can expand attention to 40,960 rows for decode or 65,536 for a larger prefill input, subject to the context cap. Added mask columns contain negative infinity. The current cache-only batched measurements used `GGML_OPENVINO_ENABLE_KV_4D=1`, the default `KV_SLICE` setting and `GGML_OPENVINO_GPU_KV_ROUND_UP=0`. + +On static NPU, `GGML_OPENVINO_KV_SLICE` also selects the base of the compiled KV windows. The default base is 1024 and an explicit multiple of 256 changes it. The window is the smallest `base * 2^k` that covers the attended length, capped by the context. ## Stable MTP sampling diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index b749da521daa..88d438a535da 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -50,7 +50,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 | 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, and replaced when that size changes; 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_KV_SLICE` | all | Integer | `1` | `0` disables slicing. Dynamic CPU and GPU use any valid positive value to bind eligible ordinary attention KV as a view of the attended prefix. The 4-D GPU binding takes precedence. Dynamic compiled blobs support both bindings. Static NPU uses `1` for a base of 1024 or a positive multiple of 256 for that base. Prefill and `GGML_OPENVINO_NPU_BLOB_PREBUILD` decode windows use the smallest `base * 2^k` that covers the attended length, capped by the context. With `0`, `llama-bench -d` fails on the NPU. Keep the same window setting when writing and reading static blobs. | +| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Controls the extra attended-width rounding on dynamic stateless GPU. With `1`, a graph input over 16 tokens uses the next power-of-two window and smaller batches use an aligned step that grows with the attended length. With `0`, the decoder uses the original GGML mask width. This setting is separate from prefix binding. | | `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. All windows are built, or read from the cache, together with the first prefill and decode pair (with the weightless bank the prefill graphs of every window are exported too). `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. | @@ -86,7 +87,6 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_NATIVE_SOFTPLUS` | all | Boolean | `0` | Translate `SOFTPLUS` to the OpenVINO `SoftPlus` op instead of the default `relu(x) + log(1 + exp(-abs(x)))`. | | `GGML_OPENVINO_KV_SCATTER_ELEMENTS` | all | Boolean | `0` | Use `ScatterElementsUpdate` instead of `ScatterUpdate` for single-row KV writes in stateless execution. | | `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | `0` | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]`, so the GPU plugin can update and read it in place. Needs an OpenVINO build newer than 2026.4.1; do not use it with 2026.4.1. | -| `GGML_OPENVINO_GPU_KV_ROUND_UP` | GPU | Boolean | `1` | Round the attended KV length to a window on the dynamic stateless GPU path. Set to `0` to use the unrounded attended length while keeping KV slicing enabled. | | `GGML_OPENVINO_MEMORY_OPTIMIZE` | all | Boolean | `0` | Turn on `GGML_OPENVINO_REDUCE_COMPILE_MEM` and, on GPU, `GGML_OPENVINO_RELEASE_WEIGHTS`, unless they are set. | | `GGML_OPENVINO_REDUCE_COMPILE_MEM` | all | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Create fewer weight nodes during compilation, to lower the host memory in use. | | `GGML_OPENVINO_RELEASE_WEIGHTS` | GPU | Boolean | value of `GGML_OPENVINO_MEMORY_OPTIMIZE` | Release the host weight buffers when the compiled model holds its own copy. Needs stable graph shapes; do not use it for workloads that compile again. | diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp index 8c5b166868bc..e4b6777c2056 100644 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp +++ b/ggml/src/ggml-openvino/openvino/op/recurrent_replay_graph.hpp @@ -18,6 +18,8 @@ void disable_conversion(const std::shared_ptr& node, const element::Type& } namespace ov::recurrent_replay { +// OpenVINO's GPU RecurrentReplayFusion checks this emitted graph against its +// reference replay graph. Keep the patterns in both repositories in sync. namespace ops = ov::opset13; using Value = ov::Output; From 7b5027740d68401c828c21f505c02bdbbc34262c Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 09:25:10 +0100 Subject: [PATCH 20/21] ggml-openvino: remove legacy native recurrent cache ops --- ggml/src/ggml-openvino/CMakeLists.txt | 17 - ggml/src/ggml-openvino/README.md | 19 +- .../dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-decoder.cpp | 55 --- .../openvino/op/gated_delta_net.cpp | 38 +-- .../openvino/op/recurrent_cache_update.hpp | 65 ---- ggml/src/ggml-openvino/openvino/op_table.h | 3 - .../openvino/recurrent_cache_fusion.cpp | 315 ------------------ .../openvino/recurrent_cache_fusion.h | 26 -- .../openvino/translate_session.cpp | 25 +- ggml/src/ggml-openvino/utils.cpp | 19 +- 11 files changed, 16 insertions(+), 568 deletions(-) delete mode 100644 ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp delete mode 100644 ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp delete mode 100644 ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index 3ed43b9fab27..347c24f4f526 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -31,20 +31,3 @@ if (GGML_OPENVINO) message(FATAL_ERROR "OpenVINO: OpenVINO toolkit supports x86-64 and arm64 but not ${CMAKE_SYSTEM_PROCESSOR}") endif() endif() - -# Released runtimes retain the ordinary cache translators. -include(CheckCXXSourceCompiles) -unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE) -set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) -set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino/op") -check_cxx_source_compiles("#include -int main() { - auto conv = std::make_shared(ov::OutputVector{}, 3); - auto gdn = std::make_shared(ov::OutputVector{}); -}" - GGML_OPENVINO_HAS_CACHE_UPDATE) -unset(CMAKE_REQUIRED_LIBRARIES) -unset(CMAKE_REQUIRED_INCLUDES) -if(GGML_OPENVINO_HAS_CACHE_UPDATE) - target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_CACHE_UPDATE=1) -endif() diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 497cf46df47c..5bdead151942 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -1,21 +1,10 @@ # Qwen MTP -The default Qwen3.5/Qwen3.6 GPU path is dynamic stateless execution with in-place fused recurrent ops and stable MTP sampling. Build against the matching OpenVINO runtime/GPU plugin with independent `RecurrentConvCacheUpdate` and `RecurrentGatedDeltaNetUpdate` ops. The native Update ops return computation results and update writable cache inputs in place, including rollback snapshots where required. No recurrent/sampling opt-in flag is needed on supported graphs. See the [development documentation index](dev_doc/README.md) for the implementation and the MTP sampling graph. +The OpenVINO backend translates Qwen recurrent replay for complete dynamic stateless GPU graphs and supports stable MTP sampling. See the [development documentation index](dev_doc/README.md) for the implementation and the MTP sampling graph. -Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. CPU snapshot execution, NPU execution, and forced static MTP are not supported. +Use `--spec-type draft-mtp --spec-draft-n-max 2` with a GGUF that contains MTP weights. Parallel execution uses `-np` and `--kv-unified`. OpenVINO replay requires dynamic stateless GPU execution. -Stateless recurrent execution uses the same reset, reorder, and partial cache-writeback paths at every slot capacity, including one slot without MTP. - -The matched stateless GPU path uses `RecurrentConvCacheUpdate` and -`RecurrentGatedDeltaNetUpdate`. Each cache is a writable Parameter backed by one -stable caller-owned USM allocation. The ops return only convolution or attention; -there are no recurrent cache Results. Required source rows are staged before -writes, preserving resets, cyclic reorders and rollback. Cache readers must be -exclusive, including Reshape aliases. -`GGML_OPENVINO_DISABLE_FUSED_RECURRENCE=1` retains the ordinary cache decomposition. -Unmatched snapshot GDN uses ordinary GDN token prefixes with functional writeback. -Build both repos against the matching single-output op spec. Translation revision -15 requires regenerating compiled-model blobs once without cache-only mode. +The backend emits standard OpenVINO ops and `Assign` sinks for replay cache writeback. A GPU plugin with recurrent replay fusion replaces each matched group with an internal op that writes directly to the caller-owned GPU cache. If an `Assign` sink remains, the backend copies its state back to the GGML cache after inference. See the [replay graph contract](dev_doc/OPENVINO-RECURRENT-CACHE.md#replay-graph-contract). Cache-only MTP serving still requires the separate OpenVINO dynamic output-binding fix (PR #39354). Removing recurrent cache Results does not eliminate that independent trigger in imported MTP graphs. @@ -31,7 +20,7 @@ The recommended Qwen3.6-35B-A3B Q4_K_M setup uses GPU with `GGML_OPENVINO_REQUAN `q4_asym64_all` converts Q4_K/Q5_K/Q6_K/Q8_0/Q5_1 weights, including dense Q8_0 projections, to asymmetric INT4 with group size 64. `token_embd.weight` and `output.weight` retain symmetric channel-wise INT8. Q8_0/Q5_1 rows whose width is not divisible by 64 also use channel-wise INT8. This follows the primary/backup precision scheme of NNCF `INT4_ASYM`, `ratio=1.0`, `group_size=64`, `backup_mode=INT8_SYM` for these supported source types; it requantizes GGUF values rather than the original floating-point model and leaves floating-point weights unchanged. Earlier versions kept dense Q8_0 at INT8/group-32. Repopulate compiled-model caches without cache-only mode after this change; the cache fingerprint invalidates the old precision policy. -See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and rollback. +See the [implementation guide](dev_doc/OPENVINO-RECURRENT-CACHE.md) for buffer ownership and replay. # Compiled model cache diff --git a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md index 88d438a535da..3daaf895b267 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -60,7 +60,7 @@ Each variable turns off an optimization that is on by default, or sets its stren | `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK` | CPU, GPU | Boolean | `0` | By default the model reads the sequence count and the attended KV length from the shape of the KQ mask, so the GPU plugin can select its fused attention kernel. `1` passes them as separate inputs. | | `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT` | CPU, GPU | Boolean | `0` | Stateful execution only. By default the sequence axis of the KV state is moved so that new tokens are appended in place. `1` keeps the original layout. | | `GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS` | GPU | Boolean | `0` | By default an output tensor in a GPU buffer is bound directly to the infer request when its shape and type match. `1` turns this off. | -| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | Stateless execution only, with an OpenVINO build newer than 2026.4.1 (2026.4.1 does not build the fusion). By default the recurrent-state cache updates (Qwen3.5, LFM2) are fused into the OpenVINO model. `1` keeps the separate copies. | +| `GGML_OPENVINO_DISABLE_FUSED_RECURRENCE` | GPU | Boolean | `0` | `1` disables the OpenVINO backend's recurrent replay translation, so replay ops require another eligible GGML backend. For an unfused OpenVINO replay graph, leave this at `0` and use a GPU plugin without the replay fusion pass. | | `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN` | GPU | Boolean | `0` | By default the operands of an element-wise op get the same rank, which works around a GPU plugin defect when the op is fused into RMS norm (gemma-4 in stateful execution gave wrong output). `1` turns the workaround off. | ```bash diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 2008ac56a52e..ad3a7ed60cc7 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1821,61 +1821,6 @@ void GgmlOvDecoder::add_extra_inputs() { } } m_compute_params.recurrent_controls.clear(); -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - // Naive graphs have no full-model cache fusion and node cases are not initialized here. - if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && - !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { - for (int i = 0; i < m_cgraph->n_nodes; ++i) { - const auto node = m_cgraph->nodes[i]; - const auto op_case = m_node_info_list[i].node_op_case; - if (node->op == GGML_OP_CPY && (op_case == 10 || op_case == 12)) { - m_model_extra_inputs["rs_update_" + get_tensor_ov_name(m_cgraph, node)] = - {ov::element::i64, ov::Shape{1, 1, 1, 4}, 0, true, {}, -1}; - } - } - for (const auto & [name, write] : m_compute_params.rs_writebacks) { - if (write.src_begin >= 0) { - auto & values = m_compute_params.recurrent_controls["rs_offsets_" + name]; - values = {write.slot_begin, write.src_begin}; - m_model_extra_inputs["rs_offsets_" + name] = - {ov::element::i64, ov::Shape{1, 1, 1, 2}, 0, true, {}, -1}; - } - } - for (int i = 0; i < m_cgraph->n_nodes; ++i) { - const auto concat = m_cgraph->nodes[i]; - if (concat->op != GGML_OP_CONCAT || !concat->src[0] || concat->src[0]->op != GGML_OP_RESHAPE || - !concat->src[0]->src[0] || concat->src[0]->src[0]->op != GGML_OP_VIEW || - concat->src[0]->src[0]->src[0]->op != GGML_OP_GET_ROWS) { - continue; - } - std::vector values; - for (int j = i + 1; j < m_cgraph->n_nodes; ++j) { - const auto write = m_cgraph->nodes[j]; - if ((is_conv_state_writeback(write) || is_conv_state_snapshot_writeback(write)) && - write->src[0]->src[0] == concat) { - const auto it = m_compute_params.rs_writebacks.find(get_tensor_ov_name(m_cgraph, write)); - if (it == m_compute_params.rs_writebacks.end()) { - values.clear(); - break; - } - const auto & wb = it->second; - const int64_t count = wb.window_count >= 0 ? wb.window_count : 1; - for (int64_t w = 0; w < count; ++w) { - values.push_back(wb.src_begin + w); - values.push_back(wb.slot_begin + (count - 1 - w) * - (wb.window_count >= 0 ? wb.snapshot_stride : 0)); - } - break; - } - } - if (!values.empty()) { - const auto name = "rs_windows_" + get_tensor_ov_name(m_cgraph, concat); - m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1, 1, values.size() / 2, 2}, 0, true, {}, -1}; - m_compute_params.recurrent_controls[name] = std::move(values); - } - } - } -#endif if (!m_naive && !m_is_static && !m_is_stateful && !m_model_is_splitted && ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { for (int i = 0; i < m_cgraph->n_nodes; ++i) { diff --git a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp index 53625f5ab3f5..1666861af078 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -4,9 +4,6 @@ #include "recurrent_replay_graph.hpp" #include "../op_table.h" #include "../utils.h" -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -#include "recurrent_cache_update.hpp" -#endif #include "ggml-openvino/ggml-openvino-extra.h" #include @@ -404,7 +401,9 @@ static OutputVector translate_gdn_snapshots(const Output & q, return {attention, states}; } -static OutputVector translate_gdn(const NodeContext & context, const OutputVector * cache_inputs) { +OutputVector translate_gated_delta_net(const NodeContext & context) { + FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[1] == 0, + "GATED_DELTA_NET replay requires a complete recurrent cache group"); auto v_shape = context.get_input_shape(2).to_shape(); // [B, T, H_v, S_v] auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k] @@ -413,7 +412,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto const bool kda = context.get_input_shape(3)[3] != 1; if (kda && !gdn_per_key_gate_supported()) { // the reference loop reads and writes the state in the ggml layout, one state per call - FRONT_END_OP_CONVERSION_CHECK(!cache_inputs && context.get_output_op_params()[0] == 1 && + FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[0] == 1 && !ggml_openvino_gdn_native_state_enabled(), "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 " "gate for recurrent caches, state snapshots or the native state layout"); @@ -481,7 +480,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // resets and slot copies move whole states, and supports_op aborts instead of falling back to CPU. const bool native_state = ggml_openvino_gdn_native_state_enabled(); auto state_perm = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, 1, 3, 2}); - if (!native_state && !cache_inputs && snapshot_count == 1) { + if (!native_state && snapshot_count == 1) { state = std::make_shared(state, state_perm); } @@ -520,22 +519,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto // << ", 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}; - args.insert(args.end(), cache_inputs->begin() + 1, cache_inputs->end()); - auto fused = std::make_shared( - args, fuse_qk_l2norm, q_eps, k_eps, snapshot_count); - fused->set_friendly_name(context.get_name() + "/RecurrentGatedDeltaNetUpdate"); - // The matched state VIEW is consumed only by the overridden full-cache - // writeback. Route that cache directly instead of materializing snapshots. - if (context.get_output_names().size() == 3) { - return {fused->output(0), fused->output(0), (*cache_inputs)[0]}; - } - return {fused->output(0), (*cache_inputs)[0]}; - } -#endif - Output attn_4d, states; if (snapshot_count > 1) { auto outputs = translate_gdn_snapshots(q, k, v, state, g, beta, H_v * S_v * q_shape[3], @@ -576,17 +559,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto return rename_outputs_with_suffix({res}, context.get_name()); } -OutputVector translate_gated_delta_net(const NodeContext & context) { - FRONT_END_OP_CONVERSION_CHECK(context.get_output_op_params()[1] == 0, "Replay requires a complete cache-bank fusion; functional replay translation is not implemented yet"); - return translate_gdn(context, nullptr); -} - -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs) { - return translate_gdn(context, &cache_inputs); -} -#endif - OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks) { auto q = context.get_input(0), k = context.get_input(1); const auto shape = context.get_input_shape(2); diff --git a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp b/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp deleted file mode 100644 index a4daf8c86b63..000000000000 --- a/ggml/src/ggml-openvino/openvino/op/recurrent_cache_update.hpp +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) 2026 Intel Corporation -// SPDX-License-Identifier: Apache-2.0 -#pragma once -#include "openvino/op/op.hpp" - -namespace ov::op::internal { -/// Qwen3.5/Qwen3.6 llama.cpp convolution and generic cache_r maintenance. -/// Inputs: original cache, active rows, extra rows, reset begin/length, -/// extra offsets, QKV [1,B,C,T], windows and depthwise weights. -/// Nine inputs; output 0 is convolution [1,B,T,C]. -/// Cache input 0 is a writable GPU RemoteTensor, updated in place. -/// Other inputs and output 0 must not overlap its allocation. -/// The cache must be a Parameter or an exclusive Reshape alias; no other op -/// may read it in the same inference. Required original rows are staged before -/// reset, reorder and window writes, preserving cycles and duplicate sources. -/// A failed inference may partially modify the cache; clear or restore it before retrying. -class OPENVINO_API RecurrentConvCacheUpdate : public Op { -public: - OPENVINO_OP("RecurrentConvCacheUpdate", "internal") - RecurrentConvCacheUpdate() = default; - RecurrentConvCacheUpdate(const OutputVector & args, int64_t history); - void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor &) override; - std::shared_ptr clone_with_new_inputs(const OutputVector &) const override; - - int64_t get_history() const { return m_history; } - -private: - int64_t m_history = 0; -}; - -/// Qwen3.5/Qwen3.6 llama.cpp GDN and generic cache_s maintenance. -/// Twelve inputs: Q/K/V, cache, gate/beta, -/// active/extra rows, reset begin/length, extra offsets, ordered write control. -/// The only output is attention [B,T,H,V]. Cache input 3 is updated in place -/// under the same writable-input contract as RecurrentConvCacheUpdate. -/// snapshot_count saves the newest min(T,count) states in cache, newest first. -/// Active/nonidentity rows are staged before writes; identity rows need no copy. -class OPENVINO_API RecurrentGatedDeltaNetUpdate : public Op { -public: - OPENVINO_OP("RecurrentGatedDeltaNetUpdate", "internal") - RecurrentGatedDeltaNetUpdate() = default; - RecurrentGatedDeltaNetUpdate(const OutputVector & args, - bool fuse_qk_l2norm = false, - float q_l2_norm_eps = 1e-6f, - float k_l2_norm_eps = 1e-6f, - int64_t snapshot_count = 1); - void validate_and_infer_types() override; - bool visit_attributes(AttributeVisitor &) override; - std::shared_ptr clone_with_new_inputs(const OutputVector &) const override; - - bool get_fuse_qk_l2norm() const { return m_fuse_qk_l2norm; } - - float get_q_l2_norm_eps() const { return m_q_l2_norm_eps; } - - float get_k_l2_norm_eps() const { return m_k_l2_norm_eps; } - - int64_t get_snapshot_count() const { return m_snapshot_count; } - -private: - bool m_fuse_qk_l2norm = false; - float m_q_l2_norm_eps = 1e-6f, m_k_l2_norm_eps = 1e-6f; - int64_t m_snapshot_count = 1; -}; -} // namespace ov::op::internal diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index aed1ff7a895f..b26a23373232 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -54,9 +54,6 @@ GGML_OP_CONVERTER(translate_ssm_scan); GGML_OP_CONVERTER(translate_gated_delta_net); // The device runs GatedDeltaNet with a gate per key dimension; otherwise the translator falls back to its reference loop bool gdn_per_key_gate_supported(); -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, const OutputVector & cache_inputs); -#endif OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks); GGML_OP_CONVERTER(translate_repeat); GGML_OP_CONVERTER(translate_cumsum); diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp deleted file mode 100644 index 160a7337fafa..000000000000 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ /dev/null @@ -1,315 +0,0 @@ -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -# include "recurrent_cache_fusion.h" - -# include "../ggml-openvino-extra.h" -# include "ggml-impl.h" -# include "op_table.h" -# ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -# include "op/recurrent_cache_update.hpp" -# endif -# include "utils.h" - -# include -# include -# include -# include -# include -# include - -namespace ov::frontend::ggml { -RecurrentCacheFusion::RecurrentCacheFusion(const std::shared_ptr & decoder, - const std::shared_ptr & tensors) : - m_decoder(decoder), - m_tensors(tensors) { - if (!ggml_openvino_is_gpu() || decoder->is_static() || decoder->is_stateful() || decoder->is_splited_model() || - ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE")) { - return; - } - auto actual = std::dynamic_pointer_cast(decoder); - if (!actual || actual->m_naive || !tensors->count("cache_rs_reset_idx") || !tensors->count("cache_rs_reset_len") || - !tensors->count("s_copy_active_slot_len")) { - return; - } - const auto graph = actual->get_cgraph(); - std::map indices; - for (int i = 0; i < graph->n_nodes; ++i) { - indices[graph->nodes[i]] = i; - } - for (int i = 0; i < graph->n_nodes; ++i) { - const auto cp = graph->nodes[i]; - if (cp->op != GGML_OP_CPY || decoder->get_op_case(i) != 3 || !cp->src[0] || cp->src[0]->op != GGML_OP_VIEW || - !cp->src[0]->src[0] || cp->src[0]->src[0]->op != GGML_OP_GET_ROWS) { - continue; - } - const auto gather = cp->src[0]->src[0]; - const auto root = cp->view_src; - if (!root || (root->type != GGML_TYPE_F32 && root->type != GGML_TYPE_F16) || root->ne[2] != 1 || - root->ne[3] != 1 || gather->src[0]->op != GGML_OP_RESHAPE || gather->src[0]->src[0] != root || - gather->src[1]->op != GGML_OP_NONE || gather->src[1]->type != GGML_TYPE_I32) { - continue; - } - Group group; - group.gather = indices.at(gather); - group.remainder = i; - for (int j = 0; j < group.gather; ++j) { - const auto node = graph->nodes[j]; - if (GgmlOvDecoder::is_recurrent_cache_reset(node) && - node->view_src == root && decoder->get_op_case(j) == 1) { - // SCALE stores (scale, bias); FILL stores its value first and leaves the second parameter 0. - float scale, bias; - memcpy(&scale, node->op_params, sizeof(float)); - memcpy(&bias, node->op_params + 1, sizeof(float)); - if (scale == 0 && bias == 0) { - group.reset = j; - } - } - } - if (group.reset < 0) { - continue; - } - // build_conv_state_store emits one CPY without rollback or one SET_ROWS with rollback. - for (int j = i + 1; j < graph->n_nodes; ++j) { - const auto node = graph->nodes[j]; - if (node->op != GGML_OP_CONCAT || node->op_params[0] != 0 || !node->src[0] || - node->src[0]->op != GGML_OP_RESHAPE) { - continue; - } - const auto active = node->src[0]->src[0]; - if (active && active->op == GGML_OP_VIEW && active->src[0] == gather && active->view_offs == 0 && - node->src[0]->ne[3] == 1 && node->src[0]->ne[0] * node->src[0]->ne[1] == root->ne[0]) { - group.concat = j; - for (int k = j + 1; k < graph->n_nodes; ++k) { - const auto write = graph->nodes[k]; - const bool copy = GgmlOvDecoder::is_conv_state_writeback(write); - const bool slots = GgmlOvDecoder::is_conv_state_snapshot_writeback(write); - if ((copy || slots) && write->view_src == root && write->src[0]->src[0] == node && - write->src[0]->ne[0] == node->src[0]->ne[0] && - write->src[0]->ne[slots ? 2 : 1] == node->src[0]->ne[1] && - (slots ? write->src[2] : write->src[1])->view_offs % root->nb[1] == 0) { - if (group.writeback >= 0) { - group.writeback = -1; - break; - } - group.writeback = k; - } - } - break; - } - } - if (group.concat >= 0) { - if (group.writeback < 0) { - continue; - } - for (int j = group.concat + 1; j < graph->n_nodes; ++j) { - const auto node = graph->nodes[j]; - if (node->op == GGML_OP_SSM_CONV && node->src[0] == graph->nodes[group.concat] && node->src[1] && - node->src[1]->op == GGML_OP_NONE && - node->src[1]->ne[0] == graph->nodes[group.concat]->src[0]->ne[0] + 1 && - node->src[1]->ne[1] == graph->nodes[group.concat]->src[0]->ne[1] && node->src[1]->ne[2] == 1 && - node->src[1]->ne[3] == 1) { - if (group.compute >= 0) { - group.compute = -1; - break; - } - group.compute = j; - } - } - } else { - for (int j = i + 1; j < graph->n_nodes; ++j) { - const auto node = graph->nodes[j]; - if (node->op != GGML_OP_GATED_DELTA_NET || node->op_params[1] != 0 || !node->src[5] || node->src[5]->op != GGML_OP_RESHAPE) { - continue; - } - const auto active = node->src[5]->src[0]; - if (!active || active->op != GGML_OP_VIEW || active->src[0] != gather || active->view_offs != 0 || - node->src[5]->ne[0] * node->src[5]->ne[1] * node->src[5]->ne[2] != root->ne[0] || - decoder->get_output_names(j).size() < 2) { - continue; - } - group.compute = j; - for (int k = j + 1; k < graph->n_nodes; ++k) { - const auto write = graph->nodes[k]; - if (write->op == GGML_OP_CPY && write->view_src == root && write->src[0] && - write->src[0]->op == GGML_OP_VIEW && write->src[0]->src[0] == node && - (decoder->get_op_case(k) == 10 || decoder->get_op_case(k) == 12)) { - if (group.writeback >= 0) { - group.writeback = -1; - break; - } - group.writeback = k; - } - } - break; - } - if (group.writeback < 0 || !tensors->count("rs_update_" + decoder->get_op_name(group.writeback))) { - continue; - } - } - if (group.compute < 0) { - continue; - } - bool complete = tensors->count("rs_slot_begin_" + decoder->get_op_name(i)) && - tensors->count("rs_src_begin_" + decoder->get_op_name(i)); - if (group.concat >= 0) { - complete &= tensors->count("rs_windows_" + decoder->get_op_name(group.concat)); - const auto & name = decoder->get_op_name(group.writeback); - complete &= tensors->count("rs_slot_begin_" + name) && tensors->count("rs_src_begin_" + name); - } - for (int j = 0; j < graph->n_nodes && complete; ++j) { - const auto node = graph->nodes[j]; - // Other cache readers or writers require functional translation. - for (int source = 0; source < GGML_MAX_SRC; ++source) { - const auto input = node->src[source]; - if (!input || (input != root && input->view_src != root)) { - continue; - } - const bool alias = node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE; - const bool matched_read = j == group.gather || j == group.reset; - const bool destination = (node->op == GGML_OP_CPY && source == 1) || - (GgmlOvDecoder::is_conv_state_snapshot_writeback(node) && source == 2); - if (!alias && !matched_read && !destination) { - complete = false; - } - } - if (node->view_src == root && - (node->op == GGML_OP_SCALE || node->op == GGML_OP_CPY || node->op == GGML_OP_SET_ROWS) && - j != group.reset && j != group.remainder && j != group.writeback) { - complete = false; - } - } - // Every read of the gathered state or convolution input must belong to - // this recurrence. Shared readers retain the ordinary GGML translation. - const auto compute = graph->nodes[group.compute]; - const auto active = group.concat >= 0 ? graph->nodes[group.concat]->src[0]->src[0] : compute->src[5]->src[0]; - const auto reshaped = group.concat >= 0 ? graph->nodes[group.concat]->src[0] : compute->src[5]; - for (int j = group.gather + 1; j < graph->n_nodes && complete; ++j) { - const auto node = graph->nodes[j]; - for (int source = 0; source < GGML_MAX_SRC; ++source) { - const auto input = node->src[source]; - if (!input) { - continue; - } - if (input == gather && node != active && node != graph->nodes[group.remainder]->src[0]) { - complete = false; - } - if (input == active && node != reshaped) { - complete = false; - } - if (input == reshaped && node != (group.concat >= 0 ? graph->nodes[group.concat] : compute)) { - complete = false; - } - if (group.concat >= 0 && input == graph->nodes[group.concat] && node != compute) { - complete &= node == graph->nodes[group.writeback]->src[0]; - } - if (input == compute && group.concat < 0 && node->op != GGML_OP_VIEW) { - complete = false; - } - if (group.concat < 0 && input == graph->nodes[group.writeback]->src[0] && - node != graph->nodes[group.writeback]) { - complete = false; - } - } - } - if (!complete) { - continue; - } - group.root_name = GgmlOvDecoder::get_tensor_name(graph, root); - const auto id = m_groups.size(); - for (int n : {group.reset, group.gather, group.remainder}) { - m_nodes[n] = id; - } - if (group.concat >= 0) { - m_nodes[group.concat] = id; - } - m_nodes[group.compute] = id; - if (group.writeback >= 0) { - m_nodes[group.writeback] = id; - } - m_groups.push_back(std::move(group)); - } -} - -OutputVector RecurrentCacheFusion::translate(int index, const NodeContext & context) { - const auto it = m_nodes.find(index); - if (it == m_nodes.end()) { - return {}; - } - auto & group = m_groups[it->second]; - using namespace ov::op; - auto constant = [](std::initializer_list shape, std::initializer_list values) { - return v0::Constant::create(element::i64, Shape(shape), std::vector(values)); - }; - auto metadata = [&](const std::string & name) -> Output { - return std::make_shared(context.get_input(name), constant({4}, {1, 1, 1, 1}), false); - }; - if (index == group.reset) { - group.old_cache = context.get_input(0); - auto root = group.old_cache.get_node_shared_ptr(); - while (ov::is_type(root)) { - root = root->input_value(0).get_node_shared_ptr(); - } - group.enabled = ov::is_type(root); - if (!group.enabled) { - return {}; - } - return {group.old_cache}; - } - if (!group.enabled) { - return {}; - } - NodeContext gather_context(m_decoder, m_tensors, group.gather); - auto rows = process_view_input_new(gather_context, 1); - const auto remainder_name = m_decoder->get_op_name(group.remainder); - auto offsets = std::make_shared(OutputVector{context.get_input("rs_slot_begin_" + remainder_name), - context.get_input("rs_src_begin_" + remainder_name)}, - 0); - OutputVector inputs{group.old_cache, - rows, - rows, - metadata("cache_rs_reset_idx"), - metadata("cache_rs_reset_len"), - context.has_input("rs_offsets_" + remainder_name) ? - context.get_input("rs_offsets_" + remainder_name) : - std::make_shared(offsets, constant({4}, {1, 1, 1, 2}), false)}; - inputs[1] = context.has_input("rs_active_rows") ? - context.get_input("rs_active_rows") : - std::make_shared(rows, constant({1}, {0}), context.get_input("s_copy_active_slot_len"), - constant({1}, {1}), constant({1}, {3})); - if (index == group.gather) { - // Ordinary nodes keep intermediate translation shapes valid. They become - // unreachable once the complete recurrence is replaced by its fused op. - return op::translate_get_rows(context); - } - if (index == group.remainder) { - return {group.old_cache}; - } - if (index == group.concat) { - inputs.push_back(process_view_input_new(context, 1)); - // Runtime pairs [source column, destination slot] cover the current CPY or SET_ROWS store. - inputs.push_back(context.get_input("rs_windows_" + context.get_name())); - const auto history = context.get_input_shape(0)[3].get_length(); - NodeContext compute_context(m_decoder, m_tensors, group.compute); - const auto channels = context.get_input_shape(0)[2].get_length(); - inputs.push_back(std::make_shared(compute_context.get_input(1), - constant({4}, {1, 1, channels, history + 1}), false)); - auto fused = std::make_shared(inputs, history); - fused->set_friendly_name(compute_context.get_name() + "/RecurrentConvCacheUpdate"); - group.conv = fused->output(0); - return op::translate_concat(context); - } - if (index == group.compute) { - if (group.concat >= 0) { - return {group.conv}; - } - inputs.push_back(context.get_input("rs_update_" + m_decoder->get_op_name(group.writeback))); - return op::translate_recurrent_gated_delta_net(context, inputs); - } - return {group.old_cache}; -} - -bool RecurrentCacheFusion::is_inplace_output(const std::string & name) const { - return std::any_of(m_groups.begin(), m_groups.end(), - [&](const Group & group) { return group.enabled && group.root_name == name; }); -} -} // namespace ov::frontend::ggml -#endif diff --git a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h deleted file mode 100644 index 1d9d494acd8b..000000000000 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include "../ggml-decoder.h" -#include "node_context.h" - -namespace ov::frontend::ggml { -// Match complete build_rs groups before replacing reset/reorder. Unmatched graphs retain -// their ordinary translators, including CPU, static and released-runtime execution. -class RecurrentCacheFusion { -public: - RecurrentCacheFusion(const std::shared_ptr & decoder, const std::shared_ptr & tensors); - OutputVector translate(int index, const NodeContext & context); - bool is_inplace_output(const std::string & name) const; -private: - struct Group { - int reset = -1, gather = -1, remainder = -1, concat = -1, compute = -1, writeback = -1; - std::string root_name; - bool enabled = false; - Output old_cache, conv; - }; - - std::shared_ptr m_decoder; - std::shared_ptr m_tensors; - std::vector m_groups; - std::map m_nodes; -}; -} // namespace ov::frontend::ggml diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp index c23f3206288f..bb9fe2b94f64 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -6,9 +6,6 @@ #include "ggml-openvino/openvino/utils.h" #include "input_model.h" #include "recurrent_replay_fusion.h" -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -#include "recurrent_cache_fusion.h" -#endif #include "pass/mark_decompression_convert_constant_folding.h" #include "pass/mark_dequantization_subgraph.h" #include "pass_registry/pipeline.h" @@ -77,11 +74,8 @@ std::shared_ptr create_parameter(const std::string & name std::shared_ptr create_extra_input(const std::string & name, const ModelExtraInputInfo & input_info) { if (input_info.is_parameter) { - ov::PartialShape shape = input_info.parameter_shape.rank().is_static() ? input_info.parameter_shape : ov::PartialShape(input_info.shape); - // One SET_ROWS emits min(tokens, snapshot capacity) windows on each batch. - if (name.compare(0, 11, "rs_windows_") == 0) { - shape[2] = ov::Dimension::dynamic(); - } + const auto shape = input_info.parameter_shape.rank().is_static() ? input_info.parameter_shape : + ov::PartialShape(input_info.shape); auto param_node = std::make_shared(input_info.type, shape); param_node->set_friendly_name(name); param_node->output(0).get_tensor().set_names({name}); @@ -305,9 +299,6 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } } -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - RecurrentCacheFusion recurrent_fusion(ggml_model_decoder, tensor_map); -#endif RecurrentReplayFusion replay_fusion(ggml_model_decoder, tensor_map); auto translate_node = [&](const std::shared_ptr & decoder, int node_idx) { auto operation_type = decoder->get_op_type(node_idx); @@ -329,11 +320,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo 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); - ov::OutputVector converted_outputs; -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - converted_outputs = recurrent_fusion.translate(node_idx, node_context); -#endif - if (converted_outputs.empty()) converted_outputs = replay_fusion.translate(node_idx, node_context); + auto converted_outputs = replay_fusion.translate(node_idx, node_context); if (converted_outputs.empty()) { converted_outputs = it->second(node_context); } @@ -399,12 +386,6 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo const auto actual_decoder = std::dynamic_pointer_cast(ggml_model_decoder); for (const auto & updated : replay_fusion.updated_banks()) (*tensor_map)[updated.first] = updated.second; for (const auto & name : ggml_model_decoder->get_model_output_names()) { -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - if (recurrent_fusion.is_inplace_output(name)) { - // The fused kernel updates the bound cache input; no cache Result is needed. - continue; - } -#endif FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(), "Output name not found in tensor map: ", name); if (const auto bank = replay_fusion.updated_banks().find(name); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 7f8a96198cf6..047221c384d7 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -221,12 +221,8 @@ static size_t get_static_attention_size(const std::shared_ptr & g static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) { const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled(); - uint64_t extra_cfg = 18; // Convolution replay uses a shared graph and a dynamic history slice. -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE - extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_FUSED_RECURRENCE") ? 0u : 1u); -#else - extra_cfg = extra_cfg * 131; -#endif + // Preserve the fingerprint for graphs compiled without the old native cache update ops. + uint64_t extra_cfg = 18 * 131; extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u); extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_KV_4D") > 0 ? 1u : 0u); @@ -775,19 +771,10 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) { *data++ = row.second; } - } else if (param_name.compare(0, 11, "rs_offsets_") == 0 || param_name.compare(0, 11, "rs_windows_") == 0 || param_name.compare(0, 10, "rs_replay_") == 0) { + } else if (param_name.compare(0, 10, "rs_replay_") == 0) { const auto & controls = ggml_decoder->get_compute_params(); const auto & values = controls.recurrent_controls.at(param_name); std::copy(values.begin(), values.end(), input_tensor.data()); - } else if (param_name.compare(0, 10, "rs_update_") == 0) { - const auto & controls = ggml_decoder->get_compute_params(); - const auto & write = controls.rs_writebacks.at(param_name.substr(10)); - auto data = input_tensor.data(); - data[0] = write.slot_begin; - data[1] = write.seq_count >= 0 ? write.seq_count : controls.s_copy_active_slot_len; - data[2] = write.snapshot_stride >= 0 ? write.snapshot_stride : data[1]; - // Direct GDN states contain no attention prefix. - data[3] = 0; } else { if (extra_input->second.type == ov::element::i64) { *input_tensor.data() = extra_input->second.value; From 690606b7591a91264cd777acc7fc82fd917559a0 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 27 Nov 2026 08:46:53 +0100 Subject: [PATCH 21/21] ggml-openvino: document replay graph selection during prefill --- ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md index f111e274bcf4..9b04962f38f6 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -27,6 +27,10 @@ The structural replay graph gathers history using the retained-token count, conc ## Replay graph contract +Qwen selects the recurrent graph when the target context is created. `n_rs_seq=0` selects the ordinary graph. With `--spec-type draft-mtp` and a positive draft limit, `n_rs_seq` is the draft limit and `rs_replay` selects the replay graph even for a fresh prefill. Both forms use `GGML_OP_GATED_DELTA_NET`. The replay form sets `op_params[1]` to the pending-token capacity and adds inputs for pending K, V, gate/beta, and the per-sequence replay count. + +A fresh prompt supplies a replay count of zero. Prefill microbatches longer than `n_rs_seq + 1` tokens per sequence commit their final state. The unfused OpenVINO graph processes current tokens in a `Loop` and uses a bounded unrolled recurrence for the retained prefix. + The backend emits a standard-op graph for each complete dynamic stateless replay group. The computation feeds later layers and the updated banks feed standard `Assign` sinks. Fusion requires each bank to be a direct FP32 `Parameter` of shape `[1, 1, slots, features]` backed by caller-owned writable GPU USM. The backend opts each bank into in-place fusion by giving its sink the variable ID `__ggml_replay_cache_`. The GPU plugin requires the transformed model to preserve its `Result` count. Sinks express writeback separately from that output interface. The pass can replace the computation and remove its matched sinks and variables while keeping the Results. The internal op then writes through the original input binding, which avoids the GPU runtime changes that would be needed to alias a cache output to its input.