Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ The GPU plugin uses two stages:

Both kernels write their cache inputs directly.

## Plain GDN on PagedGatedDeltaNet

Without replay (`n_rs_seq=0`), a GPU graph runs each `GGML_OP_GATED_DELTA_NET` whose state is one recurrent cache cell per sequence as the existing `ov::op::internal::PagedGatedDeltaNet`, the op that OpenVINO GenAI uses for linear attention:

- The state table is the cache bank itself, a caller-owned GPU USM `Parameter`. A cell (`[H_v, S_v, S_k]`, `S_k` contiguous) is one row of the table, so no transpose is needed.
- Sequence `s` reads and writes row `head + s` (`block_indices = [head + s, head + s]`, `cache_interval = 0`). `head` is the runtime input `rs_slot_begin_<state write-back>`. The bank is no longer a model output.
- Before the inference, `prepare_paged_gdn_banks()` clears the reset cells and, when `s_copy` is not the identity, copies the source cells into cells `head..head + n_rs` on the device. All sources are read before any cell is written, as in GGML.
- The op keeps the table in FP32: f16 conversion is disabled on the node and the table input is precision-sensitive. A converted copy would receive the update instead of the cache.
- The convolution state keeps the standard-op path: `PagedCausalConv1D` stores `K` columns per channel, the GGML cell `K - 1`.

It needs a GPU plugin with `PagedGatedDeltaNet` (queried once). `GGML_OPENVINO_DISABLE_PAGED_GDN=1` turns it off.

## Replay graph contract

Graph selection:
Expand Down
1 change: 1 addition & 0 deletions ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,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_PAGED_GDN` | GPU | Boolean | `0` | `1` keeps a plain `GATED_DELTA_NET` on the `GatedDeltaNet` op with the cache rows as model outputs, instead of the `PagedGatedDeltaNet` op that updates the recurrent cache in place. Part of the model cache key. |
| `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. |
| `GGML_OPENVINO_ENABLE_KV_4D` | GPU | Boolean | auto | Bind the KV cache as `[1, ctx, n_heads_kv, head_size]` for in-place updates. Unset: on with OpenVINO 2026.5 or later. `0` forces it off, a positive value forces it on. Not used with `-fa off`, for soft-capped attention (gemma-2), or in static, stateful or split graphs. See [KV cache binding](README.md#kv-cache-binding). |
Expand Down
2 changes: 1 addition & 1 deletion ggml/src/ggml-openvino/dev_doc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ Settings that must stay exactly the same between the runs, including set versus

- `GGML_OPENVINO_GPU_CONFIG`, `GGML_OPENVINO_CPU_CONFIG`, `GGML_OPENVINO_REQUANT_KQUANT`, `GGML_OPENVINO_EXACT_ZERO_POINT`, `GGML_OPENVINO_NATIVE_SOFTPLUS`, `GGML_OPENVINO_MANUAL_GQA_ATTN`
- `GGML_OPENVINO_STATEFUL_EXECUTION`, `GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT`, `GGML_OPENVINO_KV_SCATTER_ELEMENTS`
- `GGML_OPENVINO_GDN_NATIVE_STATE`, `GGML_OPENVINO_GDN_DECOMPOSE`, `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK`
- `GGML_OPENVINO_GDN_NATIVE_STATE`, `GGML_OPENVINO_GDN_DECOMPOSE`, `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK`, `GGML_OPENVINO_DISABLE_PAGED_GDN`
- `GGML_OPENVINO_REDUCE_COMPILE_MEM`, `GGML_OPENVINO_MEMORY_OPTIMIZE`, `GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK`
- `GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN`, `GGML_OPENVINO_DEBUG_NODE`
- `GGML_OPENVINO_ENABLE_KV_4D` and `GGML_OPENVINO_ROPE_SINCOS` (their effective values).
Expand Down
1 change: 1 addition & 0 deletions ggml/src/ggml-openvino/ggml-openvino-extra.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,7 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_CACHE", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_FUSED_RECURRENCE", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_PAGED_GDN", env_type::BOOL},
{"GGML_OPENVINO_ENABLE_KV_4D", env_type::BOOL},
{"GGML_OPENVINO_ENABLE_FALLBACK", env_type::BOOL},
{"GGML_OPENVINO_KV_SCATTER_ELEMENTS", env_type::BOOL},
Expand Down
5 changes: 5 additions & 0 deletions ggml/src/ggml-openvino/ggml-openvino-extra.h
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,11 @@ bool ggml_openvino_npu_is_4000();
// Snapshot (MTP) graphs still use the op.
bool ggml_openvino_gdn_decompose_enabled();

// On GPU, a plain GATED_DELTA_NET on recurrent cache cells runs as a PagedGatedDeltaNet that updates the cache in place
// (openvino/paged_gdn_fusion.cpp). Default: on when the GPU plugin supports the op. GGML_OPENVINO_DISABLE_PAGED_GDN=1
// turns it off.
bool ggml_openvino_paged_gdn_enabled();

// Translate the MoE block of a model (router, experts, expert sum) into the batched form of the NPUW MoE support:
// every expert is computed (Tile + batched MatMul) and weighted by scattered router scores, and NPUW runs only the
// routed experts. The NPU has no GatherMatmul.
Expand Down
4 changes: 3 additions & 1 deletion ggml/src/ggml-openvino/model-cache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_GDN_NATIVE_STATE",
"GGML_OPENVINO_GDN_DECOMPOSE",
"GGML_OPENVINO_GDN_DECOMPOSE_CHUNK",
"GGML_OPENVINO_DISABLE_PAGED_GDN",
"GGML_OPENVINO_MANUAL_GQA_ATTN",
"GGML_OPENVINO_EXACT_ZERO_POINT",
"GGML_OPENVINO_STATEFUL_EXECUTION",
Expand Down Expand Up @@ -362,7 +363,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 12 keeps the Q5_0 layout (was Q4_0_64).
// Version 13 keeps models converted from an ambiguous one-token graph apart (see can_run_tokens()).
// Version 14 hashes the effective GGML_OPENVINO_ROPE_SINCOS (in extra_cfg) instead of GGML_OPENVINO_ROPE_F32_ANGLE.
h = fnv1a_u64(h, 14);
// Version 15 runs plain GDN on GPU as PagedGatedDeltaNet, which updates the cache in place.
h = fnv1a_u64(h, 15);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
Expand Down
59 changes: 58 additions & 1 deletion ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "gated_delta_net.hpp"
#include "paged_gated_delta_net.hpp"

#include "../node_context.h"
#include "recurrent_replay_graph.hpp"
Expand Down Expand Up @@ -43,9 +44,15 @@
#include <openvino/op/tile.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
#include <openvino/op/util/precision_sensitive_attribute.hpp>
#include <utility>
#include <vector>

namespace ov {
// exported by libopenvino, declared in transformations/rt_info/disable_precision_conversion.hpp
void disable_conversion(const std::shared_ptr<Node> & node, const element::Type & to);
} // namespace ov

namespace ov {
namespace frontend {
namespace ggml {
Expand Down Expand Up @@ -401,7 +408,7 @@ static OutputVector translate_gdn_snapshots(const Output<Node> & q,
return {attention, states};
}

OutputVector translate_gated_delta_net(const NodeContext & context) {
static OutputVector translate_gated_delta_net_impl(const NodeContext & context, const PagedGdnRows * paged) {
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]
Expand Down Expand Up @@ -515,6 +522,48 @@ OutputVector translate_gated_delta_net(const NodeContext & context) {
g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}

if (paged) {
FRONT_END_OP_CONVERSION_CHECK(snapshot_count == 1 && !kda && context.get_output_names().size() == 2,
"Paged GATED_DELTA_NET needs one state, a scalar gate and split outputs");
auto i64c = [](const std::vector<int64_t> & values) {
return ov::op::v0::Constant::create(ov::element::i64, {values.size()}, values);
};
auto i32s = [](int32_t value) { return ov::op::v0::Constant::create(ov::element::i32, {}, {value}); };
auto flat = [&](const Output<Node> & x, const std::vector<int64_t> & dims) -> Output<Node> {
return std::make_shared<ov::op::v1::Reshape>(x, i64c(dims), false);
};
const int64_t S_k = q_shape[3];
// [B, T, H, S] -> [B * T, H, S]: one subsequence of T tokens per sequence
auto shape = std::make_shared<ov::op::v3::ShapeOf>(v, ov::element::i32);
auto dim = [&](int64_t axis) {
return std::make_shared<ov::op::v8::Gather>(shape, i32s((int32_t) axis), i32s(0));
};
auto seqs = std::make_shared<ov::op::v4::Range>(i32s(0), dim(0), i32s(1), ov::element::i32);
auto bounds = std::make_shared<ov::op::v4::Range>(i32s(0), std::make_shared<ov::op::v1::Add>(dim(0), i32s(1)),
i32s(1), ov::element::i32);
auto begins = std::make_shared<ov::op::v1::Multiply>(bounds, dim(1));
auto unsq = [&](const Output<Node> & x) {
return std::make_shared<ov::op::v0::Unsqueeze>(x, i32s(1));
};
// each sequence s reads and writes cell head + s: prepare_paged_gdn_banks has moved its state there
Output<Node> rows = std::make_shared<ov::op::v1::Add>(
seqs, flat(std::make_shared<ov::op::v0::Convert>(paged->head, ov::element::i32), {1}));
auto blocks = flat(std::make_shared<ov::op::v0::Concat>(ov::OutputVector{unsq(rows), unsq(rows)}, 1), {-1});
auto block_begins = std::make_shared<ov::op::v1::Multiply>(bounds, i32s(2));
auto zeros = std::make_shared<ov::op::v1::Multiply>(seqs, i32s(0));
// ggml rows hold [H_v, S_v, S_k] with S_k contiguous, the table layout of the op
auto table = flat(paged->table, {-1, H_v, S_v, S_k});
auto pgdn = std::make_shared<ov::op::internal::PagedGatedDeltaNet>(
flat(q, {-1, H_v, S_k}), flat(k, {-1, H_v, S_k}), flat(v, {-1, H_v, S_v}), table, flat(g, {-1, H_v}),
flat(beta, {-1, H_v}), begins, blocks, block_begins, zeros, zeros, fuse_qk_l2norm, q_eps, k_eps);
// the op writes the f32 table in place: keep it f32, a converted copy would drop the update
ov::disable_conversion(pgdn, ov::element::f16);
ov::mark_as_precision_sensitive(pgdn->input(3));
Output<Node> attn = std::make_shared<ov::op::v1::Reshape>(
pgdn, std::make_shared<ov::op::v3::ShapeOf>(v, ov::element::i64), false);
// the state output is unused: the write-back CPY maps to the updated table
return rename_outputs_with_suffix({attn, table}, context.get_name());
}

Output<Node> attn_4d, states;
if (snapshot_count > 1) {
Expand Down Expand Up @@ -556,6 +605,14 @@ OutputVector translate_gated_delta_net(const NodeContext & context) {
return rename_outputs_with_suffix({res}, context.get_name());
}

OutputVector translate_gated_delta_net(const NodeContext & context) {
return translate_gated_delta_net_impl(context, nullptr);
}

OutputVector translate_paged_gated_delta_net(const NodeContext & context, const PagedGdnRows & rows) {
return translate_gated_delta_net_impl(context, &rows);
}

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);
Expand Down
95 changes: 95 additions & 0 deletions ggml/src/ggml-openvino/openvino/op/paged_gated_delta_net.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
// Copyright (C) 2018-2026 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once

#include "openvino/op/op.hpp"

namespace ov::op::internal {
/// \note PagedGatedDeltaNet op class is under development and subject to change
///
/// \brief Operator performing paged Gated Delta Net computation for linear attention models.
///
/// Computes gated delta net attention over input tokens using a block-based recurrent state table
/// managed by the paged execution pipeline. The recurrent state table is updated in-place by the kernel.
///
/// This operation uses grouped-query linear attention. The number of groups is
/// ``num_groups = v_num_heads / num_heads``. Each query and key head is shared by
/// ``num_groups`` consecutive value heads, with the mapping ``h_q = h_v / num_groups``.
/// \ingroup ov_ops_cpp_api
class OPENVINO_API PagedGatedDeltaNet : public ov::op::Op {
public:
OPENVINO_OP("PagedGatedDeltaNet")

PagedGatedDeltaNet() = default;
/// \brief Constructs a PagedGatedDeltaNet operation.
///
/// \param query Query tensor [batch_size_in_tokens, num_heads, key_head_dim].
/// num_heads is the number of query/key heads; v_num_heads must be divisible by num_heads.
/// \param key Key tensor [batch_size_in_tokens, num_heads, key_head_dim].
/// \param value Value tensor [batch_size_in_tokens, v_num_heads, value_head_dim].
/// v_num_heads >= num_heads; the ratio v_num_heads/num_heads gives the number of GQA groups.
/// \param recurrent_state_table Block table containing recurrent states
/// [num_blocks, v_num_heads, value_head_dim, key_head_dim].
/// \param gate Gate tensor [batch_size_in_tokens, v_num_heads].
/// \param beta Beta tensor [batch_size_in_tokens, v_num_heads].
/// \param subsequence_begins Start indices of tokens from current sequences [batch_size_in_sequences+1],
/// element type i32.
/// \param la_block_indices Block index along 0-th dim in recurrent_state table [num_blocks],
/// element type i32.
/// \param la_block_indices_begins Defines how block indices are split among sequences [batch_size_in_sequences+1],
/// element type i32.
/// \param processed_tokens Number of tokens already handled per sequence [batch_size_in_sequences],
/// element type i32.
/// \param cache_interval Interval between tokens to cache state [batch_size_in_sequences],
/// element type i32.
/// \param use_qk_l2norm Enables q/k L2-normalization inside this op.
/// \param q_l2_norm_eps Positive floating-point epsilon used for query L2-normalization.
/// \param k_l2_norm_eps Positive floating-point epsilon used for key L2-normalization.
PagedGatedDeltaNet(const Output<Node>& query,
const Output<Node>& key,
const Output<Node>& value,
const Output<Node>& recurrent_state_table,
const Output<Node>& gate,
const Output<Node>& beta,
const Output<Node>& subsequence_begins,
const Output<Node>& la_block_indices,
const Output<Node>& la_block_indices_begins,
const Output<Node>& processed_tokens,
const Output<Node>& cache_interval,
bool use_qk_l2norm = false,
float q_l2_norm_eps = 1e-6F,
float k_l2_norm_eps = 1e-6F);

/// \brief Constructs a PagedGatedDeltaNet operation from input vector.
///
/// \param args Input tensor vector (11 inputs in order listed above).
/// \param use_qk_l2norm Enables q/k L2-normalization inside this op.
/// \param q_l2_norm_eps Positive floating-point epsilon used for query L2-normalization.
/// \param k_l2_norm_eps Positive floating-point epsilon used for key L2-normalization.
PagedGatedDeltaNet(const ov::OutputVector& args,
bool use_qk_l2norm = false,
float q_l2_norm_eps = 1e-6F,
float k_l2_norm_eps = 1e-6F);

void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
std::shared_ptr<ov::Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;

bool get_use_qk_l2norm() const {
return m_use_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;
}

private:
bool m_use_qk_l2norm = false;
float m_q_l2_norm_eps = 1e-6F;
float m_k_l2_norm_eps = 1e-6F;
};

} // namespace ov::op::internal
6 changes: 6 additions & 0 deletions ggml/src/ggml-openvino/openvino/op_table.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ 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();
OutputVector translate_recurrent_gated_delta_net_replay(const NodeContext & context, const OutputVector & banks);
// GDN as a PagedGatedDeltaNet that reads and writes row head + s of the cache bank table in place
struct PagedGdnRows {
Output<Node> table;
Output<Node> head;
};
OutputVector translate_paged_gated_delta_net(const NodeContext & context, const PagedGdnRows & rows);
GGML_OP_CONVERTER(translate_repeat);
GGML_OP_CONVERTER(translate_cumsum);
GGML_OP_CONVERTER(translate_set);
Expand Down
Loading