From 6d07a7f98fc74e1342cf91883c19e4959074839b Mon Sep 17 00:00:00 2001 From: Mustafa Cavus Date: Sat, 5 Dec 2026 02:17:56 +0530 Subject: [PATCH] ggml-openvino: run plain GDN on GPU as PagedGatedDeltaNet that updates the recurrent cache in place --- .../dev_doc/OPENVINO-RECURRENT-CACHE.md | 12 ++ .../dev_doc/OpenVINO-ENV-VARS.md | 1 + ggml/src/ggml-openvino/dev_doc/README.md | 2 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 1 + ggml/src/ggml-openvino/ggml-openvino-extra.h | 5 + ggml/src/ggml-openvino/model-cache.cpp | 4 +- .../openvino/op/gated_delta_net.cpp | 59 +++++- .../openvino/op/paged_gated_delta_net.hpp | 95 +++++++++ ggml/src/ggml-openvino/openvino/op_table.h | 6 + .../openvino/paged_gdn_fusion.cpp | 198 ++++++++++++++++++ .../ggml-openvino/openvino/paged_gdn_fusion.h | 46 ++++ .../openvino/translate_session.cpp | 8 + ggml/src/ggml-openvino/utils.cpp | 2 + 13 files changed, 436 insertions(+), 3 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/paged_gated_delta_net.hpp create mode 100644 ggml/src/ggml-openvino/openvino/paged_gdn_fusion.cpp create mode 100644 ggml/src/ggml-openvino/openvino/paged_gdn_fusion.h 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 1294f0f9b87f..b59c9031674a 100644 --- a/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md +++ b/ggml/src/ggml-openvino/dev_doc/OPENVINO-RECURRENT-CACHE.md @@ -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_`. 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: 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 243a40c5cf2a..a7345faa10e5 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -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). | diff --git a/ggml/src/ggml-openvino/dev_doc/README.md b/ggml/src/ggml-openvino/dev_doc/README.md index ee169e909cf9..dcdc9e0c8549 100644 --- a/ggml/src/ggml-openvino/dev_doc/README.md +++ b/ggml/src/ggml-openvino/dev_doc/README.md @@ -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). diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 2ab49ba53300..1e7b5546bd7d 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -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}, diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 267ff32dc78b..43dec59e10ff 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -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. diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index bb1ef896919d..c9d81cc6b4a6 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -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", @@ -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, ""); 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 92648e212aa0..a2edc0b7b7b9 100644 --- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp +++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp @@ -1,4 +1,5 @@ #include "gated_delta_net.hpp" +#include "paged_gated_delta_net.hpp" #include "../node_context.h" #include "recurrent_replay_graph.hpp" @@ -43,9 +44,15 @@ #include #include #include +#include #include #include +namespace ov { +// exported by libopenvino, declared in transformations/rt_info/disable_precision_conversion.hpp +void disable_conversion(const std::shared_ptr & node, const element::Type & to); +} // namespace ov + namespace ov { namespace frontend { namespace ggml { @@ -401,7 +408,7 @@ static OutputVector translate_gdn_snapshots(const Output & 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] @@ -515,6 +522,48 @@ OutputVector translate_gated_delta_net(const NodeContext & context) { g = std::make_shared(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 & 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 & x, const std::vector & dims) -> Output { + return std::make_shared(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(v, ov::element::i32); + auto dim = [&](int64_t axis) { + return std::make_shared(shape, i32s((int32_t) axis), i32s(0)); + }; + auto seqs = std::make_shared(i32s(0), dim(0), i32s(1), ov::element::i32); + auto bounds = std::make_shared(i32s(0), std::make_shared(dim(0), i32s(1)), + i32s(1), ov::element::i32); + auto begins = std::make_shared(bounds, dim(1)); + auto unsq = [&](const Output & x) { + return std::make_shared(x, i32s(1)); + }; + // each sequence s reads and writes cell head + s: prepare_paged_gdn_banks has moved its state there + Output rows = std::make_shared( + seqs, flat(std::make_shared(paged->head, ov::element::i32), {1})); + auto blocks = flat(std::make_shared(ov::OutputVector{unsq(rows), unsq(rows)}, 1), {-1}); + auto block_begins = std::make_shared(bounds, i32s(2)); + auto zeros = std::make_shared(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( + 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 attn = std::make_shared( + pgdn, std::make_shared(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 attn_4d, states; if (snapshot_count > 1) { @@ -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); diff --git a/ggml/src/ggml-openvino/openvino/op/paged_gated_delta_net.hpp b/ggml/src/ggml-openvino/openvino/op/paged_gated_delta_net.hpp new file mode 100644 index 000000000000..7badfcf6e9da --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/paged_gated_delta_net.hpp @@ -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& query, + const Output& key, + const Output& value, + const Output& recurrent_state_table, + const Output& gate, + const Output& beta, + const Output& subsequence_begins, + const Output& la_block_indices, + const Output& la_block_indices_begins, + const Output& processed_tokens, + const Output& 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 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 diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index 0f5305c4c025..89441b191918 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -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 table; + Output 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); diff --git a/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.cpp b/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.cpp new file mode 100644 index 000000000000..c3f479160aa7 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.cpp @@ -0,0 +1,198 @@ +#include "paged_gdn_fusion.h" + +#include "../ggml-openvino-extra.h" +#include "ggml-backend.h" +#include "ggml-impl.h" +#include "op_table.h" +#include "utils.h" + +#include "op/paged_gated_delta_net.hpp" + +#include +#include +#include + +namespace ov::frontend::ggml { +namespace { +const ggml_tensor * view_root(const ggml_tensor * node) { + while (node && (node->op == GGML_OP_VIEW || node->op == GGML_OP_RESHAPE)) { + node = node->src[0]; + } + return node; +} + +bool reads_bank(const ggml_tensor * t, const ggml_tensor * bank) { + if (t->view_src == bank) { + return true; + } + for (int port = 0; port < GGML_MAX_SRC; ++port) { + if (t->src[port] && view_root(t->src[port]) == bank) { + return true; + } + } + return false; +} + +bool is_gather_of(const ggml_tensor * t, const ggml_tensor * bank) { + return t && t->op == GGML_OP_GET_ROWS && view_root(t->src[0]) == bank; +} +} // namespace + +bool paged_gdn_enabled(const GgmlOvDecoder & decoder) { + return !decoder.m_naive && !decoder.is_static() && !decoder.is_stateful() && !decoder.is_splited_model() && + ggml_openvino_paged_gdn_enabled() && !decoder.get_model_extra_inputs().count("rs_replay_rows"); +} + +std::vector find_paged_gdn_groups(const ggml_cgraph * graph) { + std::vector groups; + for (int i = 0; i < graph->n_nodes; ++i) { + const auto node = graph->nodes[i]; + if (node->op != GGML_OP_GATED_DELTA_NET || node->op_params[0] != 1 || node->op_params[1] != 0 || + node->src[3]->ne[0] != 1) { + continue; + } + const auto state = node->src[5]; + // the state is a view of the cache cells, or a gather of them + const auto root = view_root(state); + const auto bank = root && root->op == GGML_OP_GET_ROWS ? view_root(root->src[0]) : root; + if (!bank || bank->op != GGML_OP_NONE || !GgmlOvDecoder::is_recurrent_cache(bank) || + bank->type != GGML_TYPE_F32 || !ggml_is_contiguous(bank) || bank->ne[2] != 1 || bank->ne[3] != 1 || + !ggml_openvino_buffer_is_remote(bank) || !ggml_is_contiguous(state) || + ggml_nbytes(state) != state->ne[3] * bank->nb[1]) { + continue; + } + PagedGdnGroup group; + group.compute = i; + group.bank = bank; + bool ok = true; + for (int j = 0; j < graph->n_nodes && ok; ++j) { + const auto t = graph->nodes[j]; + if (j == i || t->op == GGML_OP_VIEW || t->op == GGML_OP_RESHAPE || !reads_bank(t, bank)) { + continue; + } + if (is_gather_of(t, bank)) { + const auto map = view_root(t->src[1]); + ok = map->type == GGML_TYPE_I32 && (!group.copy || group.copy == map); + group.copy = map; + } else if (t->op == GGML_OP_CPY && is_gather_of(view_root(t->src[0]), bank)) { + // moves the gathered states into their cells, done by prepare_paged_gdn_banks + } else if (GgmlOvDecoder::is_recurrent_cache_reset(t)) { + ok = !group.reset; + group.reset = t; + } else if (t->op == GGML_OP_CPY && t->src[0]->op == GGML_OP_VIEW && t->src[0]->src[0] == node && + ggml_nbytes(t) == ggml_nbytes(state) && group.write < 0) { + ok = ((const char *) t->data - (const char *) bank->data) % bank->nb[1] == 0; + group.write = j; + } else { + ok = ggml_nelements(t) == 0; + } + } + if (ok && group.write >= 0) { + groups.push_back(group); + } + } + return groups; +} + +void prepare_paged_gdn_banks(const GgmlOvDecoder & decoder) { + if (!paged_gdn_enabled(decoder)) { + return; + } + const auto graph = decoder.get_cgraph(); + std::vector rows; + for (const auto & group : find_paged_gdn_groups(graph)) { + // the bank is a graph leaf in a writable buffer + auto * bank = const_cast(group.bank); + const size_t row = bank->nb[1]; + if (group.reset && ggml_nbytes(group.reset) > 0) { + const size_t offset = (const char *) group.reset->data - (const char *) bank->data; + ggml_backend_tensor_memset(bank, 0, offset, ggml_nbytes(group.reset)); + } + if (!group.copy) { + continue; + } + // cell head + i takes the state of cell s_copy[i]; all sources are read before any cell is written + const int64_t head = ((const char *) graph->nodes[group.write]->data - (const char *) bank->data) / row; + const auto * map = (const int32_t *) group.copy->data; + const int64_t n = group.copy->ne[0]; + bool moved = false; + for (int64_t i = 0; i < n && !moved; ++i) { + moved = map[i] != head + i; + } + if (!moved) { + continue; + } + rows.resize(n * row); + for (int64_t i = 0; i < n; ++i) { + ggml_backend_tensor_get(bank, rows.data() + i * row, map[i] * row, row); + } + ggml_backend_tensor_set(bank, rows.data(), head * row, n * row); + } +} + +PagedGdnFusion::PagedGdnFusion(const std::shared_ptr & decoder, + const std::shared_ptr & tensors) { + auto actual = std::dynamic_pointer_cast(decoder); + if (!actual || !paged_gdn_enabled(*actual)) { + return; + } + const auto graph = actual->get_cgraph(); + for (const auto & rows : find_paged_gdn_groups(graph)) { + // taken before translation: in-place resets replace the bank in the tensor map + const auto name = GgmlOvDecoder::get_tensor_name(graph, rows.bank); + const auto table = tensors->find(name); + const auto head = tensors->find("rs_slot_begin_" + GgmlOvDecoder::get_tensor_name(graph, graph->nodes[rows.write])); + if (table == tensors->end() || head == tensors->end() || + !ov::is_type(table->second.get_node_shared_ptr())) { + continue; + } + m_nodes[rows.compute] = m_groups.size(); + m_nodes[rows.write] = m_groups.size(); + m_banks.insert(name); + m_groups.push_back({rows.compute, table->second, head->second}); + } + if (!m_groups.empty() && ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_CGRAPH")) { + GGML_LOG_INFO("ggml-openvino: paged GDN: %zu groups\n", m_groups.size()); + } +} + +OutputVector PagedGdnFusion::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]; + if (index != group.compute) { + // the write-back CPY: the op already updated the bank + return OutputVector(context.get_output_names().size(), group.table); + } + return op::translate_paged_gated_delta_net(context, {group.table, group.head}); +} +} // namespace ov::frontend::ggml + +// Asks the device once: OpenVINO releases without a GPU PagedGatedDeltaNet leave the node out of query_model +bool ggml_openvino_paged_gdn_enabled() { + static const bool enabled = [] { + if (!ggml_openvino_is_gpu() || ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_PAGED_GDN")) { + return false; + } + ov::ParameterVector params; + auto param = [¶ms](ov::element::Type type, const ov::Shape & shape) { + params.push_back(std::make_shared(type, shape)); + return params.back(); + }; + const auto f32 = ov::element::f32, i32 = ov::element::i32; + const auto gdn = std::make_shared( + param(f32, {1, 1, 16}), param(f32, {1, 1, 16}), param(f32, {1, 1, 16}), param(f32, {1, 1, 16, 16}), + param(f32, {1, 1}), param(f32, {1, 1}), param(i32, {2}), param(i32, {2}), param(i32, {2}), param(i32, {1}), + param(i32, {1})); + const auto model = std::make_shared(gdn->outputs(), params); + try { + const auto supported = ov_singleton_core().query_model(model, ggml_openvino_get_device_name()); + return supported.count(gdn->get_friendly_name()) != 0; + } catch (const ov::Exception &) { + return false; + } + }(); + return enabled; +} diff --git a/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.h b/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.h new file mode 100644 index 000000000000..5cd4ed586ca1 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/paged_gdn_fusion.h @@ -0,0 +1,46 @@ +#pragma once +#include "../ggml-decoder.h" +#include "node_context.h" + +#include +#include +#include +#include + +namespace ov::frontend::ggml { +// A plain GATED_DELTA_NET whose state is one cache row per sequence runs as a PagedGatedDeltaNet that updates the +// remote cache bank in place, so the bank is not a model output (see ggml_openvino_paged_gdn_enabled()). +struct PagedGdnGroup { + int compute = -1; + int write = -1; + const ggml_tensor * bank = nullptr; + // moves of the bank before the GDN, done by prepare_paged_gdn_banks: the reset and the s_copy row map + const ggml_tensor * reset = nullptr; + const ggml_tensor * copy = nullptr; +}; + +bool paged_gdn_enabled(const GgmlOvDecoder & decoder); +std::vector find_paged_gdn_groups(const ggml_cgraph * graph); + +// Runs the reset and the s_copy row moves of the paged banks on the device before the inference, so that the state of +// every sequence is in its cell and the op reads and writes row head + s +void prepare_paged_gdn_banks(const GgmlOvDecoder & decoder); + +class PagedGdnFusion { +public: + PagedGdnFusion(const std::shared_ptr &, const std::shared_ptr &); + OutputVector translate(int index, const NodeContext & context); + + const std::set & inplace_banks() const { return m_banks; } +private: + struct Group { + int compute = -1; + Output table; + Output head; + }; + + std::vector m_groups; + std::map m_nodes; + std::set m_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 5c5a6a8bd99e..0c76fa0507c7 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 "paged_gdn_fusion.h" #include "recurrent_replay_fusion.h" #include "pass/mark_decompression_convert_constant_folding.h" #include "pass/mark_dequantization_subgraph.h" @@ -299,6 +300,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo } RecurrentReplayFusion replay_fusion(ggml_model_decoder, tensor_map); + PagedGdnFusion paged_gdn(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") { @@ -320,6 +322,9 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo " is not implemented."); NodeContext node_context(decoder, tensor_map, node_idx); auto converted_outputs = replay_fusion.translate(node_idx, node_context); + if (converted_outputs.empty()) { + converted_outputs = paged_gdn.translate(node_idx, node_context); + } if (converted_outputs.empty()) { converted_outputs = it->second(node_context); } @@ -387,6 +392,9 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo for (const auto & name : ggml_model_decoder->get_model_output_names()) { FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(), "Output name not found in tensor map: ", name); + if (paged_gdn.inplace_banks().count(name)) { + continue; + } 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))) { diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 6925e8458775..b6a3c82295be 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/paged_gdn_fusion.h" #include "openvino/recurrent_replay_fusion.h" #include @@ -1930,6 +1931,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share } } + ov::frontend::ggml::prepare_paged_gdn_banks(*ggml_decoder); ov_raw_infer_start = ggml_time_us(); try { infer_request->infer();