Commit 51fc2f90e for llama.cpp
commit 51fc2f90e23d4faf0f726f476a5452652b535145
Author: Ravi Panchumarthy <ravi.panchumarthy@intel.com>
Date: Mon Nov 23 06:29:20 2026 -0800
ggml-openvino: CI fixes, new model support, fixes and improvements. (#32861)
* ggml-openvino: keep the rope angle in f32 under the f16 inference hint
* ggml-openvino: add a GGML_OP_ARGMAX translator
* ggml-openvino: keep the token dim dynamic for a 2-D activation graph input
* ggml-openvino: tolerate graph inputs and outputs with no backing storage
* ggml-openvino: invalidate a cached graph when its output set changes
* ggml-openvino: bound the compiled-model cache to N shapes instead of 1
* ggml-openvino: add GGML_OPENVINO_LOG_SUPPORTS_OP diagnostic
* ggml-openvino: honour a node's dynamic-dim classification on non-split graphs too
* ggml-openvino: fold consecutive SET_ROWS column writes into one scatter
* ggml-openvino: keep the speculative decoding feature buffers in device memory
* ggml-openvino: keep the fixed token count of static graph inputs for npu
GDN
In a static (NPU) graph that overwrites the fixed token count that
get_graph_input_shape set just before, for example of inp_tokens, so the NPU
graph got a dynamic token dimension. GATED_DELTA_NET models (Qwen3.5, Qwen3.6)
then fail to translate: "GATED_DELTA_NET pad masking requires a static token
dimension". Keep the change for dynamic graphs and the previous behaviour for
static ones.
* ggml-openvino: one output in the decode model of a static NPU pair
The decode model of a static prefill/decode pair copied the compute params of the
prefill graph, including output_len. With llama-perplexity the prefill graph has many
outputs (128 at -c 256), so the decode model gathered 128 rows from its one token in
the last layer. For a MoE model that layer then differs from the others and NPUW fails
to lower its experts ("could not lower the isolated expert partition"). A decode step
outputs one token; the model cache key already assumes it (decode_signature out=1).
* ggml-openvino: fix gated delta net when v is a view with padded heads
The GDN translator assumed v is a view of the fused qkv conv output with
the heads packed in each row, and sliced H_v * S_v elements off that row.
test-backend-ops now has padded_v cases, where v views a wider tensor and
each head row is padded (nb[1] > S_v * nb[0]). The slice then read the
padding, and the results were wrong on CPU and GPU.
Take the packed path only when nb[1] == S_v * nb[0]. Any other view goes
through the generic view resolution, which already returns
[B, T, H_v, S_v], so the reshape of the packed case is skipped too. Model
graphs build v with packed heads and keep the packed path.
* ggml-openvino: make the f32 rope angle opt-in
GGML_OPENVINO_ROPE_F32_ANGLE was on by default. It changes the RoPE of
every model on every device, and it was validated on one model on the
GPU only. On the CPU device, which computes in f32, its f16 round trip
rounds cos and sin, and ROPE cases of test-backend-ops fail against the
CPU backend.
Turn it off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. Fix
the comment that called the round trip a no-op on f32 paths. Document
the variable, and the two diagnostics added with it
(GGML_OPENVINO_LOG_SUPPORTS_OP, GGML_OPENVINO_DIAG_GRAPH_IO), in the
dev_doc.
* docs : add the Muse-Glimmer-30B DFlash memory limit and env var samples
Muse-Glimmer-30B with a DFlash draft peaks at about 45 GB of RAM on an
integrated GPU. Add it to the GPU limitations as a runnable sample, and
add samples for GGML_OPENVINO_LOG_SUPPORTS_OP and
GGML_OPENVINO_DIAG_GRAPH_IO to the dev_doc.
* ggml-openvino: fix weight zero points, buffer extras and cache-key gaps
A code review of ggml/src/ggml-openvino found these bugs:
- Q4_1 weights: `extract_q4_1_data` packs two zero points per byte from a `parallel_for` over blocks, so two threads can write the same byte.
- Zero points out of the u4/u8 range wrap around instead of saturating. gemma-4-E2B has 6 Q4_K sub-blocks with a zero point of 16 or more; 16 wrapped to 0.
- `set_tensor` overwrote the extra that `init_tensor` created for a weight without deleting it.
- The two buffer constructors had separate id counters, and the buffer id is part of the shared graph key.
- A freed weight buffer stayed in the release registry, so a later release could madvise memory it no longer owned.
- `GGML_OPENVINO_ROPE_F32_ANGLE` changes the graph but was not in the compiled-model cache key.
- On NPU, group-128 requantization ignored the row width. A model whose rows are not a multiple of 128 failed to load its weights (SmolLM2-360M).
- The static Split cache held a strong reference to the Split on its own input (a reference cycle) and ignored the output port.
- `rms_norm` took op_case 3 for both a direct and a packed pre-scaled GDN output, so the packed one was not sliced.
- Smaller items: static decode read `out_ids` even when it is empty; the static path aborted where the dynamic path returns an error; a damaged weights `.meta` hash threw from `std::stoull`; `extract_layer_from_name` threw on a non-numeric suffix; `GGML_OP_FILL` was registered twice.
- ggml-quants.cpp: one `parallel_for` iteration per zero point byte for Q4_1; clamp zero points to [0, 15] (u4) and [0, 255] (u8).
- ggml-openvino.cpp: `ggml_openvino_set_extra` replaces and deletes the old extra at every site; one id counter; `ggml_openvino_unregister_weight_buffer` in the buffer destructor; a failed KV re-allocation returns `GGML_STATUS_ALLOC_FAILED`.
- model-cache.cpp: hash `GGML_OPENVINO_ROPE_F32_ANGLE`, cache version 9; `strtoull` for the `.meta` hash.
- npu_quant_policy.cpp: Q4_0_128 falls back to Q4_0_C when `ne[0] % 128 != 0`. ggml-openvino-extra.cpp: the group-64 requant targets fall back to Q8_0_C when `ne[0] % 64 != 0`.
- openvino/utils.cpp: the static Split cache uses a weak reference and the output port in its key, like the dynamic one.
- rms_norm.cpp, ggml-decoder.cpp: op_case 5 for a packed pre-scaled GDN output.
- utils.cpp: static decode writes 0 to `out_ids`; a compile after a weight release returns `GGML_STATUS_FAILED`.
- ggml-decoder.cpp: `extract_layer_from_name` returns nullopt for a non-numeric suffix.
- op_table.cpp/.h: remove the duplicate `GGML_OP_FILL`.
* ggml-openvino: copy the decoder once per graph conversion
`GgmlOvDecoder::visit_subgraph` made a full copy of the decoder for every node it visited. Translators only read the decoder, so one copy per walk is enough. Graph conversion time drops 12-24x (Qwen3.5-0.8B: 4.1 s to 0.17 s over the six graphs of a short run).
- ggml-decoder.cpp: make one decoder copy before the node loop.
- utils.cpp: `get_static_attention_size` takes the decoder by const reference and does not copy the compute params.
* ggml-openvino: remove dead code and fix stale comments
Code that nothing calls or registers, and comments that no longer match the code. No behavior change.
- Remove `translate_gated_delta_net_ref`, `translate_solve_tri` (not registered), the unused `FuseToSDPA` pass, `add_rope_sin_cos`, `checksum`, `save_ggml_tensor_data_to_txt`, `non_cont_dim`, the unused templates in openvino/utils.h and the undefined `getCurrentTime` declaration.
- ggml-decoder.cpp: drop the VIEW op_case tail that only ever set 0.
- utils.cpp: drop a duplicate `entry->ptr` store and the always-false `!model_leafs.empty() == false` term.
- `ggml_openvino_manual_gqa_enabled()` replaces two copies of the GGML_OPENVINO_MANUAL_GQA_ATTN default (flash_attn_ext.cpp and the cache key).
- ggml-openvino.cpp: remove the SSM_CONV case whose comment said it stays on CPU (it runs on OpenVINO); fix the gemma3n reason text (not GPU-only) and two typos.
* ggml-openvino: track dynamic dims through bailingmoe3's GDN views and conv state
bailingmoe3 uses GATED_DELTA_NET views to expose its attention and
state outputs. Preserve their dynamic dimensions in the decoder.
- Assign the dynamic dimensions of the translated attention and state
outputs to the corresponding GATED_DELTA_NET result VIEWs.
- Count the convolution state slots using the rows spanned by the
destination view. bailingmoe3 packs the q/k/v convolution states
into a single row.
- Preserve the tracked dynamic dimension in RESHAPE op case 0 when
the reshape only adds a trailing size-1 dimension.
* ggml-openvino: translate the per-key gate of GATED_DELTA_NET
Ling-3.0-tiny (bailingmoe3) uses a gate per key dimension (kda),
which the backend previously rejected, causing these layers to
fall back to the CPU.
- Use the fused GatedDeltaNet when the OpenVINO runtime and target
device support a rank-4 gate.
- Detect support once by compiling a one-node GatedDeltaNet with
a rank-4 gate and checking the target device with query_model.
Older runtimes reject this gate, and the CPU plugin does not
support it.
- Fall back to the reference loop when the fused path is unavailable.
- Support a dynamic token count in the reference loop by using
dynamic reshapes and deriving the trip count from the input shape.
- Reject unsupported cases with a reason: padded chunks, recurrent
caches, state snapshots, and the native state layout. The loop
currently handles one state in the ggml layout.
* ggml-openvino: Fix issue highlighted by tests
* ggml-openvino: reject a padded permuted v in gated delta net
supports_op rejected a permuted v only when src2 was the PERMUTE itself. With padded heads, v is a VIEW of the PERMUTE, so the check missed it and the per-key gate reference loop ran on a v layout it does not handle. Look through the VIEW so this case falls back like the other permuted v inputs.
* ggml-openvino: write back intermediate nodes of op-test graphs
The ADD_RMS_NORM_MUL op test checks the intermediate sum of its graph as
well as the final output. compute_model_outputs() made a node a model
output only when the graph does not consume all of it, so the sum was
never written back and the test read uninitialised memory (28 failures
on GPU and CPU). MUL_MAT_ID_SHARED, which checks its routed and shared
results, failed the same way on CPU.
Op-test graphs (the naive path) can read any node, so make every
non-in-place node a model output there. Model graphs are unchanged.
---------
Co-authored-by: Mustafa Cavus <mustafa.cavus@intel.com>
Co-authored-by: yzhou51 <yaowei.zhou@intel.com>
Co-authored-by: Sabnis, Omkar <omkar.sabnis@intel.com>
diff --git a/docs/backend/OPENVINO.md b/docs/backend/OPENVINO.md
index a3a94aa16..27c17c3ef 100644
--- a/docs/backend/OPENVINO.md
+++ b/docs/backend/OPENVINO.md
@@ -995,6 +995,16 @@ build\ReleaseOV\bin\llama-simple.exe -m "C:\models\Llama-3.2-1B-Instruct-Q4_K_M.
**GPU-specific**
+- Muse-Glimmer-30B with a DFlash draft needs a 64 GB system (peak about 45 GB of RAM):
+
+ ```bash
+ export GGML_OPENVINO_DEVICE=GPU
+ export GGML_OPENVINO_SPILL_DIR=$HOME/ov_spill # local disk, not tmpfs
+ export GGML_OPENVINO_ROPE_F32_ANGLE=1 # long prompts
+ mkdir -p $GGML_OPENVINO_SPILL_DIR
+ ./build/ReleaseOV/bin/llama-server -m Muse-Glimmer-30B-Q4_K_M.gguf -md <dflash-draft>.gguf \
+ --spec-type draft-dflash --spec-draft-n-max 4
+ ```
- Multiple GPUs (`GGML_OPENVINO_DEVICE=GPU.0,GPU.1` with `-sm layer`):
- `-sm tensor` is not supported.
- Copies between GPUs go through host memory. There is no asynchronous copy and no peer-to-peer copy.
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 a43ac1d6a..9d72ceacb 100644
--- a/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
+++ b/ggml/src/ggml-openvino/dev_doc/OpenVINO-ENV-VARS.md
@@ -13,6 +13,8 @@ The variables for users, and the rules for values, are in [docs/backend/OPENVINO
| `GGML_OPENVINO_DEBUG_NODE` | all | String | `not set` | Add the named graph nodes as outputs of the compiled model. Separate several names with commas. |
| `GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS` | all | Boolean | `0` | Print the tensor address map once. |
| `GGML_OPENVINO_LOG_UNSUPPORTED_OPS` | all | Boolean | `0` | Log each op that the backend does not support, with the tensor details and the reason. |
+| `GGML_OPENVINO_LOG_SUPPORTS_OP` | all | Integer | `0` | Log what `supports_op` accepts and rejects. `1`: summary at exit. `2`: also each call (the first calls are missing). |
+| `GGML_OPENVINO_DIAG_GRAPH_IO` | all | Boolean | `0` | When binding a tensor or `infer()` throws, log the graph key and the shapes of the model and the bound tensors. |
| `GGML_OPENVINO_DISABLE_CACHE` | all | Boolean | `0` | Turn the in-process cache of compiled models and decoders off. |
| `GGML_OPENVINO_FULL_GRAPH_KEY` | all | Boolean | `0` | Add the external inputs of a graph to the key of the in-process cache. By default the key is the node count and the names of the first and last nodes. Use it when two different graphs could share that key. |
| `GGML_OPENVINO_LOG_SWA_LAYERS` | all | Boolean | `0` | Log the attention extent of each layer and which layers use sliding-window attention, on an `ov-swa:` line at the WARN level. |
@@ -29,6 +31,12 @@ GGML_OPENVINO_DUMP_CGRAPH=1 GGML_OPENVINO_DUMP_IR=1 \
# Log unsupported ops. The lines have the WARN level, which the default log verbosity shows (-lv 2 or higher).
GGML_OPENVINO_LOG_UNSUPPORTED_OPS=1 ./build/ReleaseOV/bin/llama-cli -m model.gguf -c 512
+# What supports_op accepts and rejects: 1 = summary at exit, 2 = also each call
+GGML_OPENVINO_LOG_SUPPORTS_OP=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep ov-supports-op
+
+# Graph key and tensor shapes when an inference throws
+GGML_OPENVINO_DIAG_GRAPH_IO=1 ./build/ReleaseOV/bin/llama-completion -m model.gguf -c 512 -n 16 -no-cnv -p "Hello" 2>&1 | grep DIAG
+
# NPUW dumps. They need an OpenVINO developer build (NPU_PLUGIN_DEVELOPER_BUILD).
export GGML_OPENVINO_DEVICE=NPU
export GGML_OPENVINO_NPUW_DUMP_SUBS=YES
@@ -74,6 +82,7 @@ These options are off by default. They are not validated for general use: some h
| `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_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)))`. |
| `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. |
diff --git a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
index 1f7343bba..d29175ab0 100644
--- a/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
+++ b/ggml/src/ggml-openvino/device/npu_quant_policy.cpp
@@ -45,6 +45,10 @@ std::optional<ExtraQuantType> ggml_openvino_npu_token_embd_requant_type(const gg
}
std::optional<ExtraQuantType> ggml_openvino_npu_weight_requant_type(const ggml_tensor * tensor) {
- GGML_UNUSED(tensor);
- return ggml_openvino_get_npu_requant_type();
+ const ExtraQuantType type = ggml_openvino_get_npu_requant_type();
+ // a group must fit within a row
+ if (type == ExtraQuantType::Q4_0_128 && tensor->ne[0] % 128 != 0) {
+ return ExtraQuantType::Q4_0_C;
+ }
+ return type;
}
diff --git a/ggml/src/ggml-openvino/ggml-decoder.cpp b/ggml/src/ggml-openvino/ggml-decoder.cpp
index 519c35bc2..a9fac74b1 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.cpp
+++ b/ggml/src/ggml-openvino/ggml-decoder.cpp
@@ -9,9 +9,11 @@
#include <algorithm>
#include <cassert>
+#include <cctype>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
+#include <cstring>
#include <fstream>
#include <iomanip>
#include <map>
@@ -31,10 +33,27 @@
#include <set>
#include <stdexcept>
#include <string>
-#include <cstring>
#include <unordered_map>
#include <vector>
+static std::set<std::string> collect_graph_output_names(const ggml_cgraph * cgraph) {
+ std::set<std::string> outputs;
+ for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
+ auto * node = cgraph->nodes[node_n];
+ if (node->flags & GGML_TENSOR_FLAG_OUTPUT) {
+ outputs.insert(node->name);
+ }
+ }
+ return outputs;
+}
+
+bool GgmlOvDecoder::has_same_graph_io(const ggml_cgraph * cgraph) const {
+ if (m_built_output_names.empty()) {
+ return true; // no snapshot (naive / test decoders): nothing to compare against
+ }
+ return collect_graph_output_names(cgraph) == m_built_output_names;
+}
+
GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
ModelParams & model_params,
ComputeParams & compute_params,
@@ -64,6 +83,8 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
validate_cgraph();
+ m_built_output_names = collect_graph_output_names(cgraph);
+
set_input_output();
compute_node_dynamic_dims();
compute_model_inputs();
@@ -79,6 +100,7 @@ GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
m_cgraph = cgraph;
+ m_built_output_names = collect_graph_output_names(cgraph);
m_model_inputs.clear();
m_model_outputs.clear();
m_node_info_list.clear();
@@ -694,45 +716,6 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
op_case = 1;
break;
}
- if (node->src[0]->op == GGML_OP_VIEW) {
- auto * src = node->src[0];
- if (ggml_nelements(node) != ggml_nelements(src)) {
- // throw std::runtime_error("Unsupported VIEW case");
- }
- op_case = 0;
- if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) {
- op_case = 0;
- }
- }
- {
- auto * src = node->src[0];
- if (ggml_nelements(node) != ggml_nelements(src)) {
- // Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1.
- // Typical pattern:
- // src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3]
- // dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3]
- if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 &&
- node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) {
- op_case = 0;
- break;
- }
-
- // General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing.
- int diff_count = 0;
- for (int i = 0; i < GGML_MAX_DIMS; i++) {
- if (node->ne[i] != src->ne[i]) {
- diff_count++;
- }
- // if node ne[i] > src ne[i], case = 0
- if (node->ne[i] > src->ne[i]) {
- return 0;
- }
- }
- if (diff_count >= 1) {
- op_case = 0;
- }
- }
- }
break;
}
case GGML_OP_RMS_NORM: {
@@ -744,7 +727,8 @@ int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
// pre-scaled, and the norm then scales its eps to match; 4: it is not.
op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 4;
} else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
- op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 3 : 2;
+ // packed [attn | state] output, sliced by the norm. 5: pre-scaled, as in 3; 2: not.
+ op_case = is_gdn_out_prescaled(node->src[0]->src[0]) ? 5 : 2;
}
}
break;
@@ -897,13 +881,10 @@ std::optional<int> extract_layer_from_name(const std::string & name) {
return std::nullopt;
}
pos1 += 2;
- size_t pos2 = name.find(' ', pos1);
- if (pos2 == std::string::npos) {
- pos2 = name.length();
+ if (pos1 >= name.size() || !std::isdigit(static_cast<unsigned char>(name[pos1]))) {
+ return std::nullopt;
}
- std::string layer_str = name.substr(pos1, pos2 - pos1);
- int layer = std::stoi(layer_str);
- return layer;
+ return std::stoi(name.substr(pos1));
}
// Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a
@@ -1202,7 +1183,11 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
}
ggml_tensor * cache_k = cache_k_view->src[0];
- int layer = extract_layer_from_name(cache_k->name).value();
+ const auto layer_opt = extract_layer_from_name(cache_k->name);
+ if (!layer_opt) {
+ continue;
+ }
+ const int layer = *layer_opt;
// Classified by the pre-pass above, which groups layers by mask tensor identity. The
// mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name.
@@ -1372,7 +1357,9 @@ std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgr
compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
}
if (is_conv || is_gdn) {
- compute_params.s_copy_active_slot_len = (int) dest_view->ne[1];
+ // One cache row per active sequence: [conv_state_size, n_seqs] (qwen35) or, with the q/k/v conv
+ // states packed in one row, [d_conv - 1, d_inner, n_seqs] (bailingmoe3), so count the rows spanned.
+ compute_params.s_copy_active_slot_len = (int) ((ggml_nbytes(dest_view) + row_bytes - 1) / row_bytes);
}
}
}
@@ -1573,7 +1560,10 @@ ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
else {
input_shape = ov::PartialShape{get_shape(input)};
}
- if (dynamic_dim_index != -1 && m_model_is_splitted) {
+ // A static graph (NPU) keeps the fixed token count set above; only a split static graph, whose parts are
+ // fed by other backends, marks the dimension dynamic. Without this the token dimension of inp_tokens becomes
+ // dynamic in the NPU graph (and, for example, the GATED_DELTA_NET pad masking fails).
+ if (dynamic_dim_index != -1 && (!m_is_static || m_model_is_splitted)) {
input_shape[3 - dynamic_dim_index] = -1;
}
if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE &&
@@ -1985,7 +1975,9 @@ void GgmlOvDecoder::compute_model_outputs() {
}
}
}
- if (input_use_count == cur_node_use_count) {
+ // op tests (the naive path) can read any node of the graph, e.g. the intermediate sum of a fused
+ // ADD + RMS_NORM + MUL, so every non-in-place node is a model output there
+ if (input_use_count == cur_node_use_count && (!m_naive || ::is_inplace_op(cur_node))) {
cur_node = nullptr;
}
}
@@ -2774,11 +2766,14 @@ size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const {
}
void GgmlOvDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const {
+ // One copy for the whole walk: translators only read the decoder, and a copy per node costs a full
+ // copy of the node list for every node.
+ auto decoder = std::make_shared<GgmlOvDecoder>(*this);
for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) {
if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) {
continue;
}
- node_visitor(std::make_shared<GgmlOvDecoder>(*this), node_idx);
+ node_visitor(decoder, node_idx);
}
}
@@ -2851,6 +2846,10 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[src] = 1;
continue;
}
+ if (is_inp_embd_2d(src, node)) {
+ m_node_dynamic_dims[src] = 1;
+ continue;
+ }
self(self, src);
}
}
@@ -2921,10 +2920,22 @@ void GgmlOvDecoder::compute_node_dynamic_dims() {
m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
break;
}
+
+ // A VIEW that does not change the shape is a pass-through for dynamic-dim purposes.
+ if (is_same_shape(node->src[0], node)) {
+ m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
+ break;
+ }
// Use stride-based matching: the stride of a VIEW dimension directly
// encodes which source dimension it indexes into, so it uniquely
// identifies the dynamic dim even when two dims share the same size.
m_node_dynamic_dims[node] = -1;
+ if (!m_model_params.has_rs_rollback && node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
+ // The GDN translator publishes attention [S_v, H_v, n_tokens, n_seqs] and state directly under these
+ // VIEW names (get_output_names), not the packed [attention | state] the strides describe.
+ m_node_dynamic_dims[node] = node->view_offs == 0 ? 2 : -1;
+ break;
+ }
if (m_node_dynamic_dims[node->src[0]] != -1) {
auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
diff --git a/ggml/src/ggml-openvino/ggml-decoder.h b/ggml/src/ggml-openvino/ggml-decoder.h
index 12b08cebc..39b3496e5 100644
--- a/ggml/src/ggml-openvino/ggml-decoder.h
+++ b/ggml/src/ggml-openvino/ggml-decoder.h
@@ -458,6 +458,11 @@ public:
void update_io(ggml_cgraph * cgraph);
bool is_bound_to(const ggml_cgraph * cgraph) const;
+ // Was this decoder built for a graph with the same OUTPUT set as `cgraph`? The cache key is
+ // only (n_nodes, first/last node name), which cannot see a change in which tensors are marked
+ // as outputs, and the compiled model's Results are fixed at compile time.
+ bool has_same_graph_io(const ggml_cgraph * cgraph) const;
+
static bool is_inp_tok(const ggml_tensor * tensor, const ggml_tensor * op) {
return op->op == GGML_OP_GET_ROWS && tensor == op->src[1] && op->src[0]->op == GGML_OP_NONE;
}
@@ -501,6 +506,16 @@ public:
(tensor->op == GGML_OP_NONE || tensor->op == GGML_OP_CPY);
}
+ // A 2-D float graph input feeding a matmul as src[1]. Speculative decoding hands the draft the
+ // target's hidden features this way ([n_embd, n_tokens], with no GET_ROWS lookup, so none of the
+ // other seeds match it) and the token count differs between the prompt pass and the shorter
+ // draft blocks, so its token dim must stay dynamic.
+ static bool is_inp_embd_2d(const ggml_tensor * tensor, const ggml_tensor * op) {
+ return (tensor->flags & GGML_TENSOR_FLAG_INPUT) && tensor->op == GGML_OP_NONE &&
+ tensor->type == GGML_TYPE_F32 && tensor->ne[2] == 1 && tensor->ne[3] == 1 &&
+ op->op == GGML_OP_MUL_MAT && tensor == op->src[1];
+ }
+
static bool is_inp_mask(const ggml_tensor * tensor, const ggml_tensor * op) {
return op->op == GGML_OP_CPY || (op->op == GGML_OP_FLASH_ATTN_EXT && tensor == op->src[3]) ||
(op->op == GGML_OP_SOFT_MAX && tensor == op->src[1]);
@@ -759,6 +774,8 @@ private:
std::map<std::string, std::shared_ptr<ov::Node>> m_model_weights;
std::map<std::string, ggml_tensor *> m_model_outputs;
std::set<std::string> m_model_output_names;
+ // The output set the compiled model was built from, for has_same_graph_io().
+ std::set<std::string> m_built_output_names;
std::vector<NodeInfo> m_node_info_list;
std::map<ggml_tensor *, int> m_node_dynamic_dims;
std::set<const ggml_tensor *> m_kvcache_4d;
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
index 2537f8af3..7e6711dd8 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.cpp
@@ -179,6 +179,9 @@ constexpr env_var env_vars[] = {
{"GGML_OPENVINO_RELEASE_WEIGHTS", env_type::BOOL},
{"GGML_OPENVINO_REDUCE_COMPILE_MEM", env_type::BOOL},
{"GGML_OPENVINO_LOG_UNSUPPORTED_OPS", env_type::BOOL},
+ {"GGML_OPENVINO_LOG_SUPPORTS_OP", env_type::INT},
+ {"GGML_OPENVINO_DIAG_GRAPH_IO", env_type::BOOL},
+ {"GGML_OPENVINO_ROPE_F32_ANGLE", env_type::BOOL},
{"GGML_OPENVINO_LOG_SWA_LAYERS", env_type::BOOL},
{"GGML_OPENVINO_NATIVE_SOFTPLUS", env_type::BOOL},
{"GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS", env_type::BOOL},
@@ -543,6 +546,14 @@ std::string ggml_openvino_config_overrides_in_use() {
return value ? std::string(name) + "=" + value : std::string();
}
+bool ggml_openvino_manual_gqa_enabled() {
+ // set: a positive value enables it, 0 disables it; unset: on GPU only
+ if (ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN") != nullptr) {
+ return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
+ }
+ return ggml_openvino_is_gpu();
+}
+
bool ggml_openvino_gdn_prescale_enabled() {
// float value, so not getenv_int: "64.0" must enable it. Unset means on.
const char * v = ggml_openvino_getenv_str("GGML_OPENVINO_GDN_Q_SCALE", nullptr);
@@ -997,6 +1008,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
const bool sym128_all = is_opt("q4_sym128_all");
const bool asym64_all = is_opt("q4_asym64_all");
const bool asym64 = is_opt("q4_asym64");
+ // A group of 64 must fit within each row; other widths keep channel-wise INT8.
+ auto group64 = [tensor](ExtraQuantType type) {
+ return tensor->ne[0] % 64 == 0 ? type : ExtraQuantType::Q8_0_C;
+ };
// TODO: temporary workaround for slow GPU-plugin GatherMatmul prefill above 16 tokens.
// Q4_1_64 experts let the plugin fuse the MoE into MOECompressed.
@@ -1021,8 +1036,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
return tensor->ne[0] % 64 == 0 ? ExtraQuantType::Q4_1_64 : ExtraQuantType::Q8_0_C;
}
if (tensor->type == GGML_TYPE_Q5_0) {
- //return ExtraQuantType::Q4_0_128;
- return ExtraQuantType::Q4_0_64;
+ return group64(ExtraQuantType::Q4_0_64);
}
// MoE expert weights (3D, ne[2] = n_expert) stored as Q5_1/Q8_0 are the expert-side
// equivalent of Q6_K/Q5_K: kept at 8 bits by default while the rest of the model is at 4
@@ -1031,10 +1045,10 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// (704/64 = 11) and 128 does not.
if (tensor->ne[2] > 1 && (tensor->type == GGML_TYPE_Q5_1 || tensor->type == GGML_TYPE_Q8_0)) {
if (sym128 || sym128_all) {
- return ExtraQuantType::Q4_0_64;
+ return group64(ExtraQuantType::Q4_0_64);
}
if (asym64 || asym64_all) {
- return ExtraQuantType::Q4_1_64;
+ return group64(ExtraQuantType::Q4_1_64);
}
// TODO: temporary workaround for a known OpenVINO GPU-plugin bug -- remove once the
// plugin computes grouped 8-bit GatherMatmulCompressed correctly. This costs accuracy
@@ -1049,7 +1063,7 @@ std::optional<ExtraQuantType> ggml_openvino_get_requant_type(const ggml_tensor *
// avoids the broken layout and restores correct output.
// Opt out with GGML_OPENVINO_REQUANT_KQUANT=native.
if (ggml_openvino_is_gpu() && !is_opt("native")) {
- return ExtraQuantType::Q4_0_64;
+ return group64(ExtraQuantType::Q4_0_64);
}
}
switch (tensor->type) {
diff --git a/ggml/src/ggml-openvino/ggml-openvino-extra.h b/ggml/src/ggml-openvino/ggml-openvino-extra.h
index 406ac6d4c..ca3227a41 100644
--- a/ggml/src/ggml-openvino/ggml-openvino-extra.h
+++ b/ggml/src/ggml-openvino/ggml-openvino-extra.h
@@ -206,6 +206,9 @@ bool ggml_openvino_is_gpu();
// Read n_seq_active and attention_size(_swa) from the KQ mask shape (off with GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK=1)
bool ggml_openvino_shape_from_mask_enabled();
+// Manual GQA attention instead of SDPA (GGML_OPENVINO_MANUAL_GQA_ATTN, on GPU by default)
+bool ggml_openvino_manual_gqa_enabled();
+
// GDN q pre-scale for eligible graphs on the NPU static path. On by default;
// GGML_OPENVINO_GDN_Q_SCALE=0 (or a negative or non-numeric value) turns it off.
bool ggml_openvino_gdn_prescale_enabled();
@@ -242,6 +245,7 @@ size_t ggml_openvino_max_alloc_size(const std::string & device);
// release: madvise(MADV_DONTNEED) all registered buffers, dropping their RSS.
// released: true once release has run (used to fail-fast on post-release recompile).
void ggml_openvino_register_weight_buffer(void * data, size_t size);
+void ggml_openvino_unregister_weight_buffer(const void * data);
void ggml_openvino_release_weight_buffers();
bool ggml_openvino_weight_buffers_released();
diff --git a/ggml/src/ggml-openvino/ggml-openvino.cpp b/ggml/src/ggml-openvino/ggml-openvino.cpp
index bd49560d8..b331349d1 100644
--- a/ggml/src/ggml-openvino/ggml-openvino.cpp
+++ b/ggml/src/ggml-openvino/ggml-openvino.cpp
@@ -18,6 +18,7 @@
#include <cstdio>
#include <cstdlib>
#include <cstring>
+#include <map>
#include <memory>
#include <mutex>
#include <openvino/core/type/element_type.hpp>
@@ -99,14 +100,20 @@ struct ggml_backend_openvino_buffer_context {
// Used for re-allocation on device for kvcache
void * data_prev = nullptr;
+ // data is in the weight buffer registry
+ bool weight_registered = false;
+
+ // One counter for both constructors: the id is part of the weight identity in the graph key, so a host-pointer
+ // buffer and an allocated buffer must never share one.
+ static size_t next_buffer_id() {
+ static std::atomic<size_t> next_id{1};
+ return next_id.fetch_add(1);
+ }
ggml_backend_openvino_buffer_context(int device, void * external_data, size_t size) :
device(device),
name(std::string(GGML_OPENVINO_NAME) + std::to_string(device)),
- id([]() {
- static std::atomic<size_t> next_id{1};
- return next_id.fetch_add(1);
- }()),
+ id(next_buffer_id()),
data(external_data),
size(size),
is_remote(false),
@@ -117,10 +124,7 @@ struct ggml_backend_openvino_buffer_context {
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([]() {
- static std::atomic<size_t> next_id{1};
- return next_id.fetch_add(1);
- }()),
+ id(next_buffer_id()),
data(nullptr),
size(size),
is_remote(is_remote) {
@@ -260,6 +264,10 @@ struct ggml_backend_openvino_buffer_context {
delete pair.second;
}
tensor_extras.clear();
+ // a later release must not madvise memory this buffer no longer owns
+ if (weight_registered) {
+ ggml_openvino_unregister_weight_buffer(data);
+ }
if (kv_on_demand) {
ggml_openvino_kv_storage_unregister(data, size);
}
@@ -321,6 +329,17 @@ void ggml_openvino_register_weight_buffer(void * data, size_t size) {
reg.buffers.emplace_back(data, size);
}
+void ggml_openvino_unregister_weight_buffer(const void * data) {
+ if (data == nullptr) {
+ return;
+ }
+ auto & reg = ov_weight_registry();
+ std::lock_guard<std::mutex> lock(reg.mutex);
+ reg.buffers.erase(std::remove_if(reg.buffers.begin(), reg.buffers.end(),
+ [data](const std::pair<void *, size_t> & b) { return b.first == data; }),
+ reg.buffers.end());
+}
+
bool ggml_openvino_weight_buffers_released() {
auto & reg = ov_weight_registry();
std::lock_guard<std::mutex> lock(reg.mutex);
@@ -378,21 +397,53 @@ static bool is_self_contained_mmap_enabled() {
ggml_openvino_getenv_str("GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR");
}
+// Stores extra as the tensor's extra, deleting the one it replaces
+static void ggml_openvino_set_extra(ggml_backend_openvino_buffer_context * ctx,
+ ggml_tensor * tensor,
+ ggml_openvino_extra_base * extra) {
+ auto it = ctx->tensor_extras.find(tensor);
+ if (it != ctx->tensor_extras.end() && it->second != extra) {
+ delete it->second;
+ }
+ ctx->tensor_extras[tensor] = extra;
+ tensor->extra = extra;
+}
+
+// Replaces the buffer's context with a new allocation of the same size and moves tensor->data to it. The old
+// allocation is freed first, so the two never take memory at the same time. Returns false when the new
+// allocation fails.
+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) {
+ 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);
+ buffer->context = ctx;
+ if (ctx->data == nullptr) {
+ return false;
+ }
+ tensor->data = (char *) ctx->data + offset;
+ return true;
+}
+
static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor) {
// GGML_LOG_DEBUG("%s: buffer usage=%d, tensor name=%s\n", __func__, buffer->usage, tensor->name);
ggml_backend_openvino_buffer_context * ctx = (ggml_backend_openvino_buffer_context *) buffer->context;
- // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache)
- if (strncmp(tensor->name, "cache_", 6) == 0 && !ctx->is_remote && ggml_openvino_is_gpu() &&
- !is_stateful_enabled()) {
+ // Put kvcache on device memory for GPU (NPU memory is too small even for kvcache). Same for the speculative
+ // decoding feature buffers (llama_context::layer_inp_dev / h_nextn_dev): every graph reads or writes the whole
+ // 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;
+ if (is_device_state && !ctx->is_remote && ggml_openvino_is_gpu() && !is_stateful_enabled()) {
GGML_ASSERT(ctx->tensor_extras.empty());
- auto device = ctx->device;
- auto size = ctx->size;
- auto * data_prev = ctx->data;
- delete ctx;
- ctx = new ggml_backend_openvino_buffer_context(device, size, true);
- buffer->context = ctx;
- tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
+ 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
@@ -401,14 +452,10 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
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) {
- auto device = ctx->device;
- auto size = ctx->size;
- auto * data_prev = ctx->data;
- delete ctx;
- ctx = new ggml_backend_openvino_buffer_context(device, size, false, true);
+ if (!ggml_openvino_swap_buffer_context(buffer, ctx, tensor, false, true)) {
+ return GGML_STATUS_ALLOC_FAILED;
+ }
ctx->kv_on_demand = true;
- buffer->context = ctx;
- tensor->data = (char *) ctx->data + ((char *) tensor->data - (char *) data_prev);
}
if (ctx->kv_on_demand) {
ggml_openvino_kv_storage_register(tensor->data, tensor->nb[1], tensor->ne[1]);
@@ -431,12 +478,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
if (ggml_openvino_tensor_extra * extra =
ggml_openvino_create_tensor_extra(tensor, ctx->is_remote,
ggml_openvino_get_available_devices()[ctx->device])) {
- auto it = ctx->tensor_extras.find(tensor);
- if (it != ctx->tensor_extras.end()) {
- delete it->second;
- }
- ctx->tensor_extras[tensor] = extra;
- tensor->extra = extra;
+ ggml_openvino_set_extra(ctx, tensor, extra);
return GGML_STATUS_SUCCESS;
}
}
@@ -451,12 +493,7 @@ static enum ggml_status ggml_backend_openvino_buffer_init_tensor(ggml_backend_bu
ggml_openvino_tensor_extra * extra = ggml_openvino_create_tensor_extra(
tensor, ctx->is_remote, ggml_openvino_get_available_devices()[ctx->device]);
if (extra != nullptr) {
- auto it = ctx->tensor_extras.find(tensor);
- if (it != ctx->tensor_extras.end()) {
- delete it->second;
- }
- ctx->tensor_extras[tensor] = extra;
- tensor->extra = extra;
+ ggml_openvino_set_extra(ctx, tensor, extra);
}
}
@@ -644,8 +681,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
// }
}
- ctx->tensor_extras[tensor] = extra;
- tensor->extra = extra;
+ ggml_openvino_set_extra(ctx, tensor, extra);
// Register the host buffer so its pages can be dropped after the GPU
// plugin has its own device copy (GGML_OPENVINO_RELEASE_WEIGHTS).
@@ -661,6 +697,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
"multi-model runs.");
}
ggml_openvino_register_weight_buffer(ctx->data, ctx->size);
+ ctx->weight_registered = true;
}
if (!ctx->external_memory) {
@@ -700,12 +737,7 @@ static void ggml_backend_openvino_buffer_set_tensor(ggml_backend_buffer_t buffer
return;
}
- auto it = ctx->tensor_extras.find(tensor);
- if (it != ctx->tensor_extras.end()) {
- delete it->second;
- }
- ctx->tensor_extras[tensor] = extra;
- tensor->extra = extra;
+ ggml_openvino_set_extra(ctx, tensor, extra);
}
}
@@ -1087,15 +1119,8 @@ void ggml_openvino_buffer_register_extra(ggml_tensor * tensor, ggml_openvino_ext
GGML_ASSERT(tensor->buffer != nullptr);
GGML_ASSERT(ggml_backend_buffer_is_openvino(tensor->buffer));
- auto * ctx = static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context);
-
- auto it = ctx->tensor_extras.find(tensor);
- if (it != ctx->tensor_extras.end()) {
- delete it->second;
- }
-
- ctx->tensor_extras[tensor] = extra;
- tensor->extra = extra;
+ ggml_openvino_set_extra(static_cast<ggml_backend_openvino_buffer_context *>(tensor->buffer->context), tensor,
+ extra);
}
bool ggml_backend_buft_is_openvino(ggml_backend_buffer_type_t buft) {
@@ -1837,7 +1862,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
case GGML_OP_DIV: {
// The GPU plugin can fuse broadcast DIV into the preceding FFN GEMM path
// and produce infs for per-channel scale vectors. Keep those DIVs on CPU
- // until the fused GPU kernel is reliable. (falied case llama-arch-test mpt)
+ // until the fused GPU kernel is reliable (failing case: test-llama-archs, mpt).
// Only a weight divisor is such a scale; at one token an activation divisor has the same shape
// (qwen2moe's shared-expert sigmoid, silu(x) / x).
if (ggml_openvino_is_gpu() && op->src[1]->ne[0] == op->ne[0] &&
@@ -1898,11 +1923,10 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
memcpy(&max_bias, (const float *) op_params + 1, sizeof(float));
memcpy(&logit_softcap, (const float *) op_params + 2, sizeof(float));
- // Keep gemma3n flash-attn pattern on CPU for GPU runs to avoid
- // accuracy drift in the OpenVINO path. Restrict by scale=1.0 to avoid
- // affecting non-gemma3n models such as Llama-3.2.
+ // Keep gemma3n flash-attn pattern on CPU to avoid accuracy drift in the OpenVINO path.
+ // Restrict by scale=1.0 to avoid affecting non-gemma3n models such as Llama-3.2.
if (fabsf(scale - 1.0f) < 1e-6f && is_gemma3n_flash_attn_pattern(op)) {
- return {false, "FLASH_ATTN_EXT gemma3n pattern on GPU is not supported"};
+ return {false, "FLASH_ATTN_EXT gemma3n pattern is not supported"};
}
// K/V row lists (ggml_flash_attn_ext_rows) are not supported
@@ -1948,7 +1972,7 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
return {false, "CPY with BF16 src[1] type is not supported"};
}
if (ggml_openvino_is_npu() && (op->src[0]->type == GGML_TYPE_BF16 || op->src[1]->type == GGML_TYPE_BF16)) {
- return {false, "CPY with BF16 is not supported is not supported on NPU"};
+ return {false, "CPY with BF16 is not supported on NPU"};
}
// CPY to a quantized destination (e.g. f32 -> q4_0) is numerically unstable with OpenVINO backend.
if (ggml_is_quantized(op->type)) {
@@ -2063,12 +2087,15 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
// return true;
// }
const char * reason = nullptr;
- if (op->src[2]->op == GGML_OP_PERMUTE) {
+ // a VIEW of the PERMUTE (v with padded heads) is still a permuted v
+ const ggml_tensor * v_src = op->src[2]->op == GGML_OP_VIEW ? op->src[2]->src[0] : op->src[2];
+ if (v_src->op == GGML_OP_PERMUTE) {
reason = "GATED_DELTA_NET with PERMUTE src2 is not supported";
}
- else if (op->src[3]->ne[0] != 1) {
- // kda (per-key-dimension gating) not supported by fused GatedDeltaNet op
- reason = "GATED_DELTA_NET with kda (per-key-dimension gating) is not supported";
+ else if (op->src[3]->ne[0] != 1 && (op->op_params[0] > 1 || ggml_openvino_gdn_native_state_enabled()) &&
+ !ov::frontend::ggml::op::gdn_per_key_gate_supported()) {
+ reason = "GATED_DELTA_NET with a per-key gate needs an OpenVINO GatedDeltaNet with a rank-4 gate for state "
+ "snapshots or the native state layout";
}
else if (op->op_params[0] > 1) {
if (ggml_openvino_is_static()) {
@@ -2084,12 +2111,6 @@ static ggml_openvino_op_support is_op_supported_case(const ggml_tensor * op) {
}
break;
}
- case GGML_OP_SSM_CONV: {
- // qwen3next is numerically unstable with OpenVINO SSM_CONV.
- // Keep this op on CPU until the OpenVINO implementation is fixed.
- // return true;
- break;
- }
case GGML_OP_SSM_SCAN: {
// SelectiveSSM implements the Mamba-2 recurrence: scalar decay per head, one final state
if (op->src[3]->ne[0] != 1) {
@@ -2292,9 +2313,6 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
if (!supported) {
return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " has no op translator"};
}
- // if (has_view_op_input(op)) {
- // return {false, "GLU op " + std::string(ggml_glu_op_name(ggml_get_glu_op(op))) + " with view input is not supported"};
- // }
if (op->src[1] == nullptr && op->src[0]->ne[0] % 2 != 0) {
// triggers bug in ov gpu
return {false, "GLU op with odd src0 ne[0] and null src1 is not supported"};
@@ -2347,16 +2365,114 @@ static ggml_openvino_op_support ggml_backend_openvino_device_supports_op_impl(gg
return {true, ""};
}
+// Report what supports_op() accepts and rejects, so a graph that silently falls back to another
+// backend can be diagnosed. Every op rejected here becomes a graph split; if nothing is rejected,
+// the whole graph runs on OpenVINO.
+//
+// Gated by GGML_OPENVINO_LOG_SUPPORTS_OP:
+// 1 one summary at exit listing every distinct op kind and verdict -- start here
+// 2 additionally log every individual call, with the tensor name and shape
+//
+// This wraps the decision function instead of instrumenting it, so all of its return paths are
+// covered -- including the several that reject without logging a reason of their own, and any
+// added later.
+//
+// The summary is reported at exit rather than on each op's first occurrence, because the earliest
+// calls happen before the log handler emits anything: with level 2 the first line to actually
+// appear already reads "call 1244". A first-occurrence line would therefore be silently dropped
+// for exactly the ops that are only ever seen early. Counting is unaffected, so the summary is the
+// reliable view; treat the level-2 stream as a sample, not a complete trace.
+namespace {
+
+struct supports_op_tally {
+ std::mutex mutex;
+ // key: "<op>:ok" / "<op>:no" -> number of calls
+ std::map<std::string, size_t> counts;
+
+ // Report totals once, at exit. Registered lazily so a run with the knob off costs nothing.
+ // atexit runs while the ggml log callback is still valid, which static destruction does not
+ // guarantee.
+ void arm_summary() {
+ static std::once_flag armed;
+ std::call_once(armed, [] {
+ std::atexit([] {
+ auto & self = instance();
+ std::lock_guard<std::mutex> lock(self.mutex);
+
+ size_t n_accept_kinds = 0;
+ size_t n_reject_kinds = 0;
+ GGML_LOG_WARN("ov-supports-op: ---- summary (distinct op kinds, with call counts) ----\n");
+ for (const auto & [key, count] : self.counts) {
+ const bool ok = key.size() > 3 && key.compare(key.size() - 3, 3, ":ok") == 0;
+ ok ? ++n_accept_kinds : ++n_reject_kinds;
+ GGML_LOG_WARN("ov-supports-op: %-8s %-24s %zu call(s)\n", ok ? "ACCEPT" : "REJECT",
+ key.substr(0, key.size() - 3).c_str(), count);
+ }
+ if (n_reject_kinds == 0) {
+ GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, 0 rejected"
+ " -- every op was supported, so no split originated here\n",
+ n_accept_kinds);
+ } else {
+ GGML_LOG_WARN("ov-supports-op: %zu op kind(s) accepted, %zu REJECTED"
+ " -- each rejected kind forces a graph split\n",
+ n_accept_kinds, n_reject_kinds);
+ }
+ });
+ });
+ }
+
+ static supports_op_tally & instance() {
+ static supports_op_tally tally;
+ return tally;
+ }
+};
+
+} // namespace
+
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
- if (!res.is_supported) {
+ const bool supported = res.is_supported;
+ if (!supported) {
static const bool log_unsupported = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_UNSUPPORTED_OPS") != 0;
if (log_unsupported) {
GGML_LOG_WARN("OpenVINO op unsupported: op '%s' (%s), type %s: %s\n",
op->name, ggml_op_name(op->op), ggml_type_name(op->type), res.reason.c_str());
}
}
- return res.is_supported;
+
+ static const int log_level = ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SUPPORTS_OP");
+ if (log_level <= 0) {
+ return supported;
+ }
+
+ // Name the op the way ggml does: UNARY and GLU carry their real identity in a sub-enum, so
+ // logging only "UNARY" would merge SILU with everything else.
+ std::string op_desc = ggml_op_name(op->op);
+ if (op->op == GGML_OP_UNARY) {
+ op_desc += std::string("/") + ggml_unary_op_name(ggml_get_unary_op(op));
+ } else if (op->op == GGML_OP_GLU) {
+ op_desc += std::string("/") + ggml_glu_op_name(ggml_get_glu_op(op));
+ }
+
+ // The scheduler calls supports_op() on every graph build and may do so from several threads,
+ // so the tally needs a lock. Keyed on op identity *and* verdict, because the same op can be
+ // accepted at one shape and rejected at another (e.g. a quantized 3-D src).
+ auto & tally = supports_op_tally::instance();
+ tally.arm_summary();
+
+ size_t count;
+ {
+ std::lock_guard<std::mutex> lock(tally.mutex);
+ count = ++tally.counts[op_desc + (supported ? ":ok" : ":no")];
+ }
+
+ if (log_level >= 2) {
+ GGML_LOG_WARN("ov-supports-op: %-6s %-22s name='%s' type=%s ne=[%ld,%ld,%ld,%ld] (call %zu)\n",
+ supported ? "ACCEPT" : "REJECT", op_desc.c_str(), op->name, ggml_type_name(op->type),
+ (long) op->ne[0], (long) op->ne[1], (long) op->ne[2], (long) op->ne[3], count);
+ }
+
+ return supported;
}
static bool ggml_backend_openvino_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
diff --git a/ggml/src/ggml-openvino/ggml-quants.cpp b/ggml/src/ggml-openvino/ggml-quants.cpp
index 96b8da9be..0c0501fec 100644
--- a/ggml/src/ggml-openvino/ggml-quants.cpp
+++ b/ggml/src/ggml-openvino/ggml-quants.cpp
@@ -154,19 +154,22 @@ void extract_q4_1_data(const ggml_tensor * tensor,
});
} else {
auto * zp = static_cast<uint8_t *>(zp_arr.data());
- ov::parallel_for(scales_arr.get_size(), [&](size_t i) {
- float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
- float min = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
- scales[i] = ov::float16(scale);
- // zp = -min / scale (bias = min, so zp = -bias/scale)
- uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::round(-min / scale) : 0;
- // Pack two 4-bit zero points per byte
- if (i % 2 == 0) {
- zp[i / 2] = zp_val & 0x0F; // Lower nibble
- } else {
- zp[i / 2] |= (zp_val << 4); // Upper nibble
+ const size_t n_blocks = scales_arr.get_size();
+ // One iteration per zero point byte: the two blocks that share a byte are packed together, so no two
+ // threads write the same byte.
+ ov::parallel_for((n_blocks + 1) / 2, [&](size_t pair) {
+ uint8_t packed = 0;
+ for (size_t i = 2 * pair; i < std::min(2 * pair + 2, n_blocks); i++) {
+ float scale = static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block))));
+ float min =
+ static_cast<float>(ov::float16::from_bits(*((uint16_t *) (data + i * bytes_per_block + 2))));
+ scales[i] = ov::float16(scale);
+ // zp = -min / scale (bias = min, so zp = -bias/scale), in the u4 range
+ const uint8_t zp_val = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 15L) : 0;
+ packed |= (i % 2 == 0) ? zp_val : (uint8_t) (zp_val << 4);
+ unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
}
- unpack_32_4(data + i * bytes_per_block + 4, weights + i * 16);
+ zp[pair] = packed;
});
}
}
@@ -259,7 +262,7 @@ void extract_q5_1_data(const ggml_tensor * tensor,
float min = static_cast<float>(ov::float16::from_bits(read_u16(block + 2)));
scales[i] = ov::float16(scale);
// zp = -min / scale (dequant: (w - zp) * s == w*s + min)
- zp[i] = (scale != 0.0f) ? (uint8_t) std::lround(-min / scale) : 0;
+ zp[i] = (scale != 0.0f) ? (uint8_t) std::clamp(std::lround(-min / scale), 0L, 255L) : 0;
unpack_block(block, weights + i * qk);
});
}
@@ -378,7 +381,9 @@ void extract_q4_k_data(const ggml_tensor * tensor,
bias_f16[i * 8 + j] = ov::float16(-min_vals[j]);
} else {
// zp = min / scale (since bias = -min and zp = -bias/scale)
- uint8_t zp_val = (scale_vals[j] != 0.0f) ? (uint8_t) std::round(min_vals[j] / scale_vals[j]) : 0;
+ uint8_t zp_val = (scale_vals[j] != 0.0f) ?
+ (uint8_t) std::clamp(std::lround(min_vals[j] / scale_vals[j]), 0L, 15L) :
+ 0;
// Pack two 4-bit zero points per byte
size_t idx = i * 8 + j;
if (idx % 2 == 0) {
diff --git a/ggml/src/ggml-openvino/model-cache.cpp b/ggml/src/ggml-openvino/model-cache.cpp
index 7bfa7ad08..d35168750 100644
--- a/ggml/src/ggml-openvino/model-cache.cpp
+++ b/ggml/src/ggml-openvino/model-cache.cpp
@@ -186,6 +186,7 @@ static const char * cache_settings[] = {
"GGML_OPENVINO_DISABLE_SHAPE_FROM_MASK",
"GGML_OPENVINO_KV_SCATTER_ELEMENTS",
"GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN",
+ "GGML_OPENVINO_ROPE_F32_ANGLE",
};
void ggml_openvino_model_cache_init() {
@@ -368,7 +369,8 @@ uint64_t ggml_openvino_model_fingerprint(const ggml_cgraph * cgraph,
// Version 6 clears recurrent-cache slots with Select, so a NaN in a cleared slot does not survive.
// Version 7 reads ROPE frequency factors named other than rope_freqs.weight as a Constant, not a Parameter.
// Version 8 drops result_norm from the outputs when it has a consumer, and hashes the output flags.
- h = fnv1a_u64(h, 8);
+ // Version 9 hashes GGML_OPENVINO_ROPE_F32_ANGLE, which became opt-in.
+ h = fnv1a_u64(h, 9);
h = fnv1a(h, graph_signature.data(), graph_signature.size());
for (const char * name : cache_settings) {
const char * value = ggml_openvino_getenv_str(name, "");
@@ -548,8 +550,10 @@ static bool read_weights_hash(const std::string & path, uint64_t & hash) {
std::string key, value;
while (meta >> key >> value) {
if (key == "hash") {
- hash = std::stoull(value, nullptr, 16);
- return true;
+ // a damaged record counts as no hash, so the caller rewrites the file
+ char * end = nullptr;
+ hash = std::strtoull(value.c_str(), &end, 16);
+ return end != value.c_str() && *end == '\0';
}
}
return false;
diff --git a/ggml/src/ggml-openvino/openvino/op/argmax.cpp b/ggml/src/ggml-openvino/openvino/op/argmax.cpp
new file mode 100644
index 000000000..441a6a5b2
--- /dev/null
+++ b/ggml/src/ggml-openvino/openvino/op/argmax.cpp
@@ -0,0 +1,51 @@
+#include "../node_context.h"
+#include "../op_table.h"
+#include "../utils.h"
+#include "ggml.h"
+
+#include <openvino/frontend/exception.hpp>
+#include <openvino/op/concat.hpp>
+#include <openvino/op/constant.hpp>
+#include <openvino/op/reshape.hpp>
+#include <openvino/op/topk.hpp>
+
+namespace ov {
+namespace frontend {
+namespace ggml {
+namespace op {
+
+// GGML_OP_ARGMAX: src0 is a matrix [ne0, ne1]; the result is a 1-D I32 tensor of ne1 entries
+// holding, for each row, the index of the maximum along ne0. ggml shapes arrive reversed here, so
+// ne0 is the last OV axis and ne1 is axis 2. TopK(k=1, axis=last, MAX) yields exactly that index,
+// then reshape to the [1,1,1,ne1] layout the decoder expects for a 1-D ggml output.
+//
+// Note ggml's argmax returns the FIRST maximum on a tie, while TopK's tie-breaking is not specified
+// to match. Ties on real logits are vanishingly rare and none were observed, but the two are not
+// proven equivalent.
+OutputVector translate_argmax(const NodeContext & context) {
+ num_inputs_check(context, 1, 1);
+
+ auto input = process_view_input_new(context, 0);
+
+ auto k = ov::op::v0::Constant::create(ov::element::i64, {}, {1});
+ auto topk = std::make_shared<ov::op::v11::TopK>(input,
+ k,
+ 3,
+ ov::op::v11::TopK::Mode::MAX,
+ ov::op::v11::TopK::SortType::SORT_VALUES,
+ context.get_output_type(),
+ false);
+
+ // ne1 is the dynamic row count, so build the target shape at runtime.
+ auto leading = ov::op::v0::Constant::create(ov::element::i64, {3}, {1, 1, 1});
+ auto rows = get_dimensions(input.get_node_shared_ptr(), {2});
+ auto target_shape = std::make_shared<ov::op::v0::Concat>(OutputVector{leading, rows}, 0);
+ auto res = std::make_shared<ov::op::v1::Reshape>(topk->output(1), target_shape, false);
+
+ return rename_outputs_with_suffix({res}, context.get_name());
+}
+
+} // namespace op
+} // namespace ggml
+} // namespace frontend
+} // namespace ov
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 065e92fcd..b83c6de3a 100644
--- a/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/flash_attn_ext.cpp
@@ -182,13 +182,7 @@ OutputVector translate_flash_attn_ext(const NodeContext & context) {
// Manual GQA attention: enabled by default on GPU in stateless mode.
// Set GGML_OPENVINO_MANUAL_GQA_ATTN to a positive value (e.g. 1) to force-enable,
// or to 0 to force-disable. Unset falls back to the device-based default.
- static const bool manual_gqa_enabled = []() {
- const char * env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
- if (env != nullptr) {
- return ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0;
- }
- return ggml_openvino_is_gpu();
- }();
+ static const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
// The manual path reshapes Q, K, V and the output with one head size; models whose K/V head sizes differ
// from Q's (e.g. MLA) take the SDPA path.
const bool same_head_size = k_shape[3] == q_shape[3] && v_shape[3] == q_shape[3];
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 9acf3effb..6caafeb4f 100644
--- a/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/gated_delta_net.cpp
@@ -15,6 +15,7 @@
#include <memory>
#include <mutex>
#include <numeric>
+#include <openvino/core/model.hpp>
#include <openvino/op/add.hpp>
#include <openvino/op/broadcast.hpp>
#include <openvino/op/concat.hpp>
@@ -29,6 +30,7 @@
#include <openvino/op/maximum.hpp>
#include <openvino/op/minimum.hpp>
#include <openvino/op/multiply.hpp>
+#include <openvino/op/parameter.hpp>
#include <openvino/op/range.hpp>
#include <openvino/op/reduce_mean.hpp>
#include <openvino/op/reshape.hpp>
@@ -52,6 +54,31 @@ namespace op {
static OutputVector translate_gated_delta_net_ref(const NodeContext & context);
+// Asks the device: OpenVINO releases without the per-key gate reject a rank-4 gate when the node is built, and a plugin
+// without a per-key kernel leaves the node out of query_model
+bool gdn_per_key_gate_supported() {
+ static const bool supported = [] {
+ ov::ParameterVector params;
+ auto param = [¶ms](const ov::Shape & shape) {
+ params.push_back(std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shape));
+ return params.back();
+ };
+ std::shared_ptr<ov::Node> gdn;
+ try {
+ gdn = std::make_shared<ov::op::internal::GatedDeltaNet>(param({1, 1, 1, 2}), param({1, 1, 1, 2}),
+ param({1, 1, 1, 2}), param({1, 1, 2, 2}),
+ param({1, 1, 1, 2}), param({1, 1, 1}));
+ } catch (const ov::Exception &) {
+ return false;
+ }
+ const auto model = std::make_shared<ov::Model>(gdn->outputs(), params);
+ return ov_singleton_core()
+ .query_model(model, ggml_openvino_get_device_name())
+ .count(gdn->get_friendly_name()) != 0;
+ }();
+ return supported;
+}
+
static bool match_gdn_l2_norm(const Output<Node> & normalized, Output<Node> & input, float & eps) {
// Match the RMSNorm decomposition emitted by translate_rms_norm, followed by GGML SCALE.
const auto scale = ov::as_type_ptr<ov::op::v1::Multiply>(normalized.get_node_shared_ptr());
@@ -379,23 +406,36 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
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]
- // Fused GatedDeltaNet op only supports scalar gate (kda=0).
- // Fall back to reference implementation for per-key-dimension gating.
- // if (kda) {
- // return translate_gated_delta_net_ref(context);
- // }
+ // g [B, T, H_v, 1] gates each head, g [B, T, H_v, S_k] each key dimension (kda); the fused op takes the latter as
+ // a rank-4 gate
+ 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 &&
+ !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");
+ return translate_gated_delta_net_ref(context);
+ }
- // const int64_t B = v_shape[0];
- // const int64_t T = v_shape[1];
const int64_t H_v = v_shape[2];
const int64_t S_v = v_shape[3];
const int64_t H_k = q_shape[2];
const int64_t snapshot_count = context.get_output_op_params()[0];
- // const int64_t S_k = q_shape[3];
+
+ // v is usually a VIEW of the fused qkv conv output, [S_v, H_v, T, B] over [conv_dim, T, B], with the heads packed
+ // in each row: a Slice of that row plus the Reshape below. Any other view layout, e.g. heads padded to a wider
+ // row, goes through the generic view resolution, which already returns [B, T, H_v, S_v].
+ const bool v_is_view = context.get_view_input_size(2) > 0;
+ bool v_packed_heads = true;
+ if (v_is_view) {
+ const auto v_stride = context.get_view_input_stride(2, 0); // OV order: v_stride[3] = nb[0], v_stride[2] = nb[1]
+ v_packed_heads = v_stride.size() == 4 && v_stride[2] == (size_t) S_v * v_stride[3];
+ }
auto q = context.get_input(0);
auto k = context.get_input(1);
- auto v = process_view_input(context, 2, H_v * S_v, 3);
+ auto v = v_packed_heads ? process_view_input(context, 2, H_v * S_v, 3) : process_view_input_new(context, 2);
auto g = context.get_input(3);
auto beta = context.get_input(4);
auto state = context.get_input(5);
@@ -424,7 +464,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
k = std::make_shared<ov::op::v0::Tile>(k, repeats);
}
- if (context.get_view_input_size(2)) {
+ if (v_is_view && v_packed_heads) {
// Same as l2_norm case 1
v = std::make_shared<ov::op::v0::Squeeze>(v, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
auto v_shape = context.get_input_shape(2).to_shape();
@@ -443,7 +483,9 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
state = std::make_shared<ov::op::v1::Transpose>(state, state_perm);
}
- g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
+ if (!kda) {
+ g = std::make_shared<ov::op::v0::Squeeze>(g, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
+ }
beta = std::make_shared<ov::op::v0::Squeeze>(beta, ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
if (context.has_input("chunk_valid_len")) {
@@ -453,7 +495,7 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
// state equal to the state after the last real token. Attention output at those positions
// is garbage but never read.
const auto & g_ps = g.get_partial_shape();
- FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps.rank().get_length() == 3 && g_ps[1].is_static(),
+ FRONT_END_OP_CONVERSION_CHECK(g_ps.rank().is_static() && g_ps[1].is_static(),
"GATED_DELTA_NET pad masking requires a static token dimension");
const int64_t n_tokens = g_ps[1].get_length();
std::vector<int64_t> positions(n_tokens);
@@ -464,8 +506,12 @@ static OutputVector translate_gdn(const NodeContext & context, const OutputVecto
auto mask = std::make_shared<ov::op::v0::Unsqueeze>(
std::make_shared<ov::op::v0::Convert>(valid, g.get_element_type()),
ov::op::v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{0, 2}));
- g = std::make_shared<ov::op::v1::Multiply>(g, mask);
beta = std::make_shared<ov::op::v1::Multiply>(beta, mask);
+ if (kda) {
+ mask = std::make_shared<ov::op::v0::Unsqueeze>(mask,
+ ov::op::v0::Constant::create(ov::element::i64, {1}, {3}));
+ }
+ g = std::make_shared<ov::op::v1::Multiply>(g, mask);
}
// std::cout << "GatedDeltaNet input shapes: q=" << q.get_partial_shape() << ", k=" << k.get_partial_shape()
@@ -540,6 +586,8 @@ OutputVector translate_recurrent_gated_delta_net(const NodeContext & context, co
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"),
+ "GATED_DELTA_NET reference loop does not support padded prefill chunks");
// Inputs (OV shapes are reversed from ggml):
// ggml: q[S_k, H_k, T, B], k[S_k, H_k, T, B], v[S_v, H_v, T, B]
@@ -559,8 +607,8 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
auto q_shape = context.get_input_shape(0).to_shape(); // [B, T, H_k, S_k]
auto g_shape = context.get_input_shape(3).to_shape(); // [B, T, H_v, 1 or S_v]
+ // The token count T is dynamic: shapes below use -1 for it and the loop runs once per input token.
const int64_t B = v_shape[0];
- const int64_t T = v_shape[1];
const int64_t H_v = v_shape[2];
const int64_t S_v = v_shape[3];
const int64_t H_k = q_shape[2];
@@ -599,14 +647,14 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
auto q_transposed = std::make_shared<ov::op::v1::Transpose>(q_bcast, perm_5d);
auto k_transposed = std::make_shared<ov::op::v1::Transpose>(k_bcast, perm_5d);
- auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
+ auto new_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
q_bh = std::make_shared<ov::op::v1::Reshape>(q_transposed, new_shape, false);
k_bh = std::make_shared<ov::op::v1::Reshape>(k_transposed, new_shape, false);
}
// Merge batch and head dims: [B*H_v, T, S_v]
auto merge_bh = [&](const ov::Output<ov::Node> & x, int64_t last_dim) {
- auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, T, last_dim});
+ auto shape = ov::op::v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{B * H_v, -1, last_dim});
return std::make_shared<ov::op::v1::Reshape>(x, shape, false);
};
@@ -682,7 +730,9 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
ov::OutputVector{body_cond_out, state_updated, attn_out_unsq},
ov::ParameterVector{body_iter, body_state, body_q, body_k, body_v, body_g, body_beta});
- auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{T});
+ auto vm_shape = std::make_shared<ov::op::v3::ShapeOf>(v_m, ov::element::i64);
+ auto trip_count =
+ std::make_shared<ov::op::v8::Gather>(vm_shape, axis_1, ov::op::v0::Constant::create(ov::element::i64, {}, {0}));
auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, std::vector<bool>{true});
auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
@@ -709,7 +759,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
// attn: [B, T, H_v, S_v] row-major, state: [B, H_v, S_v, S_v] row-major
// attn: [B*H_v, T, S_v] -> [B, H_v, T, S_v] -> transpose to [B, T, H_v, S_v] -> flatten
- auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, T, S_v});
+ auto attn_4d_shape = ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{B, H_v, -1, S_v});
auto attn_4d = std::make_shared<ov::op::v1::Reshape>(attn_concat_out, attn_4d_shape, false);
auto attn_perm = std::make_shared<ov::op::v1::Transpose>(attn_4d, perm_0213); // [B, T, H_v, S_v]
@@ -729,7 +779,7 @@ static OutputVector translate_gated_delta_net_ref(const NodeContext & context) {
// Concat [attn | state] and reshape to final output
auto packed = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{attn_1d, state_1d}, 0);
auto out_shape =
- ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, T * B + S_v * B, S_v * H_v});
+ ov::op::v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, -1, S_v * H_v});
auto res = std::make_shared<ov::op::v1::Reshape>(packed, out_shape, false);
return rename_outputs_with_suffix({res}, context.get_name());
diff --git a/ggml/src/ggml-openvino/openvino/op/reshape.cpp b/ggml/src/ggml-openvino/openvino/op/reshape.cpp
index 98ef6fa2c..203d3d396 100644
--- a/ggml/src/ggml-openvino/openvino/op/reshape.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/reshape.cpp
@@ -30,6 +30,10 @@ OutputVector translate_reshape(const NodeContext & context) {
std::shared_ptr<ov::Node> new_shape_node;
switch (op_case) {
case 0:
+ // keep the tracked dynamic dim, e.g. the tokens of a reshape that only adds a trailing 1 (see translate_cont)
+ if (context.get_op_dynamic_dim() != -1) {
+ shape[3 - context.get_op_dynamic_dim()] = -1;
+ }
break;
case 1:
case 9:
diff --git a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp
index fb9eb5cc1..078b31823 100644
--- a/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/rms_norm.cpp
@@ -34,7 +34,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
input_node = context.get_input(0);
} else if (op_case == 1) {
input_node = process_view_input_new(context, 0);
- } else if (op_case == 2 || op_case == 3) {
+ } else if (op_case == 2 || op_case == 5) {
auto ssm_state_size = context.get_ssm_state_size();
// The GDN op packs [attn | new_state] along the row axis; the state occupies the last
// ssm_state_size * n_seqs rows. Slice it off (scaling by the active sequence count) to keep
@@ -83,7 +83,7 @@ OutputVector translate_rms_norm(const NodeContext & context) {
float eps;
memcpy(&eps, context.get_output_op_params(), sizeof(float));
- if (op_case == 3 && ggml_openvino_gdn_prescale_enabled()) {
+ if ((op_case == 3 || op_case == 5) && ggml_openvino_gdn_prescale_enabled()) {
// input is the GDN output pre-scaled by ggml_openvino_gdn_q_scale(): rms_norm(s*x, s*s*eps) == rms_norm(x, eps)
const float q_scale = ggml_openvino_gdn_q_scale();
eps *= q_scale * q_scale;
diff --git a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
index 476890911..24cbeac35 100644
--- a/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
+++ b/ggml/src/ggml-openvino/openvino/op/set_rows.cpp
@@ -118,16 +118,41 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
if (data.get_element_type() != context.get_output_type()) {
data = std::make_shared<v0::Convert>(data, context.get_output_type());
}
- Output<Node> rows = std::make_shared<v1::Reshape>(process_view_input_new(context, 1), i64_const({-1}), false);
+ auto row_ids = process_view_input_new(context, 1);
+ Output<Node> rows = std::make_shared<v1::Reshape>(row_ids, i64_const({-1}), false);
if (rows.get_element_type() != ov::element::i64) {
rows = std::make_shared<v0::Convert>(rows, ov::element::i64);
}
auto axis = v0::Constant::create(ov::element::i64, {}, {2});
- auto buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
+ Output<Node> buffer = std::make_shared<v1::Reshape>(base, i64_const({1, 1, -1, row_size}), false);
+ Output<Node> base_shape_of = std::make_shared<v3::ShapeOf>(base, ov::element::i64);
+ Output<Node> existing;
+
+ // Every write copies the whole buffer, so fold this one into the previous column write when both use the same
+ // rows (DFlash writes every target layer at the same batch rows): splice into its rows and scatter once
+ auto rows_source = [](Output<Node> r) {
+ if (ov::as_type_ptr<v0::Convert>(r.get_node_shared_ptr())) {
+ r = r.get_node()->input_value(0);
+ }
+ return ov::as_type_ptr<v1::Reshape>(r.get_node_shared_ptr()) ? r.get_node()->input_value(0) : Output<Node>();
+ };
+ auto prev_res = ov::as_type_ptr<v1::Reshape>(base.get_node_shared_ptr());
+ auto prev = prev_res ? ov::as_type_ptr<v3::ScatterUpdate>(prev_res->get_input_node_shared_ptr(0)) : nullptr;
+ if (prev && rows_source(prev->input_value(1)) == row_ids &&
+ prev->input_value(2).get_partial_shape().rank().is_static() &&
+ prev->input_value(2).get_partial_shape()[3] == row_size) {
+ buffer = prev->input_value(0);
+ rows = prev->input_value(1);
+ existing = prev->input_value(2);
+ base_shape_of = prev_res->input_value(1);
+ }
+
Output<Node> updates = data;
if (width < row_size) {
- auto existing = std::make_shared<v8::Gather>(buffer, rows, axis);
+ if (!existing.get_node_shared_ptr()) {
+ existing = std::make_shared<v8::Gather>(buffer, rows, axis);
+ }
auto col_axis = i64_const({3});
OutputVector parts;
if (col_begin > 0) {
@@ -142,7 +167,7 @@ static OutputVector translate_column_set_rows(const NodeContext & context) {
updates = std::make_shared<v0::Concat>(parts, 3);
}
auto updated = std::make_shared<v3::ScatterUpdate>(buffer, rows, updates, axis);
- auto res = std::make_shared<v1::Reshape>(updated, std::make_shared<v3::ShapeOf>(base, ov::element::i64), false);
+ auto res = std::make_shared<v1::Reshape>(updated, base_shape_of, false);
return rename_outputs_with_suffix({res}, context.get_name());
}
diff --git a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp b/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp
deleted file mode 100644
index 840233f85..000000000
--- a/ggml/src/ggml-openvino/openvino/op/solve_tri.cpp
+++ /dev/null
@@ -1,108 +0,0 @@
-#include "../node_context.h"
-#include "../op_table.h"
-#include "../utils.h"
-
-#include <openvino/op/broadcast.hpp>
-#include <openvino/op/constant.hpp>
-#include <openvino/op/divide.hpp>
-#include <openvino/op/gather.hpp>
-#include <openvino/op/loop.hpp>
-#include <openvino/op/matmul.hpp>
-#include <openvino/op/scatter_update.hpp>
-#include <openvino/op/shape_of.hpp>
-#include <openvino/op/subtract.hpp>
-
-namespace ov {
-namespace frontend {
-namespace ggml {
-namespace op {
-
-// GGML SOLVE_TRI: solve Ax = B for lower-triangular A via forward substitution.
-// Currently only lower, right, non-unitriangular variant is implemented.
-//
-// ggml layout: A [n, n, B1, B2], B [k, n, B1, B2] → X [k, n, B1, B2]
-// OV layout: A [B2, B1, n, n], B [B2, B1, n, k] → X [B2, B1, n, k]
-//
-// Forward substitution row i:
-// x[i] = (b[i] - sum_{t<i} A[i,t]*x[t]) / A[i,i]
-//
-// Implemented as an OV Loop op iterating n times with a carried X accumulator.
-// Key insight: A is lower-triangular and X starts as zeros, so the full matmul
-// A_row_i @ X_partial = sum_{t<i} A[i,t]*x[t] exactly (upper triangle of A
-// is zero; unfilled rows of X are zero).
-OutputVector translate_solve_tri(const NodeContext & context) {
- num_inputs_check(context, 2, 2);
-
- auto A = context.get_input(0); // [B2, B1, n, n]
- auto B = context.get_input(1); // [B2, B1, n, k]
-
- auto A_shape = context.get_input_shape(0).to_shape();
- int64_t n = static_cast<int64_t>(A_shape[2]);
-
- // Initial X: zeros with shape of B
- auto B_shape_node = std::make_shared<ov::op::v3::ShapeOf>(B, ov::element::i64);
- auto zero_f32 = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f});
- auto X_init = std::make_shared<ov::op::v3::Broadcast>(zero_f32, B_shape_node);
-
- // --- Loop body parameters ---
- // body_iter: iteration counter injected by the Loop op (i64, shape {1})
- auto body_iter = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::Shape{1});
- auto body_X = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
- auto body_A = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
- auto body_B_p = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape::dynamic(4));
-
- auto c_axis2 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(2)});
- auto c_axis3 = ov::op::v0::Constant::create(ov::element::i64, {1}, {int64_t(3)});
- auto c_axis2_scalar = ov::op::v0::Constant::create(ov::element::i64, {}, {int64_t(2)});
-
- // b_i = B[..., i, :] [B2, B1, 1, k]
- auto b_i = std::make_shared<ov::op::v8::Gather>(body_B_p, body_iter, c_axis2);
-
- // A_row_i = A[..., i, :] [B2, B1, 1, n]
- auto A_row_i = std::make_shared<ov::op::v8::Gather>(body_A, body_iter, c_axis2);
-
- // sum_i = A_row_i @ X [B2, B1, 1, k]
- // (lower-tri zeros + unfilled-X zeros make this equal to the partial sum)
- auto sum_i = std::make_shared<ov::op::v0::MatMul>(A_row_i, body_X, false, false);
-
- // diag_i = A[..., i, i] [B2, B1, 1, 1]
- auto diag_i = std::make_shared<ov::op::v8::Gather>(A_row_i, body_iter, c_axis3);
-
- // x_i = (b_i - sum_i) / diag_i [B2, B1, 1, k]
- auto x_i = std::make_shared<ov::op::v1::Divide>(
- std::make_shared<ov::op::v1::Subtract>(b_i, sum_i), diag_i);
-
- // X_updated: scatter x_i into body_X at row i along axis 2
- auto X_updated = std::make_shared<ov::op::v3::ScatterUpdate>(body_X, body_iter, x_i, c_axis2_scalar);
-
- auto body_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
-
- auto body = std::make_shared<ov::Model>(
- ov::OutputVector{body_cond, X_updated},
- ov::ParameterVector{body_iter, body_X, body_A, body_B_p});
-
- // --- Assemble Loop ---
- auto trip_count = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{n});
- auto exec_cond = ov::op::v0::Constant::create(ov::element::boolean, ov::Shape{1}, {true});
-
- auto loop = std::make_shared<ov::op::v5::Loop>(trip_count, exec_cond);
- loop->set_function(body);
- // iter_counter_body_param_idx=0 (body_iter), exec_condition_body_result_idx=0 (body_cond)
- loop->set_special_body_ports(ov::op::v5::Loop::SpecialBodyPorts{0, 0});
-
- // Carried state: X feeds back from X_updated each iteration
- loop->set_merged_input(body_X, X_init, X_updated);
- // Invariant inputs passed through unchanged
- loop->set_invariant_input(body_A, A);
- loop->set_invariant_input(body_B_p, B);
-
- // Final output: value of X_updated after the last iteration
- auto X_final = loop->get_iter_value(X_updated, -1);
-
- return rename_outputs_with_suffix({X_final}, context.get_name());
-}
-
-} // namespace op
-} // namespace ggml
-} // namespace frontend
-} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/op_table.cpp b/ggml/src/ggml-openvino/openvino/op_table.cpp
index defc428d1..4983e2a7c 100644
--- a/ggml/src/ggml-openvino/openvino/op_table.cpp
+++ b/ggml/src/ggml-openvino/openvino/op_table.cpp
@@ -57,6 +57,7 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_SQR", op::translate_sqr },
{"GGML_OP_SQRT", op::translate_sqrt },
{"GGML_OP_SOFT_MAX", op::translate_soft_max },
+ {"GGML_OP_ARGMAX", op::translate_argmax },
{"GGML_OP_ARGSORT", op::translate_argsort },
{"GGML_OP_SUB", op::translate_1to1_match_2_inputs<v1::Subtract>},
{"GGML_OP_TRANSPOSE", op::translate_transpose },
@@ -102,7 +103,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_GATED_DELTA_NET", op::translate_gated_delta_net },
{"GGML_OP_REPEAT", op::translate_repeat },
{"GGML_OP_CUMSUM", op::translate_cumsum },
- {"GGML_OP_FILL", op::translate_fill },
{"GGML_OP_DIAG", op::translate_diag },
{"GGML_OP_TRI", op::translate_tri },
{"GGML_OP_SET", op::translate_set },
@@ -115,8 +115,6 @@ std::unordered_map<std::string, CreatorFunction> get_supported_ops() {
{"GGML_OP_CONV_TRANSPOSE_1D", op::translate_conv_transpose_1d },
{"GGML_OP_CONV_TRANSPOSE_2D", op::translate_conv_transpose_2d },
{"GGML_OP_CONV_3D", op::translate_conv_3d },
- // solve_tri has accuracy issues on GPU
- // {"GGML_OP_SOLVE_TRI", op::translate_solve_tri },
};
}
diff --git a/ggml/src/ggml-openvino/openvino/op_table.h b/ggml/src/ggml-openvino/openvino/op_table.h
index 54c60c634..766ca4e6f 100644
--- a/ggml/src/ggml-openvino/openvino/op_table.h
+++ b/ggml/src/ggml-openvino/openvino/op_table.h
@@ -43,6 +43,7 @@ GGML_OP_CONVERTER(translate_glu_geglu);
GGML_OP_CONVERTER(translate_glu_geglu_quick);
GGML_OP_CONVERTER(translate_set_rows);
GGML_OP_CONVERTER(translate_cpy);
+GGML_OP_CONVERTER(translate_argmax);
GGML_OP_CONVERTER(translate_argsort);
GGML_OP_CONVERTER(translate_top_k);
GGML_OP_CONVERTER(translate_flash_attn_ext);
@@ -51,16 +52,16 @@ GGML_OP_CONVERTER(translate_pad);
GGML_OP_CONVERTER(translate_ssm_conv);
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
GGML_OP_CONVERTER(translate_repeat);
GGML_OP_CONVERTER(translate_cumsum);
-GGML_OP_CONVERTER(translate_fill);
GGML_OP_CONVERTER(translate_set);
GGML_OP_CONVERTER(translate_diag);
GGML_OP_CONVERTER(translate_tri);
-GGML_OP_CONVERTER(translate_solve_tri);
GGML_OP_CONVERTER(translate_pool_1d);
GGML_OP_CONVERTER(translate_pool_2d);
GGML_OP_CONVERTER(translate_roll);
diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp
deleted file mode 100644
index 0671542ee..000000000
--- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-#include "fuse_to_sdpa.h"
-
-#include <openvino/core/graph_util.hpp>
-#include <openvino/core/rt_info.hpp>
-#include <openvino/op/add.hpp>
-#include <openvino/op/convert.hpp>
-#include <openvino/op/matmul.hpp>
-#include <openvino/op/multiply.hpp>
-#include <openvino/op/scaled_dot_product_attention.hpp>
-#include <openvino/op/softmax.hpp>
-#include <openvino/op/transpose.hpp>
-#include <openvino/pass/pattern/op/label.hpp>
-#include <openvino/pass/pattern/op/pattern.hpp>
-#include <openvino/pass/pattern/op/wrap_type.hpp>
-
-namespace ov {
-namespace frontend {
-namespace ggml {
-namespace pass {
-
-FuseToSDPA::FuseToSDPA() {
- // Not maintained since FLASH_ATTN_EXT has replaced this pattern
- const auto m_k = ov::pass::pattern::any_input();
- const auto m_q = ov::pass::pattern::any_input();
- const auto m_qk = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_q, m_k});
- const auto m_qk_f32 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_qk});
- const auto m_scale = ov::pass::pattern::any_input();
- const auto m_scaled_qk = ov::pass::pattern::wrap_type<ov::op::v1::Multiply>({m_qk_f32, m_scale});
- const auto m_mask = ov::pass::pattern::any_input();
- const auto m_masked_qk = ov::pass::pattern::wrap_type<ov::op::v1::Add>({m_scaled_qk, m_mask});
- const auto m_softmax_qk = ov::pass::pattern::wrap_type<ov::op::v8::Softmax>({m_masked_qk});
- const auto m_softmax_qk_f16 = ov::pass::pattern::wrap_type<ov::op::v0::Convert>({m_softmax_qk});
- const auto m_v = ov::pass::pattern::any_input();
- const auto m_qkv = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({m_softmax_qk_f16, m_v});
-
- const auto callback = [=](ov::pass::pattern::Matcher & m) {
- auto & pattern_to_output = m.get_pattern_value_map();
- auto k = pattern_to_output[m_k];
- auto q = pattern_to_output[m_q];
- auto v = pattern_to_output[m_v];
- auto mask = pattern_to_output[m_mask];
- auto scale = pattern_to_output[m_scale];
-
- auto mask_f16 = register_new_node<ov::op::v0::Convert>(mask, ov::element::f16);
- auto scale_f16 = register_new_node<ov::op::v0::Convert>(scale, ov::element::f16);
- auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q, k, v, mask_f16, scale_f16, false);
-
- ov::replace_node(m.get_match_root(), sdpa);
- ov::copy_runtime_info(m.get_matched_nodes(), sdpa);
-
- return true;
- };
- register_matcher(std::make_shared<ov::pass::pattern::Matcher>(m_qkv, "ov::frontend::ggml::pass::FuseToSDPA"),
- callback);
-}
-
-} // namespace pass
-} // namespace ggml
-} // namespace frontend
-} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h b/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h
deleted file mode 100644
index 8b5164d23..000000000
--- a/ggml/src/ggml-openvino/openvino/pass/fuse_to_sdpa.h
+++ /dev/null
@@ -1,17 +0,0 @@
-#include "openvino/pass/matcher_pass.hpp"
-
-namespace ov {
-namespace frontend {
-namespace ggml {
-namespace pass {
-
-class FuseToSDPA : public ov::pass::MatcherPass {
-public:
- OPENVINO_MATCHER_PASS_RTTI("ov::frontend::ggml::pass::FuseToSDPA")
- FuseToSDPA();
-};
-
-} // namespace pass
-} // namespace ggml
-} // namespace frontend
-} // namespace ov
diff --git a/ggml/src/ggml-openvino/openvino/translate_session.cpp b/ggml/src/ggml-openvino/openvino/translate_session.cpp
index 3da712f72..eddebd901 100644
--- a/ggml/src/ggml-openvino/openvino/translate_session.cpp
+++ b/ggml/src/ggml-openvino/openvino/translate_session.cpp
@@ -225,42 +225,12 @@ void add_position_mask_stateful_swa(TensorMap & tensor_map) {
tensor_map["KQ_mask_swa_sliced"] = mask->output(0);
}
-void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
- // When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed
- // SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos
- // precompute cannot broadcast across every ROPE use. Skip it here and let
- // translate_rope() build sin/cos per-op from its own op_params.
- if (ggml_model_decoder.has_mixed_rope_params()) {
- return;
- }
- int32_t * rope_params = ggml_model_decoder.get_rope_params();
- if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) {
- return;
- }
- auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
- std::shared_ptr<ov::Node> rope_freqs_weight;
- if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) {
- rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr();
- }
-
- auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight);
- auto sin_theta = sin_cos.first;
- auto cos_theta = sin_cos.second;
-
- cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos");
- sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin");
- tensor_map.insert({"rope_cos", cos_theta});
- tensor_map.insert({"rope_sin", sin_theta});
-}
-
// Create common patterns
void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
if (ggml_model_decoder.is_stateful()) {
add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE);
add_position_mask_stateful_swa(tensor_map);
}
- // This optimization is error-prone
- // add_rope_sin_cos(tensor_map, ggml_model_decoder);
}
} // namespace
diff --git a/ggml/src/ggml-openvino/openvino/utils.cpp b/ggml/src/ggml-openvino/openvino/utils.cpp
index e82a6c92f..7094cb733 100644
--- a/ggml/src/ggml-openvino/openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/openvino/utils.cpp
@@ -31,6 +31,7 @@
#include <openvino/op/subtract.hpp>
#include <openvino/op/transpose.hpp>
#include <openvino/op/unsqueeze.hpp>
+#include <openvino/op/util/precision_sensitive_attribute.hpp>
#include <string>
namespace ov {
@@ -43,18 +44,6 @@ void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max
FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");
}
-int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
- int dim = nb.size() - 1;
- size_t bytes = nb[dim];
- for (int i = dim; i > 0; i--) {
- bytes *= ne[i];
- if (bytes != nb[i - 1]) {
- return i;
- }
- }
- return 0;
-}
-
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
const std::vector<int> & dims) {
using namespace ov::op;
@@ -311,14 +300,77 @@ std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params
}
}
- Output<Node> cos_theta = std::make_shared<ov::op::v0::Cos>(theta);
- Output<Node> sin_theta = std::make_shared<ov::op::v0::Sin>(theta);
+ // Keep the ROPE ANGLE in f32 even under INFERENCE_PRECISION_HINT=f16.
+ //
+ // Everything above builds theta = pos * freq_factors with a declared f32 type, but a declared
+ // element type is not an execution precision: under the f16 hint the GPU plugin compresses these
+ // subgraphs to f16 anyway. theta's magnitude IS the token position, so at position 6525 it lands
+ // where f16 spacing is 4 and the value is not even representable. Worse, a model whose freq_base
+ // and head_dim make factor[0] == 1.0 exactly feeds the raw position in as the top-frequency
+ // angle, so an absolute error of 1-2 becomes an error of 1-2 RADIANS -- up to a third of a cycle. Sin/Cos of an angle wrong by radians is not approximately
+ // right, it is arbitrary, and trig amplifies the error without bound.
+ //
+ // Measured on a large decoder-only model at inp_pos=6525, same device, f16 vs f32 execution: the
+ // whole Q/K projection chain is clean at rel ~1e-4, then Cos jumps to rel 0.124 and Sin to 0.155,
+ // and K right after the rotation carries rel 0.081. The error is depth-dependent because f16
+ // spacing grows with magnitude: sin rel is 0.006 at position 512 and 0.16 at 6525.
+ //
+ // mark_as_precision_sensitive disables fp16 compression of the subgraph feeding an input, which is
+ // exactly the guarantee needed. Marking Sin/Cos's input covers the whole theta chain back to the
+ // Convert of inp_pos. The cost is negligible: theta is a few dozen values per token, against the
+ // matmuls that dominate. The rotation itself and everything downstream stay f16.
+ //
+ // Off by default; GGML_OPENVINO_ROPE_F32_ANGLE=1 turns it on. It changes the RoPE of every model,
+ // it is validated on one model on the GPU only, and on an f32 path the round trip below makes
+ // cos and sin less accurate.
+ const bool pin_angle = ggml_openvino_getenv_int("GGML_OPENVINO_ROPE_F32_ANGLE") != 0;
+
+ auto cos_op = std::make_shared<ov::op::v0::Cos>(theta);
+ auto sin_op = std::make_shared<ov::op::v0::Sin>(theta);
+ if (pin_angle) {
+ ov::mark_as_precision_sensitive(cos_op->input(0));
+ ov::mark_as_precision_sensitive(sin_op->input(0));
+ }
+ Output<Node> cos_theta = cos_op;
+ Output<Node> sin_theta = sin_op;
if (mscale != 1.0f) {
auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});
- cos_theta = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
- sin_theta = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
+ auto cos_scaled = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
+ auto sin_scaled = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
+ // Mark this Constant's input too. Marking only Sin/Cos keeps those nodes f32 but leaves the
+ // sibling mscale Constant to be compressed to f16, and the pass does not reconcile the pair,
+ // so compilation fails with "Arguments do not have the same element type".
+ if (pin_angle) {
+ ov::mark_as_precision_sensitive(cos_scaled->input(1));
+ ov::mark_as_precision_sensitive(sin_scaled->input(1));
+ }
+ cos_theta = cos_scaled;
+ sin_theta = sin_scaled;
+ }
+
+ // Close the f32 island explicitly with an f16 round trip.
+ //
+ // ConvertPrecision does not insert the boundary Convert: with only the marking above, the f32
+ // region propagates forward through the shape-only ops of the cos/sin expansion and then collides
+ // with f16 data in the rotation, so the type mismatch just moves one step down the graph.
+ //
+ // Rounding the RESULT of the trig is harmless -- cos/sin are in [-1,1], where f16 spacing is ~6e-4,
+ // the ordinary f16 cost accepted everywhere else. What must not be rounded is the ANGLE, which the
+ // marking above protects. So this spends the cheap rounding to buy a type-consistent graph: the
+ // chain from inp_pos through Sin/Cos stays f32, everything downstream is f16, and the transition is
+ // a node we control rather than one the pass has to infer.
+ //
+ // Declared types are f32 on both sides at build time, so the frontend sees no type change. On an
+ // f32 path (the CPU device in test-backend-ops) the two Converts still round cos and sin to f16.
+ if (pin_angle) {
+ auto pin_boundary = [](Output<Node> x) -> Output<Node> {
+ auto down = std::make_shared<ov::op::v0::Convert>(x, ov::element::f16);
+ return std::make_shared<ov::op::v0::Convert>(down, ov::element::f32);
+ };
+ cos_theta = pin_boundary(cos_theta);
+ sin_theta = pin_boundary(sin_theta);
}
return std::make_pair(sin_theta, cos_theta);
@@ -784,20 +836,23 @@ ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int inp
return split_node->output(static_cast<size_t>(split_index));
}
if (split_index >= 0 && split_index < num_splits && !dynamic_split) {
+ // as above: a weak reference, and one Split per output port
auto src_node = input.get_node_shared_ptr();
- std::string rt_key = "split_dim_" + std::to_string(split_dim);
+ std::string rt_key =
+ "split_dim_static_" + std::to_string(split_dim) + "_" + std::to_string(input.get_index());
auto & rt_info = src_node->get_rt_info();
-
- if (rt_info.find(rt_key) == rt_info.end()) {
+ std::shared_ptr<ov::Node> split_node;
+ if (rt_info.count(rt_key) != 0) {
+ split_node = rt_info[rt_key].as<std::weak_ptr<ov::Node>>().lock();
+ }
+ if (split_node == nullptr) {
auto axis_const =
ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast<int64_t>(split_dim)});
- auto split_node =
+ split_node =
std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
- rt_info[rt_key] = split_node;
+ rt_info[rt_key] = std::weak_ptr<ov::Node>(split_node);
}
-
- auto split_node = rt_info[rt_key].as<std::shared_ptr<ov::op::v1::Split>>();
return split_node->output(static_cast<size_t>(split_index));
}
}
diff --git a/ggml/src/ggml-openvino/openvino/utils.h b/ggml/src/ggml-openvino/openvino/utils.h
index aaee05116..3fe3b60f9 100644
--- a/ggml/src/ggml-openvino/openvino/utils.h
+++ b/ggml/src/ggml-openvino/openvino/utils.h
@@ -13,42 +13,8 @@ namespace ov {
namespace frontend {
namespace ggml {
-std::string getCurrentTime();
-
void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs);
-int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb);
-
-template <typename T> std::vector<int> argsort_descend(const std::vector<T> & v) {
- std::vector<int> idx(v.size());
- std::iota(idx.begin(), idx.end(), 0);
- std::sort(idx.begin(), idx.end(), [&v](int i1, int i2) { return v[i1] > v[i2]; });
- return idx;
-}
-
-template <typename T> std::vector<T> sorted_descend(std::vector<T> v) {
- std::sort(v.begin(), v.end(), [](T a, T b) { return a > b; });
- return v;
-}
-
-template <typename T> bool is_permuted(const std::vector<T> & strides) {
- for (size_t i = 0; i < strides.size() - 1; ++i) {
- if (strides[i] < strides[i + 1]) {
- return true;
- }
- }
- return false;
-}
-
-template <typename T> std::vector<T> permute(const std::vector<T> & x, const std::vector<int> & perm) {
- std::vector<T> result;
- result.reserve(perm.size());
- for (int i : perm) {
- result.push_back(x[i]);
- }
- return result;
-}
-
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
const std::vector<int> & dims);
std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node, const std::vector<int> & dims);
diff --git a/ggml/src/ggml-openvino/utils.cpp b/ggml/src/ggml-openvino/utils.cpp
index c959ce0d9..03479f35e 100644
--- a/ggml/src/ggml-openvino/utils.cpp
+++ b/ggml/src/ggml-openvino/utils.cpp
@@ -151,6 +151,12 @@ std::optional<ov::Tensor> try_make_kv_sliced_tensor(const std::shared_ptr<GgmlOv
return std::nullopt;
}
+ if (ggml_tensor->data == nullptr) {
+ // unallocated input: let the caller build an owning zero tensor rather than slice a null
+ // pointer
+ return std::nullopt;
+ }
+
ov::Shape sliced_shape = full_shape;
sliced_shape[2] = static_cast<size_t>(n_kv);
@@ -192,10 +198,10 @@ std::optional<ov::Tensor> try_make_kv_4d_tensor(const std::shared_ptr<GgmlOvDeco
}
// Column count of a static KQ mask input; must match GgmlOvDecoder::get_graph_input_shape().
-static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_decoder, const std::string & name) {
+static size_t get_static_attention_size(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & name) {
const bool is_swa = ggml_decoder->is_swa_mask(ggml_decoder->get_input_ggml_tensor(name));
if (ggml_decoder->m_is_prefill ? ggml_openvino_kv_slice_enabled() : ggml_openvino_npu_decode_bucket() > 0) {
- const auto params = ggml_decoder->get_compute_params();
+ const auto & params = ggml_decoder->get_compute_params();
const int attention_size = is_swa ? params.attention_size_swa : params.attention_size;
if (attention_size > 0) {
return static_cast<size_t>(attention_size);
@@ -209,10 +215,7 @@ static size_t get_static_attention_size(std::shared_ptr<GgmlOvDecoder> ggml_deco
}
static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) {
- const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
- const bool manual_gqa_enabled = manual_gqa_env != nullptr ?
- ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 :
- ggml_openvino_is_gpu();
+ const bool manual_gqa_enabled = ggml_openvino_manual_gqa_enabled();
uint64_t extra_cfg = 15; // Recurrent caches are writable inputs without cache Results.
#ifdef GGML_OPENVINO_HAS_CACHE_UPDATE
@@ -561,6 +564,11 @@ ov::Tensor create_ov_output_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_d
return context.create_tensor(output_type, output_shape, resolved);
}
+ // A graph output can also have no backing storage. Give OV an owning tensor so the infer request
+ // has somewhere to write; nothing downstream reads it.
+ if (output_data == nullptr) {
+ return ov::Tensor(output_type, output_shape);
+ }
ov::Tensor output_tensor(output_type, output_shape, output_data);
return output_tensor;
}
@@ -713,6 +721,20 @@ ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr<GgmlOvDecoder> & ggml_
return make_contiguous_split_input_tensor(ggml_tensor, input_shape);
}
+ // A graph input may legitimately be left unallocated (data == nullptr, no buffer): llama.cpp
+ // skips filling the attention mask when a graph only stores K/V without attending, which is what
+ // a speculative KV-injection pass does. Such an input is never read, but OpenVINO still requires
+ // a backing tensor for the Parameter and constructing an ov::Tensor over a null pointer asserts.
+ // Hand OV an owning zero-filled tensor; its contents cannot affect the result because no op
+ // consumes them.
+ if (input_data == nullptr) {
+ GGML_LOG_WARN("ggml-openvino: unallocated INPUT '%s' (ggml name '%s', type %s, ne=[%ld,%ld,%ld,%ld]) "
+ "-> zero tensor\n",
+ name.c_str(), ggml_tensor->name, ggml_type_name(ggml_tensor->type),
+ (long) ggml_tensor->ne[0], (long) ggml_tensor->ne[1], (long) ggml_tensor->ne[2],
+ (long) ggml_tensor->ne[3]);
+ return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
+ }
auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data);
return input_tensor;
}
@@ -790,10 +812,8 @@ ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder
if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
ov::Shape input_shape = {1, 1, 1, 1};
ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
- int32_t inp_out_id = *((int32_t *) ggml_tensor->data);
- assert(ggml_tensor->ne[0] == 1);
- assert(inp_out_id == 0);
- *input_tensor.data<int32_t>() = inp_out_id;
+ // The only decode token is row 0. out_ids is empty when the graph has no output, so it is not read.
+ *input_tensor.data<int32_t>() = 0;
return input_tensor;
}
@@ -1256,13 +1276,15 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
cache_hit = it != r_ctx->decoder_cache.end();
if (cache_hit) {
entry = it->second;
+ r_ctx->touch_locked(key);
} else {
- if (r_ctx->stateful || r_ctx->decoder_cache.size() >= 8) {
+ if (r_ctx->stateful) {
r_ctx->clear_caches_locked();
}
auto mutex = std::make_shared<std::mutex>();
entry = std::make_shared<decoder_runtime_ctx>(mutex);
r_ctx->decoder_cache[key] = entry;
+ r_ctx->admit_locked(key);
}
} else {
auto mutex = std::make_shared<std::mutex>();
@@ -1276,10 +1298,21 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
if (cache_hit) {
ggml_decoder = entry->ptr;
+ // The cache key is only (n_nodes, first/last node name), so it cannot see a change in
+ // WHICH tensors are graph outputs -- and the compiled model's Results are fixed when it is
+ // built. A consumer that starts requesting extra outputs later (speculative decoding marks
+ // the target's per-layer residuals only once the draft is initialised) would otherwise keep
+ // reusing a model that never produces them, and the host would read unwritten buffers as
+ // zeros. Recompile when the output set differs.
old_m_params = ggml_decoder->get_model_params();
if (!ggml_decoder->is_splited_model()) {
cache_hit = old_m_params.can_reuse_dynamically(m_params);
}
+ // Must come AFTER can_reuse_dynamically(), which ASSIGNS to cache_hit rather than
+ // and-ing into it and would otherwise silently undo this invalidation.
+ if (cache_hit && !ggml_decoder->has_same_graph_io(cgraph)) {
+ cache_hit = false;
+ }
}
std::vector<std::string> ov_input_names;
@@ -1654,8 +1687,6 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
shared_model = compiled_model;
- entry->ptr = ggml_decoder;
-
} // end non-imported (compile) path
entry->ptr = ggml_decoder;
@@ -1725,7 +1756,20 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
id = binding.staging_id;
}
if (needs_bind(binding, input_tensor, id)) {
- infer_request->set_input_tensor(i, input_tensor);
+ try {
+ infer_request->set_input_tensor(i, input_tensor);
+ } catch (const std::exception & e) {
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
+ auto port = infer_request->get_compiled_model().input(i);
+ GGML_LOG_WARN(
+ "ggml-openvino: DIAG set_input_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
+ " model_shape=%s bound_shape=%s\n",
+ i, param_name.c_str(), key.n_nodes, key.first_node_name.c_str(),
+ key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
+ input_tensor.get_shape().to_string().c_str());
+ }
+ throw;
+ }
}
if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
@@ -1786,12 +1830,40 @@ enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::share
id = binding.staging_id;
}
if (needs_bind(binding, output_tensor, id)) {
- infer_request->set_output_tensor(i, output_tensor);
+ try {
+ infer_request->set_output_tensor(i, output_tensor);
+ } catch (const std::exception & e) {
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
+ auto port = infer_request->get_compiled_model().output(i);
+ GGML_LOG_WARN(
+ "ggml-openvino: DIAG set_output_tensor[%zu] '%s' threw for n_nodes=%d first=%s last=%s: %s\n"
+ " model_shape=%s bound_shape=%s\n",
+ i, ov_output_names[i].c_str(), key.n_nodes, key.first_node_name.c_str(),
+ key.last_node_name.c_str(), e.what(), port.get_partial_shape().to_string().c_str(),
+ output_tensor.get_shape().to_string().c_str());
+ }
+ throw;
+ }
}
}
ov_raw_infer_start = ggml_time_us();
- infer_request->infer();
+ try {
+ infer_request->infer();
+ } catch (const std::exception & e) {
+ if (ggml_openvino_getenv_int("GGML_OPENVINO_DIAG_GRAPH_IO")) {
+ auto cm = infer_request->get_compiled_model();
+ GGML_LOG_WARN("ggml-openvino: DIAG infer() threw for n_nodes=%d first=%s last=%s: %s\n", key.n_nodes,
+ key.first_node_name.c_str(), key.last_node_name.c_str(), e.what());
+ for (size_t i = 0; i < ov_input_names.size(); i++) {
+ auto port = cm.input(i);
+ GGML_LOG_WARN(" param[%zu] name=%s model_shape=%s bound_shape=%s\n", i,
+ ov_input_names[i].c_str(), port.get_partial_shape().to_string().c_str(),
+ infer_request->get_input_tensor(i).get_shape().to_string().c_str());
+ }
+ }
+ throw;
+ }
infer_end_time = ggml_time_us();
for (const auto & out : staged_outputs) {
std::memcpy(out.dst, out.src, out.bytes);
@@ -2190,11 +2262,12 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
cache_hit = it != r_ctx->decoder_cache.end();
if (cache_hit) {
entry = it->second;
+ r_ctx->touch_locked(key);
} else {
- r_ctx->clear_caches_locked();
auto mutex = std::make_shared<std::mutex>();
entry = std::make_shared<decoder_runtime_ctx>(mutex);
r_ctx->decoder_cache[key] = entry;
+ r_ctx->admit_locked(key);
}
} else {
auto mutex = std::make_shared<std::mutex>();
@@ -2265,10 +2338,8 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
// Same fail-fast as the dynamic path: once the host weight pages have been dropped
// they read as zeros, so a recompile here would bake garbage into the new model.
if (ggml_openvino_weight_buffers_released()) {
- GGML_ABORT(
- "ggml-openvino: a new graph needs to be compiled but host weight buffers were already "
- "released via GGML_OPENVINO_RELEASE_WEIGHTS. This mode requires "
- "stable graph shapes; disable host weight release for dynamic workloads.");
+ GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
+ return GGML_STATUS_FAILED;
}
if (cache_enabled) {
std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
@@ -2318,6 +2389,10 @@ enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared
}
} else {
auto decode_c_params = c_params;
+ // A decode step outputs its one token. llama-perplexity asks for many outputs in the prefill graph; the
+ // decode model of the pair keeps one (decode_signature below), or its last layer would gather more rows
+ // than the graph has tokens.
+ decode_c_params.output_len = 1;
if (ggml_openvino_kv_slice_enabled()) {
decode_c_params.attention_size = m_params.ctx_per_seq;
decode_c_params.attention_size_swa = m_params.ctx_per_seq_swa;
@@ -3322,7 +3397,7 @@ bool is_model_splitted(ggml_cgraph * cgraph) {
// the src is also not the model weights, we think the model is splitted.
// the src is also not in model leafs, we think the model is splitted.
if (src != nullptr && model_nodes.find(src) == model_nodes.end() &&
- model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false &&
+ model_weights.find(std::string(src->name)) == model_weights.end() &&
model_leafs.find(src) == model_leafs.end()) {
if (GgmlOvDecoder::is_inp_tok(src, node)) {
return false;
@@ -3345,75 +3420,6 @@ bool is_naive(ggml_cgraph * cgraph) {
return count < naive_graph_size_threshold;
}
-size_t checksum(const void * data, size_t size) {
- const uint8_t * bytes = static_cast<const uint8_t *>(data);
- size_t sum = 0;
- for (size_t i = 0; i < size; ++i) {
- sum += (uint8_t) i;
- sum += bytes[i];
- }
- return sum;
-}
-
-bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) {
- if (tensor == nullptr || tensor->data == nullptr) {
- return false;
- }
-
- std::ofstream out(file_path);
- if (!out.is_open()) {
- return false;
- }
-
- const size_t n = ggml_nelements(tensor);
- out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0]
- << ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n
- << ", data:" << '\n';
-
- switch (tensor->type) {
- case GGML_TYPE_F32: {
- const auto * data = static_cast<const float *>(tensor->data);
- for (size_t i = 0; i < n; ++i) {
- out << data[i] << '\n';
- }
- break;
- }
- case GGML_TYPE_F16: {
- const auto * data = static_cast<const ggml_fp16_t *>(tensor->data);
- for (size_t i = 0; i < n; ++i) {
- out << ggml_fp16_to_fp32(data[i]) << '\n';
- }
- break;
- }
- case GGML_TYPE_BF16: {
- const auto * data = static_cast<const ggml_bf16_t *>(tensor->data);
- for (size_t i = 0; i < n; ++i) {
- out << ggml_bf16_to_fp32(data[i]) << '\n';
- }
- break;
- }
- case GGML_TYPE_I32: {
- const auto * data = static_cast<const int32_t *>(tensor->data);
- for (size_t i = 0; i < n; ++i) {
- out << data[i] << '\n';
- }
- break;
- }
- case GGML_TYPE_I64: {
- const auto * data = static_cast<const int64_t *>(tensor->data);
- for (size_t i = 0; i < n; ++i) {
- out << data[i] << '\n';
- }
- break;
- }
- default:
- out << "unsupported tensor type for text dump" << '\n';
- return false;
- }
-
- return true;
-}
-
void print_input_tensor_info(const std::string & name, const ov::Tensor & input) {
// GPU inputs can be device (USM) tensors, whose data() throws; print a host copy of those.
const bool is_remote = input.is<ov::RemoteTensor>();
diff --git a/ggml/src/ggml-openvino/utils.h b/ggml/src/ggml-openvino/utils.h
index c4450a387..270676b07 100644
--- a/ggml/src/ggml-openvino/utils.h
+++ b/ggml/src/ggml-openvino/utils.h
@@ -6,6 +6,7 @@
#include <cstddef>
#include <cstdint>
#include <functional>
+#include <list>
#include <map>
#include <memory>
#include <mutex>
@@ -158,6 +159,12 @@ struct ov_runtime_context {
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_input_names_cache_prefill;
std::unordered_map<graph_key, std::vector<std::string>, graph_key_hash> ov_output_names_cache_prefill;
+ // LRU order of decoder_cache's keys, oldest (least recently used) at the front. A pipeline
+ // that interleaves distinct graph shapes every call -- e.g. DFlash cycling target/draft/
+ // injection graphs every round -- needs a slot per shape open at once; a single-entry cache
+ // would evict and recompile all of them, every call, forever.
+ std::list<graph_key> lru_keys;
+ static constexpr size_t max_cached_graphs = 8;
size_t stateful_kv_size;
std::map<std::string, std::string> kv_state_input_name_map;
// compute-only copies of graphs that carry unselected ggml_build_forward_select() branches
@@ -169,6 +176,39 @@ struct ov_runtime_context {
ov_runtime_context() : device("CPU"), stateful(false), stateful_kv_size(0) {}
+ // Mark `key` as the most recently used entry. Call on every cache hit and after inserting a
+ // new entry, so eviction always picks the graph shape that has gone longest unused.
+ void touch_locked(const graph_key & key) {
+ lru_keys.remove(key);
+ lru_keys.push_back(key);
+ }
+
+ // Drop the least recently used graph shape's compiled model and its associated per-key
+ // caches. Leaves every other shape's compiled model intact.
+ void evict_lru_locked() {
+ if (lru_keys.empty()) {
+ return;
+ }
+ graph_key victim = lru_keys.front();
+ lru_keys.pop_front();
+ decoder_cache.erase(victim);
+ infer_request_cache.erase(victim);
+ infer_request_cache_prefill.erase(victim);
+ ov_input_names_cache.erase(victim);
+ ov_output_names_cache.erase(victim);
+ ov_input_names_cache_prefill.erase(victim);
+ ov_output_names_cache_prefill.erase(victim);
+ }
+
+ // Make room for one more graph shape if the cache is at capacity, then mark `key` as most
+ // recently used. Call right after inserting `key` into decoder_cache.
+ void admit_locked(const graph_key & key) {
+ while (decoder_cache.size() > max_cached_graphs) {
+ evict_lru_locked();
+ }
+ touch_locked(key);
+ }
+
void clear_caches_locked() {
decoder_cache.clear();
infer_request_cache.clear();
@@ -177,6 +217,7 @@ struct ov_runtime_context {
ov_output_names_cache.clear();
ov_input_names_cache_prefill.clear();
ov_output_names_cache_prefill.clear();
+ lru_keys.clear();
kv_state_input_name_map.clear();
stateful_kv_size = 0;
}
@@ -192,10 +233,6 @@ enum ggml_status ov_graph_compute(struct ggml_cgraph * cgraph, ggml_backend_t ba
// Releases the cached blobs this process imported (GGML_OPENVINO_COMPILED_MODEL_CACHE_DIR).
void ov_clear_imported_blobs();
-size_t checksum(const void * data, size_t size);
-
-bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path);
-
void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor);
void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst);