From 62a910833a8c4c8f551074675b95f846ce56cd4b Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 09:22:52 +0100 Subject: [PATCH 01/19] 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 57deb264e455..3dfff481514c 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -89,6 +89,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 1eb7ae9fc790..800923e2bccd 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -485,6 +485,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]; @@ -1372,7 +1375,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; @@ -1454,7 +1457,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); @@ -1817,8 +1821,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")) { @@ -1873,6 +1877,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 4c2106df9edb..f5e97efa3b0d 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -563,7 +563,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 054d78c31580..7b254e3454b5 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -193,6 +193,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_SELF_CONTAINED_MMAP", env_type::BOOL}, diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 7f592b3c45a4..2bc19c796299 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1634,6 +1634,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; @@ -1644,7 +1663,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); } // SET_ROWS writes whole rows of a contiguous destination. Other destination views (e.g. a permuted view of a @@ -2090,7 +2109,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 3a05c8b436d9..15a39f8166f8 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 eef3874fa63f..7cfd3fde1881 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 @@ -571,6 +573,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); } @@ -580,6 +583,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 a3b56bb5ec29..3c370d03faea 100644 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ b/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp @@ -115,7 +115,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 1c43c8ae0df5..7d01f08e1207 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 @@ -74,7 +75,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(); @@ -305,6 +306,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") { @@ -329,6 +331,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); } @@ -390,6 +393,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 29f7f404155b..6598d0960f59 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -216,7 +216,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 @@ -766,7 +766,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 f71e5a0bee857bcc3ff7eebb807ec1e90aef8c12 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 11:43:31 +0100 Subject: [PATCH 02/19] 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 3dfff481514c..fcda27f61aee 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -88,7 +88,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 2bc19c796299..3639e3c0c372 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -64,6 +64,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 { @@ -116,7 +118,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()), @@ -133,8 +136,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 { @@ -402,12 +415,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; @@ -424,16 +438,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 37f1086c7ccab2b608c99b02e2c65b36495eaad4 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 12:00:08 +0100 Subject: [PATCH 03/19] 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 fcda27f61aee..3dfff481514c 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -88,7 +88,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 3639e3c0c372..2bc19c796299 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -64,8 +64,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 { @@ -118,8 +116,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()), @@ -136,18 +133,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 { @@ -415,13 +402,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; @@ -438,20 +424,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 eff6adf41f059bbb5c381fefde55f96c3158f416 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Wed, 25 Nov 2026 12:12:13 +0100 Subject: [PATCH 04/19] 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 6598d0960f59..5fca74436ac6 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -368,9 +369,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 8afbd7c6ace798a9a204ba745b46fd4a88bfd955 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 05:26:19 +0100 Subject: [PATCH 05/19] 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 7d01f08e1207..955e3f44bf88 100644 --- a/ggml/src/ggml-openvino/openvino/translate_session.cpp +++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -393,6 +394,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 @@ -403,6 +406,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); @@ -454,7 +469,7 @@ std::shared_ptr TranslateSession::translate_graph(const frontend::InputMo used_params.push_back(param); } } - 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 5fca74436ac6..8b61175c5b37 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 ee170a2666f1..3db84a2541a7 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -125,6 +125,7 @@ struct decoder_runtime_ctx { std::shared_ptr mutex; std::shared_ptr ptr; + std::vector> replay_writebacks; // Static path: the compiled models of this graph with their requests (ov_graph_compute_static). std::map variants; From 5129f9cc9c25dcccb79d9104f6e3357f67c253e5 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 06:09:21 +0100 Subject: [PATCH 06/19] 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 3dfff481514c..1b7fcbb3263a 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -54,7 +54,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; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); 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` | 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`. Dynamic CPU and GPU use a 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 path (NPU): the prefill graph is compiled at the smallest `N * 2^k` rows (clamped to the context) that cover the attended length; a loaded prefill graph of a larger window also serves a shorter prompt (with `GGML_OPENVINO_NPU_KV_ON_DEMAND=1`, only the exact window); 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_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. Every decode window is built, or read from the cache, on the first call. With `GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR`, the first prompt also writes (or reads) the prefill graph of every window; only the prefill graph in use stays loaded, unless `GGML_OPENVINO_SELF_CONTAINED_MMAP=1` or `GGML_OPENVINO_NPU_KV_ON_DEMAND=1` keeps them all loaded. `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. | @@ -89,7 +90,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 75ec84e3bce3f0089b583039c18d9126a4d8a593 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 09:25:10 +0100 Subject: [PATCH 07/19] ggml-openvino: remove legacy native recurrent cache ops --- ggml/src/ggml-openvino/CMakeLists.txt | 18 - 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 | 37 +-- .../openvino/op/recurrent_cache_update.hpp | 65 ---- ggml/src/ggml-openvino/openvino/op_table.h | 3 - .../openvino/recurrent_cache_fusion.cpp | 313 ------------------ .../openvino/recurrent_cache_fusion.h | 26 -- .../openvino/translate_session.cpp | 25 +- ggml/src/ggml-openvino/utils.cpp | 19 +- 11 files changed, 16 insertions(+), 566 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 250593a3839c..a33da0677815 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -27,21 +27,3 @@ endif() if (WIN32) target_link_libraries(ggml-openvino PRIVATE psapi) endif() - -# Released runtimes retain the ordinary cache translators. -include(CheckCXXSourceCompiles) -include(CMakePushCheckState) -unset(GGML_OPENVINO_HAS_CACHE_UPDATE CACHE) -cmake_push_check_state(RESET) -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) -cmake_pop_check_state() -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 1b7fcbb3263a..8424460a038c 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -64,7 +64,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 800923e2bccd..ac25634177d5 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -1822,61 +1822,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 7cfd3fde1881..92648e212aa0 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); } @@ -516,21 +515,6 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto g = std::make_shared(g, mask); } -#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) { @@ -572,17 +556,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 3c370d03faea..000000000000 --- a/ggml/src/ggml-openvino/openvino/recurrent_cache_fusion.cpp +++ /dev/null @@ -1,313 +0,0 @@ -#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE -# include "recurrent_cache_fusion.h" - -# include "../ggml-openvino-extra.h" -# include "ggml-impl.h" -# include "op/recurrent_cache_update.hpp" -# include "op_table.h" -# 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 955e3f44bf88..5c5a6a8bd99e 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" @@ -76,11 +73,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}); @@ -304,9 +298,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); @@ -328,11 +319,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); - 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); } @@ -398,12 +385,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 8b61175c5b37..9470302a7efa 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -218,12 +218,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); @@ -776,19 +772,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 0b2f83b7653385241dd66874a6a7826323320097 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 27 Nov 2026 08:46:53 +0100 Subject: [PATCH 08/19] 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. From fba8f85a5a36bb889466e624bff55e5a12fc84bb Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 20 Nov 2026 04:37:19 +0100 Subject: [PATCH 09/19] ggml-openvino: enable Qwen3.5 and Gemma4 image inputs Reuse Qwen vision graphs across image resolutions with runtime spatial shapes and interpolation targets. Support Gemma spatial positions, normalized vision attention and variable image-embedding counts. Preserve recurrent cache state and sequence grouping during parallel serving, using the native single-output cache-update contract. Keep KV head dimensions fixed after relayout when applying dynamic axes. Validated image requests and four-slot unified/split KV serving for Qwen3.5 and Gemma4 E2B on OpenVINO CPU and GPU. Vision and recurrent backend regressions passed 21/21 on each device. (cherry picked from commit d64dcb5594db74c0f03945cac668aefcca75e0b1) --- ggml/src/ggml-openvino/README.md | 9 + ggml/src/ggml-openvino/ggml-decoder.cpp | 170 +++++++++++++++++- ggml/src/ggml-openvino/ggml-decoder.h | 27 ++- ggml/src/ggml-openvino/ggml-openvino.cpp | 15 ++ ggml/src/ggml-openvino/openvino/decoder.h | 2 + .../src/ggml-openvino/openvino/node_context.h | 5 +- ggml/src/ggml-openvino/openvino/op/cont.cpp | 10 ++ .../openvino/op/flash_attn_ext.cpp | 4 +- ggml/src/ggml-openvino/openvino/op/im2col.cpp | 25 +-- .../src/ggml-openvino/openvino/op/reshape.cpp | 5 + .../src/ggml-openvino/openvino/op/upscale.cpp | 74 ++------ ggml/src/ggml-openvino/openvino/op/view.cpp | 11 ++ ggml/src/ggml-openvino/openvino/utils.cpp | 53 +++++- ggml/src/ggml-openvino/openvino/utils.h | 3 + ggml/src/ggml-openvino/utils.cpp | 27 ++- ggml/src/ggml-openvino/utils.h | 47 ++++- 16 files changed, 392 insertions(+), 95 deletions(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index 5bdead151942..d520328c6469 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -84,3 +84,12 @@ On the static path (NPU, or any device with `GGML_OPENVINO_FORCE_STATIC=1`), mod # 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. + +## Multimodal + +Qwen3.5 and Gemma4 E2B image input work on OpenVINO CPU and GPU with their matching +projectors. Four-slot serving was validated with unified and split KV. +Qwen3.5 reuses its vision graph across image resolutions; Gemma4 uses +resolution-specific encoder graphs. + +Gemma4 audio is not enabled. Static/NPU multimodal execution is untested. diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index ac25634177d5..91e967ad99df 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -6,6 +6,7 @@ #include "ggml-quants.h" #include "ggml.h" #include "utils.h" +#include "openvino/utils.h" #include #include @@ -33,6 +34,7 @@ #include #include #include +#include #include static std::set collect_graph_output_names(const ggml_cgraph * cgraph) { @@ -302,12 +304,24 @@ static std::string get_tensor_ov_name(const ggml_cgraph * cgraph, const ggml_ten return GgmlOvDecoder::get_tensor_name(cgraph, tensor); } +std::string GgmlOvDecoder::get_position_input_ov_name(const ggml_tensor * tensor) const { + // Keep independent spatial position tensors on independent ports. + for (int i = 0; i < m_cgraph->n_nodes; ++i) { + const auto * node = m_cgraph->nodes[i]; + if (node->op == GGML_OP_ROPE) { + if (node->src[1] != tensor) { return get_tensor_name(m_cgraph, tensor); } + break; + } + } + return "inp_pos"; +} + static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder, const ggml_cgraph * cgraph, const ggml_tensor * tensor, const ggml_tensor * op) { if (GgmlOvDecoder::is_inp_pos(tensor, op)) { - return "inp_pos"; + return decoder->get_position_input_ov_name(tensor); } if (GgmlOvDecoder::is_inp_emb(tensor, op)) { return "embd"; @@ -435,6 +449,29 @@ bool GgmlOvDecoder::is_gdn_out_prescaled(const ggml_tensor * gdn) const { return has_norm; } +static bool is_gdn_output_gate_view(const ggml_tensor * node, const ggml_cgraph * graph) { + if (node->op != GGML_OP_VIEW || !ggml_is_contiguous(node) || node->view_offs != 0 || + !node->src[0] || node->src[0]->op != GGML_OP_MUL_MAT || + ggml_nelements(node) != ggml_nelements(node->src[0])) { + return false; + } + for (int i = 0; i < graph->n_nodes; ++i) { + const auto * consumer = graph->nodes[i]; + if (consumer->op != GGML_OP_MUL || std::memcmp(node->ne, consumer->ne, sizeof(node->ne)) != 0) { continue; } + for (int j = 0; j < 2; ++j) { + const auto * gate = consumer->src[j]; + const auto * norm = consumer->src[1 - j]; + if (gate->op != GGML_OP_UNARY || gate->src[0] != node) { continue; } + if (norm->op == GGML_OP_MUL) { norm = norm->src[0]; } + if (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW && + norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) { + return true; + } + } + } + return false; +} + int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { int op_case = 0; switch (node->op) { @@ -702,6 +739,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } case GGML_OP_VIEW: { + if (!m_naive && !m_is_static && is_gdn_output_gate_view(node, m_cgraph)) { + return 5; + } if (is_sampling_view(node)) { return 3; } @@ -950,9 +990,114 @@ static const ggml_tensor * softmax_scores_source(const ggml_tensor * scores) { return scores; } -std::pair GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) { +std::vector GgmlOvDecoder::vision_reshape_pattern(const ggml_tensor * node) { + const auto * src = node->src[0]; + if (node->op == GGML_OP_CONT && std::memcmp(node->ne, src->ne, sizeof(node->ne)) == 0) { + // No reshape is emitted; all dimensions come directly from the input. + return {-2, -2, -2, -2}; + } + if (node->ne[2] == 1 && node->ne[3] == 1) { + return {1, 1, -1, node->ne[0]}; + } + if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_MUL_MAT && src->src[0] && + src->src[0]->op == GGML_OP_RESHAPE && src->src[0]->src[0]->op == GGML_OP_IM2COL && + node->ne[2] == 1 && node->ne[3] == src->ne[1]) { + // Unflatten patch convolution: [channels, 1, patch_height, patch_width]. + return {node->ne[3], 1, -2, -2}; + } + if (node->op == GGML_OP_RESHAPE && src->op == GGML_OP_CONT && src->ne[3] == 1 && + node->ne[0] == src->ne[0] && node->ne[1] == src->ne[1] && node->ne[2] * node->ne[3] == src->ne[2]) { + // Split rows into fixed-size merge groups while retaining both grid axes. + return {-2, node->ne[2], -2, node->ne[0]}; + } + if (node->op == GGML_OP_CONT && src->ne[3] == 1 && node->ne[3] == 1 && + node->ne[2] == src->ne[2] && node->ne[0] * node->ne[1] == src->ne[0] * src->ne[1]) { + // Merge adjacent patch features into each column; the feature width is fixed. + return {1, -2, -2, node->ne[0]}; + } + return {-2, -2, -2, -2}; +} + +bool GgmlOvDecoder::is_dynamic_vision_graph(const ggml_cgraph * cgraph) { + bool image_patches = false, vision_rope = false, attention = false; + // Recognize the operation patterns covered by the dynamic patch-encoder path. + // Reject language graphs before allocating the set used to check external sources. + for (int i = 0; i < cgraph->n_nodes; ++i) { + const auto * node = cgraph->nodes[i]; + switch (node->op) { + case GGML_OP_NONE: case GGML_OP_RESHAPE: case GGML_OP_PERMUTE: case GGML_OP_CONT: + case GGML_OP_VIEW: case GGML_OP_MUL_MAT: case GGML_OP_ADD: case GGML_OP_MUL: + case GGML_OP_NORM: case GGML_OP_RMS_NORM: case GGML_OP_UNARY: case GGML_OP_CPY: + break; + case GGML_OP_IM2COL: + if (node->op_params[6] != 1) { return false; } + image_patches |= node->src[1] && node->src[1]->op == GGML_OP_NONE && + (node->src[1]->flags & GGML_TENSOR_FLAG_INPUT); + break; + case GGML_OP_UPSCALE: + // Spatial position-grid interpolation; channel/batch resampling stays static. + if (node->ne[2] != node->src[0]->ne[2] || node->ne[3] != node->src[0]->ne[3]) { return false; } + break; + case GGML_OP_ROPE: + if (node->op_params[2] != GGML_ROPE_TYPE_VISION) { return false; } + vision_rope = true; + break; + case GGML_OP_FLASH_ATTN_EXT: + if (node->src[3] || node->src[4]) { return false; } + attention = true; + break; + default: + return false; + } + } + if (!image_patches || !vision_rope || !attention) { + return false; + } + std::unordered_set nodes; + nodes.reserve(cgraph->n_nodes); + for (int i = 0; i < cgraph->n_nodes; ++i) { + nodes.insert(cgraph->nodes[i]); + } + // Require declared inputs or weights at graph boundaries before enabling spatial reuse. + for (int i = 0; i < cgraph->n_nodes; ++i) { + for (const auto * src : cgraph->nodes[i]->src) { + if (!src || nodes.count(src)) { continue; } + const auto * root = src->view_src ? src->view_src : src; + if (!(root->flags & GGML_TENSOR_FLAG_INPUT) && + !(root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { return false; } + } + } + return true; +} + +std::pair GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, + bool is_static, + bool dynamic_vision) { ModelParams model_params; ComputeParams compute_params; + model_params.is_dynamic_vision = !is_static && dynamic_vision; + if (model_params.is_dynamic_vision) { + for (int i = 0; i < cgraph->n_nodes; ++i) { + const auto * node = cgraph->nodes[i]; + const auto name = get_tensor_ov_name(cgraph, node); + const auto * root = node->view_src ? node->view_src : node; + const bool weight = root->buffer && root->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS; + if ((node->op == GGML_OP_RESHAPE || node->op == GGML_OP_CONT) && !weight) { + const auto shape = get_shape(node); + compute_params.vision_shapes["vision_shape_" + name] = {shape.begin(), shape.end()}; + } + if (node->op == GGML_OP_UPSCALE) { + compute_params.vision_shapes["vision_size_" + name] = {node->ne[1], node->ne[0]}; + if ((node->op_params[0] & 0xff) == GGML_SCALE_MODE_BILINEAR && + (node->op_params[0] & GGML_SCALE_FLAG_ANTIALIAS)) { + compute_params.vision_projections["vision_y_" + name] = + ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[1], node->ne[1], false); + compute_params.vision_projections["vision_x_" + name] = + ov::frontend::ggml::bilinear_antialias_projection(node->src[0]->ne[0], node->ne[0], true); + } + } + } + } auto get_attention_pattern_case = [](const ggml_tensor * node) -> int { if (node == nullptr) { return -1; @@ -1492,6 +1637,11 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op, ov::PartialShape input_shape; bool kv_layout_4d = false; + if (m_model_params.is_dynamic_vision && input && op->op == GGML_OP_IM2COL && + input == op->src[1]) { + return ov::PartialShape{input->ne[3], input->ne[2], -1, -1}; + } + if (is_inp_tok(input, op) || is_inp_pos(input, op)) { // tokens or positions int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1; @@ -1706,6 +1856,22 @@ void GgmlOvDecoder::add_extra_inputs() { m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static, {}, -1}; }; + for (const auto & [name, shape] : m_compute_params.vision_shapes) { + m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{shape.size()}, 0, true, {}, -1}; + } + for (int i = 0; i < m_cgraph->n_nodes && !m_compute_params.vision_projections.empty(); ++i) { + const auto * node = m_cgraph->nodes[i]; + if (node->op != GGML_OP_UPSCALE) { continue; } + const auto name = get_tensor_ov_name(m_cgraph, node); + if (m_compute_params.vision_projections.count("vision_y_" + name) == 0) { continue; } + m_model_extra_inputs["vision_y_" + name] = {ov::element::f32, + ov::Shape{size_t(node->ne[1]), size_t(node->src[0]->ne[1])}, 0, true, {}, -1, + ov::PartialShape{-1, node->src[0]->ne[1]}}; + m_model_extra_inputs["vision_x_" + name] = {ov::element::f32, + ov::Shape{size_t(node->src[0]->ne[0]), size_t(node->ne[0])}, 0, true, {}, -1, + ov::PartialShape{node->src[0]->ne[0], -1}}; + } + if (m_compute_params.attention_size != -1) { create_1d_input("attention_size", m_compute_params.attention_size); } diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index f5e97efa3b0d..2085c1a36501 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -35,6 +35,7 @@ struct ModelParams { bool has_rs_rollback = false; bool mixed_rope_params = false; bool is_cacheless_attn = false; + bool is_dynamic_vision = false; // the graph writes a transposed V cache (`-fa off`: one value element per row, tokens along the row) bool v_trans = false; // the graph has FLASH_ATTN_EXT with logit soft-capping (gemma-2) @@ -140,6 +141,9 @@ struct ComputeParams { std::map sampling_rows; std::map gdn_attention_rows; std::map> recurrent_controls; + // GGML layout metadata that cannot be recovered after flattening a vision grid. + std::map> vision_shapes; + std::map> vision_projections; }; // defined below; declared here because GgmlOvDecoder uses it inline @@ -150,6 +154,12 @@ bool is_moe_expert_sum_add(const ggml_tensor * node); class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { public: + static bool is_dynamic_vision_graph(const ggml_cgraph * cgraph); + // OV order: -2 reads the runtime target; -1 infers one extent; nonnegative values are invariant. + static std::vector vision_reshape_pattern(const ggml_tensor * node); + std::vector get_vision_reshape_pattern(int node_idx) const override { + return vision_reshape_pattern(m_node_info_list[node_idx].node); + } static std::string get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor); struct NodeInfo { ggml_tensor * node; @@ -447,7 +457,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { void clear_model_weights() { m_model_weights.clear(); } - static std::pair compute_llm_params(ggml_cgraph * cgraph, bool is_static); + // The execution path supplies the structural vision classification once per compute. + static std::pair compute_llm_params(ggml_cgraph * cgraph, + bool is_static, + bool dynamic_vision = false); const ModelParams & get_model_params() const { return m_model_params; } @@ -526,7 +539,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { tensor->ne[3] != 1 || (tensor->buffer != nullptr && tensor->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS)) { return false; } - return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM) && op->src[0] == tensor && + // Gemma applies per-token scaling to supplied image embeddings. + const bool scaled_input = op->op == GGML_OP_MUL && (tensor->flags & GGML_TENSOR_FLAG_INPUT) && + is_inp_scale_rows(op->src[1], op); + return (op->op == GGML_OP_RMS_NORM || op->op == GGML_OP_L2_NORM || scaled_input) && op->src[0] == tensor && (tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY); } @@ -553,7 +569,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // per-token embedding scale [1, n_tokens] (inp->scale_rows in llama-graph.cpp) static bool is_inp_scale_rows(const ggml_tensor * tensor, const ggml_tensor * op) { - return op->op == GGML_OP_MUL && tensor == op->src[1] && strcmp(tensor->name, "inp_scale_rows") == 0; + return tensor && op->op == GGML_OP_MUL && tensor == op->src[1] && + (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->type == GGML_TYPE_F32 && + tensor->ne[0] == 1 && tensor->ne[2] == 1 && tensor->ne[3] == 1 && + op->src[0]->ne[1] == tensor->ne[1] && op->src[0]->ne[2] == 1 && op->src[0]->ne[3] == 1; } static bool is_rope_freqs_weight(const ggml_tensor * tensor, const ggml_tensor * op) { @@ -745,6 +764,8 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { op->src[0]->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY; } + std::string get_position_input_ov_name(const ggml_tensor * tensor) const; + private: void set_input_output(); int compute_op_case(const ggml_tensor * node) const; diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 2bc19c796299..2f03371c4902 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -1542,12 +1542,20 @@ static bool is_supported_flash_attn_pattern(const ggml_tensor * op) { // PERMUTE -> RESHAPE -> base (view_src==nullptr) (whisper Q) // VIEW -> base (view_src==nullptr) (whisper K/V from kv_pad) // PERMUTE -> VIEW -> RESHAPE -> base (Q of a layer without RoPE, e.g. SmolLM3) + // PERMUTE -> ROPE (view_src==nullptr) (cacheless vision Q/K) + // PERMUTE -> RMS_NORM (view_src==nullptr) (Gemma4 vision V) for (int i = 0; i < 3; i++) { const ggml_tensor * src = op->src[i]; if (src->op == GGML_OP_PERMUTE) { if (src->src[0] == nullptr) { return false; } + if (src->src[0]->op == GGML_OP_ROPE && src->src[0]->view_src == nullptr) { + continue; + } + if (i == 2 && src->src[0]->op == GGML_OP_RMS_NORM && src->src[0]->view_src == nullptr) { + continue; + } // MLA: Q = PERMUTE -> CONCAT(q_nope_absorbed, q_pe); V = PERMUTE -> VIEW -> VIEW -> K cache // (V is the first kv_lora_rank values of each K cache row) if (i == 0 && src->src[0]->op == GGML_OP_CONCAT) { @@ -1588,6 +1596,13 @@ static bool is_gemma3n_flash_attn_pattern(const ggml_tensor * op) { return false; } + // Gemma4 vision rotates the two head halves with consecutive spatial RoPEs. + const auto * q = op->src[0]; + if (q->op == GGML_OP_PERMUTE && q->src[0]->op == GGML_OP_ROPE && + q->src[0]->src[0] && q->src[0]->src[0]->op == GGML_OP_ROPE) { + return false; + } + const ggml_tensor * q_base = op->src[0] != nullptr && op->src[0]->src[0] != nullptr ? op->src[0]->src[0]->src[0] : nullptr; const ggml_tensor * k_base = diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 15a39f8166f8..4c4d3941d513 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; + // Optional model shape for runtime controls whose allocation changes per compute. PartialShape parameter_shape = PartialShape::dynamic(); }; @@ -135,6 +136,7 @@ class GgmlDecoder : public DecoderBase { virtual int is_swa_layer(int layer) const = 0; virtual int32_t get_op_dynamic_dim(int node_idx) const = 0; + virtual std::vector get_vision_reshape_pattern(int node_idx) const = 0; }; } // namespace ggml diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h index 51f7f63527be..d117267755cd 100644 --- a/ggml/src/ggml-openvino/openvino/node_context.h +++ b/ggml/src/ggml-openvino/openvino/node_context.h @@ -46,6 +46,7 @@ class NodeContext : public frontend::NodeContext { std::string get_output_name() const { return m_output_names[0]; } PartialShape get_output_shape() const { return m_decoder->get_output_shape(m_node_idx); } + std::vector get_vision_reshape_pattern() const { return m_decoder->get_vision_reshape_pattern(m_node_idx); } int32_t * get_input_op_params(size_t index) const { return m_decoder->get_input_op_params(m_node_idx, m_input_names[index]); @@ -120,9 +121,9 @@ class NodeContext : public frontend::NodeContext { auto base_it = m_tensor_map->find(base_name); // A multi-output translator can publish a VIEW directly without materializing // its packed parent (GatedDeltaNet attention/state). In that case the VIEW is the - // authoritative value. The node comparison retains the existing resolved-VIEW path. + // authoritative value. Compare output ports as well as nodes for resolved Split views. if (base_it == m_tensor_map->end() || - view_it->second.get_node_shared_ptr() != base_it->second.get_node_shared_ptr()) { + view_it->second != base_it->second) { return view_it->second; } return base_it->second; diff --git a/ggml/src/ggml-openvino/openvino/op/cont.cpp b/ggml/src/ggml-openvino/openvino/op/cont.cpp index 9888f6b93fd3..7ea7ee0833b7 100644 --- a/ggml/src/ggml-openvino/openvino/op/cont.cpp +++ b/ggml/src/ggml-openvino/openvino/op/cont.cpp @@ -18,6 +18,16 @@ OutputVector translate_cont(const NodeContext & context) { auto src_shape = context.get_input_shape(0).to_shape(); auto dst_shape = context.get_output_shape().to_shape(); + if (context.has_input("vision_shape_" + context.get_name())) { + auto input = process_view_input_new(context, 0); + // CONT without a layout change already has its runtime shape. + if (src_shape == dst_shape) { + return rename_outputs_with_suffix({input}, context.get_name()); + } + auto target = vision_reshape_target(context); + return rename_outputs_with_suffix({std::make_shared(input, target, false)}, context.get_name()); + } + if (context.get_op_dynamic_dim() != -1) { dst_shape[3 - context.get_op_dynamic_dim()] = -1; } 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 ea223973f559..cd6ef1ac530d 100644 --- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp +++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp @@ -389,7 +389,9 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) { res = std::make_shared( sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3})); } else { - auto sdpa = std::make_shared(q, k, v, scale_node, causal); + // SDPA's fourth input is a mask; use a neutral mask to pass the requested scale as input five. + auto neutral_mask = ov::op::v0::Constant::create(ov::element::f16, ov::Shape{}, {0.0f}); + auto sdpa = std::make_shared(q, k, v, neutral_mask, scale_node, causal); res = std::make_shared( sdpa, ov::op::v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3})); } diff --git a/ggml/src/ggml-openvino/openvino/op/im2col.cpp b/ggml/src/ggml-openvino/openvino/op/im2col.cpp index 469d1de1f466..e278023820a0 100644 --- a/ggml/src/ggml-openvino/openvino/op/im2col.cpp +++ b/ggml/src/ggml-openvino/openvino/op/im2col.cpp @@ -13,6 +13,8 @@ #include #include #include +#include +#include #include #include @@ -78,14 +80,13 @@ OutputVector translate_im2col(const NodeContext & context) { auto t1 = std::make_shared(patches, perm1); // [N, OH, OW, KH*KW*IC] → [N, OH, OW, KH*KW, IC] - const ov::Shape out_shape = t1->get_output_shape(0); - const size_t N = out_shape[0]; - const size_t OH = out_shape[1]; - const size_t OW = out_shape[2]; - auto reshape1_shape = ov::op::v0::Constant::create( - ov::element::i64, ov::Shape{5}, - std::vector{static_cast(N), static_cast(OH), static_cast(OW), - static_cast(KH * KW), static_cast(IC)}); + auto spatial_shape = std::make_shared( + std::make_shared(t1, ov::element::i64), + ov::op::v0::Constant::create(ov::element::i64, {3}, {0, 1, 2}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0})); + auto reshape1_shape = std::make_shared(ov::OutputVector{spatial_shape, + ov::op::v0::Constant::create(ov::element::i64, {2}, + std::vector{int64_t(KH * KW), int64_t(IC)})}, 0); auto r1 = std::make_shared(t1, reshape1_shape, false); // [N, OH, OW, KH*KW, IC] → [N, OH, OW, IC, KH*KW] @@ -93,13 +94,13 @@ OutputVector translate_im2col(const NodeContext & context) { auto t2 = std::make_shared(r1, perm2); // flatten back to [N, OH, OW, IC*KH*KW] - auto r2_shape = ov::op::v0::Constant::create( - ov::element::i64, ov::Shape{4}, - std::vector{static_cast(N), static_cast(OH), static_cast(OW), - static_cast(IC * KH * KW)}); + auto r2_shape = std::make_shared(ov::OutputVector{spatial_shape, + ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(IC * KH * KW)})}, 0); res = std::make_shared(t2, r2_shape, false); if (!is_2D) { + const auto out_shape = t1->get_output_shape(0); + const size_t N = out_shape[0], OW = out_shape[2]; // [N, 1, OW, IC * KW] -> [1, N, OW, IC * KW] auto final_reshape_shape = ov::op::v0::Constant::create( ov::element::i64, ov::Shape{4}, diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp index 203d3d396d54..c2d0ff8079c1 100644 --- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp +++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp @@ -19,6 +19,11 @@ namespace op { OutputVector translate_reshape(const NodeContext & context) { num_inputs_check(context, 1, 1); + if (context.has_input("vision_shape_" + context.get_name())) { + auto target = vision_reshape_target(context); + auto res = std::make_shared(context.get_input(0), target, false); + return rename_outputs_with_suffix({res}, context.get_name()); + } if (context.get_input(0).get_partial_shape().is_static() && context.get_input_shape(0) == context.get_output_shape()) { return {context.get_input(0)}; diff --git a/ggml/src/ggml-openvino/openvino/op/upscale.cpp b/ggml/src/ggml-openvino/openvino/op/upscale.cpp index 03f3a91b2e61..e9050e0399fb 100644 --- a/ggml/src/ggml-openvino/openvino/op/upscale.cpp +++ b/ggml/src/ggml-openvino/openvino/op/upscale.cpp @@ -26,7 +26,8 @@ OutputVector translate_upscale(const NodeContext & context) { const auto input_shape = context.get_input_shape(0).to_shape(); const auto output_shape = context.get_output_shape().to_shape(); - if (input_shape == output_shape) { + const bool dynamic = context.has_input("vision_size_" + context.get_name()); + if (!dynamic && input_shape == output_shape) { return rename_outputs_with_suffix({input}, context.get_name()); } @@ -49,7 +50,7 @@ OutputVector translate_upscale(const NodeContext & context) { } // Spatial interpolation for ne[1] and ne[0] (OV axes 2 and 3) - if (input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) { + if (dynamic || input_shape[2] != output_shape[2] || input_shape[3] != output_shape[3]) { const int32_t * op_params = context.get_output_op_params(); const int32_t mode_flags = op_params != nullptr ? op_params[0] : 0; @@ -63,65 +64,17 @@ OutputVector translate_upscale(const NodeContext & context) { const size_t H_out = output_shape[2]; const size_t W_out = output_shape[3]; - const float pixel_offset = 0.5f; - - // Height projection: [H_out, H_in] - std::vector Wy_data(H_out * H_in, 0.0f); - const float sf1 = static_cast(H_out) / H_in; - const float support1 = std::max(1.0f, 1.0f / sf1); - const float invscale1 = 1.0f / support1; - - for (size_t i1 = 0; i1 < H_out; ++i1) { - const float y = (static_cast(i1) + pixel_offset) / sf1; - const auto y_start = static_cast(y - support1 + pixel_offset); - const size_t y_min = y_start > 0 ? static_cast(y_start) : 0; - const auto y_end = static_cast(y + support1 + pixel_offset); - const size_t y_max = y_end > 0 ? std::min(static_cast(y_end), H_in) : 0; - - float total_weight = 0.0f; - for (size_t sy = y_min; sy < y_max; ++sy) { - float diff = std::abs((static_cast(sy) - y + pixel_offset) * invscale1); - float weight = std::max(1.0f - diff, 0.0f); - Wy_data[i1 * H_in + sy] = weight; - total_weight += weight; - } - if (total_weight > 0.0f) { - for (size_t sy = y_min; sy < y_max; ++sy) { - Wy_data[i1 * H_in + sy] /= total_weight; - } - } + ov::Output Wy_node, Wx_node; + if (dynamic) { + Wy_node = context.get_input("vision_y_" + context.get_name()); + Wx_node = context.get_input("vision_x_" + context.get_name()); + } else { + Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in}, + bilinear_antialias_projection(H_in, H_out, false)); + Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out}, + bilinear_antialias_projection(W_in, W_out, true)); } - // Width projection: [W_in, W_out] - std::vector Wx_data(W_in * W_out, 0.0f); - const float sf0 = static_cast(W_out) / W_in; - const float support0 = std::max(1.0f, 1.0f / sf0); - const float invscale0 = 1.0f / support0; - - for (size_t i0 = 0; i0 < W_out; ++i0) { - const float x = (static_cast(i0) + pixel_offset) / sf0; - const auto x_start = static_cast(x - support0 + pixel_offset); - const size_t x_min = x_start > 0 ? static_cast(x_start) : 0; - const auto x_end = static_cast(x + support0 + pixel_offset); - const size_t x_max = x_end > 0 ? std::min(static_cast(x_end), W_in) : 0; - - float total_weight = 0.0f; - for (size_t sx = x_min; sx < x_max; ++sx) { - float diff = std::abs((static_cast(sx) - x + pixel_offset) * invscale0); - float weight = std::max(1.0f - diff, 0.0f); - Wx_data[sx * W_out + i0] = weight; - total_weight += weight; - } - if (total_weight > 0.0f) { - for (size_t sx = x_min; sx < x_max; ++sx) { - Wx_data[sx * W_out + i0] /= total_weight; - } - } - } - - auto Wy_node = ov::op::v0::Constant::create(ov::element::f32, {H_out, H_in}, Wy_data); - auto Wx_node = ov::op::v0::Constant::create(ov::element::f32, {W_in, W_out}, Wx_data); - auto res_y = std::make_shared(Wy_node, res); res = std::make_shared(res_y, Wx_node); } else { @@ -163,7 +116,8 @@ OutputVector translate_upscale(const NodeContext & context) { static_cast(output_shape[3]) / static_cast(input_shape[3]), }; - auto target_shape_node = ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec); + ov::Output target_shape_node = dynamic ? context.get_input("vision_size_" + context.get_name()) : + ov::op::v0::Constant::create(ov::element::i64, {2}, target_shape_vec); auto scales_node = ov::op::v0::Constant::create(ov::element::f32, {2}, scales_vec); auto axes_node = ov::op::v0::Constant::create(ov::element::i64, {2}, {2, 3}); diff --git a/ggml/src/ggml-openvino/openvino/op/view.cpp b/ggml/src/ggml-openvino/openvino/op/view.cpp index 4ebe9c4b483a..eb4630bcb116 100644 --- a/ggml/src/ggml-openvino/openvino/op/view.cpp +++ b/ggml/src/ggml-openvino/openvino/op/view.cpp @@ -16,6 +16,17 @@ namespace op { OutputVector translate_view(const NodeContext & context) { num_inputs_check(context, 1, 1); + if (context.get_op_case() == 5) { + const auto shape = context.get_output_shape(); + // Keep the output gate grouped like GDN: [active sequences, tokens per sequence, heads, width]. + auto target = std::make_shared(ov::OutputVector{ + context.get_input("s_copy_active_slot_len"), + ov::op::v0::Constant::create(ov::element::i64, {3}, + std::vector{-1, shape[2].get_length(), shape[3].get_length()})}, 0); + return rename_outputs_with_suffix({std::make_shared(context.get_input(0), target, false)}, + context.get_name()); + } + if (context.get_op_case() == 3) { auto row = context.get_input("sampling_row_" + context.get_name()); auto selected = std::make_shared(context.get_input(0), row, diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp index 0a5d5b8c05cf..23402b0a141f 100644 --- a/ggml/src/ggml-openvino/openvino/utils.cpp +++ b/ggml/src/ggml-openvino/openvino/utils.cpp @@ -38,6 +38,48 @@ namespace ov { namespace frontend { namespace ggml { +ov::Output vision_reshape_target(const NodeContext & context) { + auto runtime = context.get_input("vision_shape_" + context.get_name()); + const auto pattern = context.get_vision_reshape_pattern(); + ov::OutputVector dimensions; + for (size_t axis = 0; axis < pattern.size(); ++axis) { + if (pattern[axis] == -2) { + dimensions.push_back(std::make_shared(runtime, + ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(axis)}), + ov::op::v0::Constant::create(ov::element::i64, {}, {0}))); + } else { + dimensions.push_back(ov::op::v0::Constant::create(ov::element::i64, {1}, {pattern[axis]})); + } + } + return std::make_shared(dimensions, 0); +} + +std::vector bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose) { + std::vector weights(input_size * output_size, 0.0f); + const float scale = static_cast(output_size) / input_size; + const float support = std::max(1.0f, 1.0f / scale); + const float invscale = 1.0f / support; + for (size_t out = 0; out < output_size; ++out) { + const float center = (static_cast(out) + 0.5f) / scale; + const auto start = static_cast(center - support + 0.5f); + const auto end = static_cast(center + support + 0.5f); + const size_t begin = start > 0 ? static_cast(start) : 0; + const size_t finish = end > 0 ? std::min(end, input_size) : 0; + float sum = 0.0f; + for (size_t in = begin; in < finish; ++in) { + const float weight = std::max(1.0f - std::abs((static_cast(in) - center + 0.5f) * invscale), 0.0f); + weights[transpose ? in * output_size + out : out * input_size + in] = weight; + sum += weight; + } + if (sum > 0.0f) { + for (size_t in = begin; in < finish; ++in) { + weights[transpose ? in * output_size + out : out * input_size + in] /= sum; + } + } + } + return weights; +} + void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs) { auto input_size = context.get_input_size(); FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected"); @@ -558,6 +600,14 @@ ov::Output process_view_input_new(const NodeContext & context, int inp return std::make_shared(part, target, false); } + // A translated VIEW is authoritative; packed-projection slicing applies only to its unresolved base. + const auto view_name = context.get_view_input_name(input_index, 0); + const auto base_name = context.get_view_input_src_name(input_index, view_input_size - 1); + if (context.has_input(view_name) && + (!context.has_input(base_name) || context.get_input(view_name) != context.get_input(base_name))) { + return input; + } + // Integer router views can share these strides when their row count is zero. // Packed projections can store query and gate in separate halves of each head. if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { @@ -591,8 +641,7 @@ ov::Output process_view_input_new(const NodeContext & context, int inp } } - if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real() && - context.has_input("s_copy_active_slot_len")) { + if (!context.is_static() && view_input_size == 1 && input.get_element_type().is_real()) { const auto source = context.get_view_input_src_ggml_shape(input_index, 0); const auto view = context.get_view_input_ggml_shape(input_index, 0); const auto source_stride = context.get_view_input_src_stride(input_index, 0); diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h index 499596e6f14b..194f08be5e76 100644 --- a/ggml/src/ggml-openvino/openvino/utils.h +++ b/ggml/src/ggml-openvino/openvino/utils.h @@ -21,6 +21,9 @@ std::shared_ptr get_dimensions(const std::shared_ptr & node, OutputVector rename_outputs_with_suffix(const OutputVector & outputs, const std::string & suffix); +std::vector bilinear_antialias_projection(size_t input_size, size_t output_size, bool transpose); +ov::Output vision_reshape_target(const NodeContext & context); + std::pair, ov::Output> make_sin_cos(int32_t * rope_params, std::shared_ptr inp_pos, std::shared_ptr rope_freqs_weight = nullptr, diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 9470302a7efa..8f833c93b05c 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -218,8 +218,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(); - // Preserve the fingerprint for graphs compiled without the old native cache update ops. - uint64_t extra_cfg = 18 * 131; + // Vision graphs carry runtime spatial shapes and independent position inputs. + uint64_t extra_cfg = 19 * 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); @@ -309,9 +309,11 @@ static std::string compiled_graph_key(const ggml_cgraph * graph, for (const auto & input : decoder.get_model_extra_inputs()) { append_string(input.first); append_string(input.second.type.get_type_name()); - append(input.second.shape.size()); - for (auto dim : input.second.shape) { - append(dim); + if (input.second.parameter_shape.rank().is_static()) { + append_string(input.second.parameter_shape.to_string()); + } else { + append(input.second.shape.size()); + for (auto dim : input.second.shape) { append(dim); } } append(input.second.is_parameter); if (!input.second.is_parameter) { @@ -336,7 +338,7 @@ static std::string dynamic_graph_signature(const ggml_cgraph * graph, append(value.size()); key.append(value); }; - graph_key graph_id(graph, true); + graph_key graph_id(graph, true, params.is_dynamic_vision); append(graph_id.n_nodes); append(graph_id.n_leaves); append_string(graph_id.first_node_name); @@ -767,7 +769,13 @@ ov::Tensor get_ov_input_tensor(const std::shared_ptr & ggml_decod } } input_tensor = cached; - if (param_name == "sampling_rows") { + if (param_name.compare(0, 13, "vision_shape_") == 0 || param_name.compare(0, 12, "vision_size_") == 0) { + const auto & values = ggml_decoder->get_compute_params().vision_shapes.at(param_name); + std::copy(values.begin(), values.end(), input_tensor.data()); + } else if (param_name.compare(0, 9, "vision_y_") == 0 || param_name.compare(0, 9, "vision_x_") == 0) { + const auto & values = ggml_decoder->get_compute_params().vision_projections.at(param_name); + std::copy(values.begin(), values.end(), input_tensor.data()); + } else if (param_name == "sampling_rows") { auto * data = input_tensor.data(); for (const auto & row : ggml_decoder->get_compute_params().sampling_rows) { *data++ = row.second; @@ -1249,7 +1257,8 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share // graph_key first (a few hundred us), and if the same key is already in decoder_cache // we know the graph is not splitted (only not-splitted graphs get inserted there). const int64_t cache_key_start_time = ggml_time_us(); - graph_key key(cgraph); + const bool dynamic_vision = GgmlOvDecoder::is_dynamic_vision_graph(cgraph); + graph_key key(cgraph, false, dynamic_vision); const int64_t cache_key_compute_time = ggml_time_us() - cache_key_start_time; int64_t cache_lookup_time = 0; bool key_seen = false; @@ -1279,7 +1288,7 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share ModelParams m_params; ComputeParams c_params; const int64_t graph_param_compute_start_time = ggml_time_us(); - std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static); + std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static, dynamic_vision); const int64_t graph_param_compute_time = ggml_time_us() - graph_param_compute_start_time; const bool cache_enabled = !model_is_splitted && !cache_disabled; diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 3db84a2541a7..43a2d986052e 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -1,6 +1,7 @@ #include "ggml-decoder.h" #include "ggml-impl.h" #include "ggml-openvino-extra.h" +#include "ggml-openvino.h" #include "model-cache.h" #include @@ -23,24 +24,44 @@ // graph during inference, where the same few graphs repeat for the whole session. The list of // external input names below tells those apart more precisely, but it walks every node and every // src slot, so it is built only when GGML_OPENVINO_FULL_GRAPH_KEY is set. Sampler row names are -// always included to distinguish sampler configurations, even when active subsets share the packed input. Op tests run -// many small graphs that can share a node count and end names, and need the full key. +// always included, along with weight allocation generations. Static or unqualified image graphs +// also include input shapes. Op tests run many small graphs that can share a node count and end +// names, and need the full key. struct graph_key { int n_nodes; int n_leaves; std::string first_node_name; std::string last_node_name; - // External source descriptors "::" and sampler row Parameter names. + // External source descriptors, sampler row names, image shapes and weight allocation generations. std::vector input_srcs; - graph_key(const ggml_cgraph * cgraph, bool include_inputs = false) : n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { + graph_key(const ggml_cgraph * cgraph, bool include_inputs = false, bool dynamic_vision = false) : + n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { if (n_nodes > 0) { first_node_name = cgraph->nodes[0]->name; last_node_name = cgraph->nodes[n_nodes - 1]->name; } + std::unordered_set weight_buffers; for (int i = 0; i < n_nodes; ++i) { const auto * node = cgraph->nodes[i]; + // A later model load may use the same graph names and shapes but new + // weights. Allocation generations survive pointer reuse, whereas + // the lightweight topology key alone would select stale Constants. + for (const auto * src : node->src) { + if (!src) { + continue; + } + const auto * root = src->view_src ? src->view_src : src; + const auto buffer = root->buffer; + if (buffer && buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS && + weight_buffers.insert(buffer).second) { + const auto id = ggml_backend_openvino_buffer_get_ctx_id(buffer); + if (id != 0) { + input_srcs.push_back("weight_buffer:" + std::to_string(id)); + } + } + } if (GgmlOvDecoder::is_sampling_view(node)) { input_srcs.push_back("sampling_row_" + std::string(node->name) + "#n" + std::to_string(i)); } @@ -49,6 +70,24 @@ struct graph_key { if (node->flags & GGML_TENSOR_FLAG_OUTPUT) { input_srcs.push_back("output_" + std::string(node->name) + "#n" + std::to_string(i)); } + // Qualified vision graphs reuse a fixed model configuration; only spatial sizes vary. + // Static or unqualified image graphs keep their full input shape in the key. + if (!dynamic_vision && (node->op == GGML_OP_CONV_2D || node->op == GGML_OP_CONV_2D_DW || + node->op == GGML_OP_IM2COL) && node->src[1] != nullptr) { + const auto * input = node->src[1]; + const auto * root = input->view_src ? input->view_src : input; + // Gemma4 normalizes image pixels with SCALE before patch extraction. + while (root->op == GGML_OP_SCALE && root->src[0]) { + root = root->src[0]->view_src ? root->src[0]->view_src : root->src[0]; + } + if (root->flags & GGML_TENSOR_FLAG_INPUT) { + std::string shape = "image_input_" + std::to_string(i) + ":" + root->name; + for (int dim = 0; dim < GGML_MAX_DIMS; ++dim) { + shape += ":" + std::to_string(root->ne[dim]); + } + input_srcs.push_back(std::move(shape)); + } + } } static const bool full_key = ggml_openvino_getenv_int("GGML_OPENVINO_FULL_GRAPH_KEY") != 0; From a3ad48104a8d3a5f2eb48ceac5cfb99a33773e26 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Fri, 20 Nov 2026 08:13:05 +0100 Subject: [PATCH 10/19] ggml-openvino: keep allocation IDs out of persistent cache signatures Store weight allocation generations separately from graph descriptors. Private cache keys retain allocation isolation, while dynamic model fingerprints stay stable when the same source weights are reloaded. --- ggml/src/ggml-openvino/utils.h | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index 43a2d986052e..da081f992fd3 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -32,8 +32,10 @@ struct graph_key { int n_leaves; std::string first_node_name; std::string last_node_name; - // External source descriptors, sampler row names, image shapes and weight allocation generations. + // External source descriptors, sampler row names and image shapes. std::vector input_srcs; + // Process-local identities used only by the private cache key. + std::vector weight_buffer_ids; graph_key(const ggml_cgraph * cgraph, bool include_inputs = false, bool dynamic_vision = false) : n_nodes(cgraph->n_nodes), n_leaves(cgraph->n_leafs) { @@ -58,7 +60,7 @@ struct graph_key { weight_buffers.insert(buffer).second) { const auto id = ggml_backend_openvino_buffer_get_ctx_id(buffer); if (id != 0) { - input_srcs.push_back("weight_buffer:" + std::to_string(id)); + weight_buffer_ids.push_back(id); } } } @@ -117,7 +119,8 @@ struct graph_key { bool operator==(const graph_key & other) const { return n_nodes == other.n_nodes && n_leaves == other.n_leaves && first_node_name == other.first_node_name && - last_node_name == other.last_node_name && input_srcs == other.input_srcs; + last_node_name == other.last_node_name && input_srcs == other.input_srcs && + weight_buffer_ids == other.weight_buffer_ids; } }; @@ -132,6 +135,9 @@ struct graph_key_hash { for (const auto & s : key.input_srcs) { hash ^= std::hash{}(s) + 0x9e3779b9 + (hash << 6) + (hash >> 2); } + for (const auto id : key.weight_buffer_ids) { + hash ^= std::hash{}(id) + 0x9e3779b9 + (hash << 6) + (hash >> 2); + } return hash; } }; From 1d172cb7251496d2c2a1514351a071b98c76842e Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Tue, 24 Nov 2026 08:29:28 +0100 Subject: [PATCH 11/19] ggml-openvino: preserve explicit F32 MatMul precision per node Honor GGML_PREC_F32 on MatMul src1 with node precision guards and precision-sensitive input paths, including grouped-query attention. Keep other branches at their configured precision. Probe the runtime helper and include precision guards in cache identities. Validated on the local OpenVINO 2026.5.1 CPU/GPU runtime: 12/12 F32 precision cases under CPU default, CPU BF16 and GPU FP16 hints; mixed-precision branches and cached F32/default/F32 transitions; five real audio preprocessing lengths per device. --- ggml/src/ggml-openvino/CMakeLists.txt | 17 +++++++++ ggml/src/ggml-openvino/ggml-openvino.cpp | 12 +++++- ggml/src/ggml-openvino/model-cache.cpp | 3 +- ggml/src/ggml-openvino/openvino/op/mulmat.cpp | 38 +++++++++++++++++-- .../openvino/precision_control.hpp | 12 ++++++ ggml/src/ggml-openvino/utils.h | 4 ++ 6 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/precision_control.hpp diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index a33da0677815..fc37d48c1304 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -27,3 +27,20 @@ endif() if (WIN32) target_link_libraries(ggml-openvino PRIVATE psapi) endif() + +# Precision-sensitive MatMul needs a node-level guard, not a whole-model precision hint. +unset(GGML_OPENVINO_HAS_PRECISION_CONTROL CACHE) +set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) +set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino") +check_cxx_source_compiles("#include +int main() { + std::shared_ptr node; + ov::disable_conversion(node, ov::element::f16); + ov::disable_conversion(node, ov::element::bf16); +}" + GGML_OPENVINO_HAS_PRECISION_CONTROL) +unset(CMAKE_REQUIRED_LIBRARIES) +unset(CMAKE_REQUIRED_INCLUDES) +if(GGML_OPENVINO_HAS_PRECISION_CONTROL) + target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_PRECISION_CONTROL=1) +endif() diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 2f03371c4902..90d720c7b6a8 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -2007,9 +2007,17 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { break; } case GGML_OP_MUL_MAT: { - if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16 || ggml_prec_get_src(op, 1) == GGML_PREC_F32) { - return {false, "MUL_MAT with a BF16 or F32 src1 precision is not supported"}; + if (ggml_prec_get_src(op, 1) == GGML_PREC_BF16) { + return {false, "MUL_MAT with a BF16 src1 precision is not supported"}; } + if (ggml_prec_get_src(op, 1) == GGML_PREC_F32 && ggml_openvino_is_npu()) { + return {false, "MUL_MAT with F32 src1 precision requires CPU or GPU"}; + } +#ifndef GGML_OPENVINO_HAS_PRECISION_CONTROL + if (ggml_prec_get_src(op, 1) == GGML_PREC_F32) { + return {false, "MUL_MAT with F32 src1 precision requires OpenVINO node precision control"}; + } +#endif if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[1] != nullptr && ggml_is_quantized(op->src[0]->type) && strcmp(op->src[0]->name, "a") == 0 && strcmp(op->src[1]->name, "b") == 0 && op->src[0]->ne[1] == 1 && op->src[1]->ne[1] == 64 && diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp index 74ba8a1cecba..e4ed6e6cd89e 100644 --- a/ggml/src/ggml-openvino/model-cache.cpp +++ b/ggml/src/ggml-openvino/model-cache.cpp @@ -334,7 +334,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph, // Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in. // Version 10 hashes only whether GGML_OPENVINO_PROFILING is 2 or more (it then compiles with enable_profiling), // and no longer GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS, which only changes the output bindings. - h = fnv1a_u64(h, 10); + // Version 11 honors explicit F32 MatMul input precision with node-level guards. + h = fnv1a_u64(h, 11); 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/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp index 45fc1a547390..874e5e68b7f1 100644 --- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp +++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp @@ -1,6 +1,11 @@ #include "../node_context.h" #include "../op_table.h" #include "../utils.h" +#include "ggml.h" + +#ifdef GGML_OPENVINO_HAS_PRECISION_CONTROL +# include "../precision_control.hpp" +#endif #include #include @@ -16,6 +21,7 @@ #include #include #include +#include #include namespace ov { @@ -33,10 +39,36 @@ OutputVector translate_mulmat(const NodeContext & context) { // the stateful V cache with `-fa off` is not transposed (see permute) const bool transpose_b = B.get_node()->get_rt_info().count(GGML_OV_V_TOKEN_MAJOR) == 0; - if (A.get_element_type() != B.get_element_type()) { + // MUL_MAT stores the minimum src1 precision in op_params[3]. + const auto * params = context.get_output_op_params(); + const bool preserve_f32 = params != nullptr && params[3] == GGML_PREC_F32; + if (preserve_f32) { + if (A.get_element_type() != ov::element::f32) { + A = std::make_shared(A, ov::element::f32); + } + if (B.get_element_type() != ov::element::f32) { + B = std::make_shared(B, ov::element::f32); + } + } else if (A.get_element_type() != B.get_element_type()) { B = std::make_shared(B, context.get_input_type(1)); } + auto make_matmul = [&](const ov::Output & a, const ov::Output & b) { + auto node = std::make_shared(a, b, false, transpose_b); + if (preserve_f32) { +#ifdef GGML_OPENVINO_HAS_PRECISION_CONTROL + // Keep this MatMul and its input layout/conversion paths in F32; other branches keep their precision. + ov::disable_conversion(node, ov::element::f16); + ov::disable_conversion(node, ov::element::bf16); + ov::mark_as_precision_sensitive(node->input(0)); + ov::mark_as_precision_sensitive(node->input(1)); +#else + FRONT_END_CHECK_IMPLEMENTED(false, "F32 MatMul input precision requires OpenVINO node precision control"); +#endif + } + return node; + }; + auto B_shape = context.get_input_shape(0).to_shape(); auto A_shape = context.get_input_shape(1).to_shape(); int64_t A_batch = A_shape[1]; @@ -68,7 +100,7 @@ OutputVector translate_mulmat(const NodeContext & context) { A_reshape->get_input_partial_shape(0)[1] == batch_small) { A_grouped = A_reshape->input_value(0); } - ov::Output res = std::make_shared(A_grouped, B, false, transpose_b); + ov::Output res = make_matmul(A_grouped, B); res = std::make_shared( res, ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector{0, batch_large, -1, 0}), true); @@ -107,7 +139,7 @@ OutputVector translate_mulmat(const NodeContext & context) { A = Z; } - ov::Output res = std::make_shared(A, B, false, transpose_b); + ov::Output res = make_matmul(A, B); const auto output_type = context.get_output_type(); if (res.get_element_type() != output_type) { diff --git a/ggml/src/ggml-openvino/openvino/precision_control.hpp b/ggml/src/ggml-openvino/openvino/precision_control.hpp new file mode 100644 index 000000000000..40b6c0d9bb02 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/precision_control.hpp @@ -0,0 +1,12 @@ +#pragma once + +#include + +#if __has_include() +# include +#else +// Runtime SDKs omit transformation headers. CMake checks that this exported helper is available. +namespace ov { +OPENVINO_API void disable_conversion(const std::shared_ptr & node, const element::Type & to); +} +#endif diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h index da081f992fd3..c0b263f6fbd8 100644 --- a/ggml/src/ggml-openvino/utils.h +++ b/ggml/src/ggml-openvino/utils.h @@ -47,6 +47,10 @@ struct graph_key { std::unordered_set weight_buffers; for (int i = 0; i < n_nodes; ++i) { const auto * node = cgraph->nodes[i]; + if (node->op == GGML_OP_MUL_MAT && ggml_prec_get_src(node, 1) == GGML_PREC_F32) { + // Node precision guards are part of the compiled graph, including in the dynamic disk cache. + input_srcs.push_back("f32_matmul_" + std::to_string(i)); + } // A later model load may use the same graph names and shapes but new // weights. Allocation generations survive pointer reuse, whereas // the lightweight topology key alone would select stale Constants. From 0de408b74377c5bb36bb785102191be8507f62b5 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 07:51:57 +0100 Subject: [PATCH 12/19] ggml-openvino: remove the node precision availability guard The official OpenVINO 2026.4.1 Runtime SDK exports the node precision helper. Remove its link probe and conditional fallback while retaining the Runtime SDK declaration shim and the recurrent-cache-op guard. Validated the downloaded SDK with a compiled/linked API probe and 12/12 F32 MatMul cases on default CPU and FP16-hint GPU. The local 2026.5.1 build also passes 12/12 on each device. An additional 2026.4.1 CPU BF16-hint check has seven precision failures, independent of this availability-guard removal. --- ggml/src/ggml-openvino/CMakeLists.txt | 17 ----------------- ggml/src/ggml-openvino/ggml-openvino.cpp | 5 ----- ggml/src/ggml-openvino/openvino/op/mulmat.cpp | 8 +------- .../openvino/precision_control.hpp | 2 +- 4 files changed, 2 insertions(+), 30 deletions(-) diff --git a/ggml/src/ggml-openvino/CMakeLists.txt b/ggml/src/ggml-openvino/CMakeLists.txt index fc37d48c1304..a33da0677815 100644 --- a/ggml/src/ggml-openvino/CMakeLists.txt +++ b/ggml/src/ggml-openvino/CMakeLists.txt @@ -27,20 +27,3 @@ endif() if (WIN32) target_link_libraries(ggml-openvino PRIVATE psapi) endif() - -# Precision-sensitive MatMul needs a node-level guard, not a whole-model precision hint. -unset(GGML_OPENVINO_HAS_PRECISION_CONTROL CACHE) -set(CMAKE_REQUIRED_LIBRARIES openvino::runtime) -set(CMAKE_REQUIRED_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/openvino") -check_cxx_source_compiles("#include -int main() { - std::shared_ptr node; - ov::disable_conversion(node, ov::element::f16); - ov::disable_conversion(node, ov::element::bf16); -}" - GGML_OPENVINO_HAS_PRECISION_CONTROL) -unset(CMAKE_REQUIRED_LIBRARIES) -unset(CMAKE_REQUIRED_INCLUDES) -if(GGML_OPENVINO_HAS_PRECISION_CONTROL) - target_compile_definitions(ggml-openvino PRIVATE GGML_OPENVINO_HAS_PRECISION_CONTROL=1) -endif() diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 90d720c7b6a8..968c8c2c80be 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -2013,11 +2013,6 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) { if (ggml_prec_get_src(op, 1) == GGML_PREC_F32 && ggml_openvino_is_npu()) { return {false, "MUL_MAT with F32 src1 precision requires CPU or GPU"}; } -#ifndef GGML_OPENVINO_HAS_PRECISION_CONTROL - if (ggml_prec_get_src(op, 1) == GGML_PREC_F32) { - return {false, "MUL_MAT with F32 src1 precision requires OpenVINO node precision control"}; - } -#endif if (ggml_openvino_is_gpu() && op->src[0] != nullptr && op->src[1] != nullptr && ggml_is_quantized(op->src[0]->type) && strcmp(op->src[0]->name, "a") == 0 && strcmp(op->src[1]->name, "b") == 0 && op->src[0]->ne[1] == 1 && op->src[1]->ne[1] == 64 && diff --git a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp index 874e5e68b7f1..d129128198a4 100644 --- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp +++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp @@ -3,9 +3,7 @@ #include "../utils.h" #include "ggml.h" -#ifdef GGML_OPENVINO_HAS_PRECISION_CONTROL -# include "../precision_control.hpp" -#endif +#include "../precision_control.hpp" #include #include @@ -56,15 +54,11 @@ OutputVector translate_mulmat(const NodeContext & context) { auto make_matmul = [&](const ov::Output & a, const ov::Output & b) { auto node = std::make_shared(a, b, false, transpose_b); if (preserve_f32) { -#ifdef GGML_OPENVINO_HAS_PRECISION_CONTROL // Keep this MatMul and its input layout/conversion paths in F32; other branches keep their precision. ov::disable_conversion(node, ov::element::f16); ov::disable_conversion(node, ov::element::bf16); ov::mark_as_precision_sensitive(node->input(0)); ov::mark_as_precision_sensitive(node->input(1)); -#else - FRONT_END_CHECK_IMPLEMENTED(false, "F32 MatMul input precision requires OpenVINO node precision control"); -#endif } return node; }; diff --git a/ggml/src/ggml-openvino/openvino/precision_control.hpp b/ggml/src/ggml-openvino/openvino/precision_control.hpp index 40b6c0d9bb02..8f260af199ee 100644 --- a/ggml/src/ggml-openvino/openvino/precision_control.hpp +++ b/ggml/src/ggml-openvino/openvino/precision_control.hpp @@ -5,7 +5,7 @@ #if __has_include() # include #else -// Runtime SDKs omit transformation headers. CMake checks that this exported helper is available. +// Runtime SDKs omit transformation headers; this exported helper is present in OpenVINO 2026.4.1. namespace ov { OPENVINO_API void disable_conversion(const std::shared_ptr & node, const element::Type & to); } From b8b4254b5ca849d9711086524cae615d69005ae8 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 09:04:03 +0100 Subject: [PATCH 13/19] ggml-openvino: document pending audio dynamics and preprocessing caching Assisted-by: Codex --- ggml/src/ggml-openvino/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ggml/src/ggml-openvino/README.md b/ggml/src/ggml-openvino/README.md index d520328c6469..520236dc203d 100644 --- a/ggml/src/ggml-openvino/README.md +++ b/ggml/src/ggml-openvino/README.md @@ -92,4 +92,6 @@ projectors. Four-slot serving was validated with unified and split KV. Qwen3.5 reuses its vision graph across image resolutions; Gemma4 uses resolution-specific encoder graphs. -Gemma4 audio is not enabled. Static/NPU multimodal execution is untested. +Gemma4 audio is not enabled: preprocessing and Conformer still need dynamic length/block handling, runtime padding and view/state offsets, and cross-length compiled-model reuse. The small weightless preprocessing graph currently runs uncached because of the naive path's node-count heuristic. + +Static/NPU multimodal execution is untested. From 993cdc3d1d46ebe57c7a000bbabefd4e893a7a16 Mon Sep 17 00:00:00 2001 From: "Yu, Zijun" Date: Thu, 26 Nov 2026 09:31:23 +0100 Subject: [PATCH 14/19] ggml-openvino: declare the node precision helper in mulmat Move the exported helper declaration into mulmat.cpp and remove the single-consumer precision_control.hpp header. Validated builds and 12/12 F32 MatMul cases on CPU/GPU with both the local OpenVINO build and the official 2026.4.1 Runtime SDK. Assisted-by: Codex --- ggml/src/ggml-openvino/openvino/op/mulmat.cpp | 5 +++-- .../src/ggml-openvino/openvino/precision_control.hpp | 12 ------------ 2 files changed, 3 insertions(+), 14 deletions(-) delete mode 100644 ggml/src/ggml-openvino/openvino/precision_control.hpp diff --git a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp index d129128198a4..4ef1c78712d6 100644 --- a/ggml/src/ggml-openvino/openvino/op/mulmat.cpp +++ b/ggml/src/ggml-openvino/openvino/op/mulmat.cpp @@ -3,8 +3,6 @@ #include "../utils.h" #include "ggml.h" -#include "../precision_control.hpp" - #include #include #include @@ -23,6 +21,9 @@ #include namespace ov { +// Runtime SDKs omit the transformation header but export this helper. +OPENVINO_API void disable_conversion(const std::shared_ptr & node, const element::Type & to); + namespace frontend { namespace ggml { namespace op { diff --git a/ggml/src/ggml-openvino/openvino/precision_control.hpp b/ggml/src/ggml-openvino/openvino/precision_control.hpp deleted file mode 100644 index 8f260af199ee..000000000000 --- a/ggml/src/ggml-openvino/openvino/precision_control.hpp +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -#if __has_include() -# include -#else -// Runtime SDKs omit transformation headers; this exported helper is present in OpenVINO 2026.4.1. -namespace ov { -OPENVINO_API void disable_conversion(const std::shared_ptr & node, const element::Type & to); -} -#endif From a57b17605b3bf4b966d35d4276e0c19d40d1b769 Mon Sep 17 00:00:00 2001 From: yzhou51 Date: Fri, 20 Nov 2026 10:14:16 +0800 Subject: [PATCH 15/19] ggml-openvino: Enable MOE models on NPU for Qwen3.6-35B-A3B NPUW, the partitioning layer of the NPU plugin, has its own MoE support. It isolates the experts into functions and runs only the routed experts for each token, with the router on the host (the `HOST_ROUTED` mode). This PR translates the MoE block of a model into the form NPUW recognises, and sets the NPUW properties for that mode. --- docs/backend/OPENVINO.md | 23 +++ .../dev_doc/OpenVINO-ENV-VARS.md | 14 +- ggml/src/ggml-openvino/device/npu_config.cpp | 36 +++- ggml/src/ggml-openvino/device/npu_config.h | 6 + ggml/src/ggml-openvino/ggml-decoder.cpp | 120 ++++++++++++- ggml/src/ggml-openvino/ggml-decoder.h | 19 +- .../src/ggml-openvino/ggml-openvino-extra.cpp | 4 + ggml/src/ggml-openvino/ggml-openvino-extra.h | 7 + ggml/src/ggml-openvino/openvino/decoder.h | 3 + .../src/ggml-openvino/openvino/node_context.h | 2 + ggml/src/ggml-openvino/openvino/op/add.cpp | 8 + .../ggml-openvino/openvino/op/moe_tiled.cpp | 168 ++++++++++++++++++ ggml/src/ggml-openvino/openvino/op_table.h | 1 + ggml/src/ggml-openvino/utils.cpp | 23 ++- 14 files changed, 427 insertions(+), 7 deletions(-) create mode 100644 ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index f645f25d3f05..d141991516e9 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -1035,6 +1035,29 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - Lunar Lake NPU: `gemma-4-12B` does not run. The first inference fails with `ZE_RESULT_ERROR_UNINITIALIZED` from the NPU driver. The model runs on CPU and GPU. - The first load of a model on the NPU compiles it for the device, which can take minutes for large models. - **Workaround:** Use the [compiled model cache](#compiled-model-cache). +- MoE models with a softmax router and SwiGLU experts (for example Qwen3.6-35B-A3B) run on the NPU through the MoE support of NPUW: only the routed experts run for each token, with the router on the host. Tested with `Qwen3.6-35B-A3B-Q4_0` on Panther Lake (Windows) and Lunar Lake (Windows, Ubuntu) systems with 32 GB. + - A 35B MoE model needs nearly all of a 32 GB system: the backend and NPUW each hold a copy of the weights (about 18 GB each), and the NPU can address 18 GB of the shared memory. Use a small context and these settings: + + ```bash + export GGML_OPENVINO_DEVICE=NPU + export GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 + export GGML_OPENVINO_NPU_CONFIG="NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1" + ./llama-cli -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 + ``` + + ```bat + REM Windows + set GGML_OPENVINO_DEVICE=NPU + set GGML_OPENVINO_PREFILL_CHUNK_SIZE=128 + set GGML_OPENVINO_NPU_CONFIG=NPUW_WEIGHTS_BANK_ALLOC=CPU,NPUW_FUNCALL_ASYNC=NO,COMPILATION_NUM_THREADS=1 + llama-cli.exe -m Qwen_Qwen3.6-35B-A3B-Q4_0.gguf -c 256 + ``` + + - `NPUW_WEIGHTS_BANK_ALLOC=CPU` keeps the NPUW copy of the weights in host memory instead of the NPU-addressable memory, at some cost in speed. + - `NPUW_FUNCALL_ASYNC=NO` and `COMPILATION_NUM_THREADS=1` lower the memory peak. `GGML_OPENVINO_COMPILATION_NUM_THREADS=1` is an older name for the second one. + - The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties)). Without them the load can hang on a 32 GB system. + - The NPU compiler type can stay unset: models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO. `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result. + - `llama-perplexity` with these models: use a `-c` of at most twice `GGML_OPENVINO_PREFILL_CHUNK_SIZE` (for example `-c 256` with a chunk size of 128). The output rows of the last layer must not exceed the chunk size. > [!NOTE] > The OpenVINO backend is actively under development. Fixes and improvements are underway, and this document will continue to be updated. 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 8424460a038c..e371d50be7fa 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -84,7 +84,7 @@ These options are off by default. They are not validated for general use: some h | `GGML_OPENVINO_NPU_REQUANT_POLICY` | NPU | String | `group-128` | Layout of requantized weights: `group-128` (`Q4_0_128`) or `channel-wise` (`Q4_0_C`, lower accuracy). | | `GGML_OPENVINO_GDN_DECOMPOSE_CHUNK` | all | Integer | `16` | Tokens in one chunk when `GGML_OPENVINO_GDN_DECOMPOSE` is on. A power of 2 from 2 to 128; other values use `16`. | | `GGML_OPENVINO_GDN_NATIVE_STATE` | NPU | Boolean | `0` | Keep the `GATED_DELTA_NET` state in the layout of the OpenVINO op instead of the GGML layout. Every `GATED_DELTA_NET` must then run on the OpenVINO backend; the load aborts if one would run on the CPU backend. Saved states and `GGML_OPENVINO_DEBUG_NODE` dumps hold the OpenVINO layout. `test-backend-ops` fails with it. | -| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | +| `GGML_OPENVINO_FORCE_STATIC` | CPU, GPU | Boolean | `0` | Run the static-shape path of the NPU on the CPU or the GPU, to separate translation bugs from NPU plugin or driver problems. This includes the NPU translation of MoE blocks, which computes every expert on the CPU or the GPU and is slow. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | | `GGML_OPENVINO_ENABLE_FALLBACK` | all | Boolean | `0` | Detect graphs that the scheduler splits between OpenVINO and another backend, and translate them as partial graphs, without the compiled model cache. By default every graph is treated as a complete model graph. Cannot be used with `GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY`. | | `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)))`. | @@ -174,6 +174,18 @@ The backend sets the properties below for the NPU. `GGML_OPENVINO_NPU_CONFIG` ca | `NPU_COMPILER_TYPE` | String | `DRIVER` | `PREFER_PLUGIN` | The NPU compiler: `DRIVER` (in the NPU driver), `PLUGIN` (in OpenVINO) or `PREFER_PLUGIN` (`PLUGIN` when it is available, `DRIVER` if not). Models with `GATED_DELTA_NET` layers (Qwen3.5) compile with `PLUGIN` unless the user sets this property. | | `NPUW_CACHE_DIR` | String | value of `GGML_OPENVINO_CACHE_DIR` | empty | Directory for the compiled parts. | +Graphs with a MoE block (softmax router and SwiGLU experts, translated into the batched form that NPUW recognises) also get the properties below. They make NPUW run only the routed experts, with the router on the host (the `HOST_ROUTED` mode of `NPUW_LLM_*_MOE_HINT`). `GGML_OPENVINO_NPU_CONFIG` can change them. + +| Property | Type | Backend default | OpenVINO default | Description | +|---|---|---|---|---| +| `NPUW_ONLINE_PIPELINE` | String | `REP` | `REG` | Partitioning pipeline. `REP` finds the repeating blocks, which the MoE support needs. | +| `NPUW_ONLINE_ISOLATE` | String | `MOE` added | empty | Isolate the experts into their own functions. Added to a value that is already set. | +| `NPUW_ONLINE_KEEP_BLOCKS_TAGGED` | String | `expert` added | empty | Keep the isolated experts even below the repeating-block threshold. | +| `NPUW_ONLINE_KEEP_BLOCK_SIZE` | Integer | `4` | `10` | Smallest repeating block that is kept. | +| `NPUW_UNFOLD_IREQS` | Boolean | `NO` | `NO` | One infer request for each part. | +| `NPUW_MOE_TOKEN_CHUNK_SIZE` | Integer | `16` | `0` | Tokens per expert call in prefill. `0` compiles 8 sizes (16 to 512); one small size uses less memory. | +| `NPUW_MOE_POOL_SIZE` | Integer | `0` | `8` | Infer requests per MoE layer kept for decode, each bound to a set of experts. With 40 MoE layers, the default of 8 fills the NPU memory of a 32 GB system and the load hangs. | + Other properties that are useful with `GGML_OPENVINO_NPU_CONFIG`. The backend does not set them. | Property | Type | Backend default | OpenVINO default | Description | diff --git a/ggml/src/ggml-openvino/device/npu_config.cpp b/ggml/src/ggml-openvino/device/npu_config.cpp index 637083066ee7..0c469adac8b5 100644 --- a/ggml/src/ggml-openvino/device/npu_config.cpp +++ b/ggml/src/ggml-openvino/device/npu_config.cpp @@ -78,6 +78,35 @@ ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base) { return gdn_config; } +ov::AnyMap ggml_openvino_npu_moe_config(const ov::AnyMap & base) { + ov::AnyMap moe_config = base; + // Same properties as the HOST_ROUTED hint of the NPUW LLM pipeline (apply_moe_config) + moe_config.insert({"NPUW_ONLINE_PIPELINE", "REP"}); + moe_config.insert({"NPUW_ONLINE_KEEP_BLOCK_SIZE", "4"}); + moe_config.insert({"NPUW_UNFOLD_IREQS", "NO"}); + // NPUW keeps a pool of 8 infer requests per MoE layer for decode, caching the requests bound to a set of + // experts. Each one holds NPU memory: with 40 MoE layers (Qwen3.6-35B-A3B) the pool fills the 18 GB the NPU can + // address on a 32 GB system and the load hangs. A cache hit needs the same experts as an earlier token, which is + // rare with 256 experts, so the pool is off by default. + moe_config.insert({"NPUW_MOE_POOL_SIZE", "0"}); + // Prefill runs the routed experts in chunks of tokens. By default NPUW compiles 8 chunk sizes (16 to 512); a + // 128-token chunk gives each of 256 experts about 4 tokens, so one small size is enough. + moe_config.insert({"NPUW_MOE_TOKEN_CHUNK_SIZE", "16"}); + // tags are appended to the ones that are set + auto append_tag = [&](const char * key, const std::string & tag) { + auto it = moe_config.find(key); + const std::string current = it == moe_config.end() ? "" : it->second.as(); + if (current.empty()) { + moe_config[key] = tag; + } else if (("," + current + ",").find("," + tag + ",") == std::string::npos) { + moe_config[key] = current + "," + tag; + } + }; + append_tag("NPUW_ONLINE_KEEP_BLOCKS_TAGGED", "expert"); + append_tag("NPUW_ONLINE_ISOLATE", "MOE"); + return moe_config; +} + ov::AnyMap ggml_openvino_npu_without_npuw(const ov::AnyMap & config) { ov::AnyMap out; for (const auto & kv : config) { @@ -94,7 +123,12 @@ ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlO if (ggml_openvino_npu_hfa_prefill_enabled()) { prefill_config["NPUW_ATTN_HISTORY_SIZE_INPUT"] = decoder.get_hfa_history_input_name(); prefill_config["NPUW_ONLINE_PIPELINE"] = "REP"; - prefill_config["NPUW_ONLINE_ISOLATE"] = "ATTN"; + // keep the tags of a MoE graph + const auto isolate = prefill_config.find("NPUW_ONLINE_ISOLATE"); + prefill_config["NPUW_ONLINE_ISOLATE"] = + isolate != prefill_config.end() && !isolate->second.as().empty() ? + "ATTN," + isolate->second.as() : + std::string("ATTN"); prefill_config["NPUW_ONLINE_KEEP_BLOCK_SIZE"] = "4"; prefill_config["NPUW_UNFOLD_IREQS"] = "NO"; prefill_config["NPUW_ATTN"] = "HFA"; diff --git a/ggml/src/ggml-openvino/device/npu_config.h b/ggml/src/ggml-openvino/device/npu_config.h index 89f41da5402b..0773422e27b6 100644 --- a/ggml/src/ggml-openvino/device/npu_config.h +++ b/ggml/src/ggml-openvino/device/npu_config.h @@ -25,6 +25,12 @@ ov::AnyMap ggml_openvino_npu_gdn_config(const ov::AnyMap & base); // True when ggml_openvino_npu_gdn_config() switches the compiler. Part of the model cache key. bool ggml_openvino_npu_gdn_uses_plugin_compiler(); +// Graphs with a MoE block in the batched form (see translate_moe_tiled). NPUW isolates the +// experts into functions and runs only the routed experts per token, with the router on the host (the HOST_ROUTED mode of +// NPUW_LLM_*_MOE_HINT, which only the NPUW LLM pipeline sets itself), with one expert chunk size and no expert request +// pool. Keys the environment already sets (GGML_OPENVINO_NPU_CONFIG) are kept. +ov::AnyMap ggml_openvino_npu_moe_config(const ov::AnyMap & base); + // Static prefill graph. With GGML_OPENVINO_NPU_HFA_PREFILL, switches NPUW to the HFA attention pipeline. ov::AnyMap ggml_openvino_npu_prefill_config(const ov::AnyMap & base, const GgmlOvDecoder & decoder); diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 91e967ad99df..354cb9f526f9 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -269,6 +269,90 @@ bool is_moe_expert_sum_add(const ggml_tensor * node) { return base != nullptr && base->ne[1] > 1 && plane_indices.size() == static_cast(base->ne[1]); } +// Walks the graph that build_moe_ffn emits for a softmax router with SwiGLU experts: +// probs = softmax(logits); ids = top_k(probs); w = get_rows(probs, ids); [w = w / clamp(sum_rows(w))] +// out = sum_i(down(swiglu(gate(x, ids), up(x, ids)), ids)[i] * w[i]) +// and returns false for any other shape of the block (bias on the router, sigmoid gating, scaled weights, GELU ...). +bool match_moe_block(const ggml_tensor * sum_add, moe_block & block) { + // build_moe_ffn reshapes the router probs and the weights between the steps matched below + auto skip_reshape = [](const ggml_tensor * t) { + while (t != nullptr && t->op == GGML_OP_RESHAPE) { + t = t->src[0]; + } + return t; + }; + + if (sum_add->op != GGML_OP_ADD || !is_moe_expert_sum_add(sum_add)) { + return false; + } + const ggml_tensor * plane = sum_add; + while (plane->op == GGML_OP_ADD) { + plane = plane->src[0]; + } + const ggml_tensor * weighted = plane->src[0]; + if (weighted == nullptr || weighted->op != GGML_OP_MUL) { + return false; + } + const ggml_tensor * down = weighted->src[0]; + if (down == nullptr || down->op != GGML_OP_MUL_MAT_ID) { + return false; + } + const ggml_tensor * glu = down->src[1]; + if (glu == nullptr || glu->op != GGML_OP_GLU || ggml_get_glu_op(glu) != GGML_GLU_OP_SWIGLU || + ggml_get_op_params_i32(glu, 1) != 0) { + return false; + } + const ggml_tensor * gate = glu->src[0]; + const ggml_tensor * up = glu->src[1]; + const ggml_tensor * ids = down->src[2]; + if (gate == nullptr || up == nullptr || gate->op != GGML_OP_MUL_MAT_ID || up->op != GGML_OP_MUL_MAT_ID || + gate->src[1] != up->src[1] || gate->src[2] != ids || up->src[2] != ids) { + return false; + } + // ids = view(argsort(probs)) or top_k(probs) + const ggml_tensor * selection = ids; + while (selection != nullptr && selection->op == GGML_OP_VIEW) { + selection = selection->src[0]; + } + if (selection == nullptr || (selection->op != GGML_OP_ARGSORT && selection->op != GGML_OP_TOP_K) || + selection->src[0] == nullptr || selection->src[0]->op != GGML_OP_SOFT_MAX) { + return false; + } + const ggml_tensor * probs = selection->src[0]; + + const ggml_tensor * w = skip_reshape(weighted->src[1]); + const ggml_tensor * clamp = nullptr; + if (w != nullptr && w->op == GGML_OP_DIV) { + const ggml_tensor * den = w->src[1]; + if (den == nullptr || den->op != GGML_OP_CLAMP || den->src[0] == nullptr || + den->src[0]->op != GGML_OP_SUM_ROWS || skip_reshape(den->src[0]->src[0]) != skip_reshape(w->src[0])) { + return false; + } + float bounds[2]; + memcpy(bounds, den->op_params, sizeof(bounds)); + if (bounds[1] < 1e30f) { + return false; // only a lower bound is translated + } + clamp = den; + w = skip_reshape(w->src[0]); + } + if (w == nullptr || w->op != GGML_OP_GET_ROWS || w->src[1] != ids || skip_reshape(w->src[0]) != probs) { + return false; + } + if (gate->src[0]->ne[2] != probs->ne[0] || gate->src[0]->ne[2] <= ids->ne[0]) { + return false; + } + + block.probs = probs; + block.x = gate->src[1]; + block.gate = gate->src[0]; + block.up = up->src[0]; + block.down = down->src[0]; + block.down_out = down; + block.clamp = clamp; + return true; +} + std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) { if (tensor == nullptr) { return ""; @@ -367,6 +451,7 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder, } void GgmlOvDecoder::set_input_output() { + m_moe_tiled_replaced.clear(); for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) { auto * node = m_cgraph->nodes[node_n]; @@ -418,6 +503,28 @@ void GgmlOvDecoder::set_input_output() { } } + // The expert sum of a MoE block also reads the router, the input and the expert weights (translate_moe_tiled). + moe_block block; + if (ggml_openvino_moe_tiled_enabled() && match_moe_block(node, block)) { + for (const ggml_tensor * t : {block.probs, block.x, block.gate, block.up, block.down, block.down_out, block.clamp}) { + if (t != nullptr) { + auto name = get_tensor_ov_name(m_cgraph, t); + current_node_info.node_inputs[name] = const_cast(t); + current_node_info.node_inputs_names.push_back(name); + } + } + // the ADD chain below this node and its expert-plane VIEWs + for (const ggml_tensor * cur = node; cur->op == GGML_OP_ADD; cur = cur->src[0]) { + if (cur != node) { + m_moe_tiled_replaced.insert(cur); + } + m_moe_tiled_replaced.insert(cur->src[1]); + if (cur->src[0]->op != GGML_OP_ADD) { + m_moe_tiled_replaced.insert(cur->src[0]); + } + } + } + m_node_info_list.push_back(current_node_info); } } @@ -745,6 +852,9 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { if (is_sampling_view(node)) { return 3; } + if (m_moe_tiled_replaced.count(node)) { + return 1; // identity: expert-plane view of an expert sum replaced by translate_moe_tiled + } if (node->view_offs == 0 && node->src[0]->op == GGML_OP_GET_ROWS && is_recurrent_cache(node->src[0]->src[0]) && node->ne[0] == node->src[0]->ne[0] && node->ne[2] == 1 && node->ne[3] == 1 && m_compute_params.s_copy_active_slot_len != -1) { @@ -899,7 +1009,15 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const { break; } case GGML_OP_ADD: { - if (is_moe_expert_sum_add(node)) { + if (m_moe_tiled_replaced.count(node)) { + op_case = 4; // inner ADD of an expert sum replaced by translate_moe_tiled + break; + } + moe_block block; + if (ggml_openvino_moe_tiled_enabled() && match_moe_block(node, block)) { + // The whole MoE block in the batched form: 2 with the weights as they are, 3 normalized and clamped + op_case = block.clamp != nullptr ? 3 : 2; + } else if (is_moe_expert_sum_add(node)) { // Outermost ADD of a MoE expert-plane sum chain: translated as a single // ReduceSum over the base tensor instead of N-1 chained Adds over N Slices. op_case = 1; diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index 2085c1a36501..cedb33471cef 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -152,6 +152,19 @@ std::optional extract_layer_from_name(const std::string & name); // detects the MoE expert-plane-sum ADD chain (see definition); used by supports_op too bool is_moe_expert_sum_add(const ggml_tensor * node); +// The tensors of one MoE block (build_moe_ffn: softmax router, top-k, SwiGLU experts, weighted expert sum), found from the +// outermost ADD of the expert sum. Used to translate the block as a whole (see translate_moe_tiled). +struct moe_block { + const ggml_tensor * probs = nullptr; // router SOFT_MAX + const ggml_tensor * x = nullptr; // input of the gate and up projections + const ggml_tensor * gate = nullptr; // expert weights [k, m, n_expert] + const ggml_tensor * up = nullptr; + const ggml_tensor * down = nullptr; + const ggml_tensor * down_out = nullptr; // MUL_MAT_ID of the down projection, [n_embd, n_expert_used, n_tokens] + const ggml_tensor * clamp = nullptr; // CLAMP of the weight sum when the top-k weights are normalized +}; +bool match_moe_block(const ggml_tensor * sum_add, moe_block & block); + class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { public: static bool is_dynamic_vision_graph(const ggml_cgraph * cgraph); @@ -372,7 +385,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { virtual bool is_prefill() const override { return m_is_prefill; } - int get_static_n_tokens() const { return m_is_prefill ? m_prefill_chunk_size : 1; } + virtual int get_static_n_tokens() const override { return m_is_prefill ? m_prefill_chunk_size : 1; } virtual bool is_splited_model() const override { return m_model_is_splitted; } @@ -798,6 +811,10 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { std::vector m_node_info_list; std::map m_node_dynamic_dims; std::set m_kvcache_4d; + // The expert-plane VIEWs and inner ADDs of the expert sums that translate_moe_tiled replaces. They are not + // used, and are translated as pass-throughs: building them can fail, e.g. a VIEW of the last layer whose row + // count (the output rows) differs from the one its static shape was derived with. + std::set m_moe_tiled_replaced; struct kv_tensor_entry { const void * data = nullptr; diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp index 7b254e3454b5..f5ea5c6dad1c 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp @@ -586,6 +586,10 @@ bool ggml_openvino_gdn_decompose_enabled() { return ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE", ggml_openvino_npu_is_4000() ? 1 : 0) > 0; } +bool ggml_openvino_moe_tiled_enabled() { + return ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC") != 0; +} + int ggml_openvino_gdn_decompose_chunk() { const int chunk = ggml_openvino_getenv_int("GGML_OPENVINO_GDN_DECOMPOSE_CHUNK"); if (chunk >= 2 && chunk <= 128 && (chunk & (chunk - 1)) == 0) { diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h index 7c4d1bdb6a67..0dd4e35e4de8 100644 --- a/ggml/src/ggml-openvino/ggml-openvino-extra.h +++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h @@ -256,6 +256,13 @@ bool ggml_openvino_npu_is_4000(); // Snapshot (MTP) graphs still use the op. bool ggml_openvino_gdn_decompose_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. +// On for the NPU, and with GGML_OPENVINO_FORCE_STATIC on the CPU or the GPU, which then computes every expert: that +// mode reproduces the NPU path to check the translation. +bool ggml_openvino_moe_tiled_enabled(); + // Tokens per chunk of the decomposed GATED_DELTA_NET: GGML_OPENVINO_GDN_DECOMPOSE_CHUNK, // a power of 2 in [2, 128], default 16. int ggml_openvino_gdn_decompose_chunk(); diff --git a/ggml/src/ggml-openvino/openvino/decoder.h b/ggml/src/ggml-openvino/openvino/decoder.h index 4c4d3941d513..ad2c556cfa4a 100644 --- a/ggml/src/ggml-openvino/openvino/decoder.h +++ b/ggml/src/ggml-openvino/openvino/decoder.h @@ -131,6 +131,9 @@ class GgmlDecoder : public DecoderBase { virtual bool is_prefill() const = 0; + // Tokens of a static graph: the prefill chunk size or 1 for decode + virtual int get_static_n_tokens() const = 0; + virtual bool is_splited_model() const = 0; virtual int is_swa_layer(int layer) const = 0; diff --git a/ggml/src/ggml-openvino/openvino/node_context.h b/ggml/src/ggml-openvino/openvino/node_context.h index d117267755cd..d49d1d97f2cd 100644 --- a/ggml/src/ggml-openvino/openvino/node_context.h +++ b/ggml/src/ggml-openvino/openvino/node_context.h @@ -161,6 +161,8 @@ class NodeContext : public frontend::NodeContext { bool is_prefill() const { return m_decoder->is_prefill(); } + int get_static_n_tokens() const { return m_decoder->get_static_n_tokens(); } + int get_ssm_state_size() const { return m_decoder->get_ssm_state_size(); } private: diff --git a/ggml/src/ggml-openvino/openvino/op/add.cpp b/ggml/src/ggml-openvino/openvino/op/add.cpp index 84bc85618a3b..fea6384fb042 100644 --- a/ggml/src/ggml-openvino/openvino/op/add.cpp +++ b/ggml/src/ggml-openvino/openvino/op/add.cpp @@ -15,6 +15,14 @@ namespace ggml { namespace op { OutputVector translate_add(const NodeContext & context) { + if (context.get_op_case() == 2 || context.get_op_case() == 3) { + return translate_moe_tiled(context); + } + if (context.get_op_case() == 4) { + // Inner ADD of an expert sum that translate_moe_tiled replaces: not used, so pass input 0 through + // instead of building the Add and the slices of its VIEW inputs. + return {context.get_input(0)}; + } num_inputs_check(context, 2, 2); if (context.get_op_case() == 1) { diff --git a/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp b/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp new file mode 100644 index 000000000000..0c6b5b3337a5 --- /dev/null +++ b/ggml/src/ggml-openvino/openvino/op/moe_tiled.cpp @@ -0,0 +1,168 @@ +#include "../node_context.h" +#include "../op_table.h" +#include "../utils.h" + +#include +#include +#include +#include + +namespace ov { +namespace frontend { +namespace ggml { +namespace op { + +namespace { + +ov::Output const_i32(const std::vector & values) { + return ov::op::v0::Constant::create(ov::element::i32, ov::Shape{values.size()}, values); +} + +ov::Output const_i32_scalar(int32_t value) { + return ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {value}); +} + +// Expert weights as [n_expert, rows, cols] in the type of the activations +ov::Output expert_weights_3d(ov::Output weights, + int64_t n_expert, + const ov::element::Type & type) { + const auto rank = weights.get_partial_shape().rank(); + FRONT_END_OP_CONVERSION_CHECK(rank.is_static(), "Expected static rank for MoE expert weights"); + if (rank.get_length() == 4) { + const auto shape = weights.get_partial_shape(); + FRONT_END_OP_CONVERSION_CHECK(shape.is_static(), "Expected static shape for MoE expert weights"); + weights = std::make_shared( + weights, + const_i32({static_cast(n_expert), static_cast(shape[2].get_length()), + static_cast(shape[3].get_length())}), + false); + } + if (weights.get_element_type() != type) { + weights = std::make_shared(weights, type); + } + return weights; +} + +} // namespace + +// The MoE block in the batched form that the NPUW MoE support (intel_npu/src/plugin/npuw/moe*) looks for; the same graph +// optimum-intel exports for Qwen3-30B-A3B. Every expert is computed for every token and the result is weighted by the +// router scores scattered to all experts (0 for a not selected one); NPUW runs only the routed experts. +// +// router: probs -> TopK(K) -> [ReduceSum -> Maximum -> Divide] -> ScatterElementsUpdate(zeros, ids, scores) +// -> Transpose -> Reshape [n_expert, 1, n_tokens] -> Unsqueeze = scores [n_expert, 1, n_tokens, 1] +// experts: x -> Tile -> Reshape [n_expert, n_tokens, n_embd] -> MatMul(gate) -> Swish, MatMul(up) -> Multiply +// -> MatMul(down) -> Reshape [n_expert, 1, n_tokens, n_embd] -> Multiply(scores) -> ReduceSum(axis 0) +// +// Inputs of the node (see GgmlOvDecoder::set_input_output): the two ADD operands, then router probs, x, the gate, up and +// down expert weights, the down MUL_MAT_ID (for the number of used experts) and, for op case 3, the CLAMP of the weights. +OutputVector translate_moe_tiled(const NodeContext & context) { + const bool normalize = context.get_op_case() == 3; + num_inputs_check(context, normalize ? 9 : 8, normalize ? 9 : 8); + + auto probs = context.get_input(2); + auto x = context.get_input(3); + const auto act_type = x.get_element_type(); + + // ggml [n_embd, n_ff, n_expert] and [n_ff, n_embd, n_expert] -> OV [1, n_expert, rows, cols] + const auto gate_shape = context.get_input_shape(4); + FRONT_END_OP_CONVERSION_CHECK(gate_shape.rank().is_static() && gate_shape.rank().get_length() == 4 && + gate_shape.is_static(), + "MoE expert weights need a static 4D shape"); + const int64_t n_expert = gate_shape[1].get_length(); + const int64_t n_embd = gate_shape[3].get_length(); + // down MUL_MAT_ID: ggml [n_embd, n_expert_used, n_tokens] -> OV [1, n_tokens, n_expert_used, n_embd] + const auto used_shape = context.get_input_shape(7); + FRONT_END_OP_CONVERSION_CHECK(used_shape[2].is_static(), "MoE needs a static number of used experts"); + const int32_t n_used = static_cast(used_shape[2].get_length()); + + auto gate_w = expert_weights_3d(context.get_input(4), n_expert, act_type); + auto up_w = expert_weights_3d(context.get_input(5), n_expert, act_type); + auto down_w = expert_weights_3d(context.get_input(6), n_expert, act_type); + + ov::Output x_2d = + std::make_shared(x, const_i32({-1, static_cast(n_embd)}), false); + ov::Output probs_2d = + std::make_shared(probs, const_i32({-1, static_cast(n_expert)}), false); + + // In a static graph the last layer can run on fewer tokens than the graph: its rows are selected by the output ids + // (1 row in the prefill graph). Pad the block to the tokens of the graph, so that it is the same as the block of the + // other layers: NPUW only lowers MoE blocks that it folds into one repeated function. The padded rows are zero and + // are dropped after the block. + int64_t n_rows = -1; + int64_t n_pad = 0; + if (context.is_static()) { + const auto rows = x_2d.get_partial_shape()[0]; + FRONT_END_OP_CONVERSION_CHECK(rows.is_static(), "MoE needs a static number of tokens in a static graph"); + n_rows = rows.get_length(); + n_pad = context.get_static_n_tokens() - n_rows; + } + if (n_pad > 0) { + auto pad = [&](const ov::Output & input) { + return std::make_shared( + input, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {0, 0}), + ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, {n_pad, int64_t{0}}), + ov::op::v0::Constant::create(input.get_element_type(), ov::Shape{}, {0.0f}), ov::op::PadMode::CONSTANT); + }; + x_2d = pad(x_2d); + probs_2d = pad(probs_2d); + } + + // Router + auto topk = std::make_shared(probs_2d, const_i32_scalar(n_used), 1, + ov::op::v11::TopK::Mode::MAX, ov::op::v11::TopK::SortType::SORT_VALUES, + ov::element::i32); + ov::Output scores = topk->output(0); + if (normalize) { + float clamp_min; + memcpy(&clamp_min, context.get_input_op_params(8), sizeof(clamp_min)); + auto sum = std::make_shared(scores, const_i32({1}), true); + auto denominator = std::make_shared( + sum, ov::op::v0::Constant::create(scores.get_element_type(), ov::Shape{}, {clamp_min})); + scores = std::make_shared(scores, denominator); + } + auto zeros = std::make_shared( + ov::op::v0::Constant::create(scores.get_element_type(), ov::Shape{}, {0.0f}), + std::make_shared(probs_2d, ov::element::i32), ov::op::BroadcastType::NUMPY); + auto scatter = std::make_shared(zeros, topk->output(1), scores, + const_i32_scalar(1)); + auto transposed = std::make_shared(scatter, const_i32({1, 0})); + auto reshaped = std::make_shared(transposed, const_i32({static_cast(n_expert), 1, -1}), + false); + auto router_scores = std::make_shared(reshaped, const_i32_scalar(3)); + + // Experts + auto tiled = std::make_shared(x_2d, const_i32({static_cast(n_expert), 1})); + auto expert_in = std::make_shared( + tiled, const_i32({static_cast(n_expert), -1, static_cast(n_embd)}), false); + auto gate_out = std::make_shared(expert_in, gate_w, false, true); + auto activated = std::make_shared(gate_out); + auto up_out = std::make_shared(expert_in, up_w, false, true); + auto merged = std::make_shared(activated, up_out); + auto down_out = std::make_shared(merged, down_w, false, true); + auto expert_out = std::make_shared( + down_out, const_i32({static_cast(n_expert), 1, -1, static_cast(n_embd)}), false); + auto weighted = std::make_shared(expert_out, router_scores); + ov::Output reduced = std::make_shared(weighted, const_i32({0}), false); + if (n_pad > 0) { + // [1, tokens, n_embd]: keep the rows of the block + reduced = std::make_shared( + reduced, ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {0}), + ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {n_rows}), + ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1}), + ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {1})); + } + + // ggml [n_embd, n_tokens] -> OV [1, 1, n_tokens, n_embd] + ov::Output result = std::make_shared( + reduced, const_i32({1, 1, -1, static_cast(n_embd)}), false); + if (result.get_element_type() != context.get_output_type()) { + result = std::make_shared(result, context.get_output_type()); + } + return rename_outputs_with_suffix({result}, context.get_name()); +} + +} // namespace op +} // namespace ggml +} // namespace frontend +} // namespace ov diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h index b26a23373232..37acac0efadd 100644 --- a/ggml/src/ggml-openvino/openvino/op_table.h +++ b/ggml/src/ggml-openvino/openvino/op_table.h @@ -22,6 +22,7 @@ GGML_OP_CONVERTER(translate_im2col); GGML_OP_CONVERTER(translate_im2col_3d); GGML_OP_CONVERTER(translate_mulmat); GGML_OP_CONVERTER(translate_mul_mat_id); +GGML_OP_CONVERTER(translate_moe_tiled); GGML_OP_CONVERTER(translate_permute); GGML_OP_CONVERTER(translate_reshape); GGML_OP_CONVERTER(translate_rms_norm); diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index 8f833c93b05c..f4bed44c06bf 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -2598,9 +2598,26 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared fprintf(stderr, "GGML OpenVINO profiling: static graph kind=%s, input_tokens=%lld, chunk_size=%d\n", is_prefill ? "prefill" : "decode", static_cast(input_tokens), prefill_chunk_size); } - 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; + // Compile properties for this graph: cacheless (encoder) graphs compile on the plain NPU plugin, graphs with + // GATED_DELTA_NET layers may switch the compiler (see npu_config.h), the others take the base config. + 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; + // A graph with a MoE block that translate_moe_tiled turns into the batched form also needs the NPUW properties + // that make NPUW isolate the experts and run only the routed ones (ggml_openvino_npu_moe_config). They are + // NPUW properties, so not for cacheless graphs, which compile without NPUW, and not for the static path that + // GGML_OPENVINO_FORCE_STATIC runs on the CPU or the GPU. One matching block is enough: the properties apply to + // the whole graph. + if (!no_kv_cache && device == "NPU" && ggml_openvino_moe_tiled_enabled()) { + for (int i = 0; i < cgraph->n_nodes; i++) { + // match_moe_block() takes the outermost ADD of an expert sum, the node translate_moe_tiled replaces + moe_block block; + if (cgraph->nodes[i]->op == GGML_OP_ADD && match_moe_block(cgraph->nodes[i], block)) { + compile_config = ggml_openvino_npu_moe_config(compile_config); + break; + } + } + } // Decided by the first call of a graph; later calls follow entry->kv_only_prefill. // The output step runs the decode model of the KV window covering the output token (the full context without // decode KV windows). From 665cadde6fff3ce3e9f4ae142462769f0cab939e Mon Sep 17 00:00:00 2001 From: ravi9 Date: Sat, 21 Nov 2026 10:25:19 +0530 Subject: [PATCH 16/19] ggml-openvino: find the moe block once per decoder for the npu config ov_graph_compute_static scanned every node of the graph for a MoE block on each call, cache hits included, to choose the NPUW MoE properties. set_input_output already matches each MoE block when the decoder is built, so it now records the result in GgmlOvDecoder::has_moe_block(), and the properties are added from that flag when a graph compiles. The properties are the same as before. --- ggml/src/ggml-openvino/ggml-decoder.cpp | 2 ++ ggml/src/ggml-openvino/ggml-decoder.h | 4 ++++ ggml/src/ggml-openvino/utils.cpp | 31 +++++++++---------------- 3 files changed, 17 insertions(+), 20 deletions(-) diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp index 354cb9f526f9..dd4b76bca6ab 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.cpp +++ b/ggml/src/ggml-openvino/ggml-decoder.cpp @@ -452,6 +452,7 @@ static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder, void GgmlOvDecoder::set_input_output() { m_moe_tiled_replaced.clear(); + m_has_moe_block = false; for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) { auto * node = m_cgraph->nodes[node_n]; @@ -506,6 +507,7 @@ void GgmlOvDecoder::set_input_output() { // The expert sum of a MoE block also reads the router, the input and the expert weights (translate_moe_tiled). moe_block block; if (ggml_openvino_moe_tiled_enabled() && match_moe_block(node, block)) { + m_has_moe_block = true; for (const ggml_tensor * t : {block.probs, block.x, block.gate, block.up, block.down, block.down_out, block.clamp}) { if (t != nullptr) { auto name = get_tensor_ov_name(m_cgraph, t); diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h index cedb33471cef..a27ca69c7dc1 100644 --- a/ggml/src/ggml-openvino/ggml-decoder.h +++ b/ggml/src/ggml-openvino/ggml-decoder.h @@ -389,6 +389,9 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { virtual bool is_splited_model() const override { return m_model_is_splitted; } + // The graph has a MoE block that translate_moe_tiled translates (found in set_input_output) + bool has_moe_block() const { return m_has_moe_block; } + ov::PartialShape get_graph_input_shape(const ggml_tensor * op, const ggml_tensor * input, int dynamic_dim_index = -1) const; @@ -815,6 +818,7 @@ class GgmlOvDecoder : public ov::frontend::ggml::GgmlDecoder { // used, and are translated as pass-throughs: building them can fail, e.g. a VIEW of the last layer whose row // count (the output rows) differs from the one its static shape was derived with. std::set m_moe_tiled_replaced; + bool m_has_moe_block = false; struct kv_tensor_entry { const void * data = nullptr; diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp index f4bed44c06bf..0855df5ce93e 100644 --- a/ggml/src/ggml-openvino/utils.cpp +++ b/ggml/src/ggml-openvino/utils.cpp @@ -2385,8 +2385,14 @@ static ov::AnyMap static_variant_config(const static_graph_args & a, const decoder_runtime_ctx & e, const GgmlOvDecoder & decoder, bool prefill) { - ov::AnyMap config = prefill ? ggml_openvino_npu_prefill_config(a.compile_config, decoder) : - ggml_openvino_npu_decode_config(a.compile_config, a.device); + // A graph with a MoE block that translate_moe_tiled turns into the batched form also needs the NPUW properties + // that make NPUW isolate the experts and run only the routed ones (ggml_openvino_npu_moe_config). They are + // NPUW properties, so not for cacheless graphs, which compile without NPUW, and not for the static path that + // GGML_OPENVINO_FORCE_STATIC runs on the CPU or the GPU. The decoder finds the block once, when it is built. + const bool moe = !a.no_kv_cache && a.device == "NPU" && decoder.has_moe_block(); + const ov::AnyMap base = moe ? ggml_openvino_npu_moe_config(a.compile_config) : a.compile_config; + ov::AnyMap config = prefill ? ggml_openvino_npu_prefill_config(base, decoder) : + ggml_openvino_npu_decode_config(base, a.device); if (!a.model_cache_dir.empty()) { config.erase("CACHE_DIR"); config.erase("CACHE_MODE"); @@ -2600,24 +2606,9 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared } // Compile properties for this graph: cacheless (encoder) graphs compile on the plain NPU plugin, graphs with // GATED_DELTA_NET layers may switch the compiler (see npu_config.h), the others take the base config. - 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; - // A graph with a MoE block that translate_moe_tiled turns into the batched form also needs the NPUW properties - // that make NPUW isolate the experts and run only the routed ones (ggml_openvino_npu_moe_config). They are - // NPUW properties, so not for cacheless graphs, which compile without NPUW, and not for the static path that - // GGML_OPENVINO_FORCE_STATIC runs on the CPU or the GPU. One matching block is enough: the properties apply to - // the whole graph. - if (!no_kv_cache && device == "NPU" && ggml_openvino_moe_tiled_enabled()) { - for (int i = 0; i < cgraph->n_nodes; i++) { - // match_moe_block() takes the outermost ADD of an expert sum, the node translate_moe_tiled replaces - moe_block block; - if (cgraph->nodes[i]->op == GGML_OP_ADD && match_moe_block(cgraph->nodes[i], block)) { - compile_config = ggml_openvino_npu_moe_config(compile_config); - break; - } - } - } + 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 by the first call of a graph; later calls follow entry->kv_only_prefill. // The output step runs the decode model of the KV window covering the output token (the full context without // decode KV windows). From 35b8f3a9b0defbc09dc2a5f707b1cb6ba173fd00 Mon Sep 17 00:00:00 2001 From: yzhou51 Date: Fri, 27 Nov 2026 13:49:26 +0800 Subject: [PATCH 17/19] ggml-openvino: docs: OpenVINO version and Linux memory setting for MoE models on the NPU --- docs/backend/OPENVINO.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md index d141991516e9..829ed69b3bde 100644 --- a/docs/backend/OPENVINO.md +++ b/docs/backend/OPENVINO.md @@ -1036,6 +1036,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - The first load of a model on the NPU compiles it for the device, which can take minutes for large models. - **Workaround:** Use the [compiled model cache](#compiled-model-cache). - MoE models with a softmax router and SwiGLU experts (for example Qwen3.6-35B-A3B) run on the NPU through the MoE support of NPUW: only the routed experts run for each token, with the router on the host. Tested with `Qwen3.6-35B-A3B-Q4_0` on Panther Lake (Windows) and Lunar Lake (Windows, Ubuntu) systems with 32 GB. + - Requires an OpenVINO build newer than 2026.4.1: a nightly build, or a build from the master branch after 2026-10-19. These models depend on two NPUW changes that 2026.4.1 does not have, [#38123](https://github.com/openvinotoolkit/openvino/pull/38123) (MoE mixing scores) and [#38124](https://github.com/openvinotoolkit/openvino/pull/38124) (batched MoE matching). With 2026.4.1 the model runs without an error, but the output is wrong: on `Qwen3.6-35B-A3B-Q4_0` the perplexity is 4.6 times that of the CPU, against 1.05 times with a master build. - A 35B MoE model needs nearly all of a 32 GB system: the backend and NPUW each hold a copy of the weights (about 18 GB each), and the NPU can address 18 GB of the shared memory. Use a small context and these settings: ```bash @@ -1057,6 +1058,7 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M. - `NPUW_FUNCALL_ASYNC=NO` and `COMPILATION_NUM_THREADS=1` lower the memory peak. `GGML_OPENVINO_COMPILATION_NUM_THREADS=1` is an older name for the second one. - The backend sets `NPUW_MOE_POOL_SIZE=0` and `NPUW_MOE_TOKEN_CHUNK_SIZE=16` itself for MoE models (see the [developer documentation](../../ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md#npu-plugin-properties)). Without them the load can hang on a 32 GB system. - The NPU compiler type can stay unset: models with `GATED_DELTA_NET` layers, such as Qwen3.6, then compile with the compiler in OpenVINO. `NPU_COMPILER_TYPE=PREFER_PLUGIN` gives the same result. + - Linux: the NPU reports almost all of the system memory, so `--fit` keeps every weight in the backend, and a 32 GB system swaps heavily. Pass `--fit-target 16384`: `--fit` then leaves part of the expert weights in the memory-mapped model file, as it does on Windows, where the NPU reports 16 GB. The graph still runs on the NPU alone. - `llama-perplexity` with these models: use a `-c` of at most twice `GGML_OPENVINO_PREFILL_CHUNK_SIZE` (for example `-c 256` with a chunk size of 128). The output rows of the last layer must not exceed the chunk size. > [!NOTE] From 5e0356242d7fb128b7d3597cca317af74f1e01a9 Mon Sep 17 00:00:00 2001 From: Suhas Somashekar Date: Tue, 17 Nov 2026 10:52:59 -0800 Subject: [PATCH 18/19] ggml-openvino: back GPU host buffers with a file by default on Linux --- .../dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 95 ++++++++++++------- 2 files changed, 61 insertions(+), 36 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 e371d50be7fa..b48256e5055e 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -93,7 +93,7 @@ These options are off by default. They are not validated for general use: some h | `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. | -| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). It is not part of the key of the compiled model cache and is ignored in cache-only mode. | +| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` (GPU on Linux: `$TMPDIR` or `/var/tmp`) | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). If it is not set, GPU on Linux uses `$TMPDIR` or `/var/tmp` when that directory is not tmpfs and has free space of the buffer size plus 1 GiB; otherwise the buffer is anonymous memory as before. It is not part of the key of the compiled model cache and is ignored in cache-only mode. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ```bash diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 968c8c2c80be..846cb7126570 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -43,8 +43,13 @@ # include # include #else +# include # include # include +# ifdef __linux__ +# include +# include +# endif #endif // ===================================================== @@ -65,6 +70,59 @@ // ===================================================== namespace { +#ifndef _WIN32 +// Back a host buffer with an unlinked temp file mapped MAP_SHARED, or return nullptr. +// Anonymous pages can only go to swap. File-backed pages are reclaimable: under memory pressure the kernel +// writes them back and drops them, then reads them again on demand. The file is freed when the process exits. +// The directory is GGML_OPENVINO_SPILL_DIR, or on GPU by default $TMPDIR or /var/tmp if it is on disk. +void * ggml_openvino_spill_alloc(size_t size) { + if (ggml_openvino_model_cache_only()) { + return nullptr; + } + const char * dir = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR"); +# ifdef __linux__ + if (dir == nullptr && ggml_openvino_is_gpu()) { + const char * candidates[] = { getenv("TMPDIR"), "/var/tmp" }; + for (const char * d : candidates) { + struct statfs fs; + // tmpfs and ramfs keep the file in RAM, which does not help. Keep 1 GiB free for the system. + if (d != nullptr && d[0] != '\0' && statfs(d, &fs) == 0 && fs.f_type != TMPFS_MAGIC && + fs.f_type != RAMFS_MAGIC && (uint64_t) fs.f_bavail * fs.f_bsize >= size + (1ull << 30)) { + dir = d; + break; + } + } + } +# endif + if (dir == nullptr) { + return nullptr; + } + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", dir, (int) getpid()); + int fd = mkstemp(path); + if (fd < 0) { + GGML_LOG_WARN("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); + return nullptr; + } + unlink(path); + // Reserve the disk space now, so that a full disk fails here and not with SIGBUS on a later page write. + int err = posix_fallocate(fd, 0, (off_t) size); + if (err != 0) { + GGML_LOG_WARN("%s: posix_fallocate(%zu) in %s failed: %s\n", __func__, size, dir, strerror(err)); + close(fd); + return nullptr; + } + void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + close(fd); + if (m == MAP_FAILED) { + GGML_LOG_WARN("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); + return nullptr; + } + GGML_LOG_INFO("%s: host buffer backed by a file in %s (%zu MB)\n", __func__, dir, size / 1024 / 1024); + return m; +} +#endif + // Buffer context that manages per-tensor allocations (no contiguous buffer for weights) struct ggml_backend_openvino_buffer_context { int device; @@ -170,42 +228,9 @@ struct ggml_backend_openvino_buffer_context { // backed by the Level Zero host tensor above } else #ifndef _WIN32 - if (const char * spill_dir = - ggml_openvino_model_cache_only() ? nullptr : ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR")) { - // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED - // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the - // repacked buffer stays pinned alongside the mmap'd source and both are resident at once - // -- that double residency is the load-time peak. File-backed pages are reclaimable: the - // kernel can write them back and drop them under pressure, then re-read on demand, so RSS - // becomes a working set rather than the whole buffer. The file is unlinked immediately, - // so it disappears when the process exits. - // - // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many - // systems) backs the "spill" with RAM and makes matters worse. - char path[PATH_MAX]; - snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid()); - int fd = mkstemp(path); - if (fd < 0) { - GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); - return; - } - unlink(path); // anonymous-but-file-backed: freed on process exit - if (ftruncate(fd, (off_t) size) != 0) { - GGML_LOG_ERROR("%s: ftruncate(%zu) failed: %s\n", __func__, size, strerror(errno)); - close(fd); - return; - } - void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - close(fd); // the mapping keeps the file alive - if (m == MAP_FAILED) { - GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); - return; - } - data = m; - spill_mapping = m; + if ((data = ggml_openvino_spill_alloc(size)) != nullptr) { + spill_mapping = data; spill_size = size; - GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, - size / 1024 / 1024); ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } else #endif From 7f1dfe0fa12032d5d17f4d8459e470a2cc40b9d3 Mon Sep 17 00:00:00 2001 From: Suhas Somashekar Date: Tue, 17 Nov 2026 14:38:53 -0800 Subject: [PATCH 19/19] ggml-openvino: back GPU host buffers with a file by default on Linux- refactor --- .../dev_doc/OpenVINO-ENV-VARS.md | 2 +- ggml/src/ggml-openvino/ggml-openvino.cpp | 89 ++++++++++--------- 2 files changed, 47 insertions(+), 44 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 b48256e5055e..13179fed5ce3 100644 --- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md +++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md @@ -93,7 +93,7 @@ These options are off by default. They are not validated for general use: some h | `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. | -| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` (GPU on Linux: `$TMPDIR` or `/var/tmp`) | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). If it is not set, GPU on Linux uses `$TMPDIR` or `/var/tmp` when that directory is not tmpfs and has free space of the buffer size plus 1 GiB; otherwise the buffer is anonymous memory as before. It is not part of the key of the compiled model cache and is ignored in cache-only mode. | +| `GGML_OPENVINO_SPILL_DIR` | all | String | `not set` (GPU on Linux: `$TMPDIR` or `/var/tmp`) | Directory for a disk-backed weight buffer, so its pages can be reclaimed under memory pressure. It must be on real storage, not on tmpfs (`/tmp` on many systems). If it is not set, GPU on Linux uses `$TMPDIR` or `/var/tmp` when that directory is writable, is not tmpfs and has free space of the buffer size plus 1 GiB; otherwise the buffer is anonymous memory as before. It is not part of the key of the compiled model cache and is ignored in cache-only mode. | | `GGML_OPENVINO_LAZY_HOST_THRESHOLD_MB` | NPU | Integer | `2048` | With `GGML_OPENVINO_SELF_CONTAINED_MMAP=1`: buffers of at least this size get demand-zero host memory instead of Level Zero host memory. | ```bash diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp index 846cb7126570..aafc568eba90 100644 --- a/ggml/src/ggml-openvino/ggml-openvino.cpp +++ b/ggml/src/ggml-openvino/ggml-openvino.cpp @@ -71,55 +71,25 @@ namespace { #ifndef _WIN32 -// Back a host buffer with an unlinked temp file mapped MAP_SHARED, or return nullptr. -// Anonymous pages can only go to swap. File-backed pages are reclaimable: under memory pressure the kernel -// writes them back and drops them, then reads them again on demand. The file is freed when the process exits. -// The directory is GGML_OPENVINO_SPILL_DIR, or on GPU by default $TMPDIR or /var/tmp if it is on disk. -void * ggml_openvino_spill_alloc(size_t size) { +// Directory for a file-backed host buffer, or nullptr for anonymous memory. GGML_OPENVINO_SPILL_DIR if set, else on +// GPU under Linux $TMPDIR or /var/tmp if it is writable, not tmpfs or ramfs, and has free space for size + 1 GiB. +const char * ggml_openvino_spill_dir(size_t size) { if (ggml_openvino_model_cache_only()) { return nullptr; } const char * dir = ggml_openvino_getenv_str("GGML_OPENVINO_SPILL_DIR"); # ifdef __linux__ - if (dir == nullptr && ggml_openvino_is_gpu()) { - const char * candidates[] = { getenv("TMPDIR"), "/var/tmp" }; - for (const char * d : candidates) { - struct statfs fs; - // tmpfs and ramfs keep the file in RAM, which does not help. Keep 1 GiB free for the system. - if (d != nullptr && d[0] != '\0' && statfs(d, &fs) == 0 && fs.f_type != TMPFS_MAGIC && - fs.f_type != RAMFS_MAGIC && (uint64_t) fs.f_bavail * fs.f_bsize >= size + (1ull << 30)) { - dir = d; - break; - } + const char * candidates[] = { getenv("TMPDIR"), "/var/tmp" }; + for (const char * d : candidates) { + struct statfs fs; + if (dir == nullptr && ggml_openvino_is_gpu() && d != nullptr && d[0] != '\0' && access(d, W_OK) == 0 && + statfs(d, &fs) == 0 && fs.f_type != TMPFS_MAGIC && fs.f_type != RAMFS_MAGIC && + (uint64_t) fs.f_bavail * fs.f_bsize >= size + (1ull << 30)) { + dir = d; } } # endif - if (dir == nullptr) { - return nullptr; - } - char path[PATH_MAX]; - snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", dir, (int) getpid()); - int fd = mkstemp(path); - if (fd < 0) { - GGML_LOG_WARN("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); - return nullptr; - } - unlink(path); - // Reserve the disk space now, so that a full disk fails here and not with SIGBUS on a later page write. - int err = posix_fallocate(fd, 0, (off_t) size); - if (err != 0) { - GGML_LOG_WARN("%s: posix_fallocate(%zu) in %s failed: %s\n", __func__, size, dir, strerror(err)); - close(fd); - return nullptr; - } - void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); - close(fd); - if (m == MAP_FAILED) { - GGML_LOG_WARN("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); - return nullptr; - } - GGML_LOG_INFO("%s: host buffer backed by a file in %s (%zu MB)\n", __func__, dir, size / 1024 / 1024); - return m; + return dir; } #endif @@ -228,9 +198,42 @@ struct ggml_backend_openvino_buffer_context { // backed by the Level Zero host tensor above } else #ifndef _WIN32 - if ((data = ggml_openvino_spill_alloc(size)) != nullptr) { - spill_mapping = data; + if (const char * spill_dir = ggml_openvino_spill_dir(size)) { + // Disk-backed weight buffer: back the repacked weights with a temp file via MAP_SHARED + // instead of anonymous memory. Anonymous pages can only be evicted to swap, so the + // repacked buffer stays pinned alongside the mmap'd source and both are resident at once + // -- that double residency is the load-time peak. File-backed pages are reclaimable: the + // kernel can write them back and drop them under pressure, then re-read on demand, so RSS + // becomes a working set rather than the whole buffer. The file is unlinked immediately, + // so it disappears when the process exits. + // + // The directory must be real storage. Pointing this at a tmpfs mount (/tmp on many + // systems) backs the "spill" with RAM and makes matters worse. + char path[PATH_MAX]; + snprintf(path, sizeof(path), "%s/ggml-ov-weights-%d-XXXXXX", spill_dir, (int) getpid()); + int fd = mkstemp(path); + if (fd < 0) { + GGML_LOG_ERROR("%s: mkstemp(%s) failed: %s\n", __func__, path, strerror(errno)); + return; + } + unlink(path); // anonymous-but-file-backed: freed on process exit + // Reserve the disk space, so that a full disk fails here and not with SIGBUS on a later page write. + if (int err = posix_fallocate(fd, 0, (off_t) size)) { + GGML_LOG_ERROR("%s: posix_fallocate(%zu) failed: %s\n", __func__, size, strerror(err)); + close(fd); + return; + } + void * m = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + close(fd); // the mapping keeps the file alive + if (m == MAP_FAILED) { + GGML_LOG_ERROR("%s: mmap(%zu) failed: %s\n", __func__, size, strerror(errno)); + return; + } + data = m; + spill_mapping = m; spill_size = size; + GGML_LOG_INFO("%s: weight buffer spilled to %s (%zu MB, file-backed)\n", __func__, spill_dir, + size / 1024 / 1024); ov_buffer = std::make_shared(ov::element::u8, ov::Shape{size}, data); } else #endif