interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / src / ggml-openvino / utils.cpp

2074 lines · 101514 bytes Raw Blame History
1#include "utils.h"
2
3#include "ggml-impl.h"
4#include "ggml-openvino-extra.h"
5#include "ggml-openvino.h"
6#include "ggml-openvino/ggml-decoder.h"
7#include "ggml.h"
8#include "model-cache.h"
9#include "openvino/frontend.h"
10#include "openvino/input_model.h"
11
12#include <algorithm>
13#include <cassert>
14#include <cmath>
15#include <cstddef>
16#include <cstdint>
17#include <cstdlib>
18#include <cstring>
19#include <fstream>
20#include <functional>
21#include <iomanip>
22#include <iostream>
23#include <memory>
24#include <openvino/core/any.hpp>
25#include <openvino/core/graph_util.hpp>
26#include <openvino/core/shape.hpp>
27#include <openvino/core/type/float16.hpp>
28#include <openvino/frontend/manager.hpp>
29#include <openvino/openvino.hpp>
30#include <openvino/runtime/compiled_model.hpp>
31#include <openvino/runtime/infer_request.hpp>
32#include <openvino/runtime/intel_gpu/ocl/ocl.hpp>
33#include <openvino/runtime/intel_npu/properties.hpp>
34#include <openvino/runtime/properties.hpp>
35#include <openvino/runtime/tensor.hpp>
36#include <optional>
37#include <set>
38#include <string>
39#include <unordered_map>
40#include <vector>
41
42namespace {
43// For a KV cache input, return an ov::Tensor sized to n_kv (== attention_size
44// for that layer) instead of the fully-allocated ctx_per_seq. Pre-conditions:
45// * non-static (CPU/GPU) backend, single sequence, seq_active_start == 0
46// * ggml KV layout is a contiguous [1, 1, ctx_per_seq, n_heads_kv*head_size]
47// so the first n_kv rows are the live prefix and shrinking the ctx axis
48// gives a valid tensor over the same host storage
49// * not an SWA layer (ring cache): once the window has wrapped the first
50// n_kv rows no longer contain the live prefix
51// On any unmet pre-condition returns std::nullopt; the caller falls back to
52// the full-size tensor.
53std::optional<ov::Tensor> try_make_kv_sliced_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder,
54 const std::string & name,
55 const ggml_tensor * ggml_tensor) {
56 static const bool kv_slice_disabled = ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE");
57 if (kv_slice_disabled) {
58 return std::nullopt;
59 }
60 if (ggml_decoder->is_static() || ggml_decoder->is_stateful()) {
61 return std::nullopt;
62 }
63 if (ggml_tensor->op != GGML_OP_NONE || ggml_tensor->view_src != nullptr) {
64 return std::nullopt;
65 }
66 const auto * op = ggml_decoder->get_tensor_used_op(ggml_tensor);
67 if (!GgmlOvDecoder::is_kvcache(ggml_tensor, op)) {
68 return std::nullopt;
69 }
70
71 const auto & compute_params = ggml_decoder->get_compute_params();
72 if (compute_params.n_seq_active != 1 || compute_params.seq_active_start != 0) {
73 return std::nullopt;
74 }
75
76 int layer;
77 if (auto layer_opt = extract_layer_from_name(name); layer_opt.has_value()) {
78 layer = layer_opt.value();
79 } else {
80 return std::nullopt;
81 }
82
83 const bool is_swa = ggml_decoder->is_swa_layer(layer);
84 if (is_swa) {
85 return std::nullopt;
86 }
87 const int ctx_per_seq = ggml_decoder->get_ctx_per_seq();
88 const int n_kv = compute_params.attention_size;
89 if (ctx_per_seq <= 0 || n_kv <= 0 || n_kv >= ctx_per_seq) {
90 return std::nullopt;
91 }
92
93 ov::Shape full_shape = GgmlOvDecoder::get_shape(ggml_tensor);
94 if (full_shape.size() != 4 || full_shape[0] != 1 || full_shape[1] != 1 ||
95 static_cast<int>(full_shape[2]) != ctx_per_seq) {
96 return std::nullopt;
97 }
98
99 ov::Shape sliced_shape = full_shape;
100 sliced_shape[2] = static_cast<size_t>(n_kv);
101
102 if (ggml_openvino_buffer_is_remote(ggml_tensor)) {
103 auto remote_context = ggml_openvino_get_remote_context();
104 auto gpu_context = remote_context->as<ov::intel_gpu::ocl::ClContext>();
105 return gpu_context.create_tensor(ggml_decoder->get_ov_type(ggml_tensor), sliced_shape, ggml_tensor->data);
106 }
107
108 return ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), sliced_shape, ggml_tensor->data);
109}
110
111static uint64_t ggml_openvino_model_cache_extra_cfg(bool stateful, bool recurrent) {
112 const char * manual_gqa_env = ggml_openvino_getenv_str("GGML_OPENVINO_MANUAL_GQA_ATTN");
113 const bool manual_gqa_enabled = manual_gqa_env != nullptr ?
114 ggml_openvino_getenv_int("GGML_OPENVINO_MANUAL_GQA_ATTN") > 0 :
115 ggml_openvino_is_gpu();
116
117 uint64_t extra_cfg = 1; // Graph-ordinal port names (invalidate older disk-cache blobs).
118 extra_cfg = extra_cfg * 131 + (stateful ? (recurrent ? 2u : 1u) : 0u);
119 extra_cfg = extra_cfg * 131 + (ggml_openvino_reduce_compile_mem_enabled() ? 1u : 0u);
120 extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_SLICE") ? 1u : 0u);
121 extra_cfg = extra_cfg * 131 + (manual_gqa_enabled ? 1u : 0u);
122 extra_cfg = extra_cfg * 131 + (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") >= 2 ? 1u : 0u);
123 return extra_cfg;
124}
125
126std::map<std::string, std::shared_ptr<ov::Node>> get_weight_names(ggml_cgraph * cgraph) {
127 std::map<std::string, std::shared_ptr<ov::Node>> names;
128 for (const auto & name : GgmlOvDecoder::collect_weight_names(cgraph)) {
129 names[name] = nullptr;
130 }
131 return names;
132}
133
134// A conservative, exact in-process key, evaluated only on a context-local cache
135// miss. Include topology, layouts, op parameters, constant extra inputs and weight
136// allocation identities. Never use a sampled weight hash or a graph name alone:
137// different models can have identical topology. OV buffer IDs survive address reuse.
138static std::string compiled_graph_key(const ggml_cgraph * graph,
139 const GgmlOvDecoder & decoder,
140 const std::string & device,
141 int prefill_chunk_size = 0,
142 bool disk_cache = false) {
143 std::string key;
144 auto append = [&key](const auto & value) {
145 key.append(reinterpret_cast<const char *>(&value), sizeof(value));
146 };
147 auto append_string = [&](const std::string & value) {
148 append(value.size());
149 key.append(value);
150 };
151 append_string(device);
152 append(decoder.is_static());
153 append(decoder.is_stateful());
154 append(prefill_chunk_size);
155 bool has_weight_buffer_id = false;
156 std::unordered_map<const ggml_tensor *, size_t> ids;
157 std::function<void(const ggml_tensor *)> visit = [&](const ggml_tensor * tensor) {
158 if (!tensor) {
159 append(size_t(0));
160 return;
161 }
162 auto inserted = ids.emplace(tensor, ids.size() + 1);
163 append(inserted.first->second);
164 if (!inserted.second) {
165 return;
166 }
167 append_string(tensor->name);
168 append(tensor->type);
169 append(tensor->op);
170 append(tensor->flags);
171 append(tensor->ne);
172 append(tensor->nb);
173 append(tensor->op_params);
174 append(tensor->view_offs);
175 const auto * base = tensor->view_src ? tensor->view_src : tensor;
176 const bool weight = base->buffer && base->buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS;
177 append(weight);
178 if (weight && !disk_cache) {
179 const size_t buffer_id = ggml_backend_openvino_buffer_get_ctx_id(base->buffer);
180 has_weight_buffer_id |= buffer_id != 0;
181 append(buffer_id);
182 append(tensor->data);
183 }
184 visit(tensor->view_src);
185 for (const auto * src : tensor->src) {
186 visit(src);
187 }
188 };
189 append(graph->n_nodes);
190 for (int i = 0; i < graph->n_nodes; ++i) {
191 visit(graph->nodes[i]);
192 }
193 append(graph->n_leafs);
194 for (int i = 0; i < graph->n_leafs; ++i) {
195 visit(graph->leafs[i]);
196 }
197 for (const auto & input : decoder.get_model_extra_inputs()) {
198 append_string(input.first);
199 append_string(input.second.type.get_type_name());
200 append(input.second.shape.size());
201 for (auto dim : input.second.shape) {
202 append(dim);
203 }
204 append(input.second.is_parameter);
205 if (!input.second.is_parameter) {
206 append(input.second.value);
207 }
208 }
209 // Without an allocation generation, pointer reuse could select stale weights.
210 // Such graphs still get private requests; they simply do not share compilation.
211 return disk_cache || has_weight_buffer_id ? key : std::string{};
212}
213
214static std::string dynamic_graph_signature(const ggml_cgraph * graph,
215 const GgmlOvDecoder & decoder,
216 const ModelParams & params) {
217 std::string key = "dynamic-1";
218 auto append = [&key](const auto & value) {
219 key.append(reinterpret_cast<const char *>(&value), sizeof(value));
220 };
221 auto append_string = [&](const std::string & value) {
222 append(value.size());
223 key.append(value);
224 };
225 graph_key graph_id(graph, true);
226 append(graph_id.n_nodes);
227 append(graph_id.n_leaves);
228 append_string(graph_id.first_node_name);
229 append_string(graph_id.last_node_name);
230 for (const auto & name : graph_id.input_srcs) {
231 append_string(name);
232 }
233 append(params.n_rs_slots);
234 append(params.has_rs_rollback);
235 append(params.mixed_rope_params);
236 append(params.is_cacheless_attn);
237 for (int layer : params.swa_layers) {
238 append(layer);
239 }
240 for (const auto & [layer, heads] : params.n_heads_kv_per_layer) {
241 append(layer);
242 append(heads);
243 }
244 for (const auto & [name, input] : decoder.get_model_inputs()) {
245 append_string(name);
246 append_string(input.type.get_type_name());
247 }
248 for (const auto & [name, tensor] : decoder.get_model_outputs()) {
249 append_string(name);
250 append(tensor->type);
251 }
252 for (const auto & [name, input] : decoder.get_model_extra_inputs()) {
253 append_string(name);
254 append_string(input.type.get_type_name());
255 append(input.is_parameter);
256 if (!input.is_parameter) {
257 append(input.value);
258 }
259 }
260 return key;
261}
262
263static bool compiled_model_matches_graph(const ov::CompiledModel & model,
264 const std::vector<std::string> & inputs,
265 const std::vector<std::string> & outputs,
266 const GgmlOvDecoder & decoder) {
267 if (model.inputs().size() != inputs.size() || model.outputs().size() != outputs.size()) {
268 return false;
269 }
270 const auto & graph_inputs = decoder.get_model_inputs();
271 const auto & extra_inputs = decoder.get_model_extra_inputs();
272 const auto & graph_outputs = decoder.get_model_outputs();
273 for (size_t i = 0; i < inputs.size(); ++i) {
274 const auto & port = model.input(i);
275 auto graph_it = graph_inputs.find(inputs[i]);
276 if (graph_it != graph_inputs.end()) {
277 if (port.get_element_type() != graph_it->second.type ||
278 !port.get_partial_shape().compatible(graph_it->second.shape)) {
279 return false;
280 }
281 continue;
282 }
283 auto extra_it = extra_inputs.find(inputs[i]);
284 if (extra_it == extra_inputs.end() || port.get_element_type() != extra_it->second.type ||
285 !port.get_partial_shape().compatible(ov::PartialShape(extra_it->second.shape))) {
286 return false;
287 }
288 }
289 for (size_t i = 0; i < outputs.size(); ++i) {
290 auto graph_it = graph_outputs.find(outputs[i]);
291 if (graph_it == graph_outputs.end()) {
292 if (outputs[i].compare(0, 8, "__debug_") != 0) {
293 return false;
294 }
295 continue;
296 }
297 const auto & port = model.output(i);
298 if (port.get_element_type() != GgmlOvDecoder::get_ov_type(graph_it->second) ||
299 !port.get_partial_shape().compatible(ov::PartialShape(GgmlOvDecoder::get_shape(graph_it->second)))) {
300 return false;
301 }
302 }
303 return true;
304}
305
306static std::string ov_profiling_csv_field(const std::string & value) {
307 std::string escaped = "\"";
308 for (char c : value) {
309 escaped += c;
310 if (c == '"') {
311 escaped += c;
312 }
313 }
314 escaped += '"';
315 return escaped;
316}
317
318static void dump_ov_profiling_info(const ov::InferRequest & infer_request) {
319 if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING") < 2) {
320 return;
321 }
322
323 static std::atomic<uint64_t> inference_index{0};
324 const uint64_t index = inference_index.fetch_add(1);
325 const std::string path = "openvino_profile_" + std::to_string(index) + ".csv";
326 std::ofstream output(path, std::ios::trunc);
327 if (!output.is_open()) {
328 GGML_LOG_WARN("ggml-openvino: failed to write profiling data to %s\n", path.c_str());
329 return;
330 }
331
332 output << "status,real_time_us,cpu_time_us,start_time_us,node_type,node_name,exec_type\n";
333 int64_t total_real_time = 0;
334 int64_t total_cpu_time = 0;
335 size_t executed_count = 0;
336 for (const auto & info : infer_request.get_profiling_info()) {
337 const char * status = "NOT_RUN";
338 if (info.status == ov::ProfilingInfo::Status::EXECUTED) {
339 status = "EXECUTED";
340 total_real_time += info.real_time.count();
341 total_cpu_time += info.cpu_time.count();
342 executed_count++;
343 } else if (info.status == ov::ProfilingInfo::Status::OPTIMIZED_OUT) {
344 status = "OPTIMIZED_OUT";
345 }
346
347 output << status << ',' << info.real_time.count() << ',' << info.cpu_time.count() << ','
348 << info.start_time.count() << ',' << ov_profiling_csv_field(info.node_type) << ','
349 << ov_profiling_csv_field(info.node_name) << ',' << ov_profiling_csv_field(info.exec_type) << '\n';
350 }
351
352 GGML_LOG_INFO("ggml-openvino: profile %s: %zu executed nodes, %.3f ms device, %.3f ms CPU\n", path.c_str(),
353 executed_count, total_real_time / 1000.0, total_cpu_time / 1000.0);
354}
355
356static void reset_single_slot_recurrent_cache(ggml_cgraph * cgraph,
357 const ModelParams & model_params,
358 const ComputeParams & compute_params) {
359 if (model_params.n_rs_slots != 1 || compute_params.cache_rs_reset_len == 0) {
360 return;
361 }
362 GGML_ASSERT(compute_params.cache_rs_reset_idx == 0 && compute_params.cache_rs_reset_len == 1);
363
364 std::set<ggml_backend_buffer_t> buffers;
365 for (int i = 0; i < cgraph->n_nodes; i++) {
366 auto * node = cgraph->nodes[i];
367 if (node->op == GGML_OP_SCALE && GgmlOvDecoder::is_recurrent_cache(node->view_src) &&
368 node->view_src->ne[1] == 1 && node->view_src->buffer != nullptr) {
369 buffers.insert(node->view_src->buffer);
370 }
371 }
372 for (auto * buffer : buffers) {
373 ggml_backend_buffer_clear(buffer, 0);
374 }
375}
376
377ov::Tensor create_ov_output_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder,
378 const std::shared_ptr<ov::InferRequest> & infer_request,
379 int output_index,
380 const ggml_tensor * ggml_tensor) {
381 if (auto sliced = try_make_kv_sliced_tensor(ggml_decoder, std::string(ggml_tensor->name), ggml_tensor)) {
382 return *sliced;
383 }
384
385 auto output_type = ggml_decoder->get_ov_type(ggml_tensor);
386 ov::Shape output_shape;
387 void * output_data = ggml_tensor->data;
388 if (ggml_decoder->is_static()) {
389 output_shape = infer_request->get_output_tensor(output_index).get_shape();
390 } else {
391 // For a CPY into a padded view_src (e.g. a padded KV cache buffer), the
392 // OV ScatterUpdate node outputs the full view_src shape, not the CPY node's
393 // own (smaller) shape. Using the CPY shape here causes set_output_tensor to
394 // fail with a shape-incompatibility error. Use view_src's shape and data
395 // pointer instead so the OV tensor matches the model output exactly.
396 if (ggml_tensor->op == GGML_OP_CPY && ggml_tensor->view_src != nullptr &&
397 ggml_nbytes(ggml_tensor) != ggml_nbytes(ggml_tensor->view_src)) {
398 output_shape = GgmlOvDecoder::get_shape(ggml_tensor->view_src);
399 output_data = ggml_tensor->view_src->data;
400 } else {
401 output_shape = GgmlOvDecoder::get_shape(ggml_tensor);
402 }
403 }
404
405 // The sliced path above covers eligible KV outputs. This also covers recurrent state and full-size KV fallbacks.
406 if (!ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_REMOTE_OUTPUTS") && !ggml_decoder->is_static() &&
407 !ggml_decoder->is_splited_model() && ggml_openvino_buffer_is_remote(ggml_tensor) &&
408 ggml_tensor->extra != nullptr) {
409 auto * extra_base = static_cast<ggml_openvino_extra_base *>(ggml_tensor->extra);
410 if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) {
411 auto * tensor_extra = static_cast<ggml_openvino_tensor_extra *>(extra_base);
412 if (tensor_extra->tensor != nullptr && tensor_extra->tensor->get_element_type() == output_type &&
413 tensor_extra->tensor->get_shape() == output_shape) {
414 return *tensor_extra->tensor;
415 }
416 }
417 }
418
419 ov::Tensor output_tensor(output_type, output_shape, output_data);
420 return output_tensor;
421}
422
423// Rewrite ggml's KV rows into a relayout state that keeps the sequence on dim 2.
424// ggml stores [seq][n_heads_kv * head_size]; the state wants [1, n_heads_kv, seq, head_size],
425// a different element order, so the rows are copied instead of reinterpreted.
426ov::Tensor kv_rows_to_seq_axis_2(const ov::Tensor & kv_tensor, size_t n_heads_kv) {
427 const size_t rows = kv_tensor.get_shape()[2];
428 const size_t head_size = kv_tensor.get_shape()[3] / n_heads_kv;
429 const size_t elem = kv_tensor.get_element_type().size();
430 const size_t head_bytes = head_size * elem;
431
432 ov::Tensor out(kv_tensor.get_element_type(), ov::Shape{1, n_heads_kv, rows, head_size});
433 const auto * src = static_cast<const uint8_t *>(kv_tensor.data());
434 auto * dst = static_cast<uint8_t *>(out.data());
435 for (size_t s = 0; s < rows; s++) {
436 for (size_t h = 0; h < n_heads_kv; h++) {
437 memcpy(dst + (h * rows + s) * head_bytes, src + (s * n_heads_kv + h) * head_bytes, head_bytes);
438 }
439 }
440 return out;
441}
442
443template <typename T> void set_zero_diagonal(std::vector<T> & matrix, size_t rows, size_t cols, T zero_value = T{}) {
444 for (size_t i = 0; i < rows; ++i) {
445 size_t diag_col = std::min(i, cols - 1);
446 matrix[i * cols + diag_col] = zero_value;
447 }
448}
449
450ov::Tensor make_contiguous_split_input_tensor(const struct ggml_tensor * ggml_tensor, const ov::Shape & input_shape) {
451 const size_t element_size = ggml_type_size(ggml_tensor->type);
452 const size_t block_size = ggml_blck_size(ggml_tensor->type);
453
454 GGML_ASSERT(block_size == 1 && "non-contiguous split inputs must be plain element types");
455
456 const struct ggml_tensor * source_tensor = ggml_tensor->view_src != nullptr ? ggml_tensor->view_src : ggml_tensor;
457 const size_t source_offset = ggml_tensor->view_src != nullptr ? ggml_tensor->view_offs : 0;
458
459 std::vector<uint8_t> source_data(ggml_nbytes(source_tensor));
460 ggml_backend_tensor_get(source_tensor, source_data.data(), 0, source_data.size());
461
462 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
463 auto * dst = static_cast<uint8_t *>(input_tensor.data());
464 size_t dst_offset = 0;
465
466 for (size_t i3 = 0; i3 < static_cast<size_t>(ggml_tensor->ne[3]); ++i3) {
467 for (size_t i2 = 0; i2 < static_cast<size_t>(ggml_tensor->ne[2]); ++i2) {
468 for (size_t i1 = 0; i1 < static_cast<size_t>(ggml_tensor->ne[1]); ++i1) {
469 for (size_t i0 = 0; i0 < static_cast<size_t>(ggml_tensor->ne[0]); ++i0) {
470 const size_t src_offset = source_offset + i3 * ggml_tensor->nb[3] + i2 * ggml_tensor->nb[2] +
471 i1 * ggml_tensor->nb[1] + i0 * ggml_tensor->nb[0];
472 std::memcpy(dst + dst_offset, source_data.data() + src_offset, element_size);
473 dst_offset += element_size;
474 }
475 }
476 }
477 }
478
479 return input_tensor;
480}
481
482ov::Tensor convert_ggml_input_to_ov(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & name) {
483 const auto * ggml_tensor = ggml_decoder->get_input_ggml_tensor(name);
484
485 if (auto sliced = try_make_kv_sliced_tensor(ggml_decoder, name, ggml_tensor)) {
486 return *sliced;
487 }
488
489 if (ggml_tensor->extra != nullptr && !ggml_decoder->is_splited_model()) {
490 auto * extra_base = static_cast<ggml_openvino_extra_base *>(ggml_tensor->extra);
491 if (extra_base->type == ggml_openvino_extra_base::Type::TENSOR) {
492 // GGML_LOG_DEBUG("Using ggml_tensor->extra as ov::Tensor for input: %s\n", name.c_str());
493 auto * tensor_extra = static_cast<ggml_openvino_tensor_extra *>(extra_base);
494 return *tensor_extra->tensor;
495 }
496 }
497
498 // GGML_LOG_DEBUG("Converting ggml tensor to ov::Tensor for input: %s\n", name.c_str());
499 auto * input_data = ggml_tensor->data;
500 ov::Shape input_shape;
501 if (ggml_tensor->op == GGML_OP_VIEW && !ggml_decoder->is_splited_model()) {
502 // This case is added to make test-backend-ops work
503 input_shape = GgmlOvDecoder::get_shape(ggml_tensor->view_src);
504 } else {
505 input_shape = GgmlOvDecoder::get_shape(ggml_tensor);
506 }
507
508 if (ggml_decoder->is_splited_model() && !ggml_is_contiguous(ggml_tensor)) {
509 return make_contiguous_split_input_tensor(ggml_tensor, input_shape);
510 }
511
512 auto input_tensor = ov::Tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape, input_data);
513 return input_tensor;
514}
515
516ov::Tensor get_ov_input_tensor(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder, const std::string & param_name) {
517 ov::Tensor input_tensor;
518 auto extra_input = ggml_decoder->get_model_extra_inputs().find(param_name);
519 if (extra_input != ggml_decoder->get_model_extra_inputs().end()) {
520 input_tensor = ov::Tensor(extra_input->second.type, extra_input->second.shape);
521 *input_tensor.data<int64_t>() = extra_input->second.value;
522 } else {
523 input_tensor = convert_ggml_input_to_ov(ggml_decoder, param_name);
524 }
525 return input_tensor;
526}
527
528ov::Tensor get_ov_input_tensor_static_decode(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder,
529 const std::string & param_name) {
530 // NPU decoding stage
531 if (ggml_decoder->get_model_extra_inputs().count(param_name)) {
532 return get_ov_input_tensor(ggml_decoder, param_name);
533 }
534 const auto * ggml_tensor = ggml_decoder->get_input_ggml_tensor(param_name);
535 const auto * op = ggml_decoder->get_tensor_used_op(ggml_tensor);
536
537 if (GgmlOvDecoder::is_inp_tok(ggml_tensor, op) || GgmlOvDecoder::is_inp_pos(ggml_tensor, op) ||
538 GgmlOvDecoder::is_kv_idx(ggml_tensor, op)) {
539 // IMROPE's inp_pos holds one value per t/h/w/e plane instead of a single position;
540 // with a single decode token the planes are still contiguous, so a flat copy works.
541 const int n_planes = GgmlOvDecoder::is_inp_pos(ggml_tensor, op) ? GgmlOvDecoder::get_inp_pos_n_planes(op) : 1;
542 assert(ggml_tensor->ne[0] == n_planes);
543 ov::Shape input_shape = {1, 1, 1, (size_t) n_planes};
544 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
545 std::memcpy(input_tensor.data(), ggml_tensor->data, n_planes * ggml_type_size(ggml_tensor->type));
546 return input_tensor;
547 }
548
549 if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
550 ov::Shape input_shape = {1, 1, 1, 1};
551 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
552 int32_t inp_out_id = *((int32_t *) ggml_tensor->data);
553 assert(ggml_tensor->ne[0] == 1);
554 assert(inp_out_id == 0);
555 *input_tensor.data<int32_t>() = inp_out_id;
556 return input_tensor;
557 }
558
559 if (GgmlOvDecoder::is_inp_mask(ggml_tensor, op)) {
560 size_t context_size = ggml_decoder->get_ctx_size();
561 if (ggml_tensor->type == GGML_TYPE_F16) {
562 std::vector<ggml_fp16_t> padded_data =
563 pad_input<ggml_fp16_t>(ggml_tensor, 1, context_size, GGML_FP32_TO_FP16(-INFINITY));
564 ov::Tensor input_tensor(ov::element::f16, ov::Shape{1, 1, 1, context_size});
565 std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(ggml_fp16_t));
566 return input_tensor;
567 }
568
569 std::vector<float> padded_data = pad_input<float>(ggml_tensor, 1, context_size, -INFINITY);
570 ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, 1, context_size});
571 auto * data_ptr = input_tensor.data<float>();
572 std::copy(padded_data.begin(), padded_data.begin() + context_size, data_ptr);
573 return input_tensor;
574 }
575
576 return get_ov_input_tensor(ggml_decoder, param_name);
577}
578
579ov::Tensor get_ov_input_tensor_static_prefill(const std::shared_ptr<GgmlOvDecoder> & ggml_decoder,
580 const std::string & param_name,
581 int chunk_index) {
582 // NPU prompt processing stage
583 const size_t input_len = ggml_decoder->get_input_len();
584 const size_t chunk_size = ggml_decoder->m_prefill_chunk_size;
585 const size_t chunk_valid_size = std::min(chunk_size, input_len - chunk_index * chunk_size);
586 const size_t chunk_pad_size = chunk_size - chunk_valid_size;
587
588 if (param_name == "chunk_valid_len") {
589 ov::Tensor input_tensor(ov::element::i64, ov::Shape{1});
590 *input_tensor.data<int64_t>() = (int64_t) chunk_valid_size;
591 return input_tensor;
592 }
593 if (chunk_index > 0 && param_name == "cache_rs_reset_len") {
594 // The recurrent-state clear belongs to the start of the sequence. Re-applying it on every
595 // chunk would wipe the state accumulated by the preceding chunks, so disable it (a zero
596 // length makes scale.cpp's keep-mask select every slot) after the first chunk.
597 ov::Tensor input_tensor(ov::element::i64, ov::Shape{1});
598 *input_tensor.data<int64_t>() = 0;
599 return input_tensor;
600 }
601 if (ggml_decoder->get_model_extra_inputs().count(param_name)) {
602 return get_ov_input_tensor(ggml_decoder, param_name);
603 }
604 const auto * ggml_tensor = ggml_decoder->get_input_ggml_tensor(param_name);
605 const auto * op = ggml_decoder->get_tensor_used_op(ggml_tensor);
606
607 if (GgmlOvDecoder::is_inp_pos(ggml_tensor, op) && GgmlOvDecoder::get_inp_pos_n_planes(op) > 1) {
608 // IMROPE: inp_pos stacks n_planes (t/h/w/e) position planes, each of length
609 // input_len; pad every plane independently so they stay aligned to chunk_size.
610 const int n_planes = GgmlOvDecoder::get_inp_pos_n_planes(op);
611 const size_t element_size = ggml_type_size(ggml_tensor->type);
612 ov::Shape input_shape = {1, 1, 1, (size_t) n_planes * chunk_size};
613 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
614 for (int p = 0; p < n_planes; p++) {
615 const char * src =
616 (const char *) ggml_tensor->data + (p * input_len + chunk_index * chunk_size) * element_size;
617 char * dst = (char *) input_tensor.data() + p * chunk_size * element_size;
618 std::memcpy(dst, src, chunk_valid_size * element_size);
619 if (chunk_pad_size > 0) {
620 if (ggml_tensor->type == GGML_TYPE_I32) {
621 int32_t last_value = *((const int32_t *) src + chunk_valid_size - 1);
622 int32_t * out = (int32_t *) dst;
623 std::fill(out + chunk_valid_size, out + chunk_size, last_value + 1);
624 } else if (ggml_tensor->type == GGML_TYPE_I64) {
625 int64_t last_value = *((const int64_t *) src + chunk_valid_size - 1);
626 int64_t * out = (int64_t *) dst;
627 std::fill(out + chunk_valid_size, out + chunk_size, last_value + 1);
628 } else {
629 throw std::runtime_error("Unexpected tensor type for " + param_name);
630 }
631 }
632 }
633 return input_tensor;
634 }
635
636 if (GgmlOvDecoder::is_inp_tok(ggml_tensor, op) || GgmlOvDecoder::is_inp_pos(ggml_tensor, op) ||
637 GgmlOvDecoder::is_kv_idx(ggml_tensor, op)) {
638 ov::Shape input_shape = {1, 1, 1, chunk_size};
639 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
640 // copy the chunk_index-th chunk from ggml_tensor
641 size_t element_size = ggml_type_size(ggml_tensor->type);
642 void * input_data = (char *) ggml_tensor->data + chunk_index * chunk_size * element_size;
643 std::memcpy(input_tensor.data(), input_data, chunk_valid_size * element_size);
644 // pad the rest with last_value + 1, so that kv's of padded positions are inserted
645 // to the next row after the valids row in the kvcache
646 if (chunk_pad_size > 0) {
647 if (ggml_tensor->type == GGML_TYPE_I32) {
648 int32_t last_value =
649 *((int32_t *) ggml_tensor->data + (chunk_index * chunk_size + chunk_valid_size - 1));
650 int32_t * output_data = input_tensor.data<int32_t>();
651 std::fill(output_data + chunk_valid_size, output_data + chunk_size, last_value + 1);
652 } else if (ggml_tensor->type == GGML_TYPE_I64) {
653 int64_t last_value =
654 *((int64_t *) ggml_tensor->data + (chunk_index * chunk_size + chunk_valid_size - 1));
655 int64_t * output_data = input_tensor.data<int64_t>();
656 std::fill(output_data + chunk_valid_size, output_data + chunk_size, last_value + 1);
657 } else {
658 throw std::runtime_error("Unexpected tensor type for " + param_name);
659 }
660 }
661 return input_tensor;
662 }
663
664 if (GgmlOvDecoder::is_output_idx(ggml_tensor, op)) {
665 size_t output_len = ggml_decoder->get_compute_params().output_len;
666 ov::Shape input_shape = {1, 1, 1, output_len};
667 ov::Tensor input_tensor(GgmlOvDecoder::get_ov_type(ggml_tensor), input_shape);
668 if (ggml_tensor->ne[0] == 0) {
669 *input_tensor.data<int32_t>() = 0;
670 } else {
671 auto * data_addr = input_tensor.data<int32_t>();
672 for (size_t i = 0; i < output_len; i++) {
673 data_addr[i] = ((int32_t *) ggml_tensor->data)[i] % chunk_size;
674 }
675 }
676 return input_tensor;
677 }
678
679 if (GgmlOvDecoder::is_inp_scale_rows(ggml_tensor, op)) {
680 ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, chunk_size, 1});
681 auto * dst = input_tensor.data<float>();
682 const auto * src = static_cast<const float *>(ggml_tensor->data) + chunk_index * chunk_size;
683 std::copy(src, src + chunk_valid_size, dst);
684 std::fill(dst + chunk_valid_size, dst + chunk_size, 1.0f);
685 return input_tensor;
686 }
687
688 if (GgmlOvDecoder::is_inp_mean(ggml_tensor, op)) {
689 const size_t n_seqs = ggml_tensor->ne[1];
690 const size_t src_stride = ggml_tensor->ne[0];
691 const size_t copy_len = std::min<size_t>(chunk_valid_size, src_stride - chunk_index * chunk_size);
692 ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, n_seqs, chunk_size});
693 auto * dst = input_tensor.data<float>();
694 std::fill(dst, dst + n_seqs * chunk_size, 0.0f);
695 const auto * src = static_cast<const float *>(ggml_tensor->data) + chunk_index * chunk_size;
696 for (size_t s = 0; s < n_seqs; s++) {
697 std::memcpy(dst + s * chunk_size, src + s * src_stride, copy_len * sizeof(float));
698 }
699 return input_tensor;
700 }
701
702 if (GgmlOvDecoder::is_inp_mask(ggml_tensor, op)) {
703 size_t cols = ggml_tensor->ne[0];
704 size_t rows = ggml_tensor->ne[1];
705 size_t chunk_valid_rows = std::min(chunk_size, rows - chunk_index * chunk_size);
706 size_t context_size = ggml_decoder->get_ctx_size();
707 if (ggml_tensor->type == GGML_TYPE_F16) {
708 const auto * ggml_data =
709 static_cast<const ggml_fp16_t *>(ggml_tensor->data) + chunk_index * chunk_size * cols;
710 std::vector<ggml_fp16_t> padded_data = pad_input<ggml_fp16_t>(ggml_data, chunk_valid_rows, cols, chunk_size,
711 context_size, GGML_FP32_TO_FP16(-INFINITY));
712 set_zero_diagonal(padded_data, chunk_size, context_size, GGML_FP32_TO_FP16(0.0f));
713 ov::Tensor input_tensor(ov::element::f16, ov::Shape{1, 1, chunk_size, context_size});
714 std::memcpy(input_tensor.data(), padded_data.data(), padded_data.size() * sizeof(ggml_fp16_t));
715 return input_tensor;
716 }
717
718 const auto * ggml_data = static_cast<const float *>(ggml_tensor->data) + chunk_index * chunk_size * cols;
719 std::vector<float> padded_data =
720 pad_input<float>(ggml_data, chunk_valid_rows, cols, chunk_size, context_size, -INFINITY);
721 set_zero_diagonal(padded_data, chunk_size, context_size);
722 ov::Tensor input_tensor(ov::element::f32, ov::Shape{1, 1, chunk_size, context_size});
723 auto * data_ptr = input_tensor.data<float>();
724 std::copy(padded_data.begin(), padded_data.begin() + chunk_size * context_size, data_ptr);
725 return input_tensor;
726 }
727
728 return get_ov_input_tensor(ggml_decoder, param_name);
729}
730
731enum ggml_status naive_compute(ggml_cgraph * cgraph,
732 ov::Core & core,
733 const std::string & device,
734 const ov::AnyMap & config,
735 ov_compiled_model_cache & cache) {
736 if (cgraph->n_nodes == 1 && (cgraph->nodes[0]->op == GGML_OP_NONE || cgraph->nodes[0]->op == GGML_OP_VIEW)) {
737 return GGML_STATUS_SUCCESS;
738 }
739
740 std::unique_lock<std::mutex> compile_lock(cache.mutex);
741 bool naive = true;
742 auto model_weights = GgmlOvDecoder::create_weight_nodes(cgraph, naive);
743 auto decoder = std::make_shared<GgmlOvDecoder>(cgraph, model_weights);
744 auto input_model = std::make_shared<ov::frontend::ggml::InputModel>(decoder);
745 auto model = ov::frontend::ggml::FrontEnd::convert(input_model, naive);
746 if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_IR")) {
747 ov::serialize(model, "IR_naive.xml");
748 }
749
750 std::shared_ptr<ov::InferRequest> infer_request;
751 auto remote_context = ggml_openvino_get_remote_context();
752 ov::AnyMap compile_config = config;
753 if (cgraph->nodes[0]->op == GGML_OP_MUL_MAT) {
754 // TODO ACCURACY hint triggers a bug in GPU plugin/driver on Lunar Lake. Remove once CVS-182166 is resolved
755 compile_config[ov::hint::execution_mode.name()] = ov::hint::ExecutionMode::PERFORMANCE;
756 } else {
757 compile_config[ov::hint::execution_mode.name()] = ov::hint::ExecutionMode::ACCURACY;
758 }
759 if (remote_context.has_value()) {
760 infer_request = std::make_shared<ov::InferRequest>(
761 core.compile_model(model, remote_context.value(), compile_config).create_infer_request());
762 } else {
763 infer_request = std::make_shared<ov::InferRequest>(
764 core.compile_model(model, device, compile_config).create_infer_request());
765 }
766 std::vector<std::string> input_names;
767 std::vector<std::string> output_names;
768 for (const auto & param : model->get_parameters()) {
769 input_names.push_back(param->get_friendly_name());
770 }
771 for (const auto & result : model->get_results()) {
772 output_names.push_back(result->get_friendly_name());
773 }
774 // Destroy the frontend graph under the compilation lock as well: it can
775 // still own edges into the shared weight nodes.
776 model.reset();
777 input_model.reset();
778 decoder->clear_model_weights();
779 model_weights.clear();
780 compile_lock.unlock();
781
782 for (size_t i = 0; i < input_names.size(); i++) {
783 const auto & param_name = input_names[i];
784 auto input_tensor = get_ov_input_tensor(decoder, param_name);
785 infer_request->set_input_tensor(i, input_tensor);
786 }
787
788 // Use get_output_tensor + memcpy instead of set_output_tensor to avoid memory overwritten
789 // when i/o buffer overlaps, e.g. the cgraph is a single PERMUTE
790
791 infer_request->infer();
792
793 for (size_t i = 0; i < output_names.size(); i++) {
794 auto output_tensor = infer_request->get_output_tensor(i);
795 const auto & model_outputs = decoder->get_model_outputs();
796 auto model_output_it = model_outputs.find(output_names[i]);
797 if (model_output_it == model_outputs.end()) {
798 // Debug-only output added via GGML_OPENVINO_DEBUG_NODE; nothing to copy into.
799 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
800 ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
801 print_output_tensor_info(output_names[i], output_tensor, output_tensor.data());
802 }
803 continue;
804 }
805 auto * ggml_tensor = model_output_it->second;
806 std::memcpy(ggml_tensor->data, output_tensor.data(), output_tensor.get_byte_size());
807 }
808 return GGML_STATUS_SUCCESS;
809}
810
811enum ggml_status ov_graph_compute_dynamic(ggml_cgraph * cgraph, const std::shared_ptr<ov_runtime_context> & r_ctx) {
812 auto & core = ov_singleton_core();
813 const auto & config = ggml_openvino_get_compile_config();
814 const auto & device = r_ctx->device;
815 static auto is_static = false;
816
817 static const bool cache_disabled = ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE");
818
819 auto start_time = ggml_time_us();
820
821 // is_model_splitted is O(n_nodes^2) plus a create_weight_nodes scan and takes ~20 ms
822 // on a Llama-1B decode graph. It is called once per graph_compute invocation but the
823 // graph shape is identical across all decode steps, so memoize by graph_key: compute
824 // graph_key first (a few hundred us), and if the same key is already in decoder_cache
825 // we know the graph is not splitted (only not-splitted graphs get inserted there).
826 const int64_t cache_key_start_time = ggml_time_us();
827 graph_key key(cgraph);
828 const int64_t cache_key_compute_time = ggml_time_us() - cache_key_start_time;
829 int64_t cache_lookup_time = 0;
830 bool key_seen = false;
831 if (!cache_disabled) {
832 const int64_t cache_lookup_start_time = ggml_time_us();
833 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
834 key_seen = r_ctx->decoder_cache.find(key) != r_ctx->decoder_cache.end();
835 cache_lookup_time += ggml_time_us() - cache_lookup_start_time;
836 }
837
838 const int64_t model_split_check_start_time = ggml_time_us();
839 bool model_is_splitted = key_seen ? false : is_model_splitted(cgraph);
840 const int64_t model_split_check_time = ggml_time_us() - model_split_check_start_time;
841
842 if (ggml_openvino_model_cache_only() && (model_is_splitted || is_naive(cgraph))) {
843 GGML_LOG_ERROR("ggml-openvino: cache-only mode requires a complete model graph\n");
844 return GGML_STATUS_FAILED;
845 }
846 if (is_naive(cgraph)) {
847 if (!model_is_splitted) {
848 return naive_compute(cgraph, core, device, config, *r_ctx->compiled_cache);
849 }
850 }
851
852 std::shared_ptr<GgmlOvDecoder> ggml_decoder;
853 std::shared_ptr<ov::InferRequest> infer_request;
854 ModelParams m_params;
855 ComputeParams c_params;
856 const int64_t graph_param_compute_start_time = ggml_time_us();
857 std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static);
858 const int64_t graph_param_compute_time = ggml_time_us() - graph_param_compute_start_time;
859
860 const bool cache_enabled = !model_is_splitted && !cache_disabled;
861 const bool stateful_recurrent = r_ctx->stateful && m_params.state_size >= 0;
862 const bool stateful_kv_only = r_ctx->stateful && !stateful_recurrent;
863 if (r_ctx->stateful &&
864 (m_params.n_seq > 1 || c_params.n_seq_active > 1 || m_params.n_rs_slots > 1 || m_params.has_rs_rollback)) {
865 GGML_LOG_ERROR("OpenVINO stateful execution requires a single slot without recurrent rollback. Use -np 1.\n");
866 return GGML_STATUS_FAILED;
867 }
868 if (stateful_recurrent && !cache_enabled) {
869 GGML_LOG_ERROR("OpenVINO recurrent stateful execution requires an unsplit graph with model caching enabled.\n");
870 return GGML_STATUS_FAILED;
871 }
872 bool cache_hit = false;
873
874 int64_t decoder_end_time;
875 int64_t conversion_end_time;
876 int64_t compile_end_time;
877 int64_t infer_end_time;
878 int64_t ov_raw_infer_start;
879
880 {
881 std::shared_ptr<decoder_runtime_ctx> entry;
882 ModelParams old_m_params;
883
884 const int64_t cache_lookup_start_time = ggml_time_us();
885 if (cache_enabled) {
886 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
887 auto it = r_ctx->decoder_cache.find(key);
888 cache_hit = it != r_ctx->decoder_cache.end();
889 if (cache_hit) {
890 entry = it->second;
891 } else {
892 r_ctx->clear_caches_locked();
893 auto mutex = std::make_shared<std::mutex>();
894 entry = std::make_shared<decoder_runtime_ctx>(mutex);
895 r_ctx->decoder_cache[key] = entry;
896 }
897 } else {
898 auto mutex = std::make_shared<std::mutex>();
899 entry = std::make_shared<decoder_runtime_ctx>(mutex);
900 cache_hit = false;
901 }
902 cache_lookup_time += ggml_time_us() - cache_lookup_start_time;
903
904 std::lock_guard<std::mutex> lock(*(entry->mutex));
905 cache_hit = cache_hit && entry->ptr && r_ctx->infer_request_cache.count(key) != 0;
906
907 if (cache_hit) {
908 ggml_decoder = entry->ptr;
909 old_m_params = ggml_decoder->get_model_params();
910 if (!ggml_decoder->is_splited_model()) {
911 cache_hit = old_m_params.can_reuse_dynamically(m_params);
912 }
913 }
914
915 std::vector<std::string> ov_input_names;
916 std::vector<std::string> ov_output_names;
917
918 if (cache_hit) {
919 std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
920 ggml_decoder->set_compute_params(c_params);
921 ggml_decoder->set_model_params(m_params);
922 if (old_m_params.kv_buffer_changed(m_params) || !ggml_decoder->is_bound_to(cgraph)) {
923 ggml_decoder->update_io(cgraph);
924 }
925 ggml_decoder->add_extra_inputs();
926 {
927 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
928 infer_request = r_ctx->infer_request_cache.at(key);
929 ov_input_names = r_ctx->ov_input_names_cache.at(key);
930 ov_output_names = r_ctx->ov_output_names_cache.at(key);
931 }
932
933 if (stateful_kv_only) {
934 const auto * inp_pos = get_inp_pos_tensor(cgraph);
935 int32_t * pos_data = (int32_t *) inp_pos->data;
936 auto pos_shape = GgmlOvDecoder::get_shape(inp_pos);
937 if (pos_data[0] == 0) {
938 infer_request->reset_state();
939 r_ctx->stateful_kv_size = pos_shape[3];
940 } else if (r_ctx->stateful_kv_size == static_cast<size_t>(pos_data[0])) {
941 r_ctx->stateful_kv_size += pos_shape[3];
942 } else {
943 const size_t pos_begin = static_cast<size_t>(pos_data[0]);
944 const bool refill = pos_begin > r_ctx->stateful_kv_size;
945
946 // A refill seeds the state from ggml's KV cache, so it needs that cache to be a
947 // plain prefix: cell i must hold position i. An SWA layer keeps only the last
948 // n_swa positions, so once a position leaves the window ggml drops it and the
949 // remaining cells shift - cell i stops holding position i. While every position
950 // is still inside the window nothing has been dropped and the refill is sound.
951 if (refill && !ggml_decoder->get_model_params().swa_layers.empty()) {
952 const int n_swa = ggml_decoder->get_compute_params().swa_window;
953 if (n_swa < 0 || static_cast<size_t>(n_swa) < pos_begin) {
954 GGML_LOG_ERROR(
955 "GGML OpenVINO backend stateful inference failed: cannot resume at position %zu from a "
956 "state that holds %zu tokens, because the sliding-window layers keep only the last %d "
957 "positions. Run without GGML_OPENVINO_STATEFUL_EXECUTION.\n",
958 pos_begin, r_ctx->stateful_kv_size, n_swa);
959 return GGML_STATUS_FAILED;
960 }
961 }
962
963 const bool relayout_enabled = !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT");
964
965 auto states = infer_request->query_state();
966 for (auto state : states) {
967 auto state_tensor = state.get_state();
968 auto state_tensor_shape = state_tensor.get_shape();
969
970 std::string state_name;
971 if (auto it = r_ctx->kv_state_input_name_map.find(state.get_name());
972 it != r_ctx->kv_state_input_name_map.end()) {
973 state_name = it->second;
974 }
975
976 // Which axis holds the sequence: pass::KVStateSeqAxis moves it from dim 1
977 // to dim 2. The head count is still needed below, because only a 1-head
978 // state stays byte-compatible with ggml's cache buffer. gemma-4 12B mixes
979 // 1-head full layers with 8-head sliding layers, so it is per state.
980 int n_heads_kv = ggml_decoder->get_model_params().n_heads_kv;
981 if (auto layer = extract_layer_from_name(state_name); layer.has_value()) {
982 n_heads_kv = ggml_decoder->get_n_heads_kv_for_layer(layer.value());
983 }
984 const bool relayout_this_state = relayout_enabled;
985 const size_t seq_axis = relayout_this_state ? 2 : 1;
986 const size_t head_axis = seq_axis == 2 ? 1 : 2;
987
988 if (refill) {
989 if (state_name.empty()) {
990 GGML_LOG_ERROR(
991 "GGML OpenVINO backend stateful inference failed: no input found for the state\n");
992 return GGML_STATUS_FAILED;
993 }
994 auto kv_tensor = get_ov_input_tensor(ggml_decoder, state_name);
995 if (relayout_this_state && n_heads_kv != 1) {
996 // several heads with seq on dim 2: not the same bytes as ggml's
997 // buffer, so the rows have to be copied into the new order
998 state_tensor = kv_rows_to_seq_axis_2(kv_tensor, (size_t) n_heads_kv);
999 } else {
1000 ov::Shape refill_shape(4);
1001 refill_shape[0] = state_tensor_shape[0];
1002 refill_shape[seq_axis] = kv_tensor.get_shape()[2];
1003 refill_shape[head_axis] = state_tensor_shape[head_axis];
1004 refill_shape[3] = state_tensor_shape[3];
1005 kv_tensor.set_shape(refill_shape);
1006 state_tensor = kv_tensor;
1007 }
1008 state_tensor_shape = state_tensor.get_shape();
1009 }
1010 // Only ever shrink to a prefix the source really has. Slicing past it used to
1011 // surface as a bare ov::Exception from the ROI constructor.
1012 if (state_tensor_shape[seq_axis] < pos_begin) {
1013 GGML_LOG_ERROR(
1014 "GGML OpenVINO backend stateful inference failed: state '%s' holds %zu tokens on axis "
1015 "%zu, cannot resume at position %zu\n",
1016 state.get_name().c_str(), state_tensor_shape[seq_axis], seq_axis, pos_begin);
1017 return GGML_STATUS_FAILED;
1018 }
1019 ov::Coordinate begin = {0, 0, 0, 0};
1020 ov::Coordinate end(state_tensor_shape.begin(), state_tensor_shape.end());
1021 end[seq_axis] = pos_begin;
1022 ov::Tensor new_state_tensor(state_tensor, begin, end);
1023 state.set_state(new_state_tensor);
1024 }
1025 r_ctx->stateful_kv_size = pos_begin + pos_shape[3];
1026 }
1027 }
1028
1029 decoder_end_time = ggml_time_us();
1030 conversion_end_time = decoder_end_time;
1031 compile_end_time = decoder_end_time;
1032 } else {
1033 // Compilation can mutate shared weight nodes, so serialize cold paths.
1034 // The lock is released before binding tensors or running inference.
1035 auto shared_cache = r_ctx->compiled_cache;
1036 std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
1037 auto weight_names = get_weight_names(cgraph);
1038 ggml_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, weight_names,
1039 is_static, r_ctx->stateful, model_is_splitted);
1040 const std::string model_cache_dir = ggml_openvino_model_cache_dir();
1041 const std::string exact_key = cache_enabled ? compiled_graph_key(cgraph, *ggml_decoder, device) : "";
1042 uint64_t model_fp = 0;
1043 uint64_t exact_fp = 0;
1044 std::string blob_path, manifest_path;
1045 if (!model_cache_dir.empty() && !model_is_splitted) {
1046 const uint64_t extra_cfg =
1047 ggml_openvino_model_cache_extra_cfg(r_ctx->stateful, stateful_recurrent);
1048 model_fp =
1049 ggml_openvino_model_fingerprint(cgraph, device, /*fa=*/true, m_params.rope_params, 16, extra_cfg,
1050 dynamic_graph_signature(cgraph, *ggml_decoder, m_params));
1051 exact_fp =
1052 ggml_openvino_model_fingerprint(cgraph, device, /*fa=*/true, m_params.rope_params, 16, extra_cfg,
1053 compiled_graph_key(cgraph, *ggml_decoder, device, 0, true));
1054 blob_path = ggml_openvino_model_cache_blob_path(model_cache_dir, model_fp);
1055 manifest_path = ggml_openvino_model_cache_manifest_path(model_cache_dir, model_fp);
1056 }
1057 std::string shared_key =
1058 cache_enabled ? (model_fp ? "dynamic:" + std::to_string(model_fp) : exact_key) : "";
1059 ov::CompiledModel shared_model;
1060 bool imported = false;
1061 auto shared_it = shared_cache->graphs.find(shared_key);
1062 if (!shared_key.empty() && shared_it != shared_cache->graphs.end() &&
1063 (model_fp == 0 || compiled_model_matches_graph(shared_it->second.decode, shared_it->second.input_names,
1064 shared_it->second.output_names, *ggml_decoder))) {
1065 shared_model = shared_it->second.decode;
1066 infer_request = std::make_shared<ov::InferRequest>(shared_model.create_infer_request());
1067 ov_input_names = shared_it->second.input_names;
1068 ov_output_names = shared_it->second.output_names;
1069 imported = true;
1070 GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (dynamic)\n");
1071 } else if (model_fp && shared_it != shared_cache->graphs.end()) {
1072 shared_key = exact_key;
1073 shared_it = shared_cache->graphs.find(shared_key);
1074 if (shared_it != shared_cache->graphs.end()) {
1075 shared_model = shared_it->second.decode;
1076 infer_request = std::make_shared<ov::InferRequest>(shared_model.create_infer_request());
1077 ov_input_names = shared_it->second.input_names;
1078 ov_output_names = shared_it->second.output_names;
1079 imported = true;
1080 }
1081 model_fp = exact_fp;
1082 blob_path = ggml_openvino_model_cache_blob_path(model_cache_dir, model_fp);
1083 manifest_path = ggml_openvino_model_cache_manifest_path(model_cache_dir, model_fp);
1084 }
1085 if (cache_enabled) {
1086 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1087 r_ctx->infer_request_cache.erase(key);
1088 }
1089
1090 // Import standalone blobs with weights before graph conversion and compilation.
1091 // Split models use the plugin cache instead. The decoder still maps graph I/O.
1092 ov::AnyMap mc_config = config;
1093 if (!model_cache_dir.empty()) {
1094 mc_config.erase("CACHE_DIR");
1095 mc_config[ov::cache_mode.name()] = ov::CacheMode::OPTIMIZE_SPEED;
1096 }
1097 if (!imported && !model_cache_dir.empty() && !model_is_splitted) {
1098 const uint64_t preferred_fp = model_fp;
1099 bool dynamic_incompatible = preferred_fp == exact_fp;
1100 for (int candidate = 0; candidate < 2; ++candidate) {
1101 if (imported || (candidate == 1 && preferred_fp == exact_fp)) {
1102 break;
1103 }
1104 const uint64_t candidate_fp = candidate == 0 ? preferred_fp : exact_fp;
1105 const std::string candidate_blob =
1106 ggml_openvino_model_cache_blob_path(model_cache_dir, candidate_fp);
1107 const std::string candidate_manifest =
1108 ggml_openvino_model_cache_manifest_path(model_cache_dir, candidate_fp);
1109 std::ifstream blob_in(candidate_blob, std::ios::binary);
1110 std::vector<std::string> saved_inputs, saved_outputs;
1111 if (!blob_in.is_open() ||
1112 !ggml_openvino_model_cache_verify_manifest(candidate_manifest, cgraph, candidate_fp,
1113 saved_inputs, saved_outputs)) {
1114 continue;
1115 }
1116 const int64_t import_start = ggml_time_us();
1117 try {
1118 ov::CompiledModel cm;
1119 auto remote_context = ggml_openvino_get_remote_context();
1120 if (remote_context.has_value()) {
1121 cm = core.import_model(blob_in, remote_context.value(), mc_config);
1122 } else {
1123 cm = core.import_model(blob_in, device, mc_config);
1124 }
1125 // CPU serialization can rename Results that share a name with a Parameter.
1126 if (!saved_inputs.empty() || !saved_outputs.empty()) {
1127 ov_input_names = std::move(saved_inputs);
1128 ov_output_names = std::move(saved_outputs);
1129 } else {
1130 for (const auto & p : cm.inputs()) {
1131 ov_input_names.push_back(p.get_node()->get_friendly_name());
1132 }
1133 for (const auto & o : cm.outputs()) {
1134 ov_output_names.push_back(o.get_node()->get_friendly_name());
1135 }
1136 }
1137 if (!compiled_model_matches_graph(cm, ov_input_names, ov_output_names, *ggml_decoder)) {
1138 dynamic_incompatible |= candidate == 0;
1139 ov_input_names.clear();
1140 ov_output_names.clear();
1141 continue;
1142 }
1143 infer_request = std::make_shared<ov::InferRequest>(cm.create_infer_request());
1144 shared_model = cm;
1145 entry->ptr = ggml_decoder;
1146 imported = true;
1147 model_fp = candidate_fp;
1148 blob_path = candidate_blob;
1149 manifest_path = candidate_manifest;
1150 if (candidate_fp == exact_fp) {
1151 shared_key = exact_key;
1152 shared_it = shared_cache->graphs.find(shared_key);
1153 }
1154 if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
1155 GGML_LOG_INFO(" - Model cache import time: %.3f ms \n",
1156 (ggml_time_us() - import_start) / 1000.0);
1157 }
1158 GGML_LOG_INFO("ggml-openvino: model cache HIT %s\n", candidate_blob.c_str());
1159 } catch (const std::exception & e) {
1160 GGML_LOG_WARN("ggml-openvino: model cache import failed: %s\n", e.what());
1161 dynamic_incompatible |= candidate == 0;
1162 imported = false;
1163 ov_input_names.clear();
1164 ov_output_names.clear();
1165 infer_request.reset();
1166 shared_model = {};
1167 }
1168 }
1169 if (!imported && dynamic_incompatible) {
1170 model_fp = exact_fp;
1171 shared_key = exact_key;
1172 shared_it = shared_cache->graphs.find(shared_key);
1173 blob_path = ggml_openvino_model_cache_blob_path(model_cache_dir, model_fp);
1174 manifest_path = ggml_openvino_model_cache_manifest_path(model_cache_dir, model_fp);
1175 }
1176 }
1177
1178 std::shared_ptr<ov::Model> model;
1179 if (!imported && ggml_openvino_model_cache_only()) {
1180 GGML_LOG_ERROR(
1181 "ggml-openvino: missing or incompatible compiled model: %s; run once without "
1182 "GGML_OPENVINO_COMPILED_MODEL_CACHE_ONLY\n",
1183 blob_path.c_str());
1184 return GGML_STATUS_FAILED;
1185 }
1186 if (!imported && ggml_openvino_weight_buffers_released()) {
1187 GGML_LOG_ERROR("ggml-openvino: cannot compile a new graph after releasing host weights\n");
1188 return GGML_STATUS_FAILED;
1189 }
1190 if (imported) {
1191 decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us();
1192 } else {
1193 auto model_weights = GgmlOvDecoder::create_weight_nodes(cgraph);
1194
1195 ggml_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, model_weights, is_static,
1196 r_ctx->stateful, model_is_splitted);
1197 decoder_end_time = ggml_time_us();
1198
1199 auto input_model = std::make_shared<ov::frontend::ggml::InputModel>(ggml_decoder);
1200 model = ov::frontend::ggml::FrontEnd::convert(input_model);
1201 ggml_decoder->clear_model_weights();
1202 conversion_end_time = ggml_time_us();
1203
1204 if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_IR")) {
1205 char timestamped_filename[64];
1206 auto timestamp = (long long) ggml_time_us();
1207 snprintf(timestamped_filename, sizeof(timestamped_filename), "model_%lld.xml", timestamp);
1208 ov::serialize(model, timestamped_filename);
1209 }
1210
1211 // Use the cache-stripped config when the frontend model cache is active, so
1212 // the resulting CompiledModel can be exported and later re-imported.
1213 const ov::AnyMap & compile_config = model_cache_dir.empty() ? config : mc_config;
1214 ov::CompiledModel compiled_model;
1215 auto remote_context = ggml_openvino_get_remote_context();
1216 if (remote_context.has_value()) {
1217 compiled_model = core.compile_model(model, remote_context.value(), compile_config);
1218 } else {
1219 compiled_model = core.compile_model(model, device, compile_config);
1220 }
1221 compile_end_time = ggml_time_us();
1222
1223 for (const auto & ov_param : model->get_parameters()) {
1224 ov_input_names.push_back(ov_param->get_friendly_name());
1225 }
1226 for (const auto & ov_output : model->get_results()) {
1227 ov_output_names.push_back(ov_output->get_friendly_name());
1228 }
1229
1230 // Export to the frontend model cache for next time. Publish the blob first,
1231 // then the manifest, so a cache hit only sees fully written artifacts.
1232 if (!model_cache_dir.empty() && !model_is_splitted && model_fp != 0) {
1233 try {
1234 const std::string blob_tmp = ggml_openvino_model_cache_temp_path(blob_path);
1235 const std::string manifest_tmp = ggml_openvino_model_cache_temp_path(manifest_path);
1236 if (ggml_openvino_model_cache_write_manifest(manifest_tmp, cgraph, model_fp, ov_input_names,
1237 ov_output_names)) {
1238 std::ofstream blob_out(blob_tmp, std::ios::binary | std::ios::trunc);
1239 if (blob_out.is_open()) {
1240 compiled_model.export_model(blob_out);
1241 blob_out.close();
1242 if (blob_out.good()) {
1243 if (std::rename(blob_tmp.c_str(), blob_path.c_str()) == 0 &&
1244 std::rename(manifest_tmp.c_str(), manifest_path.c_str()) == 0) {
1245 GGML_LOG_INFO("ggml-openvino: model cache WROTE %s\n", blob_path.c_str());
1246 } else {
1247 std::remove(blob_tmp.c_str());
1248 std::remove(manifest_tmp.c_str());
1249 }
1250 } else {
1251 std::remove(blob_tmp.c_str());
1252 std::remove(manifest_tmp.c_str());
1253 }
1254 } else {
1255 std::remove(manifest_tmp.c_str());
1256 }
1257 }
1258 } catch (const std::exception & e) {
1259 GGML_LOG_WARN("ggml-openvino: model cache export failed: %s\n", e.what());
1260 }
1261 }
1262
1263 infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
1264 shared_model = compiled_model;
1265 entry->ptr = ggml_decoder;
1266
1267 } // end non-imported (compile) path
1268
1269 entry->ptr = ggml_decoder;
1270 if (!shared_key.empty() && shared_it == shared_cache->graphs.end()) {
1271 shared_cache->graphs.emplace(shared_key,
1272 ov_compiled_graph{shared_model, {}, ov_input_names, ov_output_names});
1273 }
1274 if (cache_enabled) {
1275 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1276 r_ctx->infer_request_cache[key] = infer_request;
1277 r_ctx->ov_input_names_cache[key] = ov_input_names;
1278 r_ctx->ov_output_names_cache[key] = ov_output_names;
1279 }
1280
1281 if (stateful_kv_only && cache_enabled) {
1282 const auto * inp_pos = get_inp_pos_tensor(cgraph);
1283 auto pos_shape = GgmlOvDecoder::get_shape(inp_pos);
1284 // A freshly compiled model starts with an empty state, so it can only serve a
1285 // sequence from its beginning. A non-zero start position means the KV history was
1286 // built elsewhere (a restored ggml cache), which the state cannot adopt.
1287 const int32_t pos_begin = ((int32_t *) inp_pos->data)[0];
1288 if (pos_begin != 0) {
1289 GGML_LOG_ERROR(
1290 "GGML OpenVINO backend stateful inference failed: a new model was compiled for a sequence that "
1291 "starts at position %d, but its state is empty. Run without "
1292 "GGML_OPENVINO_STATEFUL_EXECUTION.\n",
1293 pos_begin);
1294 return GGML_STATUS_FAILED;
1295 }
1296 r_ctx->stateful_kv_size = pos_shape[3];
1297 const auto kv_param_res_names = ggml_decoder->get_kv_param_res_names();
1298 for (const auto & pair : kv_param_res_names) {
1299 r_ctx->kv_state_input_name_map[pair.first + pair.second] = pair.first;
1300 }
1301 }
1302 }
1303
1304 if (stateful_recurrent) {
1305 const auto * inp_pos = get_inp_pos_tensor(cgraph);
1306 const int32_t pos_begin = static_cast<const int32_t *>(inp_pos->data)[0];
1307 if (pos_begin == 0) {
1308 infer_request->reset_state();
1309 } else if (!cache_hit || old_m_params.kv_buffer_changed(m_params) || c_params.cache_rs_reset_len > 0 ||
1310 pos_begin < 0 || static_cast<size_t>(pos_begin) != r_ctx->stateful_kv_size) {
1311 GGML_LOG_ERROR(
1312 "OpenVINO recurrent stateful execution cannot restore or rewind a sequence. Restart at position 0 "
1313 "or disable GGML_OPENVINO_STATEFUL_EXECUTION.\n");
1314 return GGML_STATUS_FAILED;
1315 }
1316 } else {
1317 reset_single_slot_recurrent_cache(cgraph, m_params, c_params);
1318 }
1319
1320 for (size_t i = 0; i < ov_input_names.size(); i++) {
1321 const auto & param_name = ov_input_names[i];
1322 auto input_tensor = get_ov_input_tensor(ggml_decoder, param_name);
1323 infer_request->set_input_tensor(i, input_tensor);
1324
1325 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
1326 print_input_tensor_info(param_name, input_tensor);
1327 }
1328 }
1329
1330 for (size_t i = 0; i < ov_output_names.size(); i++) {
1331 // Debug-only outputs added via GGML_OPENVINO_DEBUG_NODE (see
1332 // translate_session.cpp) have no corresponding ggml tensor; leave
1333 // them unbound so OpenVINO allocates its own tensor for them,
1334 // rather than aliasing a ggml buffer that may be overwritten by a
1335 // later in-place op before we get to read it.
1336 const auto & model_outputs = ggml_decoder->get_model_outputs();
1337 auto model_output_it = model_outputs.find(ov_output_names[i]);
1338 if (model_output_it == model_outputs.end()) {
1339 continue;
1340 }
1341 auto * ggml_tensor = model_output_it->second;
1342 if (ggml_nbytes(ggml_tensor) == 0) {
1343 continue;
1344 }
1345 auto output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor);
1346 infer_request->set_output_tensor(i, output_tensor);
1347 }
1348
1349 ov_raw_infer_start = ggml_time_us();
1350 infer_request->infer();
1351 infer_end_time = ggml_time_us();
1352 if (stateful_recurrent) {
1353 const auto * inp_pos = get_inp_pos_tensor(cgraph);
1354 r_ctx->stateful_kv_size =
1355 static_cast<const int32_t *>(inp_pos->data)[0] + get_inp_pos_n_tokens(cgraph, inp_pos);
1356 }
1357 dump_ov_profiling_info(*infer_request);
1358
1359 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
1360 ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
1361 for (size_t i = 0; i < ov_output_names.size(); i++) {
1362 const auto output_tensor = infer_request->get_output_tensor(i);
1363 print_output_tensor_info(ov_output_names[i], output_tensor, output_tensor.data());
1364 }
1365 }
1366
1367 if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
1368 GGML_LOG_INFO("\nGGML OpenVINO Backend: \n");
1369 GGML_LOG_INFO(" - Graph decoder time: %.3f ms \n", (decoder_end_time - start_time) / 1000.0);
1370 GGML_LOG_INFO(" - cache key compute time: %.3f ms \n", cache_key_compute_time / 1000.0);
1371 GGML_LOG_INFO(" - model split check time: %.3f ms \n", model_split_check_time / 1000.0);
1372 GGML_LOG_INFO(" - graph param compute time: %.3f ms \n", graph_param_compute_time / 1000.0);
1373 GGML_LOG_INFO(" - cache lookup time: %.3f ms \n", cache_lookup_time / 1000.0);
1374 if (!cache_hit) {
1375 GGML_LOG_INFO(" - Graph conversion time: %.3f ms \n",
1376 (conversion_end_time - decoder_end_time) / 1000.0);
1377 GGML_LOG_INFO(" - Graph compile time: %.3f ms \n", (compile_end_time - conversion_end_time) / 1000.0);
1378 }
1379 GGML_LOG_INFO(" - Graph inference time: %.3f ms \n", (infer_end_time - compile_end_time) / 1000.0);
1380 GGML_LOG_INFO(" - OV raw infer time: %.3f ms \n", (infer_end_time - ov_raw_infer_start) / 1000.0);
1381 }
1382 }
1383
1384 // GGML_OPENVINO_RELEASE_WEIGHTS (or GGML_OPENVINO_MEMORY_OPTIMIZE on GPU): the plugin holds its own device copy of
1385 // every weight after compile, so the host weight buffers can be dropped to reclaim
1386 // RSS. Release only while holding the compilation mutex so another context cannot
1387 // be reading host weights during conversion/compilation. Pin the shared compiled
1388 // models across backend teardown; a later context can create its own request without
1389 // reading the dropped pages. A new, uncached graph still fails fast above.
1390 if (cache_hit && ggml_openvino_release_weights_enabled()) {
1391 std::lock_guard<std::mutex> compile_lock(r_ctx->compiled_cache->mutex);
1392 if (!ggml_openvino_weight_buffers_released()) {
1393 ggml_openvino_release_weight_buffers();
1394 }
1395 }
1396
1397 return GGML_STATUS_SUCCESS;
1398}
1399
1400ov::AnyMap without_npuw(const ov::AnyMap & config) {
1401 ov::AnyMap out;
1402 for (const auto & kv : config) {
1403 if (kv.first.rfind("NPUW", 0) == 0 || kv.first == "NPU_USE_NPUW") {
1404 continue;
1405 }
1406 out.insert(kv);
1407 }
1408 return out;
1409}
1410
1411enum ggml_status ov_graph_compute_static(ggml_cgraph * cgraph, const std::shared_ptr<ov_runtime_context> & r_ctx) {
1412 auto & core = ov_singleton_core();
1413
1414 auto get_prefill_chunk_size = [] {
1415 static const int chunk_size = []() {
1416 int env_prefill_chunk_size = ggml_openvino_getenv_int("GGML_OPENVINO_PREFILL_CHUNK_SIZE");
1417 return env_prefill_chunk_size > 0 ? env_prefill_chunk_size : 256;
1418 }();
1419 return chunk_size;
1420 };
1421
1422 // Normally NPU, but honors GGML_OPENVINO_DEVICE so GGML_OPENVINO_FORCE_STATIC can run the
1423 // static-shape path on CPU/GPU to isolate translation bugs from NPUW/NPU-driver issues.
1424 static std::string device = ggml_openvino_get_device_name();
1425 static auto is_static = true;
1426 static auto stateful = false;
1427
1428 auto prefill_chunk_size = get_prefill_chunk_size();
1429 const auto & config = ggml_openvino_get_compile_config();
1430
1431 if (is_naive(cgraph)) {
1432 return naive_compute(cgraph, core, device, config, *r_ctx->compiled_cache);
1433 }
1434
1435 auto start_time = ggml_time_us();
1436
1437 std::shared_ptr<GgmlOvDecoder> ggml_decoder;
1438 std::shared_ptr<ov::InferRequest> infer_request;
1439 ModelParams m_params;
1440 ComputeParams c_params;
1441 std::tie(m_params, c_params) = GgmlOvDecoder::compute_llm_params(cgraph, is_static);
1442
1443 const auto * inp_pos = get_inp_pos_tensor(cgraph);
1444 const bool no_kv_cache = m_params.is_cacheless_attn;
1445 const auto is_prefill = no_kv_cache ? true : get_is_prefill(cgraph, inp_pos);
1446 const ov::AnyMap compile_config = no_kv_cache ? without_npuw(config) : config;
1447 if (m_params.n_heads_kv == -1) {
1448 prefill_chunk_size = inp_pos->ne[0];
1449 }
1450 graph_key key(cgraph);
1451 static const bool cache_enabled = !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_CACHE");
1452 bool cache_hit = false;
1453
1454 int64_t decoder_end_time;
1455 int64_t conversion_end_time;
1456 int64_t compile_end_time;
1457 int64_t infer_end_time;
1458 int64_t ov_raw_infer_start;
1459 int64_t ov_raw_infer_total = 0;
1460
1461 std::shared_ptr<decoder_runtime_ctx> entry;
1462 ModelParams old_m_params;
1463
1464 if (cache_enabled) {
1465 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1466 auto it = r_ctx->decoder_cache.find(key);
1467 cache_hit = it != r_ctx->decoder_cache.end();
1468 if (cache_hit) {
1469 entry = it->second;
1470 } else {
1471 r_ctx->clear_caches_locked();
1472 auto mutex = std::make_shared<std::mutex>();
1473 entry = std::make_shared<decoder_runtime_ctx>(mutex);
1474 r_ctx->decoder_cache[key] = entry;
1475 }
1476 } else {
1477 auto mutex = std::make_shared<std::mutex>();
1478 entry = std::make_shared<decoder_runtime_ctx>(mutex);
1479 cache_hit = false;
1480 }
1481
1482 std::lock_guard<std::mutex> lock(*(entry->mutex));
1483 cache_hit = cache_hit && entry->ptr && r_ctx->infer_request_cache.count(key) != 0 &&
1484 r_ctx->infer_request_cache_prefill.count(key) != 0;
1485
1486 if (cache_hit) {
1487 ggml_decoder = entry->ptr;
1488 old_m_params = ggml_decoder->get_model_params();
1489 cache_hit = old_m_params.can_reuse_statically(m_params);
1490 }
1491
1492 std::vector<std::string> ov_input_names_local;
1493 std::vector<std::string> ov_output_names_local;
1494
1495 if (cache_hit) {
1496 std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
1497 ggml_decoder->m_is_prefill = is_prefill;
1498 ggml_decoder->set_model_params(m_params);
1499 ggml_decoder->set_compute_params(c_params);
1500 if (old_m_params.kv_buffer_changed(m_params) || !ggml_decoder->is_bound_to(cgraph)) {
1501 ggml_decoder->update_io(cgraph);
1502 }
1503 ggml_decoder->add_extra_inputs();
1504 {
1505 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1506 infer_request =
1507 is_prefill ? r_ctx->infer_request_cache_prefill.at(key) : r_ctx->infer_request_cache.at(key);
1508 ov_input_names_local = r_ctx->ov_input_names_cache.at(key);
1509 ov_output_names_local = r_ctx->ov_output_names_cache.at(key);
1510 }
1511
1512 decoder_end_time = ggml_time_us();
1513 conversion_end_time = decoder_end_time;
1514 compile_end_time = decoder_end_time;
1515 } else {
1516 if (cache_enabled) {
1517 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1518 r_ctx->infer_request_cache.erase(key);
1519 r_ctx->infer_request_cache_prefill.erase(key);
1520 }
1521
1522 // Static execution shares a compiled prefill/decode pair. Each backend
1523 // creates and retains its own requests for both phases.
1524 auto shared_cache = r_ctx->compiled_cache;
1525 std::unique_lock<std::mutex> compile_lock(shared_cache->mutex);
1526 auto weight_names = get_weight_names(cgraph);
1527 auto local_decoder = std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, weight_names, is_static,
1528 stateful, false, is_prefill, prefill_chunk_size);
1529 const std::string shared_key =
1530 cache_enabled ? compiled_graph_key(cgraph, *local_decoder, device, prefill_chunk_size) : "";
1531 auto shared_it = shared_cache->graphs.find(shared_key);
1532 if (!shared_key.empty() && shared_it != shared_cache->graphs.end()) {
1533 auto & compiled = shared_it->second;
1534 auto prefill_request = std::make_shared<ov::InferRequest>(compiled.prefill.create_infer_request());
1535 auto decode_request = no_kv_cache ?
1536 prefill_request :
1537 std::make_shared<ov::InferRequest>(compiled.decode.create_infer_request());
1538 ggml_decoder = local_decoder;
1539 entry->ptr = ggml_decoder;
1540 infer_request = is_prefill ? prefill_request : decode_request;
1541 ov_input_names_local = compiled.input_names;
1542 ov_output_names_local = compiled.output_names;
1543 r_ctx->infer_request_cache_prefill[key] = prefill_request;
1544 r_ctx->infer_request_cache[key] = decode_request;
1545 r_ctx->ov_input_names_cache[key] = ov_input_names_local;
1546 r_ctx->ov_output_names_cache[key] = ov_output_names_local;
1547 decoder_end_time = conversion_end_time = compile_end_time = ggml_time_us();
1548 GGML_LOG_DEBUG("ggml-openvino: shared compiled model HIT (static)\n");
1549 } else {
1550 std::shared_ptr<ov::Model> model;
1551 auto model_weights = GgmlOvDecoder::create_weight_nodes(cgraph);
1552
1553 auto ggml_decoder_prefill = std::make_shared<GgmlOvDecoder>(
1554 cgraph, m_params, c_params, model_weights, is_static, stateful, false, true, prefill_chunk_size);
1555 auto ggml_decoder_decode =
1556 no_kv_cache ? ggml_decoder_prefill :
1557 std::make_shared<GgmlOvDecoder>(cgraph, m_params, c_params, model_weights, is_static,
1558 stateful, false, false, prefill_chunk_size);
1559 decoder_end_time = ggml_time_us();
1560
1561 const bool dump_ir = ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_IR");
1562 const auto dump_ir_timestamp = static_cast<long long>(ggml_time_us());
1563
1564 auto build_static_model = [&core, &compile_config, dump_ir, dump_ir_timestamp](
1565 const std::shared_ptr<GgmlOvDecoder> & decoder, const char * tag,
1566 std::shared_ptr<ov::Model> & model, ov::CompiledModel & compiled_model,
1567 std::shared_ptr<ov::InferRequest> & infer_request,
1568 int64_t & local_conversion_end_time, int64_t & local_compile_end_time) {
1569 auto input_model = std::make_shared<ov::frontend::ggml::InputModel>(decoder);
1570 model = ov::frontend::ggml::FrontEnd::convert(input_model);
1571 decoder->clear_model_weights();
1572 local_conversion_end_time = ggml_time_us();
1573
1574 if (dump_ir) {
1575 char timestamped_filename[64];
1576 snprintf(timestamped_filename, sizeof(timestamped_filename), "model_%s_%lld.xml", tag,
1577 dump_ir_timestamp);
1578 ov::serialize(model, timestamped_filename);
1579 }
1580
1581 compiled_model = core.compile_model(model, device, compile_config);
1582 infer_request = std::make_shared<ov::InferRequest>(compiled_model.create_infer_request());
1583 local_compile_end_time = ggml_time_us();
1584 };
1585 std::shared_ptr<ov::Model> model_prefill;
1586 std::shared_ptr<ov::Model> model_decode;
1587 ov::CompiledModel compiled_model_prefill;
1588 ov::CompiledModel compiled_model_decode;
1589 std::shared_ptr<ov::InferRequest> infer_request_prefill;
1590 std::shared_ptr<ov::InferRequest> infer_request_decode;
1591 int64_t prefill_conversion_end_time;
1592 int64_t decode_conversion_end_time;
1593 int64_t prefill_compile_end_time;
1594 int64_t decode_compile_end_time;
1595 build_static_model(ggml_decoder_prefill, "prefill", model_prefill, compiled_model_prefill,
1596 infer_request_prefill, prefill_conversion_end_time, prefill_compile_end_time);
1597 if (no_kv_cache) {
1598 model_decode = model_prefill;
1599 compiled_model_decode = compiled_model_prefill;
1600 infer_request_decode = infer_request_prefill;
1601 decode_conversion_end_time = prefill_conversion_end_time;
1602 decode_compile_end_time = prefill_compile_end_time;
1603 } else {
1604 build_static_model(ggml_decoder_decode, "decode", model_decode, compiled_model_decode,
1605 infer_request_decode, decode_conversion_end_time, decode_compile_end_time);
1606 }
1607 conversion_end_time = std::max(prefill_conversion_end_time, decode_conversion_end_time);
1608 compile_end_time = std::max(prefill_compile_end_time, decode_compile_end_time);
1609
1610 model = is_prefill ? model_prefill : model_decode;
1611 ggml_decoder = is_prefill ? ggml_decoder_prefill : ggml_decoder_decode;
1612 infer_request = is_prefill ? infer_request_prefill : infer_request_decode;
1613 entry->ptr = ggml_decoder;
1614
1615 for (const auto & ov_param : model->get_parameters()) {
1616 ov_input_names_local.push_back(ov_param->get_friendly_name());
1617 }
1618 for (const auto & ov_output : model->get_results()) {
1619 ov_output_names_local.push_back(ov_output->get_friendly_name());
1620 }
1621
1622 if (!shared_key.empty()) {
1623 shared_cache->graphs.emplace(
1624 shared_key, ov_compiled_graph{compiled_model_decode, compiled_model_prefill, ov_input_names_local,
1625 ov_output_names_local});
1626 }
1627
1628 if (cache_enabled) {
1629 std::lock_guard<std::mutex> map_lock(r_ctx->ctx_mutex);
1630 r_ctx->infer_request_cache_prefill[key] = infer_request_prefill;
1631 r_ctx->infer_request_cache[key] = infer_request_decode;
1632 r_ctx->ov_input_names_cache[key] = ov_input_names_local;
1633 r_ctx->ov_output_names_cache[key] = ov_output_names_local;
1634 }
1635 }
1636 }
1637
1638 reset_single_slot_recurrent_cache(cgraph, m_params, c_params);
1639
1640 if (is_prefill) {
1641 auto inp_len = get_inp_pos_n_tokens(cgraph, inp_pos);
1642 for (int chunk_index = 0; chunk_index * prefill_chunk_size < inp_len; chunk_index++) {
1643 for (size_t i = 0; i < ov_input_names_local.size(); i++) {
1644 const auto & param_name = ov_input_names_local[i];
1645 auto input_tensor = get_ov_input_tensor_static_prefill(ggml_decoder, param_name, chunk_index);
1646 infer_request->set_input_tensor(i, input_tensor);
1647
1648 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
1649 const auto input_tensor = infer_request->get_input_tensor(i);
1650 print_input_tensor_info(param_name, input_tensor);
1651 }
1652 }
1653
1654 for (size_t i = 0; i < ov_output_names_local.size(); i++) {
1655 const auto & model_outputs = ggml_decoder->get_model_outputs();
1656 auto model_output_it = model_outputs.find(ov_output_names_local[i]);
1657 if (model_output_it == model_outputs.end()) {
1658 continue;
1659 }
1660 auto * ggml_tensor = model_output_it->second;
1661 if (ggml_nbytes(ggml_tensor) == 0) {
1662 // Zero-row in-place writeback (e.g. the empty s_copy defrag remainder). The OV
1663 // Result is the full cache, so binding it over this 0-byte buffer overflows it.
1664 continue;
1665 }
1666 auto output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor);
1667 infer_request->set_output_tensor(i, output_tensor);
1668 }
1669
1670 ov_raw_infer_start = ggml_time_us();
1671 infer_request->infer();
1672 ov_raw_infer_total += ggml_time_us() - ov_raw_infer_start;
1673
1674 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
1675 ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
1676 for (size_t i = 0; i < ov_output_names_local.size(); i++) {
1677 const auto output_tensor = infer_request->get_output_tensor(i);
1678 print_output_tensor_info(ov_output_names_local[i], output_tensor, output_tensor.data());
1679 }
1680 }
1681 }
1682 infer_end_time = ggml_time_us();
1683 } else {
1684 for (size_t i = 0; i < ov_input_names_local.size(); i++) {
1685 const auto & param_name = ov_input_names_local[i];
1686 auto input_tensor = get_ov_input_tensor_static_decode(ggml_decoder, param_name);
1687 infer_request->set_input_tensor(i, input_tensor);
1688
1689 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_INPUT")) {
1690 const auto input_tensor = infer_request->get_input_tensor(i);
1691 print_input_tensor_info(param_name, input_tensor);
1692 }
1693 }
1694
1695 for (size_t i = 0; i < ov_output_names_local.size(); i++) {
1696 const auto & model_outputs = ggml_decoder->get_model_outputs();
1697 auto model_output_it = model_outputs.find(ov_output_names_local[i]);
1698 if (model_output_it == model_outputs.end()) {
1699 continue;
1700 }
1701 auto * ggml_tensor = model_output_it->second;
1702 if (ggml_nbytes(ggml_tensor) == 0) {
1703 continue;
1704 }
1705 auto output_tensor = create_ov_output_tensor(ggml_decoder, infer_request, i, ggml_tensor);
1706 infer_request->set_output_tensor(i, output_tensor);
1707 }
1708
1709 ov_raw_infer_start = ggml_time_us();
1710 infer_request->infer();
1711 infer_end_time = ggml_time_us();
1712 ov_raw_infer_total = infer_end_time - ov_raw_infer_start;
1713
1714 if (ggml_openvino_getenv_int("GGML_OPENVINO_DEBUG_OUTPUT") ||
1715 ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
1716 for (size_t i = 0; i < ov_output_names_local.size(); i++) {
1717 const auto output_tensor = infer_request->get_output_tensor(i);
1718 print_output_tensor_info(ov_output_names_local[i], output_tensor, output_tensor.data());
1719 }
1720 }
1721 }
1722
1723 if (ggml_openvino_getenv_int("GGML_OPENVINO_PROFILING")) {
1724 GGML_LOG_INFO("\nGGML OpenVINO Backend: \n");
1725 GGML_LOG_INFO(" - Graph decoder time: %.3f ms \n", (decoder_end_time - start_time) / 1000.0);
1726 if (!cache_hit) {
1727 GGML_LOG_INFO(" - Graph conversion time: %.3f ms \n", (conversion_end_time - decoder_end_time) / 1000.0);
1728 GGML_LOG_INFO(" - Graph compile time: %.3f ms \n", (compile_end_time - conversion_end_time) / 1000.0);
1729 }
1730 GGML_LOG_INFO(" - Graph inference time: %.3f ms \n", (infer_end_time - compile_end_time) / 1000.0);
1731 GGML_LOG_INFO(" - OV raw infer time: %.3f ms \n", ov_raw_infer_total / 1000.0);
1732 }
1733
1734 return GGML_STATUS_SUCCESS;
1735}
1736} // namespace
1737
1738// Nodes on the unselected branches of ggml_build_forward_select() stay in the graph but must not be
1739// computed. Keep them out of the OV model, or their inputs become parameters with fixed shapes.
1740static ggml_cgraph * get_compute_graph(ggml_cgraph * cgraph, ov_runtime_context & r_ctx) {
1741 auto is_skipped = [](const ggml_tensor * node) {
1742 return node->op != GGML_OP_NONE && !(node->flags & GGML_TENSOR_FLAG_COMPUTE);
1743 };
1744 if (std::none_of(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, is_skipped)) {
1745 return cgraph;
1746 }
1747 auto & compute = r_ctx.compute_graphs[cgraph];
1748 compute.nodes.clear();
1749 std::copy_if(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, std::back_inserter(compute.nodes),
1750 [&](const ggml_tensor * node) { return !is_skipped(node); });
1751 compute.graph = *cgraph;
1752 compute.graph.nodes = compute.nodes.data();
1753 compute.graph.n_nodes = (int) compute.nodes.size();
1754 return &compute.graph;
1755}
1756
1757// Both execution paths use two cache levels:
1758// 1. Reuse this backend's decoder/request via graph_key and compatibility checks.
1759// 2. On a local miss, look up compiled_graph_key in the shared compilation cache,
1760// compile if needed, then create a private request from the compiled model.
1761// The shared lock covers compilation and frontend cleanup, never inference.
1762enum ggml_status ov_graph_compute(ggml_cgraph * cgraph, ggml_backend_t backend) {
1763 ggml_backend_openvino_context * ctx = (ggml_backend_openvino_context *) backend->context;
1764 try {
1765 if (ggml_openvino_getenv_int("GGML_OPENVINO_DUMP_CGRAPH")) {
1766 std::string filename = "cgraph_ov.txt";
1767 GgmlOvDecoder::dump_cgraph(cgraph, filename);
1768 }
1769
1770 const auto is_static = ggml_openvino_is_npu() || ggml_openvino_getenv_int("GGML_OPENVINO_FORCE_STATIC");
1771
1772 GGML_ASSERT(ctx->runtime_context != nullptr);
1773 std::shared_ptr<ov_runtime_context> r_ctx = std::static_pointer_cast<ov_runtime_context>(ctx->runtime_context);
1774 std::lock_guard<std::mutex> execution_lock(r_ctx->execution_mutex);
1775 cgraph = get_compute_graph(cgraph, *r_ctx);
1776
1777 return is_static ? ov_graph_compute_static(cgraph, r_ctx) : ov_graph_compute_dynamic(cgraph, r_ctx);
1778 } catch (const ov::Exception & e) {
1779 GGML_LOG_ERROR("GGML OpenVINO backend ov::Exception: %s\n", e.what());
1780 return GGML_STATUS_FAILED;
1781 } catch (const std::exception & e) {
1782 GGML_LOG_ERROR("GGML OpenVINO backend std::exception: %s\n", e.what());
1783 return GGML_STATUS_FAILED;
1784 } catch (...) {
1785 GGML_LOG_ERROR("GGML OpenVINO backend unknown exception\n");
1786 return GGML_STATUS_FAILED;
1787 }
1788}
1789
1790// Detect whether a cgraph is a split subgraph or not.
1791// Step 1 compares each node's recorded use_count with actual fan-out references in node->src.
1792// Step 2 verifies that node inputs come from model nodes/weights/leafs; external sources imply split.
1793bool is_model_splitted(ggml_cgraph * cgraph) {
1794 static const bool fallback_enabled = ggml_openvino_getenv_int("GGML_OPENVINO_ENABLE_FALLBACK") != 0;
1795 if (!fallback_enabled) {
1796 return false;
1797 }
1798
1799 // Backend op tests execute each node through ggml_graph_view(), which preserves the original
1800 // graph use_counts while exposing only one node. Treat those single-node views as regular
1801 // naive graphs so intermediate ops do not look like split-model fragments.
1802 if (cgraph->n_nodes <= 1 && cgraph->n_leafs == 0) {
1803 return false;
1804 }
1805
1806 // check the nodes of the model are used by the following nodes, through compare the node's use count and the count of nodes that use it as input. If does not match, return true, else return false.
1807 for (int i = 0; i < cgraph->n_nodes; i++) {
1808 ggml_tensor * node = cgraph->nodes[i];
1809 int use_count = cgraph->use_counts[ggml_hash_find(&cgraph->visited_hash_set, node)];
1810 // TODO: this is a workround for the tests case from llama.cpp, fix should from the root cause in the future.
1811 if ((cgraph->n_nodes <= 1 && use_count == 0) ||
1812 (cgraph->n_nodes <= 1 && node->op == GGML_OP_VIEW && use_count == 1 && node->src[0] != nullptr &&
1813 node->src[0]->op == GGML_OP_NONE)) {
1814 return false;
1815 }
1816 if (cgraph->n_nodes == 1 &&
1817 (cgraph->nodes[0]->op == GGML_OP_TRANSPOSE || cgraph->nodes[0]->op == GGML_OP_PERMUTE)) {
1818 return false;
1819 }
1820 int input_use_count = 0;
1821 for (int j = 0; j < cgraph->n_nodes; j++) {
1822 ggml_tensor * other_node = cgraph->nodes[j];
1823 for (int k = 0; k < GGML_MAX_SRC; k++) {
1824 if (other_node->src[k] == node) {
1825 input_use_count++;
1826 }
1827 }
1828 }
1829 if (use_count != input_use_count && node->op != GGML_OP_NONE) {
1830 return true;
1831 }
1832 }
1833 // if all nodes's src node's src is not come from the nodes in the model, we think the model is splitted. This is a complementary check for the above check, because for some special case like the output node is not used by any node, the use count and input use count are both 0, we can not determine whether the model is splitted or not just based on the first check.
1834 // Only weight-name membership is needed below. With GGML_OPENVINO_REDUCE_COMPILE_MEM
1835 // use the name-only collector (no weight extraction); otherwise keep the original
1836 // behavior of building (naive) weight nodes and take their names.
1837 std::set<std::string> model_weights;
1838 if (ggml_openvino_reduce_compile_mem_enabled()) {
1839 model_weights = GgmlOvDecoder::collect_weight_names(cgraph);
1840 } else {
1841 for (const auto & kv : GgmlOvDecoder::create_weight_nodes(cgraph, true)) {
1842 model_weights.insert(kv.first);
1843 }
1844 }
1845 std::set<ggml_tensor *> model_nodes(cgraph->nodes, cgraph->nodes + cgraph->n_nodes);
1846 // leaf nodes
1847 std::set<ggml_tensor *> model_leafs(cgraph->leafs, cgraph->leafs + cgraph->n_leafs);
1848 for (int i = 0; i < cgraph->n_nodes; i++) {
1849 ggml_tensor * node = cgraph->nodes[i];
1850 for (int j = 0; j < GGML_MAX_SRC; j++) {
1851 ggml_tensor * src = node->src[j];
1852 // the src is also not the model weights, we think the model is splitted.
1853 // the src is also not in model leafs, we think the model is splitted.
1854 if (src != nullptr && model_nodes.find(src) == model_nodes.end() &&
1855 model_weights.find(std::string(src->name)) == model_weights.end() && !model_leafs.empty() == false &&
1856 model_leafs.find(src) == model_leafs.end()) {
1857 if (GgmlOvDecoder::is_inp_tok(src, node)) {
1858 return false;
1859 }
1860 return true;
1861 }
1862 }
1863 }
1864 return false;
1865}
1866
1867bool is_naive(ggml_cgraph * cgraph) {
1868 constexpr int naive_graph_size_threshold = 20;
1869 int count = 0;
1870 for (int i = 0; i < cgraph->n_nodes; i++) {
1871 if (cgraph->nodes[i]->op != GGML_OP_NONE) {
1872 count++;
1873 }
1874 }
1875 return count < naive_graph_size_threshold;
1876}
1877
1878size_t checksum(const void * data, size_t size) {
1879 const uint8_t * bytes = static_cast<const uint8_t *>(data);
1880 size_t sum = 0;
1881 for (size_t i = 0; i < size; ++i) {
1882 sum += (uint8_t) i;
1883 sum += bytes[i];
1884 }
1885 return sum;
1886}
1887
1888bool save_ggml_tensor_data_to_txt(const ggml_tensor * tensor, const std::string & file_path) {
1889 if (tensor == nullptr || tensor->data == nullptr) {
1890 return false;
1891 }
1892
1893 std::ofstream out(file_path);
1894 if (!out.is_open()) {
1895 return false;
1896 }
1897
1898 const size_t n = ggml_nelements(tensor);
1899 out << "name: " << tensor->name << ", type: " << ggml_type_name(tensor->type) << ", shape: [" << tensor->ne[0]
1900 << ", " << tensor->ne[1] << ", " << tensor->ne[2] << ", " << tensor->ne[3] << "]" << ", elements: " << n
1901 << ", data:" << '\n';
1902
1903 switch (tensor->type) {
1904 case GGML_TYPE_F32: {
1905 const auto * data = static_cast<const float *>(tensor->data);
1906 for (size_t i = 0; i < n; ++i) {
1907 out << data[i] << '\n';
1908 }
1909 break;
1910 }
1911 case GGML_TYPE_F16: {
1912 const auto * data = static_cast<const ggml_fp16_t *>(tensor->data);
1913 for (size_t i = 0; i < n; ++i) {
1914 out << ggml_fp16_to_fp32(data[i]) << '\n';
1915 }
1916 break;
1917 }
1918 case GGML_TYPE_BF16: {
1919 const auto * data = static_cast<const ggml_bf16_t *>(tensor->data);
1920 for (size_t i = 0; i < n; ++i) {
1921 out << ggml_bf16_to_fp32(data[i]) << '\n';
1922 }
1923 break;
1924 }
1925 case GGML_TYPE_I32: {
1926 const auto * data = static_cast<const int32_t *>(tensor->data);
1927 for (size_t i = 0; i < n; ++i) {
1928 out << data[i] << '\n';
1929 }
1930 break;
1931 }
1932 case GGML_TYPE_I64: {
1933 const auto * data = static_cast<const int64_t *>(tensor->data);
1934 for (size_t i = 0; i < n; ++i) {
1935 out << data[i] << '\n';
1936 }
1937 break;
1938 }
1939 default:
1940 out << "unsupported tensor type for text dump" << '\n';
1941 return false;
1942 }
1943
1944 return true;
1945}
1946
1947void print_input_tensor_info(const std::string & name, const ov::Tensor & tensor) {
1948 std::cout << "Input name: " << name << ", Input shape: " << tensor.get_shape() << ", Address: " << tensor.data()
1949 << '\n';
1950 switch (tensor.get_element_type()) {
1951 case ov::element::f32: {
1952 if (name.find("self_kq_mask") == std::string::npos && name.find("KQ_mask") == std::string::npos) {
1953 std::cout << *(tensor.data<float>()) << '\n';
1954 } else {
1955 size_t rows = tensor.get_shape()[2];
1956 size_t cols = tensor.get_shape()[3];
1957 const float * data = tensor.data<float>();
1958 for (size_t i = 0; i < rows; ++i) {
1959 for (size_t j = 0; j < cols; ++j) {
1960 float val = data[i * cols + j];
1961 if (std::isinf(val) && val < 0) {
1962 std::cout << std::setw(5) << "-inf";
1963 } else {
1964 std::cout << std::setw(5) << val;
1965 }
1966 }
1967 std::cout << '\n';
1968 }
1969 }
1970
1971 break;
1972 }
1973 case ov::element::f16:
1974 std::cout << *(tensor.data<ov::float16>()) << '\n';
1975 break;
1976 case ov::element::i32:
1977 for (size_t i = 0; i < tensor.get_size(); ++i) {
1978 std::cout << tensor.data<int32_t>()[i] << ' ';
1979 }
1980 std::cout << '\n';
1981 break;
1982 case ov::element::i64:
1983 for (size_t i = 0; i < tensor.get_size(); ++i) {
1984 std::cout << tensor.data<int64_t>()[i] << ' ';
1985 }
1986 std::cout << '\n';
1987 break;
1988 default:
1989 break;
1990 }
1991}
1992
1993void print_output_tensor_info(const std::string & name, const ov::Tensor & tensor, const void * output_dst) {
1994 std::cout << "Output name: " << name << ", Output shape: " << tensor.get_shape() << ", Address: " << output_dst
1995 << '\n';
1996
1997 auto print_float_stats = [](const std::string & type_name, size_t size, auto get_value) {
1998 if (size == 0) {
1999 return;
2000 }
2001
2002 float first = get_value(0);
2003 float min = first;
2004 float max = first;
2005 double sum = first;
2006
2007 for (size_t i = 1; i < size; ++i) {
2008 float v = get_value(i);
2009 min = std::min(v, min);
2010 max = std::max(v, max);
2011 sum += v;
2012 }
2013 double mean = sum / size;
2014
2015 std::cout << std::right << std::setw(6) << type_name << std::right << std::setw(12) << "First" << std::setw(12)
2016 << "Min" << std::setw(12) << "Max" << std::setw(12) << "Mean" << '\n';
2017 std::cout << std::right << std::setw(6) << "" << std::right << std::setw(12) << first << std::setw(12) << min
2018 << std::setw(12) << max << std::setw(12) << mean << '\n';
2019 };
2020
2021 switch (tensor.get_element_type()) {
2022 case ov::element::f32: {
2023 const float * data = tensor.data<float>();
2024 size_t size = tensor.get_size();
2025 print_float_stats("[f32]", size, [data](size_t i) { return data[i]; });
2026 break;
2027 }
2028 case ov::element::f16: {
2029 const ov::float16 * data = tensor.data<ov::float16>();
2030 size_t size = tensor.get_size();
2031 print_float_stats("[f16]", size, [data](size_t i) { return static_cast<float>(data[i]); });
2032 break;
2033 }
2034 default:
2035 break;
2036 }
2037}
2038
2039const ggml_tensor * get_inp_pos_tensor(ggml_cgraph * cgraph) {
2040 for (int i = 0; i < cgraph->n_nodes; ++i) {
2041 auto * op = cgraph->nodes[i];
2042 for (int j = 0; j < GGML_MAX_SRC; ++j) {
2043 auto * src = op->src[j];
2044 if (src == nullptr) {
2045 break;
2046 }
2047 if (GgmlOvDecoder::is_inp_pos(src, op)) {
2048 return src;
2049 }
2050 }
2051 }
2052 GGML_LOG_ERROR("get_inp_pos_tensor: inp_pos not found in cgraph");
2053 throw std::runtime_error("get_inp_pos_tensor: inp_pos not found in cgraph");
2054}
2055
2056int64_t get_inp_pos_n_tokens(ggml_cgraph * cgraph, const ggml_tensor * inp_pos) {
2057 // IMROPE stacks n_planes (t/h/w/e) position planes into inp_pos, so ne[0] is
2058 // n_planes * n_tokens. Callers that need a token count must divide the planes out.
2059 int n_planes = 1;
2060 for (int i = 0; i < cgraph->n_nodes; ++i) {
2061 auto * op = cgraph->nodes[i];
2062 for (int j = 0; j < GGML_MAX_SRC; ++j) {
2063 if (op->src[j] == inp_pos) {
2064 n_planes = GgmlOvDecoder::get_inp_pos_n_planes(op);
2065 break;
2066 }
2067 }
2068 }
2069 return inp_pos->ne[0] / n_planes;
2070}
2071
2072bool get_is_prefill(ggml_cgraph * cgraph, const ggml_tensor * inp_pos) {
2073 return get_inp_pos_n_tokens(cgraph, inp_pos) > 1;
2074}