Commit 244640b7f for llama.cpp
commit 244640b7f26e2a7301b27a24edc4f7feaf97d52f
Author: Ravi Panchumarthy <ravi.panchumarthy@intel.com>
Date: Wed Nov 25 07:53:56 2026 -0800
ggml-openvino: fix CI op tests and improve KV cache decode (#33002)
* 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-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.
* 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-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-openvino : keep the head axis of the 4-D KV cache static
* 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.
---------
Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index a9fac74b1..13272f298 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -1411,12 +1411,12 @@ std::pair<ModelParams, ComputeParams> 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};
@@ -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 &&
@@ -1976,9 +1979,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) {
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
index 7e6711dd8..0e99ff194 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 ca3227a41..61d2a2f88 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();
diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h
index 948405745..faa019681 100644
--- a/ggml/src/ggml-openvino/openvino/node_context.h
+++ b/ggml/src/ggml-openvino/openvino/node_context.h
@@ -107,6 +107,8 @@ public:
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<size_t> 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 8f0689510..acdf50d3c 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 <cstdint>
#include <openvino/op/broadcast.hpp>
+#include <openvino/op/concat.hpp>
#include <openvino/op/constant.hpp>
+#include <openvino/op/reshape.hpp>
#include <openvino/op/shape_of.hpp>
+#include <openvino/op/slice.hpp>
namespace ov {
namespace frontend {
@@ -26,7 +30,39 @@ OutputVector translate_fill(const NodeContext & context) {
// the shape of the input, which keeps its dynamic token dim
auto target_shape = std::make_shared<ov::op::v3::ShapeOf>(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<ov::op::v3::Broadcast>(val, target_shape);
+ ov::Output<ov::Node> res = std::make_shared<ov::op::v3::Broadcast>(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<ov::op::v1::Reshape>(base, i64(-1), false);
+ auto head = std::make_shared<ov::op::v8::Slice>(flat, i64(0), i64(begin), i64(1), i64(0));
+ auto body = std::make_shared<ov::op::v1::Reshape>(res, i64(-1), false);
+ auto tail = std::make_shared<ov::op::v8::Slice>(flat, i64(begin + count), i64(INT64_MAX), i64(1), i64(0));
+ auto full = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{head, body, tail}, 0);
+ res = std::make_shared<ov::op::v1::Reshape>(
+ full, std::make_shared<ov::op::v3::ShapeOf>(base, ov::element::i64), false);
+ }
+ }
return rename_outputs_with_suffix({res}, context.get_name());
}
diff --git a/ggml/src/ggml-openvino/openvino/op/unary.cpp b/ggml/src/ggml-openvino/openvino/op/unary.cpp
index 1bb7aa2c8..5c338ec56 100644
--- a/ggml/src/ggml-openvino/openvino/op/unary.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/unary.cpp
@@ -14,11 +14,13 @@
#include <openvino/op/gelu.hpp>
#include <openvino/op/greater.hpp>
#include <openvino/op/hard_sigmoid.hpp>
+#include <openvino/op/less.hpp>
#include <openvino/op/log.hpp>
#include <openvino/op/multiply.hpp>
#include <openvino/op/negative.hpp>
#include <openvino/op/relu.hpp>
#include <openvino/op/round.hpp>
+#include <openvino/op/select.hpp>
#include <openvino/op/sigmoid.hpp>
#include <openvino/op/softplus.hpp>
#include <openvino/op/subtract.hpp>
@@ -125,8 +127,20 @@ OutputVector translate_unary_softplus(const NodeContext & context) {
auto positive = std::make_shared<ov::op::v0::Relu>(input);
auto abs = std::make_shared<ov::op::v0::Abs>(input);
auto neg_abs = std::make_shared<ov::op::v0::Negative>(abs);
- auto exp_neg_abs = std::make_shared<ov::op::v0::Exp>(neg_abs);
- auto log_term = std::make_shared<ov::op::v0::Log>(std::make_shared<ov::op::v1::Add>(one, exp_neg_abs));
+ auto y = std::make_shared<ov::op::v0::Exp>(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<ov::Node> series = std::make_shared<ov::op::v1::Multiply>(y, c(0.25f));
+ series = std::make_shared<ov::op::v1::Subtract>(c(1.0f / 3), series);
+ series = std::make_shared<ov::op::v1::Subtract>(c(0.5f), std::make_shared<ov::op::v1::Multiply>(y, series));
+ series = std::make_shared<ov::op::v1::Subtract>(one, std::make_shared<ov::op::v1::Multiply>(y, series));
+ series = std::make_shared<ov::op::v1::Multiply>(y, series);
+ auto log_direct = std::make_shared<ov::op::v0::Log>(std::make_shared<ov::op::v1::Add>(one, y));
+ auto small = std::make_shared<ov::op::v1::Less>(y, c(0.01f));
+ auto log_term = std::make_shared<ov::op::v1::Select>(small, series, log_direct);
auto res = std::make_shared<ov::op::v1::Add>(positive, log_term);
return rename_outputs_with_suffix({res}, context.get_name());