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 / ggml-decoder.cpp

2465 lines · 110954 bytes Raw Blame History
1#include "ggml-decoder.h"
2
3#include "ggml-impl.h"
4#include "ggml-openvino-extra.h"
5#include "ggml-openvino.h"
6#include "ggml-quants.h"
7#include "ggml.h"
8#include "utils.h"
9
10#include <algorithm>
11#include <cassert>
12#include <cstddef>
13#include <cstdint>
14#include <cstdlib>
15#include <fstream>
16#include <iomanip>
17#include <map>
18#include <memory>
19#include <mutex>
20#include <openvino/core/dimension.hpp>
21#include <openvino/core/except.hpp>
22#include <openvino/core/node.hpp>
23#include <openvino/core/partial_shape.hpp>
24#include <openvino/core/type/bfloat16.hpp>
25#include <openvino/core/type/element_type.hpp>
26#include <openvino/core/type/float16.hpp>
27#include <openvino/op/constant.hpp>
28#include <openvino/op/convert.hpp>
29#include <openvino/runtime/tensor.hpp>
30#include <ostream>
31#include <set>
32#include <stdexcept>
33#include <string>
34#include <cstring>
35#include <unordered_map>
36#include <vector>
37
38GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph,
39 ModelParams & model_params,
40 ComputeParams & compute_params,
41 std::map<std::string, std::shared_ptr<ov::Node>> & model_weights,
42 bool is_static,
43 bool is_stateful,
44 bool model_is_splitted,
45 bool is_prefill,
46 int prefill_chunk_size) :
47 m_is_static(is_static),
48 m_is_stateful(is_stateful),
49 m_is_prefill(is_prefill),
50 m_naive(false),
51 m_prefill_chunk_size(prefill_chunk_size),
52 m_model_is_splitted(model_is_splitted),
53 m_cgraph(cgraph),
54 m_model_weights(model_weights),
55 m_model_params(model_params),
56 m_compute_params(compute_params) {
57 static bool printed_address_map = false;
58 if (!printed_address_map) {
59 if (ggml_openvino_getenv_int("GGML_OPENVINO_PRINT_CGRAPH_TENSOR_ADDRESS")) {
60 printed_address_map = true;
61 print_tensor_address_map(cgraph);
62 }
63 }
64
65 validate_cgraph();
66
67 set_input_output();
68 compute_node_dynamic_dims();
69 compute_model_inputs();
70 compute_model_outputs();
71
72 for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
73 m_node_info_list[node_n].node_op_case = compute_op_case(m_node_info_list[node_n].node);
74 m_node_info_list[node_n].node_op_type = compute_op_type(m_node_info_list[node_n].node);
75 }
76
77 add_extra_inputs();
78}
79
80void GgmlOvDecoder::update_io(ggml_cgraph * cgraph) {
81 m_cgraph = cgraph;
82 m_model_inputs.clear();
83 m_model_outputs.clear();
84 m_node_info_list.clear();
85 set_input_output();
86 compute_model_inputs();
87 compute_model_outputs();
88}
89
90// llama keeps separate graphs for batches with and without outputs, so a cache hit can come from a
91// graph built in other memory. The decoder then still points at the old graph's tensors.
92bool GgmlOvDecoder::is_bound_to(const ggml_cgraph * cgraph) const {
93 return m_cgraph == cgraph && cgraph->n_nodes > 0 && m_node_info_list.size() == (size_t) cgraph->n_nodes &&
94 m_node_info_list.front().node == cgraph->nodes[0] &&
95 m_node_info_list.back().node == cgraph->nodes[cgraph->n_nodes - 1];
96}
97
98GgmlOvDecoder::GgmlOvDecoder(ggml_cgraph * cgraph, std::map<std::string, std::shared_ptr<ov::Node>> & model_weights) {
99 m_cgraph = cgraph;
100 m_model_weights = model_weights;
101 m_naive = true;
102 set_input_output();
103 compute_model_inputs();
104 compute_model_outputs();
105 for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
106 m_node_info_list[node_n].node_op_case = compute_op_case(m_node_info_list[node_n].node);
107 m_node_info_list[node_n].node_op_type = compute_op_type(m_node_info_list[node_n].node);
108 }
109}
110
111namespace {
112bool is_inplace_op(const ggml_tensor * node) {
113 return node->op == GGML_OP_SET_ROWS || node->op == GGML_OP_CPY || (node->op == GGML_OP_SCALE && node->view_src);
114}
115
116bool is_same_shape(const ggml_tensor * a, const ggml_tensor * b) {
117 for (int i = 0; i < GGML_MAX_DIMS; i++) {
118 if (a->ne[i] != b->ne[i]) {
119 return false;
120 }
121 }
122 return true;
123}
124
125bool is_conv_states_all_tensor(const ggml_tensor * tensor) {
126 return tensor != nullptr && strncmp(tensor->name, "conv_states_all", strlen("conv_states_all")) == 0;
127}
128
129bool is_full_single_slot_writeback(const ggml_tensor * node) {
130 return node->view_src != nullptr && node->view_src->ne[1] == 1 && node->src[1] != nullptr &&
131 node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src &&
132 node->src[1]->view_offs == 0 && ggml_nbytes(node->src[1]) == ggml_nbytes(node->view_src);
133}
134} // namespace
135
136// MoE expert aggregation (build_moe_ffn in llama-graph.cpp): each expert plane is
137// `ggml_view_2d(experts, n_embd, n_tokens, experts->nb[2], i*experts->nb[1])` and the planes
138// are summed with a chain of ADDs: moe_out = ((view_0 + view_1) + view_2) + ... + view_{n-1}.
139// Detected structurally by walking the ADD chain and checking every leaf is a same-shape,
140// same-stride VIEW of one common base tensor, indexed by a distinct expert-plane offset, and
141// that the chain covers every plane of that base (leaf count == base->ne[1]). Only the
142// outermost ADD of the chain satisfies this (inner ADDs see fewer leaves than base->ne[1]).
143bool is_moe_expert_sum_add(const ggml_tensor * node) {
144 std::vector<const ggml_tensor *> leaves;
145 const ggml_tensor * cur = node;
146 while (cur->op == GGML_OP_ADD) {
147 if (cur->src[0] == nullptr || cur->src[1] == nullptr) {
148 return false;
149 }
150 leaves.push_back(cur->src[1]);
151 cur = cur->src[0];
152 }
153 leaves.push_back(cur);
154
155 const ggml_tensor * base = nullptr;
156 std::set<int64_t> plane_indices;
157 for (const ggml_tensor * leaf : leaves) {
158 if (leaf->op != GGML_OP_VIEW || leaf->src[0] == nullptr) {
159 return false;
160 }
161 const ggml_tensor * leaf_base = leaf->src[0];
162 if (base == nullptr) {
163 base = leaf_base;
164 } else if (leaf_base != base) {
165 return false;
166 }
167 if (leaf->ne[0] != base->ne[0] || leaf->ne[1] != base->ne[2] || leaf->ne[2] != 1 || leaf->ne[3] != 1 ||
168 leaf->nb[1] != base->nb[2]) {
169 return false;
170 }
171 if (base->nb[1] == 0 || leaf->view_offs % base->nb[1] != 0) {
172 return false;
173 }
174 int64_t plane = static_cast<int64_t>(leaf->view_offs / base->nb[1]);
175 if (plane < 0 || plane >= base->ne[1] || !plane_indices.insert(plane).second) {
176 return false;
177 }
178 }
179
180 return base != nullptr && base->ne[1] > 1 && plane_indices.size() == static_cast<size_t>(base->ne[1]);
181}
182
183std::string GgmlOvDecoder::get_tensor_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) {
184 if (tensor == nullptr) {
185 return "";
186 }
187 if ((tensor->flags & GGML_TENSOR_FLAG_COMPUTE) || is_kvcache(tensor, nullptr)) {
188 // Hash-table slots depend on tensor addresses and differ between contexts.
189 // Graph ordinals disambiguate duplicate names while keeping compiled-model
190 // ports identical for equivalent graphs in different contexts.
191 const auto * node = std::find(cgraph->nodes, cgraph->nodes + cgraph->n_nodes, tensor);
192 if (node != cgraph->nodes + cgraph->n_nodes) {
193 return std::string(tensor->name) + "#n" + std::to_string(node - cgraph->nodes);
194 }
195 const auto * leaf = std::find(cgraph->leafs, cgraph->leafs + cgraph->n_leafs, tensor);
196 if (leaf != cgraph->leafs + cgraph->n_leafs) {
197 return std::string(tensor->name) + "#l" + std::to_string(leaf - cgraph->leafs);
198 }
199 }
200 return tensor->name;
201}
202
203static std::string get_tensor_ov_name(const ggml_cgraph * cgraph, const ggml_tensor * tensor) {
204 return GgmlOvDecoder::get_tensor_name(cgraph, tensor);
205}
206
207static std::string get_tensor_graph_input_ov_name(const GgmlOvDecoder * decoder,
208 const ggml_cgraph * cgraph,
209 const ggml_tensor * tensor,
210 const ggml_tensor * op) {
211 if (GgmlOvDecoder::is_inp_pos(tensor, op)) {
212 return "inp_pos";
213 }
214 if (GgmlOvDecoder::is_inp_emb(tensor, op)) {
215 return "embd";
216 }
217 if (GgmlOvDecoder::is_inp_mask(tensor, op)) {
218 // Give the two attention masks distinct OV parameter names. build_attn_inp_kq_mask()
219 // names the full-attention mask and the sliding-window mask identically, so keying a
220 // parameter off the name alone makes the second mask overwrite the first and both
221 // attention types read one parameter. Tell them apart by tensor identity, using the
222 // SWA classification computed in compute_llm_params(). An empty swa_layers set means
223 // there is only one mask in play and the plain name is correct.
224 const bool is_swa = decoder->is_swa_mask(tensor);
225 if (decoder->is_stateful()) {
226 return is_swa ? "self_kq_mask_swa" : "self_kq_mask";
227 }
228 if (is_swa) {
229 return get_tensor_ov_name(cgraph, tensor) + "_swa";
230 }
231 }
232 return get_tensor_ov_name(cgraph, tensor);
233}
234
235void GgmlOvDecoder::set_input_output() {
236 for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) {
237 auto * node = m_cgraph->nodes[node_n];
238
239 NodeInfo current_node_info;
240 auto node_name = get_tensor_ov_name(m_cgraph, node);
241
242 current_node_info.node = node;
243 current_node_info.node_name = node_name;
244 current_node_info.node_op_case = 0;
245 current_node_info.data_addr = node->data;
246
247 for (int i = 0; i < GGML_MAX_SRC; i++) {
248 auto * src = node->src[i];
249 if (src == nullptr) {
250 continue;
251 }
252 auto src_name = get_tensor_ov_name(m_cgraph, src);
253 if (src->flags & GGML_TENSOR_FLAG_INPUT) {
254 src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
255 }
256 current_node_info.node_inputs[src_name] = src;
257 current_node_info.node_inputs_names.push_back(src_name);
258
259 if (src->op == GGML_OP_VIEW) {
260 // Traverse upward through nested VIEW operations
261 std::remove_reference_t<decltype(current_node_info.node_inputs_views[src_name])> view_chain;
262 auto * current = src;
263
264 while (current != nullptr) {
265 auto current_name = get_tensor_ov_name(m_cgraph, current);
266 if (current->flags & GGML_TENSOR_FLAG_INPUT) {
267 current_name = get_tensor_graph_input_ov_name(this, m_cgraph, current, node);
268 }
269 view_chain.emplace_back(current_name, current);
270 // If current src is also a VIEW, continue traversing
271 if (current->src[0] != nullptr && current->src[0]->op == GGML_OP_VIEW) {
272 current = current->src[0];
273 } else {
274 break;
275 }
276 }
277
278 // Assign all collected view inputs to node_inputs_views
279 current_node_info.node_inputs_views[src_name] = view_chain;
280 }
281 }
282
283 m_node_info_list.push_back(current_node_info);
284 }
285}
286
287int GgmlOvDecoder::compute_op_case(const ggml_tensor * node) const {
288 int op_case = 0;
289 switch (node->op) {
290 case GGML_OP_RESHAPE: {
291 if (m_naive) {
292 break;
293 }
294 auto name = std::string(node->name);
295 auto * src = node->src[0];
296 // Identify recurrent sequence reshapes before size checks, which are ambiguous for one token.
297 bool recurrent_sequence = false;
298 for (int i = 0; i < m_cgraph->n_nodes && !recurrent_sequence; ++i) {
299 const auto * consumer = m_cgraph->nodes[i];
300 if (consumer->op == GGML_OP_MUL_MAT_ID && consumer->src[1] == node) {
301 return 1;
302 } else if (consumer->op == GGML_OP_SSM_CONV) {
303 const auto * concat = consumer->src[0];
304 if (concat->op == GGML_OP_CONCAT) {
305 const auto * transposed = concat->src[1];
306 recurrent_sequence = transposed->op == GGML_OP_TRANSPOSE && transposed->src[0] == node;
307 }
308 } else if (consumer->op == GGML_OP_UNARY && ggml_get_unary_op(consumer) == GGML_UNARY_OP_SOFTPLUS) {
309 const auto * biased = consumer->src[0];
310 recurrent_sequence = biased->op == GGML_OP_ADD && biased->src[0] == node;
311 }
312 }
313 if (recurrent_sequence && node->ne[0] == src->ne[0] && node->ne[3] == 1) {
314 return 6;
315 }
316 if (node->ne[0] == src->ne[0] && node->ne[2] == 1 && node->ne[3] == 1) {
317 return 5;
318 }
319 if (src->op == GGML_OP_RESHAPE && src->src[0]->ne[0] == node->ne[0] && src->src[0]->ne[1] == node->ne[1]) {
320 op_case = 4;
321 } else if (node->ne[0] * node->ne[1] == src->ne[0]) {
322 op_case = 1;
323 } else if (src->ne[0] * src->ne[1] == node->ne[0]) {
324 op_case = 2;
325 if (src->ne[2] * src->ne[3] == node->ne[1]) {
326 op_case = 5;
327 }
328 } else if (node->ne[0] == 1 && src->ne[0] * src->ne[1] * src->ne[2] == node->ne[1]) {
329 op_case = 3;
330 } else if (name.find("linear_attn_qkv_mixed") == 0 || name.find("alpha") == 0) {
331 op_case = 6;
332 } else if (name.find("linear_attn_out") == 0) {
333 op_case = 7;
334 } else if (name.find("state_predelta") == 0) {
335 op_case = 8;
336 }
337 if (op_case == 1 && m_is_stateful) {
338 // Recurrent convolution and GDN gates retain their rank-4 layout.
339 // The gathered states may come through a view of the one gather of all states (see build_rs).
340 const auto * gather = src->op == GGML_OP_VIEW ? src->src[0] : src;
341 bool recurrent = gather->op == GGML_OP_GET_ROWS && is_recurrent_cache(gather->src[0]);
342 for (int i = 0; i < m_cgraph->n_nodes && !recurrent; ++i) {
343 const auto * consumer = m_cgraph->nodes[i];
344 if (consumer->op == GGML_OP_GATED_DELTA_NET) {
345 for (int j : {3, 4}) {
346 const auto * gate = consumer->src[j];
347 if (gate->op == GGML_OP_UNARY) {
348 gate = gate->src[0];
349 }
350 recurrent = recurrent || gate == node;
351 }
352 } else if (consumer->op == GGML_OP_MUL) {
353 for (int j = 0; j < 2; ++j) {
354 const auto * gate = consumer->src[j];
355 const auto * norm = consumer->src[1 - j];
356 if (gate->op != GGML_OP_UNARY || gate->src[0] != node) {
357 continue;
358 }
359 if (norm->op == GGML_OP_MUL) {
360 norm = norm->src[0];
361 }
362 recurrent = recurrent || (norm->op == GGML_OP_RMS_NORM && norm->src[0]->op == GGML_OP_VIEW &&
363 norm->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET);
364 }
365 }
366 }
367 if (recurrent) {
368 op_case = 9;
369 }
370 }
371 break;
372 }
373 case GGML_OP_PERMUTE: {
374 if (node->src[0]->op != GGML_OP_VIEW) {
375 op_case = 1;
376 } else if (node->src[0]->src[0]->op == GGML_OP_NONE) {
377 // kv cache tensor
378 std::string src_name(node->view_src->name);
379 int layer = extract_layer_from_name(src_name).value();
380 if (ggml_is_contiguous(node->src[0])) {
381 // - 19: [ 64, 8, 256, 1] VIEW cache_k_l0 (view) [ 2, 128, 1024, 1048576]
382 // [ 512, 1024, 1, 1] 0: NONE cache_k_l0 [ 2, 1024, 1048576, 1048576]
383 // - 20: [ 64, 256, 8, 1] PERMUTE cache_k_l0 (view) (permuted) [ 2, 1024, 128, 1048576]
384 // [ 64, 8, 256, 1] 0: VIEW cache_k_l0 (view) [ 2, 128, 1024, 1048576]
385 if (!is_swa_layer(layer)) {
386 op_case = 3;
387 } else {
388 op_case = 4;
389 }
390 } else {
391 // special case of cache v when `-fa off`
392 // - 17: [ 256, 8, 64, 1] VIEW cache_v_l0 (view) [ 2, 131072, 2048, 1048576]
393 // [ 512, 1024, 1, 1] 0: NONE cache_v_l0 [ 2, 1024, 1048576, 1048576]
394 // - 18: [ 256, 64, 8, 1] PERMUTE cache_v_l0 (view) (permuted) [ 2, 2048, 131072, 1048576]
395 // [ 256, 8, 64, 1] 0: VIEW cache_v_l0 (view) [ 2, 131072, 2048, 1048576]
396 if (!is_swa_layer(layer)) {
397 op_case = 5;
398 } else {
399 op_case = 6;
400 }
401 }
402 } else {
403 // rope'ed query tensor
404 op_case = 2;
405 }
406 break;
407 }
408 case GGML_OP_MUL_MAT: {
409 if (node->src[1]->op == GGML_OP_SOFT_MAX) {
410 // In the case of `-fa off`, softmax is used, v_trans=true, the dynamic dim is ne[0] for cache_v
411 op_case = 2;
412 }
413 break;
414 }
415 case GGML_OP_GET_ROWS: {
416 // GET_ROWS gathering recurrent state cache rows via the inp->s_copy index list:
417 // src[0] is a reshape of cache_r/cache_s, src[1] is a view of the s_copy leaf, or the leaf itself
418 // when one gather covers all states (see build_rs).
419 // op_case 1/2: active/extra rows of a multi-slot cache
420 // op_case 3/4: active/extra rows of a single-slot cache
421 if (node->src[0]->op == GGML_OP_RESHAPE && node->src[0]->src[0] != nullptr &&
422 is_recurrent_cache(node->src[0]->src[0])) {
423 const bool single_slot = node->src[0]->src[0]->ne[1] == 1;
424 if (node->src[1]->op == GGML_OP_VIEW) {
425 op_case = (node->src[1]->view_offs == 0 ? 1 : 2) + (single_slot ? 2 : 0);
426 } else if (single_slot) {
427 // a single-slot cache holds exactly the one state the gather selects
428 op_case = 3;
429 }
430 }
431 break;
432 }
433 case GGML_OP_ROPE: {
434 const int mode = node->op_params[2];
435 switch (mode) {
436 case GGML_ROPE_TYPE_NEOX: {
437 op_case = 1;
438 break;
439 }
440 case GGML_ROPE_TYPE_IMROPE: {
441 op_case = 2;
442 break;
443 }
444 case GGML_ROPE_TYPE_VISION: {
445 op_case = 3;
446 break;
447 }
448 case GGML_ROPE_TYPE_MROPE: {
449 op_case = 4;
450 break;
451 }
452 default:
453 op_case = 0;
454 break;
455 }
456 break;
457 }
458 case GGML_OP_VIEW: {
459 if (!m_model_params.has_rs_rollback && node->src[0] != nullptr &&
460 node->src[0]->op == GGML_OP_GATED_DELTA_NET) {
461 // The GDN translator publishes native attention/state outputs under these VIEW names.
462 op_case = 2;
463 break;
464 }
465 if (m_is_static && node->src[0] != nullptr &&
466 (node->src[0]->op == GGML_OP_GATED_DELTA_NET || node->src[0]->op == GGML_OP_CONCAT)) {
467 // VIEW slicing a GATED_DELTA_NET combined [attn|state] output, or the conv_input
468 // CONCAT. The consuming CPY/RMS_NORM op recovers the true window at runtime via
469 // ssm_state_size / the fixed conv kernel width, so this VIEW must stay an identity
470 // pass-through of the full source here too (it already is on the dynamic path);
471 // otherwise the generic static-mode Slice below would bake in the *captured*
472 // cgraph's token count, which is wrong once the compiled static model runs with a
473 // different token count (prefill chunk size or 1).
474 op_case = 1;
475 break;
476 }
477 if (node->src[0]->op == GGML_OP_VIEW) {
478 auto * src = node->src[0];
479 if (ggml_nelements(node) != ggml_nelements(src)) {
480 // throw std::runtime_error("Unsupported VIEW case");
481 }
482 op_case = 0;
483 if (m_model_is_splitted && m_model_inputs.find(get_tensor_ov_name(m_cgraph, src)) != m_model_inputs.end()) {
484 op_case = 0;
485 }
486 }
487 {
488 auto * src = node->src[0];
489 if (ggml_nelements(node) != ggml_nelements(src)) {
490 // Case 4: select one slice on src dim1 (via view offset), keep src dim2 as output dim1.
491 // Typical pattern:
492 // src: ne=[N, M, K, 1], nb=[b0, b1, b2, b3]
493 // dst: ne=[N, K, 1, 1], nb=[b0, b2, b3, b3]
494 if (node->ne[0] == src->ne[0] && node->ne[1] == src->ne[2] && node->ne[2] == 1 &&
495 node->nb[0] == src->nb[0] && node->nb[1] == src->nb[2] && src->ne[1] > 1) {
496 op_case = 0;
497 break;
498 }
499
500 // General case 3: shape differs from source (one or more dims) and is handled as VIEW slicing.
501 int diff_count = 0;
502 for (int i = 0; i < GGML_MAX_DIMS; i++) {
503 if (node->ne[i] != src->ne[i]) {
504 diff_count++;
505 }
506 // if node ne[i] > src ne[i], case = 0
507 if (node->ne[i] > src->ne[i]) {
508 return 0;
509 }
510 }
511 if (diff_count >= 1) {
512 op_case = 0;
513 }
514 }
515 }
516 break;
517 }
518 case GGML_OP_RMS_NORM: {
519 if (node->src[0]->op == GGML_OP_VIEW) {
520 if (is_same_shape(node->src[0]->src[0], node->src[0])) {
521 op_case = 1;
522 } else if (!m_model_params.has_rs_rollback &&
523 node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
524 // GDN attention is routed directly to this VIEW by get_output_names().
525 op_case = 3;
526 } else if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
527 op_case = 2;
528 }
529 }
530 break;
531 }
532 case GGML_OP_POOL_2D: {
533 const ggml_op_pool pool_mode = static_cast<ggml_op_pool>(node->op_params[0]);
534 switch (pool_mode) {
535 case GGML_OP_POOL_MAX: {
536 op_case = 1;
537 break;
538 }
539 case GGML_OP_POOL_AVG: {
540 op_case = 2;
541 break;
542 }
543 default:
544 op_case = 0;
545 break;
546 }
547 break;
548 }
549 case GGML_OP_UPSCALE: {
550 const int32_t mode_flags = node->op_params[0];
551 const ggml_scale_mode scale_mode = static_cast<ggml_scale_mode>(mode_flags & 0xFF);
552 switch (scale_mode) {
553 case GGML_SCALE_MODE_NEAREST: {
554 op_case = 1;
555 break;
556 }
557 case GGML_SCALE_MODE_BILINEAR: {
558 op_case = 2;
559 break;
560 }
561 case GGML_SCALE_MODE_BICUBIC: {
562 op_case = 3;
563 break;
564 }
565 default:
566 op_case = 0;
567 break;
568 }
569 break;
570 }
571 case GGML_OP_CPY: {
572 if (node->src[0]->op == GGML_OP_VIEW) {
573 if (node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET) {
574 if (!m_model_params.has_rs_rollback) {
575 // op_case 7 replaces a single-slot cache; op_case 10 writes native GDN state
576 // into an active range of a larger non-rollback cache.
577 op_case = is_full_single_slot_writeback(node) ? 7 : 10;
578 } else {
579 op_case = 1;
580 }
581 } else if (GgmlOvDecoder::is_conv_state_writeback(node)) {
582 op_case = is_full_single_slot_writeback(node) ? 8 : 2;
583 break;
584 } else if (is_conv_states_all_tensor(node->view_src) && node->src[1] != nullptr &&
585 node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
586 op_case = 4;
587 break;
588 } else if (node->src[0]->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
589 node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
590 is_recurrent_cache(node->src[1]->view_src) && node->src[1]->view_src->ne[1] == 1) {
591 // defrag remainder writeback of a single-slot cache, taken from a view of the one gather of
592 // all states (see build_rs)
593 op_case = 9;
594 }
595 } else if (node->src[0]->op == GGML_OP_GET_ROWS && node->src[1] != nullptr &&
596 node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr &&
597 is_recurrent_cache(node->src[1]->view_src)) {
598 // s_copy defrag remainder writeback: gathered extra state rows copied back into the cache
599 op_case = node->src[1]->view_src->ne[1] == 1 ? 9 : 3;
600 } else if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) {
601 // op_case 5: KV write for decoder self-attention (dynamic write offset)
602 // op_case 6: KV write for encoder self-attn or cross-attn (static offset)
603 const ggml_tensor * kv_buf = node->src[1]->view_src;
604 if (kv_buf->ne[1] == 1 && kv_buf->ne[2] == 1 && kv_buf->ne[3] == 1) {
605 op_case = 6;
606 // Forward-scan the graph for a FLASH_ATTN_EXT that reads from
607 // the same buffer. Having a mask (src[3] != nullptr) implies
608 // decoder self-attention and the write offset is dynamic.
609 for (int i = 0; i < m_cgraph->n_nodes; i++) {
610 const ggml_tensor * n = m_cgraph->nodes[i];
611 if (n->op != GGML_OP_FLASH_ATTN_EXT) {
612 continue;
613 }
614 // K (src[1]) and V (src[2]) are 3-D views whose view_src is
615 // the flat KV buffer we are writing to.
616 if ((n->src[1] != nullptr && n->src[1]->view_src == kv_buf) ||
617 (n->src[2] != nullptr && n->src[2]->view_src == kv_buf)) {
618 if (n->src[3] != nullptr) {
619 op_case = 5; // decoder self-attention: mask present
620 }
621 break;
622 }
623 }
624 }
625 }
626 break;
627 }
628 case GGML_OP_ADD: {
629 if (is_moe_expert_sum_add(node)) {
630 // Outermost ADD of a MoE expert-plane sum chain: translated as a single
631 // ReduceSum over the base tensor instead of N-1 chained Adds over N Slices.
632 op_case = 1;
633 }
634 break;
635 }
636 case GGML_OP_SCALE: {
637 if (node->view_src && node->buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) {
638 op_case = node->view_src->ne[1] == 1 ? 2 : 1;
639 }
640 break;
641 }
642 case GGML_OP_L2_NORM: {
643 if (std::string(node->name).find("predelta") != std::string::npos) {
644 op_case = 1;
645 }
646 break;
647 }
648 case GGML_OP_FLASH_ATTN_EXT: {
649 if (node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src != nullptr) {
650 const ggml_tensor * kv_buf = node->src[1]->view_src;
651 if (kv_buf->ne[1] == 1 && kv_buf->ne[2] == 1 && kv_buf->ne[3] == 1) {
652 op_case = (node->src[3] != nullptr) ? 1 : 2;
653 }
654 }
655 break;
656 }
657 default:
658 break;
659 }
660 return op_case;
661}
662
663std::optional<int> extract_layer_from_name(const std::string & name) {
664 size_t pos1 = name.find("_l");
665 if (pos1 == std::string::npos) {
666 return std::nullopt;
667 }
668 pos1 += 2;
669 size_t pos2 = name.find(' ', pos1);
670 if (pos2 == std::string::npos) {
671 pos2 = name.length();
672 }
673 std::string layer_str = name.substr(pos1, pos2 - pos1);
674 int layer = std::stoi(layer_str);
675 return layer;
676}
677
678// Recover the sliding window width from ggml's own SWA mask. llama.cpp never passes n_swa to a
679// backend, but fill_mask() writes it into the mask: a query row keeps exactly the cells inside
680// its window, so the widest row counts min(pos + 1, n_swa) unmasked cells. Counting rather than
681// looking for a contiguous band is what makes this work on the KV-cache mask, where columns are
682// physical cache cells in arbitrary order, not positions.
683// Assumes LLAMA_SWA_TYPE_STANDARD, the only type the caller reconstructs.
684static int get_swa_window_from_mask(const ggml_tensor * mask) {
685 if (mask->data == nullptr || !ggml_backend_buffer_is_host(mask->buffer)) {
686 return -1;
687 }
688 if (mask->type != GGML_TYPE_F16 && mask->type != GGML_TYPE_F32) {
689 return -1;
690 }
691
692 const int64_t n_kv = mask->ne[0];
693 const int64_t n_tokens = mask->ne[1];
694 int64_t window = 0;
695
696 for (int64_t r = 0; r < n_tokens; r++) {
697 int64_t kept = 0;
698 for (int64_t c = 0; c < n_kv; c++) {
699 const size_t i = (size_t) r * n_kv + c;
700 const float v = mask->type == GGML_TYPE_F16 ? ggml_fp16_to_fp32(((const ggml_fp16_t *) mask->data)[i]) :
701 ((const float *) mask->data)[i];
702 if (v > -INFINITY) {
703 kept++;
704 }
705 }
706 window = std::max(window, kept);
707 }
708
709 return window > 0 ? (int) window : -1;
710}
711
712std::pair<ModelParams, ComputeParams> GgmlOvDecoder::compute_llm_params(ggml_cgraph * cgraph, bool is_static) {
713 ModelParams model_params;
714 ComputeParams compute_params;
715 auto get_attention_pattern_case = [](const ggml_tensor * node) -> int {
716 if (node == nullptr) {
717 return -1;
718 }
719
720 switch (node->op) {
721 case GGML_OP_FLASH_ATTN_EXT:
722 if (node->src[0] == nullptr || node->src[1] == nullptr) {
723 return -1;
724 }
725 switch (node->src[1]->op) {
726 case GGML_OP_PERMUTE:
727 // case 0: src[1] is PERMUTE of a cache VIEW, mask required
728 if (node->src[3] != nullptr && node->src[1]->src[0] != nullptr &&
729 node->src[1]->src[0]->op == GGML_OP_VIEW) {
730 return 0;
731 }
732 break;
733 case GGML_OP_CPY:
734 // case 1: src[1] is CPY of a PERMUTE(VIEW), mask required
735 if (node->src[3] != nullptr && node->src[1]->src[0] != nullptr &&
736 node->src[1]->src[0]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->src[0] != nullptr &&
737 node->src[1]->src[0]->src[0]->op == GGML_OP_VIEW) {
738 return 1;
739 }
740 break;
741 case GGML_OP_VIEW:
742 // cases 4/5/6: whisper - K is a direct non-contiguous VIEW_3D of a KV cache
743 if (node->src[1]->view_src != nullptr) {
744 if (node->src[3] != nullptr) {
745 return 4; // decoder self-attention
746 }
747 return 5; // cross-attention or encoder self-attention
748 }
749 break;
750 default:
751 break;
752 }
753 break;
754 case GGML_OP_SOFT_MAX:
755 // case 2: node op is SOFT_MAX, src 0 not null & op is MUL_MAT & the src 0 of MUL_MAT is PERMUTE & the permuted tensor src is the view of cache k
756 if (node->src[0] != nullptr && node->src[1] != nullptr && node->src[0]->op == GGML_OP_MUL_MAT &&
757 node->src[0]->src[0] != nullptr && node->src[0]->src[1] != nullptr &&
758 node->src[0]->src[0]->op == GGML_OP_PERMUTE && node->src[0]->src[0]->src[0] != nullptr &&
759 node->src[0]->src[0]->src[0]->op == GGML_OP_VIEW) {
760 return 2;
761 }
762 // case 3: node op is SOFT_MAX, src 0 not null & op is ADD & the src 0 of ADD is MUL_MAT & the src 0 of MUL_MAT is PERMUTE
763 if (node->src[0]->op == GGML_OP_ADD && node->src[0]->src[0] != nullptr &&
764 node->src[0]->src[0]->op == GGML_OP_MUL_MAT && node->src[0]->src[0]->src[0] != nullptr &&
765 node->src[0]->src[0]->src[0]->op == GGML_OP_PERMUTE) {
766 return 3;
767 }
768 break;
769 default:
770 break;
771 }
772
773 return -1;
774 };
775
776 // Resolve the attention mask an attention node consumes, mirroring the src layout that
777 // get_attention_pattern_case() classifies. Used by the SWA pre-pass below.
778 auto get_attention_op_mask = [&get_attention_pattern_case](const ggml_tensor * node) -> const ggml_tensor * {
779 switch (get_attention_pattern_case(node)) {
780 case 0:
781 case 1:
782 return node->src[3];
783 case 2:
784 case 3:
785 return node->src[1];
786 default:
787 return nullptr;
788 }
789 };
790
791 // Pre-pass: classify sliding-window vs full-attention layers.
792 //
793 // An interleaved-SWA model keeps two KV caches and two attention masks, and hands each layer
794 // whichever pair matches its attention type. The mask tensor does not say which is which: both
795 // are named "attn_inp_kq_mask" by build_attn_inp_kq_mask(), and both carry the same n_kv because
796 // llama_kv_cache::get_n_kv() pads occupancy up to a common multiple.
797 //
798 // The KV cache does say. Each cache allocates cache_k_l<N> once at load time with its own cell
799 // count: the windowed cache is sized from the window
800 // (PAD(min(size_base, n_swa*(unified ? n_seq_max : 1) + n_ubatch), 256), see
801 // llama_kv_cache_iswa), the full-attention one spans the whole context. Read the LEAF buffer
802 // behind the VIEW rather than the VIEW itself: the leaf extent is a constant per layer, known
803 // from the first graph onwards, while the view grows with context depth and would invert the
804 // comparison at shallow depth.
805 //
806 // Layers whose leaf is smaller than the largest leaf are the windowed ones. When every layer
807 // reports the same extent there is no distinction to draw -- either the model has no windowed
808 // layers, or the window is at least as large as the context so the two caches coincide, in
809 // which case a windowed layer and a full-attention one compute the same thing.
810 //
811 // Getting this wrong is silent and severe: with the windowed layers classified as
812 // full-attention, permute's KV slicing uses attention_size instead of attention_size_swa. The
813 // two agree while the context is shorter than the window, then diverge, and the mask add fails
814 // shape inference ("Failed to broadcast-merge input shapes") partway into a long prompt.
815 {
816 std::map<int, int64_t> layer_extent; // layer -> leaf cache_k cell count
817 std::map<int, const ggml_tensor *> layer_mask; // layer -> mask it consumes
818 int64_t max_extent = 0;
819
820 for (int i = 0; i < cgraph->n_nodes; i++) {
821 const ggml_tensor * mask = get_attention_op_mask(cgraph->nodes[i]);
822 if (mask == nullptr) {
823 continue;
824 }
825 const ggml_tensor * cache_k_permute = nullptr;
826 switch (get_attention_pattern_case(cgraph->nodes[i])) {
827 case 0: cache_k_permute = cgraph->nodes[i]->src[1]; break;
828 case 1: cache_k_permute = cgraph->nodes[i]->src[1]->src[0]; break;
829 case 2: cache_k_permute = cgraph->nodes[i]->src[0]->src[0]; break;
830 default: cache_k_permute = cgraph->nodes[i]->src[0]->src[0]->src[0]; break;
831 }
832 const ggml_tensor * cache_k_view = cache_k_permute->src[0];
833 if (cache_k_view->op != GGML_OP_VIEW) {
834 continue;
835 }
836 const ggml_tensor * leaf = cache_k_view->src[0];
837 auto layer = extract_layer_from_name(leaf->name);
838 if (!layer.has_value()) {
839 continue;
840 }
841 layer_extent[layer.value()] = leaf->ne[1];
842 layer_mask[layer.value()] = mask;
843 max_extent = std::max(max_extent, leaf->ne[1]);
844 }
845
846 for (const auto & [layer, extent] : layer_extent) {
847 if (extent < max_extent) {
848 model_params.swa_layers.push_back(layer);
849 if (model_params.swa_mask == nullptr) {
850 model_params.swa_mask = layer_mask[layer];
851 }
852 }
853 }
854 std::sort(model_params.swa_layers.begin(), model_params.swa_layers.end());
855
856 if (ggml_openvino_getenv_int("GGML_OPENVINO_LOG_SWA_LAYERS")) {
857 std::string per_layer;
858 for (const auto & [layer, extent] : layer_extent) {
859 per_layer += " " + std::to_string(layer) + ":" + std::to_string(extent) +
860 (extent < max_extent ? "(swa)" : "");
861 }
862 GGML_LOG_WARN("ov-swa: attn_layers=%zu max_extent=%ld swa_layers=%zu |%s\n", layer_extent.size(),
863 (long) max_extent, model_params.swa_layers.size(), per_layer.c_str());
864 }
865 }
866
867 bool rope_seen = false;
868 for (int i = 0; i < cgraph->n_nodes; i++) {
869 ggml_tensor * node = cgraph->nodes[i];
870 const int attention_pattern_case = get_attention_pattern_case(node);
871 if (attention_pattern_case != -1) {
872 ggml_tensor * cache_k_permute = nullptr;
873 ggml_tensor * mask = nullptr;
874
875 switch (attention_pattern_case) {
876 case 0:
877 cache_k_permute = node->src[1];
878 mask = node->src[3];
879 break;
880 case 1:
881 cache_k_permute = node->src[1]->src[0];
882 mask = node->src[3];
883 break;
884 case 2:
885 cache_k_permute = node->src[0]->src[0];
886 mask = node->src[1];
887 break;
888 case 3:
889 cache_k_permute = node->src[0]->src[0]->src[0];
890 mask = node->src[1];
891 break;
892 case 4:
893 case 5: {
894 // whisper: K is a direct VIEW_3D of the KV buffer, no PERMUTE node
895 auto * cache_k_view = node->src[1]; // VIEW_3D of kv_self.k or kv_cross.k`
896 compute_params.token_len_per_seq = node->src[0]->ne[1];
897 if (attention_pattern_case == 4) {
898 compute_params.attention_size = cache_k_view->ne[1];
899 } else {
900 compute_params.attention_size_static = cache_k_view->ne[1];
901 }
902 continue;
903 }
904 default:
905 break;
906 }
907
908 assert(cache_k_permute != nullptr);
909
910 model_params.head_size = cache_k_permute->ne[0];
911 model_params.n_heads_kv = cache_k_permute->ne[2];
912 compute_params.input_len = node->src[0]->ne[1];
913 compute_params.token_len_per_seq = node->src[0]->ne[1];
914
915 auto * cache_k_view = cache_k_permute->src[0];
916 if (cache_k_view->op != GGML_OP_VIEW || mask == nullptr) {
917 continue;
918 }
919
920 ggml_tensor * cache_k = cache_k_view->src[0];
921 int layer = extract_layer_from_name(cache_k->name).value();
922
923 // Classified by the pre-pass above, which groups layers by mask tensor identity. The
924 // mask NAME cannot be used: build_attn_inp_kq_mask() gives both masks the same name.
925 const bool layer_is_swa = std::find(model_params.swa_layers.begin(), model_params.swa_layers.end(),
926 layer) != model_params.swa_layers.end();
927
928 model_params.kv_buffer_ctx_id = ggml_backend_openvino_buffer_get_ctx_id(cache_k->buffer);
929 model_params.n_heads_kv_per_layer[layer] = cache_k_permute->ne[2];
930 if (layer_is_swa) {
931 model_params.ctx_per_seq_swa = cache_k->ne[1];
932 } else {
933 model_params.ctx_per_seq = cache_k->ne[1];
934 model_params.n_seq = cache_k->ne[2];
935 }
936
937 compute_params.n_seq_active = mask->ne[3];
938 auto seq_size = cache_k->ne[0] * cache_k->ne[1] * ggml_type_size(cache_k->type);
939 size_t offset;
940 memcpy(&offset, cache_k_view->op_params, sizeof(size_t));
941 compute_params.seq_active_start = offset / seq_size;
942
943 if (layer_is_swa) {
944 compute_params.attention_size_swa = mask->ne[0];
945 compute_params.swa_window = get_swa_window_from_mask(mask);
946 } else {
947 compute_params.attention_size = mask->ne[0];
948 }
949 if (is_static) {
950 compute_params.attention_size = model_params.ctx_per_seq;
951 compute_params.attention_size_swa = model_params.ctx_per_seq_swa;
952 compute_params.token_len_per_seq = 1;
953 }
954 }
955
956 if (node->op == GGML_OP_MUL_MAT && node->src[0]->op == GGML_OP_PERMUTE &&
957 node->src[0]->src[0]->op == GGML_OP_VIEW && is_kvcache(node->src[0]->view_src, node->view_src)) {
958 if (node->src[1]->op == GGML_OP_PERMUTE && node->src[1]->src[0]->op == GGML_OP_VIEW &&
959 node->src[1]->src[0]->src[0]->op == GGML_OP_ROPE) {
960 compute_params.attention_size = node->ne[0];
961 }
962 }
963
964 // if the node op is TRANSPOSE and its input is PERMUTE and the source of the PERMUTE is VIEW, then get the attention size with the TRANSPOSE node ne[0] (in case no GGML_OP_FLASH_ATTN_EXT)
965 if (node->op == GGML_OP_TRANSPOSE && node->src[0]->op == GGML_OP_PERMUTE &&
966 node->src[0]->src[0]->op == GGML_OP_VIEW) {
967 compute_params.attention_size = node->ne[0];
968 if (is_static) {
969 compute_params.attention_size = model_params.ctx_per_seq;
970 }
971 }
972 if (node->op == GGML_OP_ROPE) {
973 if (compute_params.token_len_per_seq == -1 && node->src[1] != nullptr) {
974 compute_params.token_len_per_seq = ggml_nelements(node->src[1]);
975 }
976
977 // When multiple ROPE ops in the graph disagree on op_params (e.g. gemma4's
978 // mixed SWA/non-SWA layers with different n_dims or freq_base), we cannot
979 // share a single precomputed rope_sin/rope_cos. Track divergence so the
980 // translator falls back to per-op make_sin_cos in that case.
981 static_assert(sizeof(model_params.rope_params) == sizeof(int32_t) * 16, "rope_params size");
982 if (!rope_seen) {
983 memcpy(model_params.rope_params, node->op_params, sizeof(int32_t) * 16);
984 rope_seen = true;
985 } else if (memcmp(model_params.rope_params, node->op_params, sizeof(int32_t) * 16) != 0) {
986 model_params.mixed_rope_params = true;
987 }
988 }
989 if (node->op == GGML_OP_GATED_DELTA_NET) {
990 model_params.state_size = node->src[0]->ne[0];
991 }
992 if (node->op == GGML_OP_SCALE && node->view_src != nullptr && is_recurrent_cache(node->view_src)) {
993 if (model_params.n_rs_slots == -1) {
994 model_params.n_rs_slots = node->view_src->ne[1];
995 } else {
996 GGML_ASSERT(model_params.n_rs_slots == node->view_src->ne[1]);
997 }
998 compute_params.cache_rs_reset_len = ggml_nelements(node) / node->view_src->ne[0];
999 compute_params.cache_rs_reset_idx = node->src[0]->view_offs / node->view_src->ne[0];
1000 }
1001 // Capture the destination slot block of every recurrent state cache writeback, plus the
1002 // source window needed by conv state and packed GDN rollback writes. The active sequences
1003 // occupy a contiguous slot block [begin, begin + n_seqs) of the cache; these offsets move
1004 // with the batch, so they are fed to the cached model as runtime inputs.
1005 if (node->op == GGML_OP_CPY && node->view_src != nullptr && is_recurrent_cache(node->view_src) &&
1006 node->src[1] != nullptr && node->src[1]->op == GGML_OP_VIEW && node->src[1]->view_src == node->view_src) {
1007 const bool is_conv = is_conv_state_writeback(node);
1008 const bool is_gdn = node->src[0]->op == GGML_OP_VIEW && node->src[0]->src[0] != nullptr &&
1009 node->src[0]->src[0]->op == GGML_OP_GATED_DELTA_NET;
1010 const bool is_extra = node->src[0]->op == GGML_OP_GET_ROWS;
1011 const bool is_gdn_rollback = is_gdn && is_same_shape(node->src[0], node->src[1]);
1012
1013 const ggml_tensor * dest_view = node->src[1];
1014 const ggml_tensor * cache = node->view_src;
1015 const size_t row_bytes = cache->ne[0] * ggml_type_size(cache->type);
1016 if (is_gdn_rollback) {
1017 // Rollback GDN exposes an already-flattened [state, seq, snapshot] VIEW and copies
1018 // it to an identically-shaped cache VIEW. Non-rollback copies native 4-D state
1019 // [value, key, head, seq] into flattened cache rows, so the shapes differ. This
1020 // signature is local to the CPY and still works when fallback splits the graph.
1021 model_params.has_rs_rollback = true;
1022 }
1023 if (row_bytes > 0 && (is_conv || is_gdn || is_extra) && !is_full_single_slot_writeback(node)) {
1024 ComputeParams::RsWriteback writeback;
1025 writeback.slot_begin = (int) (dest_view->view_offs / row_bytes);
1026 if (is_conv) {
1027 writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[0]);
1028 } else if (is_gdn_rollback) {
1029 writeback.src_begin = (int) (node->src[0]->view_offs / node->src[0]->view_src->nb[1]);
1030 }
1031 compute_params.rs_writebacks[get_tensor_ov_name(cgraph, node)] = writeback;
1032 }
1033 if ((is_conv || is_gdn) && !is_full_single_slot_writeback(node)) {
1034 compute_params.s_copy_active_slot_len = (int) dest_view->ne[1];
1035 }
1036 }
1037 }
1038 if (model_params.n_heads_kv == -1) {
1039 for (int i = 0; i < cgraph->n_nodes; i++) {
1040 const auto * node = cgraph->nodes[i];
1041 const ggml_tensor * mask = nullptr;
1042 if (node->op == GGML_OP_SOFT_MAX) {
1043 mask = node->src[1];
1044 } else if (node->op == GGML_OP_FLASH_ATTN_EXT) {
1045 mask = node->src[3];
1046 } else {
1047 continue;
1048 }
1049 if (mask == nullptr || mask->op != GGML_OP_NONE || !(mask->flags & GGML_TENSOR_FLAG_INPUT) ||
1050 node->src[0] == nullptr) {
1051 continue;
1052 }
1053 model_params.is_cacheless_attn = true;
1054 model_params.n_seq = 1;
1055 model_params.ctx_per_seq = mask->ne[0];
1056 compute_params.input_len = node->src[0]->ne[1];
1057 compute_params.token_len_per_seq = compute_params.input_len;
1058 break;
1059 }
1060 }
1061
1062 auto * output_tensor = cgraph->nodes[cgraph->n_nodes - 1];
1063 compute_params.output_len = output_tensor->ne[1];
1064 if (model_params.is_cacheless_attn) {
1065 for (int i = 0; i < cgraph->n_nodes; i++) {
1066 const auto * node = cgraph->nodes[i];
1067 if (node->op == GGML_OP_GET_ROWS && is_output_idx(node->src[1], node)) {
1068 compute_params.output_len = node->src[1]->ne[0];
1069 break;
1070 }
1071 }
1072 }
1073 // for NPU, output_len is always 1 except for llama-perplexity
1074 if (is_static && compute_params.output_len == 0) {
1075 compute_params.output_len = 1;
1076 }
1077 model_params.ctx = model_params.ctx_per_seq * model_params.n_seq;
1078 return {model_params, compute_params};
1079}
1080
1081void GgmlOvDecoder::validate_cgraph() const {
1082 if (m_model_params.n_seq > 1 && m_is_static == true) {
1083 throw std::runtime_error("n_seq > 1 is not supported on NPU. Try setting -np 1.");
1084 }
1085}
1086
1087ov::PartialShape GgmlOvDecoder::get_graph_input_shape(const ggml_tensor * op,
1088 const ggml_tensor * input,
1089 int dynamic_dim_index) const {
1090 if (m_naive) {
1091 return input != nullptr ? ov::PartialShape{get_shape(input)} : ov::PartialShape{get_shape(op)};
1092 }
1093 ov::PartialShape input_shape;
1094
1095 if (is_inp_tok(input, op) || is_inp_pos(input, op)) {
1096 // tokens or positions
1097 int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1;
1098 if (m_is_static && is_inp_pos(input, op)) {
1099 // IMROPE stacks n_planes (t/h/w/e) position planes back to back
1100 len *= get_inp_pos_n_planes(op);
1101 }
1102 input_shape = ov::PartialShape{1, 1, 1, len};
1103
1104 } else if (is_output_idx(input, op)) {
1105 // output index
1106 input_shape = ov::PartialShape{1, 1, 1, m_is_static ? m_compute_params.output_len : -1};
1107
1108 } else if (is_inp_mean(input, op)) {
1109 input_shape = m_is_static ? ov::PartialShape{1, 1, input->ne[1], m_prefill_chunk_size} :
1110 ov::PartialShape{1, 1, -1, -1};
1111
1112 } else if (is_inp_scale_rows(input, op)) {
1113 input_shape = ov::PartialShape{1, 1, m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1, 1};
1114
1115 } else if (is_inp_mask(input, op)) {
1116 // mask
1117 if (m_is_static) {
1118 input_shape = ov::PartialShape{1, 1, m_is_prefill ? m_prefill_chunk_size : 1, m_model_params.ctx};
1119 } else if (m_is_stateful) {
1120 input_shape = ov::PartialShape{1, 1, -1, -1};
1121 } else {
1122 input_shape = ov::PartialShape{-1, 1, -1, -1};
1123 }
1124
1125 } else if (is_recurrent_cache(input)) {
1126 input_shape = ov::PartialShape{get_shape(input)};
1127 if (!m_is_static && !m_is_stateful && input->ne[1] > 1) {
1128 input_shape[2] = -1;
1129 }
1130
1131 } else if (is_kvcache(input, op)) {
1132 // kvcache
1133 input_shape = ov::PartialShape{get_shape(input)};
1134 // Whisper.cpp uses a fixed size 1D KV buffer [N, 1, 1, 1] (GGML) or [1, 1, 1, N] (OV).
1135 // the token fill level is handled by token_len_per_seq + dynamic mask input.
1136 // skip dynamic dim and stateful reshape for this layout.
1137 const bool is_flat_kv = (input->ne[1] == 1 && input->ne[2] == 1 && input->ne[3] == 1);
1138 if (!m_is_static && !is_flat_kv) {
1139 // do not fix ctx size to make llama-bench work across test params
1140 input_shape[2] = -1;
1141 }
1142 if (is_stateful() && !is_flat_kv) {
1143 // Convert stateless KV cache layout [1, 1, seq, n_heads_kv * head_size]
1144 // to stateful layout [1, seq, n_heads_kv, head_size].
1145 // NOTE: Gemma4 uses per-layer-type KV shapes, so no single scalar describes every
1146 // layer. E2B varies only the head size (sliding 256, full 512); 12B also varies the
1147 // head COUNT (sliding 8 x 256, full 1 x 512). Take the head count for this tensor's
1148 // own layer type and derive the head size from its own combined dim, so both layer
1149 // types get the correct split. Using the model-level count split 12B's sliding
1150 // states as 1 x 2048 and decoded garbage.
1151 assert(input_shape.size() == 4 && input_shape[0] == 1 && input_shape[1] == 1 &&
1152 input_shape[2].is_dynamic() && input_shape[3].is_static());
1153 const int n_heads_kv = get_n_heads_kv_for_tensor(input);
1154 assert(n_heads_kv > 0 && input_shape[3].get_length() % n_heads_kv == 0);
1155 const int64_t combined_dim = input_shape[3].get_length(); // n_heads_kv * head_size
1156 const int64_t head_size = combined_dim / n_heads_kv;
1157 input_shape = {input_shape[0], ov::Dimension::dynamic(), n_heads_kv, head_size};
1158 }
1159
1160 } else if (is_kv_idx(input, op)) {
1161 // kv update index
1162 int len = m_is_static ? (m_is_prefill ? m_prefill_chunk_size : 1) : -1;
1163 input_shape = ov::PartialShape{1, 1, 1, len};
1164
1165 } else if (is_inp_s_copy(input, op) || is_s_copy_leaf(input)) {
1166 // On NPU the total slot count (n_seq_max) is fixed at translation time, so the s_copy
1167 // index list has a static length; on CPU/GPU it may change across compiles (defrag).
1168 input_shape = m_is_static ? ov::PartialShape{get_shape(input)} : ov::PartialShape{1, 1, 1, -1};
1169
1170 } else {
1171 input_shape = ov::PartialShape{get_shape(input)};
1172 }
1173 if (dynamic_dim_index != -1 && m_model_is_splitted) {
1174 input_shape[3 - dynamic_dim_index] = -1;
1175 }
1176 if (op->op == GGML_OP_SOFT_MAX && op->src[1] != nullptr && op->src[1]->op == GGML_OP_NONE &&
1177 op->src[1]->flags & GGML_TENSOR_FLAG_INPUT && op->src[1] == input) {
1178 // for softmax input mask, the shape is [1, 1, seq_active, seq_active], where seq_active is determined by the input active sequence length instead of the kv cache sequence length
1179 if (m_is_static) {
1180 const int64_t seq_active = m_is_prefill ? m_prefill_chunk_size : 1;
1181 input_shape[2] = seq_active;
1182 input_shape[3] = seq_active;
1183 } else {
1184 input_shape[2] = -1;
1185 input_shape[3] = -1;
1186 }
1187 }
1188 return input_shape;
1189}
1190
1191bool GgmlOvDecoder::is_s_copy_leaf(const ggml_tensor * tensor) const {
1192 if (tensor == nullptr || tensor->op != GGML_OP_NONE || m_cgraph == nullptr) {
1193 return false;
1194 }
1195 for (int i = 0; i < m_cgraph->n_nodes; i++) {
1196 const ggml_tensor * node = m_cgraph->nodes[i];
1197 if (node->op != GGML_OP_GET_ROWS || node->src[0] == nullptr || node->src[1] == nullptr) {
1198 continue;
1199 }
1200 // The index list may reach the s_copy leaf through one or more VIEWs.
1201 const ggml_tensor * idx = node->src[1];
1202 while (idx != nullptr && idx->op == GGML_OP_VIEW) {
1203 idx = idx->src[0];
1204 }
1205 if (idx != tensor) {
1206 continue;
1207 }
1208 // The gathered data must be a recurrent state cache (cache_r/cache_s).
1209 const ggml_tensor * data = node->src[0];
1210 while (data != nullptr && (data->op == GGML_OP_VIEW || data->op == GGML_OP_RESHAPE)) {
1211 data = data->src[0];
1212 }
1213 if (data != nullptr && is_recurrent_cache(data)) {
1214 return true;
1215 }
1216 }
1217 return false;
1218}
1219
1220void GgmlOvDecoder::add_extra_inputs() {
1221 // Extra inputs:
1222 // 1. `attention_size`, used in FLASH_ATTN where the shape of the matmul's are 256 aligned,
1223 // see llama_kv_cache_unified::get_n_kv and llama_kv_cache_unified::get_padding.
1224 // 2. `n_seq_active` and `seq_active_start`, used in FLASH_ATTN_EXT to indicate the active sequences in the batch
1225
1226 auto create_1d_input = [this](const std::string & name, int64_t value, bool force_parameter = false) {
1227 m_model_extra_inputs[name] = {ov::element::i64, ov::Shape{1}, value, force_parameter || !m_is_static};
1228 };
1229
1230 if (m_compute_params.attention_size != -1) {
1231 create_1d_input("attention_size", m_compute_params.attention_size);
1232 }
1233 if (m_compute_params.attention_size_static != -1) {
1234 create_1d_input("attention_size_static", m_compute_params.attention_size_static);
1235 }
1236 if (m_compute_params.attention_size_swa != -1) {
1237 create_1d_input("attention_size_swa", m_compute_params.attention_size_swa);
1238 }
1239 // only the stateful SWA mask consumes this
1240 if (is_stateful() && m_compute_params.swa_window != -1) {
1241 create_1d_input("swa_window", m_compute_params.swa_window);
1242 }
1243 create_1d_input("n_seq_active", m_compute_params.n_seq_active);
1244 create_1d_input("seq_active_start", m_compute_params.seq_active_start);
1245 create_1d_input("seq_active_end", m_compute_params.seq_active_start + m_compute_params.n_seq_active);
1246 if (m_compute_params.token_len_per_seq != -1) {
1247 create_1d_input("token_len_per_seq", m_compute_params.token_len_per_seq);
1248 }
1249 // create_1d_input("token_len", m_compute_params.token_len_per_seq * m_compute_params.n_seq_active);
1250
1251 if (m_compute_params.cache_rs_reset_idx != -1 && m_model_params.n_rs_slots != 1) {
1252 // Whether/which cache slot to reset varies per compute call (e.g. a new sequence starting
1253 // vs. continued decoding). can_reuse_statically() does not invalidate the cached static
1254 // model on ComputeParams changes, so these must stay runtime Parameters even when static
1255 // (scale.cpp op_case 1 only uses them in value comparisons, never as Slice bounds, so this
1256 // does not reintroduce dynamic shapes).
1257 create_1d_input("cache_rs_reset_idx", m_compute_params.cache_rs_reset_idx, /*force_parameter=*/true);
1258 create_1d_input("cache_rs_reset_len", m_compute_params.cache_rs_reset_len, /*force_parameter=*/true);
1259 }
1260
1261 if (m_compute_params.s_copy_active_slot_len != -1) {
1262 create_1d_input("s_copy_active_slot_len", m_compute_params.s_copy_active_slot_len);
1263 if (m_is_static) {
1264 // Number of real tokens in the current prefill chunk. The last chunk is padded with
1265 // fabricated token ids; attention masks them out, but the recurrent (GDN/conv) path
1266 // would otherwise fold them into cache_r/cache_s permanently. Varies per chunk, so it
1267 // must stay a runtime Parameter; it is only compared against a Range or used as Gather
1268 // indices, so it does not make any shape dynamic.
1269 create_1d_input("chunk_valid_len", get_static_n_tokens(), /*force_parameter=*/true);
1270 }
1271 }
1272
1273 for (const auto & [node_name, writeback] : m_compute_params.rs_writebacks) {
1274 create_1d_input("rs_slot_begin_" + node_name, writeback.slot_begin);
1275 if (!m_is_static && writeback.src_begin >= 0) {
1276 create_1d_input("rs_src_begin_" + node_name, writeback.src_begin);
1277 }
1278 }
1279}
1280
1281bool GgmlOvDecoder::node_is_used_as_src(const int node_idx) {
1282 ggml_tensor * node = m_cgraph->nodes[node_idx];
1283 for (int i = node_idx; i < m_cgraph->n_nodes; i++) {
1284 ggml_tensor * other_node = m_cgraph->nodes[i];
1285 for (int j = 0; j < GGML_MAX_SRC; j++) {
1286 if (other_node->src[j] == node) {
1287 return true;
1288 }
1289 }
1290 }
1291 return false;
1292}
1293
1294void GgmlOvDecoder::compute_model_inputs() {
1295 m_model_inputs.clear();
1296 m_inputs.clear();
1297 for (int i = 0; i < m_cgraph->n_nodes; i++) {
1298 ggml_tensor * node = m_cgraph->nodes[i];
1299 // the node op is NONE means this node maybe as input of later nodes, we should add it to model inputs for this node.
1300 if (node->op == GGML_OP_NONE && node_is_used_as_src(i)) {
1301 std::string node_name = get_tensor_ov_name(m_cgraph, node);
1302 if (m_model_weights.find(node_name) == m_model_weights.end()) {
1303 m_inputs[node_name] = node;
1304 m_model_inputs[node_name] = {get_ov_type(node),
1305 get_graph_input_shape(node, nullptr, m_node_dynamic_dims[node])};
1306 }
1307 continue;
1308 }
1309 for (int i = 0; i < GGML_MAX_SRC; i++) {
1310 auto * src = node->src[i];
1311 if (src == nullptr) {
1312 continue;
1313 }
1314 std::string src_name = get_tensor_ov_name(m_cgraph, src);
1315 if (src->flags & GGML_TENSOR_FLAG_INPUT) {
1316 src_name = get_tensor_graph_input_ov_name(this, m_cgraph, src, node);
1317 }
1318 if (m_model_weights.find(src_name) != m_model_weights.end()) {
1319 continue;
1320 }
1321 // A view over a weight is served by the base tensor's Constant, never by a Parameter.
1322 if (src->view_src != nullptr &&
1323 m_model_weights.find(get_tensor_ov_name(m_cgraph, src->view_src)) != m_model_weights.end()) {
1324 continue;
1325 }
1326
1327 bool is_intermediate_node = false;
1328 for (const auto & node_info : m_node_info_list) {
1329 if (node_info.node == src) {
1330 is_intermediate_node = true;
1331 break;
1332 }
1333 }
1334 if (is_intermediate_node) {
1335 continue;
1336 }
1337 if (m_model_inputs.find(src_name) != m_model_inputs.end()) {
1338 continue;
1339 }
1340
1341 m_inputs[src_name] = src;
1342
1343 ggml_backend_buffer * buffer = src->buffer;
1344 // GGML_BACKEND_BUFFER_USAGE_ANY are kv caches
1345 if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_ANY) {
1346 if (auto it = std::find(m_model_params.kv_names.begin(), m_model_params.kv_names.end(), src_name);
1347 it == m_model_params.kv_names.end()) {
1348 m_model_params.kv_names.push_back(src_name);
1349 }
1350 }
1351 // Resolve nested VIEW nodes by following src[0] until the first non-VIEW tensor.
1352 while (src->op == GGML_OP_VIEW && src->src[0] != nullptr) {
1353 src = src->src[0];
1354 src_name = get_tensor_ov_name(m_cgraph, src);
1355 }
1356 m_inputs[src_name] = src;
1357 m_model_inputs[src_name] = {get_ov_type(src),
1358 get_graph_input_shape(node, src, m_node_dynamic_dims[src])};
1359 }
1360 }
1361}
1362
1363void GgmlOvDecoder::compute_model_outputs() {
1364 m_model_outputs.clear();
1365 m_model_output_names.clear();
1366 for (int node_n = 0; node_n < m_cgraph->n_nodes; node_n++) {
1367 auto * cur_node = m_cgraph->nodes[node_n];
1368 // if the node op is NONE means this node is not used at all, we can skip it directly without adding to model outputs.
1369 if (cur_node->op == GGML_OP_NONE || cur_node->op == GGML_OP_VIEW || cur_node->op == GGML_OP_RESHAPE) {
1370 continue;
1371 }
1372 if (::is_inplace_op(cur_node) && ggml_nbytes(cur_node) == 0) {
1373 continue;
1374 }
1375 auto cur_node_use_count = m_cgraph->use_counts[ggml_hash_find(&m_cgraph->visited_hash_set, cur_node)];
1376 if (cur_node_use_count == 0) {
1377 // The output of in-place ops is the view_src tensor, which is updated in place. We should use the view_src name as the output name to make sure it can be correctly matched with the later ops that use the view_src.
1378 if (cur_node != nullptr && ::is_inplace_op(cur_node) && ggml_nbytes(cur_node) > 0) {
1379 cur_node = cur_node->view_src;
1380 }
1381 } else {
1382 int input_use_count = 0;
1383 for (int i = 0; i < m_cgraph->n_nodes; i++) {
1384 ggml_tensor * node = m_cgraph->nodes[i];
1385 for (int j = 0; j < GGML_MAX_SRC; j++) {
1386 if (node->src[j] != NULL && node->src[j] == cur_node) {
1387 input_use_count++;
1388 }
1389 }
1390 }
1391 if (input_use_count == cur_node_use_count) {
1392 cur_node = nullptr;
1393 }
1394 }
1395 if (cur_node != nullptr) {
1396 std::string cur_node_name = get_tensor_ov_name(m_cgraph, cur_node);
1397 m_model_outputs[cur_node_name] = cur_node;
1398 m_model_output_names.insert(cur_node_name);
1399 }
1400 }
1401}
1402
1403const ggml_tensor * GgmlOvDecoder::get_tensor_used_op(const ggml_tensor * tensor) const {
1404 if (tensor == nullptr) {
1405 return nullptr;
1406 }
1407 for (int i = 0; i < m_cgraph->n_nodes; i++) {
1408 const auto * node = m_cgraph->nodes[i];
1409 for (int j = 0; j < GGML_MAX_SRC; j++) {
1410 if (node->src[j] == tensor) {
1411 return node;
1412 }
1413 }
1414 }
1415 return nullptr;
1416}
1417
1418const ggml_tensor * GgmlOvDecoder::get_tensor_from_name(const std::string & name) const {
1419 for (int i = 0; i < m_cgraph->n_nodes; i++) {
1420 const auto * node = m_cgraph->nodes[i];
1421 for (int j = 0; j < GGML_MAX_SRC; j++) {
1422 const auto * src = node->src[j];
1423 if (src == nullptr) {
1424 break;
1425 }
1426 if (get_tensor_ov_name(m_cgraph, src) == name) {
1427 return src;
1428 }
1429 }
1430 }
1431 return nullptr;
1432}
1433
1434std::map<std::string, std::string> GgmlOvDecoder::get_kv_param_res_names() const {
1435 std::map<std::string, std::string> kv_param_res_names;
1436 for (const auto & name : m_model_params.kv_names) {
1437 kv_param_res_names[name] = name;
1438 }
1439 return kv_param_res_names;
1440}
1441
1442// MUL_MAT_ID's src[0] is the [k, m, n_expert] expert-weight tensor. It is always a constant per-expert
1443// weight table -- never a computed activation -- regardless of whether the backend happened to mark its
1444// buffer as GGML_BACKEND_BUFFER_USAGE_WEIGHTS (test-backend-ops, for example, never sets that usage
1445// flag, unlike real inference). Without this, non-quantized (F16/F32/BF16) expert weights would fall
1446// through the check below as "not a weight", get decoded as a Parameter/activation instead of a
1447// Constant, and crash GatherMatmul's "only constant weights are supported" check.
1448static bool is_mul_mat_id_expert_weight(const ggml_tensor * node, int src_index) {
1449 return node->op == GGML_OP_MUL_MAT_ID && src_index == 0;
1450}
1451
1452std::map<std::string, std::shared_ptr<ov::Node>> GgmlOvDecoder::create_weight_nodes(ggml_cgraph * cgraph, bool naive) {
1453 std::map<std::string, std::shared_ptr<ov::Node>> model_weights;
1454 auto * nodes = cgraph->nodes;
1455 auto n_nodes = cgraph->n_nodes;
1456 for (int node_i = 0; node_i < n_nodes; node_i++) {
1457 auto * node = nodes[node_i];
1458 for (int i = 0; i < GGML_MAX_SRC; i++) {
1459 auto * src = node->src[i];
1460 if (src == nullptr) {
1461 continue;
1462 }
1463
1464 // A view over a weight is served by the base tensor's Constant.
1465 ggml_tensor * base = src->view_src ? src->view_src : src;
1466 std::string src_name = get_tensor_ov_name(cgraph, base);
1467 if (is_rope_freqs_weight(base, node)) {
1468 src_name = "rope_freqs.weight";
1469 }
1470 ggml_backend_buffer * buffer = base->buffer;
1471 if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS || ggml_is_quantized(base->type) ||
1472 is_mul_mat_id_expert_weight(node, i)) {
1473 if (model_weights.find(src_name) == model_weights.end()) {
1474 auto weight_node = create_weight_node(base, naive);
1475 weight_node->set_friendly_name(src_name);
1476 model_weights[src_name] = weight_node;
1477 }
1478 }
1479 }
1480 }
1481 return model_weights;
1482}
1483
1484// Process-lifetime cache for weight nodes built from NON-OpenVINO buffers (e.g. the
1485// token_embd.weight copy that lives in a CPU/mmap buffer and feeds GET_ROWS). Such
1486// tensors have no OV buffer context to own a cached extra, so without this they are
1487// re-extracted/re-requantized on every (re)compile — for token_embd that is a ~1-2 GB
1488// F32 dequant each time. Keyed by tensor->data, which is stable for the process and
1489// uniquely identifies the immutable weight bytes. OV-buffer weights keep using the
1490// per-tensor extra cache and never reach here.
1491static std::mutex g_nonov_weight_cache_mutex;
1492static std::unordered_map<const void *, std::shared_ptr<ov::Node>> g_nonov_weight_cache;
1493
1494std::set<std::string> GgmlOvDecoder::collect_weight_names(ggml_cgraph * cgraph) {
1495 // Mirrors the name-selection logic of create_weight_nodes() but builds no nodes,
1496 // so topology checks don't trigger weight extraction/requantization.
1497 std::set<std::string> names;
1498 for (int node_i = 0; node_i < cgraph->n_nodes; node_i++) {
1499 auto * node = cgraph->nodes[node_i];
1500 for (int i = 0; i < GGML_MAX_SRC; i++) {
1501 auto * src = node->src[i];
1502 if (src == nullptr) {
1503 continue;
1504 }
1505 const ggml_tensor * base = src->view_src ? src->view_src : src;
1506 std::string src_name(base->name);
1507 if (is_rope_freqs_weight(base, node)) {
1508 src_name = "rope_freqs.weight";
1509 }
1510 ggml_backend_buffer * buffer = base->buffer;
1511 if (buffer->usage == GGML_BACKEND_BUFFER_USAGE_WEIGHTS || ggml_is_quantized(base->type)) {
1512 names.insert(src_name);
1513 }
1514 }
1515 }
1516 return names;
1517}
1518
1519std::shared_ptr<ov::Node> GgmlOvDecoder::create_weight_node(ggml_tensor * tensor, bool naive) {
1520 const bool is_ov_buffer = ggml_backend_buffer_is_openvino(tensor->buffer);
1521
1522 // Check if we have a pre-built constant from the OpenVINO backend buffer
1523 // This is set during ggml_backend_openvino_buffer_set_tensor
1524 if (tensor->extra) {
1525 OPENVINO_ASSERT(is_ov_buffer, "Unsupported weight tensor: " + std::string(tensor->name) +
1526 " Possibly this is a cpu backend repacked quantized weights");
1527 // Cast to our extra base type and check the type
1528 auto * extra_base = static_cast<ggml_openvino_extra_base *>(tensor->extra);
1529
1530 if (extra_base->type == ggml_openvino_extra_base::Type::WEIGHT) {
1531 // F16/F32/BF16 weight with shared-memory constant
1532 auto * weight_extra = static_cast<ggml_openvino_weight_extra *>(tensor->extra);
1533 if (weight_extra->weight_node) {
1534 // GGML_LOG_DEBUG("%s: using pre-built weight node for %s\n", __func__, tensor->name);
1535 return weight_extra->weight_node;
1536 }
1537 } else if (extra_base->type == ggml_openvino_extra_base::Type::QUANTIZED_WEIGHT) {
1538 // Quantized weight with pre-extracted data
1539 auto * quant_extra = static_cast<ggml_openvino_quantized_weight_extra *>(tensor->extra);
1540 if (quant_extra->weight_node) {
1541 // GGML_LOG_DEBUG("%s: using pre-extracted quantized weight node for %s\n", __func__, tensor->name);
1542 return quant_extra->weight_node;
1543 }
1544 }
1545 }
1546
1547 // MUL_MAT_ID expert weights are 3D GGML tensors [k, m, n_expert].
1548 // Keep the full reversed 4D shape when materializing non-quantized constants,
1549 // otherwise the expert dimension is collapsed and later Gather/MatMul logic
1550 // only sees a single expert slice.
1551 if (!ggml_is_quantized(tensor->type) && (tensor->ne[2] > 1 || tensor->ne[3] > 1)) {
1552 auto weight_tensor = ov::Tensor(get_ov_type(tensor), get_shape(tensor), tensor->data);
1553 auto weight_node = std::make_shared<ov::op::v0::Constant>(weight_tensor);
1554 weight_node->set_friendly_name(tensor->name);
1555 return weight_node;
1556 }
1557
1558 // Non-OV-buffer weights (CPU/mmap, e.g. the GET_ROWS token_embd copy) have no buffer
1559 // context to cache an extra in, so memoize them here keyed by their (stable) data
1560 // pointer to avoid re-extracting on every recompile. Opt-in via
1561 // GGML_OPENVINO_REDUCE_COMPILE_MEM or GGML_OPENVINO_MEMORY_OPTIMIZE. Skip
1562 // for `naive` (test/naive path) since use_bias changes the produced node.
1563 const bool cacheable_nonov = ggml_openvino_reduce_compile_mem_enabled() && !is_ov_buffer &&
1564 !naive && tensor->data != nullptr;
1565 if (cacheable_nonov) {
1566 std::lock_guard<std::mutex> lock(g_nonov_weight_cache_mutex);
1567 auto it = g_nonov_weight_cache.find(tensor->data);
1568 if (it != g_nonov_weight_cache.end()) {
1569 return it->second;
1570 }
1571 }
1572
1573 // There are three cases where we need to create a new weight node:
1574 // 1. weights are in openvino_host_buffer. Weight loading to host buffer will not trigger backend_buffer_set_tensor
1575 // 2. weights are in cpu/cpu_mapped buffer. On token_embd.weight goes to case 1 or 2, depending on whether mmap or direct_io is used
1576 // 3. test-backend-ops. buffers in test-backend-ops does not set USAGE_WEIGHT so backend_buffer_set_tensor will not create weight node
1577
1578 // GGML_LOG_DEBUG("%s: creating new weight node for %s\n", __func__, tensor->name);
1579 static const std::set<ggml_type> weight_types = {GGML_TYPE_F32, GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0,
1580 GGML_TYPE_Q4_0, GGML_TYPE_Q4_1, GGML_TYPE_Q5_1, GGML_TYPE_Q4_K,
1581 GGML_TYPE_Q5_K, GGML_TYPE_Q6_K, GGML_TYPE_MXFP4};
1582 if (weight_types.find(tensor->type) == weight_types.end()) {
1583 throw std::runtime_error("Unexpected weight tensor type: " + std::string(tensor->name) + " with type " +
1584 ggml_type_name(tensor->type));
1585 }
1586
1587 OvWeight ov_weight;
1588 if (ggml_is_quantized(tensor->type)) {
1589 auto use_bias = naive;
1590 if (is_ov_buffer) {
1591 // For quantized weights, copy raw data to a temp buffer first because
1592 // process_weight_tensor reads from data and writes extracted results
1593 // (weights/scales/zp) to output_base_ptr — they would overlap if both
1594 // point to tensor->data.
1595 size_t raw_size = ggml_nbytes(tensor);
1596 std::vector<uint8_t> tmp(raw_size);
1597 memcpy(tmp.data(), tensor->data, raw_size);
1598 ov_weight = process_weight_tensor(tensor, tmp.data(), tensor->data, use_bias);
1599 } else {
1600 ov_weight = process_weight_tensor(tensor, tensor->data, nullptr, use_bias);
1601 }
1602 } else {
1603 // For non-quantized weights (F16/F32/BF16), data is already in tensor->data.
1604 // process_weight_tensor will create an ov::Tensor wrapping tensor->data directly.
1605 ov_weight = process_weight_tensor(tensor, tensor->data, tensor->data);
1606 }
1607
1608 ov_weight.weight_node->set_friendly_name(tensor->name);
1609 if (!is_ov_buffer) {
1610 if (cacheable_nonov) {
1611 std::lock_guard<std::mutex> lock(g_nonov_weight_cache_mutex);
1612 // Another thread may have inserted concurrently; keep the first.
1613 auto [it, inserted] = g_nonov_weight_cache.emplace(tensor->data, ov_weight.weight_node);
1614 return it->second;
1615 }
1616 return ov_weight.weight_node;
1617 }
1618
1619 ggml_openvino_extra_base * extra;
1620 if (ov_weight.is_quantized()) {
1621 extra = new ggml_openvino_quantized_weight_extra(std::move(ov_weight.weights), std::move(ov_weight.scales),
1622 std::move(ov_weight.zp), ov_weight.weight_node);
1623 } else {
1624 extra = new ggml_openvino_weight_extra(std::move(ov_weight.weights), ov_weight.weight_node);
1625 }
1626 ggml_openvino_buffer_register_extra(tensor, extra);
1627
1628 return ov_weight.weight_node;
1629}
1630
1631void GgmlOvDecoder::dump_cgraph(const ggml_cgraph * cgraph, std::string & filename) {
1632 std::ofstream file(filename);
1633 if (!file.is_open()) {
1634 std::cerr << "Failed to open file" << '\n';
1635 return;
1636 }
1637
1638 file << "=== GRAPH ===\n";
1639
1640 // clang-format off
1641 file << "n_nodes = " << cgraph->n_nodes << "\n";
1642 file << " " << std::setw(3) << "nodes"
1643 << std::setw(15) << "shape"
1644 << std::setw(20) << "op"
1645 << std::setw(20) << "name"
1646 << std::setw(3) << " "
1647 << std::setw(62) << "stride"
1648 << std::setw(20) << "buffer_type"
1649 << "\n";
1650 for (int i = 0; i < cgraph->n_nodes; i++) {
1651 ggml_tensor * node = cgraph->nodes[i];
1652
1653 // Get buffer type name
1654 const char * buf_name = "none";
1655 ggml_backend_buffer_t buf = node->view_src ? node->view_src->buffer : node->buffer;
1656 if (buf) {
1657 buf_name = ggml_backend_buffer_name(buf);
1658 }
1659
1660 file << " - " << std::setw(3) << i << ": [ "
1661 << std::setw(5) << node->ne[0] << ", "
1662 << std::setw(5) << node->ne[1] << ", "
1663 << std::setw(5) << node->ne[2] << ", "
1664 << std::setw(5) << node->ne[3] << "] "
1665 << std::left << std::setw(20) << ggml_op_name(node->op) << std::right << " "
1666 << std::left << std::setw(45) << node->name << std::right
1667 << std::setw(2) << "[ "
1668 << std::setw(0) << node->nb[0] << ", "
1669 << std::setw(5) << node->nb[1] << ", "
1670 << std::setw(5) << node->nb[2] << ", "
1671 << std::setw(5) << node->nb[3] << "] "
1672 << std::right << std::setw(15) << buf_name << std::right
1673 << "\n";
1674
1675 for (int i = 0; i < GGML_MAX_SRC; i++) {
1676 if (auto* src = node->src[i]) {
1677 // Get buffer type name for source
1678 const char * src_buf_name = "none";
1679 ggml_backend_buffer_t src_buf = src->view_src ? src->view_src->buffer : src->buffer;
1680 if (src_buf) {
1681 src_buf_name = ggml_backend_buffer_name(src_buf);
1682 }
1683
1684 file << std::setw(10) << " [ "
1685 << std::setw(5) << src->ne[0] << ", "
1686 << std::setw(5) << src->ne[1] << ", "
1687 << std::setw(5) << src->ne[2] << ", "
1688 << std::setw(5) << src->ne[3] << "] "
1689 << std::setw(12)
1690 << i << ": " << std::left << std::setw(12) << ggml_op_name(src->op) << std::right;
1691 file << std::left << std::setw(30) << src->name << std::right
1692 << std::setw(16) << "[ "
1693 << std::setw(0) << src->nb[0] << ", "
1694 << std::setw(5) << src->nb[1] << ", "
1695 << std::setw(5) << src->nb[2] << ", "
1696 << std::setw(5) << src->nb[3] << "] "
1697 << std::right << std::setw(15) << src_buf_name << std::right
1698 << "\n";
1699 }
1700 }
1701 }
1702
1703 file << "n_leafs = " << cgraph->n_leafs << "\n";
1704 for (int i = 0; i < cgraph->n_leafs; i++) {
1705 ggml_tensor * node = cgraph->leafs[i];
1706
1707 // Get buffer type name for leaf
1708 const char * leaf_buf_name = "none";
1709 ggml_backend_buffer_t leaf_buf = node->view_src ? node->view_src->buffer : node->buffer;
1710 if (leaf_buf) {
1711 leaf_buf_name = ggml_backend_buffer_name(leaf_buf);
1712 }
1713
1714 file << " - " << std::setw(3) << i << ": [ "
1715 << std::setw(5) << node->ne[0] << ", "
1716 << std::setw(5) << node->ne[1] << "] "
1717 << std::setw(8) << ggml_op_name(node->op) << " "
1718 << std::setw(16) << ggml_get_name(node)
1719 << std::setw(20) << leaf_buf_name << "\n";
1720 }
1721 // clang-format on
1722 file << "========================================\n";
1723
1724 file.close();
1725}
1726
1727void print_tensor_address_map(const ggml_cgraph * cgraph) {
1728 std::map<void *, std::vector<std::string>> address_map;
1729 for (int node_n = 0; node_n < cgraph->n_nodes; node_n++) {
1730 auto * node = cgraph->nodes[node_n];
1731 if (node->data) {
1732 auto it = address_map.find(node->data);
1733 if (it == address_map.end()) {
1734 address_map[node->data] = std::vector<std::string>();
1735 }
1736 address_map[node->data].push_back(node->name);
1737 }
1738 }
1739 for (const auto & pair : address_map) {
1740 std::cout << "Address: " << pair.first << '\n';
1741 for (const auto & name : pair.second) {
1742 std::cout << name << " ; ";
1743 }
1744 std::cout << "\n\n";
1745 }
1746}
1747
1748ov::Shape GgmlOvDecoder::get_shape(const ggml_tensor * tensor) {
1749 std::vector<size_t> shape;
1750 for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
1751 shape.push_back(static_cast<size_t>(tensor->ne[i]));
1752 }
1753 return shape;
1754}
1755
1756std::vector<size_t> GgmlOvDecoder::get_stride(const ggml_tensor * tensor) {
1757 std::vector<size_t> stride;
1758 for (int i = GGML_MAX_DIMS - 1; i >= 0; --i) {
1759 stride.push_back(static_cast<size_t>(tensor->nb[i]));
1760 }
1761 return stride;
1762}
1763
1764ov::element::Type GgmlOvDecoder::get_ov_type(const ggml_tensor * tensor) {
1765 switch (tensor->type) {
1766 case GGML_TYPE_F64:
1767 return ov::element::f64;
1768 case GGML_TYPE_F32:
1769 return ov::element::f32;
1770 case GGML_TYPE_F16:
1771 return ov::element::f16;
1772 case GGML_TYPE_BF16:
1773 return ov::element::bf16;
1774 case GGML_TYPE_I8:
1775 return ov::element::i8;
1776 case GGML_TYPE_I16:
1777 return ov::element::i16;
1778 case GGML_TYPE_I32:
1779 return ov::element::i32;
1780 case GGML_TYPE_I64:
1781 return ov::element::i64;
1782 default:
1783 return ov::element::dynamic;
1784 }
1785}
1786
1787ov::PartialShape GgmlOvDecoder::get_input_shape(int node_idx, const std::string & name) const {
1788 return ov::PartialShape(get_shape(m_node_info_list[node_idx].node_inputs.at(name)));
1789}
1790
1791std::vector<size_t> GgmlOvDecoder::get_input_stride(int node_idx, const std::string & name) const {
1792 return get_stride(m_node_info_list[node_idx].node_inputs.at(name));
1793}
1794
1795size_t GgmlOvDecoder::get_view_input_size(int node_idx, const std::string & name) const {
1796 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1797 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1798 return it->second.size();
1799 }
1800 return 0;
1801}
1802
1803size_t GgmlOvDecoder::get_view_input_offset(int node_idx, const std::string & name, size_t view_index) const {
1804 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1805 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1806 if (view_index < it->second.size()) {
1807 return it->second[view_index].second->view_offs;
1808 }
1809 }
1810 return 0;
1811}
1812
1813size_t GgmlOvDecoder::get_view_input_src_offset(int node_idx, const std::string & name, size_t view_index) const {
1814 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1815 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1816 if (view_index < it->second.size()) {
1817 auto * view_tensor = it->second[view_index].second;
1818 if (view_tensor && view_tensor->src[0]) {
1819 return view_tensor->src[0]->view_offs;
1820 }
1821 }
1822 }
1823 return 0;
1824}
1825
1826std::vector<size_t> GgmlOvDecoder::get_view_input_stride(int node_idx,
1827 const std::string & name,
1828 size_t view_index) const {
1829 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1830 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1831 if (view_index < it->second.size()) {
1832 return get_stride(it->second[view_index].second);
1833 }
1834 }
1835 return {};
1836}
1837
1838std::vector<size_t> GgmlOvDecoder::get_view_input_src_stride(int node_idx,
1839 const std::string & name,
1840 size_t view_index) const {
1841 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1842 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1843 if (view_index < it->second.size()) {
1844 auto * view_tensor = it->second[view_index].second;
1845 if (view_tensor && view_tensor->src[0]) {
1846 return get_stride(view_tensor->src[0]);
1847 }
1848 }
1849 }
1850 return {};
1851}
1852
1853ov::Shape GgmlOvDecoder::get_view_input_ggml_shape(int node_idx, const std::string & name, size_t view_index) const {
1854 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1855 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1856 if (view_index < it->second.size()) {
1857 return get_shape(it->second[view_index].second);
1858 }
1859 }
1860 return {};
1861}
1862
1863ov::Shape GgmlOvDecoder::get_view_input_src_ggml_shape(int node_idx,
1864 const std::string & name,
1865 size_t view_index) const {
1866 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1867 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1868 if (view_index < it->second.size()) {
1869 auto * view_tensor = it->second[view_index].second;
1870 if (view_tensor && view_tensor->src[0]) {
1871 return get_shape(view_tensor->src[0]);
1872 }
1873 }
1874 }
1875 return {};
1876}
1877
1878ov::PartialShape GgmlOvDecoder::get_view_input_ov_shape(int node_idx,
1879 const std::string & name,
1880 size_t view_index) const {
1881 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1882 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1883 if (view_index < it->second.size()) {
1884 auto * tensor = it->second[view_index].second;
1885 ov::PartialShape shape = ov::PartialShape{get_shape(tensor)};
1886
1887 // Check if this tensor has a dynamic dimension
1888 auto dynamic_it = m_node_dynamic_dims.find(tensor);
1889 if (dynamic_it != m_node_dynamic_dims.end() && dynamic_it->second != -1) {
1890 int dynamic_dim_index = dynamic_it->second;
1891 // GGML uses reverse indexing, so convert to OpenVINO indexing
1892 shape[3 - dynamic_dim_index] = m_is_static ? get_static_n_tokens() : -1;
1893 }
1894
1895 return shape;
1896 }
1897 }
1898 return {};
1899}
1900
1901ov::PartialShape GgmlOvDecoder::get_view_input_src_ov_shape(int node_idx,
1902 const std::string & name,
1903 size_t view_index) const {
1904 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1905 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1906 if (view_index < it->second.size()) {
1907 auto * view_tensor = it->second[view_index].second;
1908 if (view_tensor && view_tensor->src[0]) {
1909 auto * src_tensor = view_tensor->src[0];
1910 ov::PartialShape shape = ov::PartialShape{get_shape(src_tensor)};
1911
1912 // Check if this tensor has a dynamic dimension
1913 auto dynamic_it = m_node_dynamic_dims.find(src_tensor);
1914 if (dynamic_it != m_node_dynamic_dims.end() && dynamic_it->second != -1) {
1915 int dynamic_dim_index = dynamic_it->second;
1916 // GGML uses reverse indexing, so convert to OpenVINO indexing
1917 shape[3 - dynamic_dim_index] = m_is_static ? get_static_n_tokens() : -1;
1918 }
1919
1920 return shape;
1921 }
1922 }
1923 }
1924 return {};
1925}
1926
1927std::string GgmlOvDecoder::get_view_input_name(int node_idx, const std::string & name, size_t view_index) const {
1928 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1929 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1930 if (view_index < it->second.size()) {
1931 return it->second[view_index].first;
1932 }
1933 }
1934 return "";
1935}
1936
1937std::string GgmlOvDecoder::get_view_input_src_name(int node_idx, const std::string & name, size_t view_index) const {
1938 auto it = m_node_info_list[node_idx].node_inputs_views.find(name);
1939 if (it != m_node_info_list[node_idx].node_inputs_views.end()) {
1940 if (view_index < it->second.size()) {
1941 auto * view_tensor = it->second[view_index].second;
1942 if (view_tensor && view_tensor->src[0]) {
1943 return get_tensor_ov_name(m_cgraph, view_tensor->src[0]);
1944 }
1945 }
1946 }
1947 return "";
1948}
1949
1950ov::element::Type GgmlOvDecoder::get_input_type(int node_idx, const std::string & name) const {
1951 return get_ov_type(m_node_info_list[node_idx].node_inputs.at(name));
1952}
1953
1954size_t GgmlOvDecoder::get_input_size() const {
1955 return m_model_inputs.size();
1956}
1957
1958size_t GgmlOvDecoder::get_input_size(int node_idx) const {
1959 return m_node_info_list[node_idx].node_inputs_names.size();
1960}
1961
1962std::vector<std::string> GgmlOvDecoder::get_input_names(int node_idx) const {
1963 return m_node_info_list[node_idx].node_inputs_names;
1964}
1965
1966ov::PartialShape GgmlOvDecoder::get_output_shape(int node_idx) const {
1967 auto * ggml_tensor = m_node_info_list[node_idx].node;
1968 return ov::PartialShape(get_shape(ggml_tensor));
1969}
1970
1971ov::element::Type GgmlOvDecoder::get_output_type(const int node_idx) const {
1972 return get_ov_type(m_node_info_list[node_idx].node);
1973}
1974
1975std::vector<size_t> GgmlOvDecoder::get_output_stride(int node_idx) const {
1976 auto * ggml_tensor = m_node_info_list[node_idx].node;
1977 return get_stride(ggml_tensor);
1978}
1979
1980std::vector<std::string> GgmlOvDecoder::get_output_names(int node_idx) const {
1981 auto * node = m_node_info_list[node_idx].node;
1982 if (node->op == GGML_OP_GATED_DELTA_NET && !m_model_params.has_rs_rollback) {
1983 std::string attn_name;
1984 std::string state_name;
1985 for (int i = node_idx + 1; i < m_cgraph->n_nodes; i++) {
1986 auto * consumer = m_cgraph->nodes[i];
1987 if (consumer->op != GGML_OP_VIEW || consumer->src[0] != node) {
1988 continue;
1989 }
1990 // GGML packs [attention | state]. The attention VIEW starts at offset 0 and the
1991 // state VIEW starts after the token-dependent attention segment.
1992 auto & name = consumer->view_offs == 0 ? attn_name : state_name;
1993 if (!name.empty()) {
1994 return {m_node_info_list[node_idx].node_name};
1995 }
1996 name = get_tensor_ov_name(m_cgraph, consumer);
1997 }
1998 if (!attn_name.empty() && !state_name.empty()) {
1999 return {attn_name, state_name};
2000 }
2001 }
2002 return {m_node_info_list[node_idx].node_name};
2003}
2004
2005std::string GgmlOvDecoder::get_inplace_op_src(int node_idx) const {
2006 auto * node = m_node_info_list[node_idx].node;
2007 if (!::is_inplace_op(node) || node->view_src == nullptr || ggml_nbytes(node) == 0) {
2008 return "";
2009 }
2010 const int op_case = m_node_info_list[node_idx].node_op_case;
2011 if (node->op == GGML_OP_CPY && (op_case == 1 || op_case == 2 || op_case == 3) &&
2012 m_compute_params.s_copy_active_slot_len == -1) {
2013 return "";
2014 }
2015 return get_tensor_ov_name(m_cgraph, node->view_src);
2016}
2017
2018bool GgmlOvDecoder::is_view_like_alias_of(int node_idx, const std::string & view_src_name) const {
2019 auto * node = m_node_info_list[node_idx].node;
2020 if (node->view_src == nullptr || get_tensor_ov_name(m_cgraph, node->view_src) != view_src_name) {
2021 return false;
2022 }
2023 return node->op == GGML_OP_RESHAPE || node->op == GGML_OP_VIEW;
2024}
2025
2026const std::string & GgmlOvDecoder::get_op_name() const {
2027 static const std::string unknown_name = "UNKNOWN_OP_NAME";
2028 return unknown_name;
2029}
2030
2031int32_t GgmlOvDecoder::get_op_dynamic_dim(int node_idx) const {
2032 auto it = m_node_dynamic_dims.find(m_node_info_list[node_idx].node);
2033 if (it == m_node_dynamic_dims.end()) {
2034 return -1;
2035 }
2036 return it->second;
2037}
2038
2039const std::string & GgmlOvDecoder::get_op_name(int node_idx) const {
2040 return m_node_info_list[node_idx].node_name;
2041}
2042
2043int32_t * GgmlOvDecoder::get_input_op_params(int node_idx, const std::string & name) const {
2044 return m_node_info_list[node_idx].node_inputs.at(name)->op_params;
2045}
2046
2047int32_t * GgmlOvDecoder::get_output_op_params(int node_idx) const {
2048 return m_node_info_list[node_idx].node->op_params;
2049}
2050
2051size_t GgmlOvDecoder::get_output_op_offset(int node_idx) const {
2052 return m_node_info_list[node_idx].node->view_offs;
2053}
2054
2055void GgmlOvDecoder::visit_subgraph(std::function<void(std::shared_ptr<GgmlDecoder>, int node_idx)> node_visitor) const {
2056 for (int node_idx = 0; node_idx < m_cgraph->n_nodes; node_idx++) {
2057 if (m_cgraph->nodes[node_idx]->op == GGML_OP_NONE) {
2058 continue;
2059 }
2060 node_visitor(std::make_shared<GgmlOvDecoder>(*this), node_idx);
2061 }
2062}
2063
2064std::string GgmlOvDecoder::compute_op_type(const ggml_tensor * node) {
2065 switch (node->op) {
2066 case GGML_OP_UNARY:
2067 return std::string("GGML_UNARY_OP_") + ggml_unary_op_name(ggml_get_unary_op(node));
2068 case GGML_OP_GLU:
2069 return std::string("GGML_GLU_OP_") + ggml_glu_op_name(ggml_get_glu_op(node));
2070 default:
2071 return std::string("GGML_OP_") + ggml_op_name(node->op);
2072 }
2073}
2074
2075const std::string & GgmlOvDecoder::get_op_type(int node_idx) const {
2076 return m_node_info_list[node_idx].node_op_type;
2077}
2078
2079const std::string & GgmlOvDecoder::get_op_type() const {
2080 static const std::string unknown_op = "UNKNOWN_GGML_OP";
2081 return unknown_op;
2082}
2083
2084void GgmlOvDecoder::compute_node_dynamic_dims() {
2085 auto visit_node = [&](auto && self, ggml_tensor * node) -> void {
2086 if (!node) {
2087 return;
2088 }
2089
2090 if (node->op == GGML_OP_CPY) {
2091 m_node_dynamic_dims[node] = -1;
2092 }
2093
2094 if (m_node_dynamic_dims.count(node)) {
2095 return;
2096 }
2097 for (int i = 0; i < GGML_MAX_SRC; i++) {
2098 ggml_tensor * src = node->src[i];
2099 if (src == nullptr) {
2100 continue;
2101 }
2102 struct ggml_tensor * root_src = nullptr;
2103 // if (src->org_src) {
2104 // root_src = src->org_src;
2105 // }
2106 if (root_src) {
2107 if (is_inp_tok(root_src, node) || is_inp_pos(root_src, node) || is_output_idx(root_src, node)) {
2108 m_node_dynamic_dims[root_src] = 0;
2109 m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
2110 continue;
2111 }
2112 self(self, root_src);
2113 m_node_dynamic_dims[src] = m_node_dynamic_dims[root_src];
2114 } else {
2115 if (is_inp_tok(src, node) || is_inp_pos(src, node) || is_output_idx(src, node)) {
2116 m_node_dynamic_dims[src] = 0;
2117 continue;
2118 }
2119 if (is_inp_scale_rows(src, node)) {
2120 m_node_dynamic_dims[src] = 1;
2121 continue;
2122 }
2123 if (node->op == GGML_OP_VIEW && src->op == GGML_OP_NONE && !is_stateful() && !m_model_is_splitted) {
2124 m_node_dynamic_dims[src] = 1;
2125 continue;
2126 }
2127 self(self, src);
2128 }
2129 }
2130 switch (node->op) {
2131 case GGML_OP_NONE:
2132 m_node_dynamic_dims[node] = -1;
2133 break;
2134 case GGML_OP_GET_ROWS:
2135 m_node_dynamic_dims[node] = -1;
2136 if (m_node_dynamic_dims[node->src[1]] != -1) {
2137 auto dynamic_dim_idx = m_node_dynamic_dims[node->src[1]];
2138 if (dynamic_dim_idx == 0) {
2139 m_node_dynamic_dims[node] = 1;
2140 } else {
2141 auto dynamic_dim_stride = node->src[1]->nb[dynamic_dim_idx] / ggml_type_size(node->src[1]->type) *
2142 ggml_type_size(node->src[0]->type);
2143 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2144 if (dynamic_dim_stride == node->src[0]->nb[i]) {
2145 m_node_dynamic_dims[node] = i;
2146 break;
2147 }
2148 }
2149 }
2150 // OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
2151 // "Dynamic dim value mismatch for node: " + std::string(node->name) +
2152 // " and its src[1]: " + std::string(node->src[1]->name));
2153 }
2154 break;
2155 case GGML_OP_MUL:
2156 case GGML_OP_MUL_MAT:
2157 m_node_dynamic_dims[node] = -1;
2158 if (m_node_dynamic_dims[node->src[0]] != -1) {
2159 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
2160 }
2161 if (m_node_dynamic_dims[node->src[1]] != -1) {
2162 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[1]];
2163 }
2164 break;
2165 case GGML_OP_PERMUTE:
2166 m_node_dynamic_dims[node] = -1;
2167 if (m_node_dynamic_dims[node->src[0]] != -1) {
2168 auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
2169 // auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
2170 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2171 if (node->op_params[i] == dynamic_dim_idx) {
2172 m_node_dynamic_dims[node] = i;
2173 break;
2174 }
2175 }
2176 // OPENVINO_ASSERT(dynamic_dim_value == node->ne[m_node_dynamic_dims[node]],
2177 // "Dynamic dim value mismatch for node: " + std::string(node->name) +
2178 // " and its src[0]: " + std::string(node->src[0]->name));
2179 }
2180 break;
2181 case GGML_OP_VIEW: {
2182 // Use stride-based matching: the stride of a VIEW dimension directly
2183 // encodes which source dimension it indexes into, so it uniquely
2184 // identifies the dynamic dim even when two dims share the same size.
2185 m_node_dynamic_dims[node] = -1;
2186 if (m_node_dynamic_dims[node->src[0]] != -1) {
2187 if (node->src[0]->op == GGML_OP_NONE) {
2188 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
2189 break;
2190 }
2191 auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
2192 auto dynamic_dim_value = node->src[0]->ne[dynamic_dim_idx];
2193 auto dynamic_dim_stride =
2194 node->src[0]->nb[dynamic_dim_idx] / ggml_type_size(node->src[0]->type) * ggml_type_size(node->type);
2195 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2196 if (node->nb[i] == dynamic_dim_stride) {
2197 m_node_dynamic_dims[node] = i;
2198 break;
2199 }
2200 }
2201 if (m_node_dynamic_dims[node] != -1 && dynamic_dim_value != node->ne[m_node_dynamic_dims[node]]) {
2202 m_node_dynamic_dims[node] = -1;
2203 // an empty view, e.g. the extra states of a single-slot recurrent cache, always mismatches
2204 if (ggml_nelements(node) > 0) {
2205 GGML_LOG_WARN("ggml-openvino: dynamic dim value mismatch for VIEW node '%s', src[0]: '%s'\n",
2206 node->name, node->src[0]->name);
2207 }
2208 }
2209 }
2210 break;
2211 }
2212 case GGML_OP_TRANSPOSE:
2213 case GGML_OP_RESHAPE: {
2214 if (is_same_shape(node->src[0], node)) {
2215 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
2216 break;
2217 }
2218 // RESHAPE requires src[0] to be contiguous, so both src and result
2219 // have standard compact strides: nb[i] = type_size * prod(ne[0..i-1]).
2220 // Match src->nb[dynamic_dim] against result->nb[i] to find the output
2221 // dimension whose flat-memory boundary aligns with the source dynamic
2222 // boundary. This is unambiguous (result strides are strictly monotone)
2223 // and handles merged-lower-dim cases that ne-value matching misses.
2224 m_node_dynamic_dims[node] = -1;
2225 if (m_node_dynamic_dims[node->src[0]] != -1) {
2226 auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
2227 auto dynamic_dim_stride = node->src[0]->nb[dynamic_dim_idx];
2228 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2229 if (node->nb[i] == dynamic_dim_stride && node->ne[i] == node->src[0]->ne[dynamic_dim_idx]) {
2230 m_node_dynamic_dims[node] = i;
2231 break;
2232 }
2233 }
2234 if (m_node_dynamic_dims[node] == -1) {
2235 GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for RESHAPE node '%s'\n", node->name);
2236 }
2237 }
2238 break;
2239 }
2240 case GGML_OP_FLASH_ATTN_EXT: {
2241 // Output shape is hard-coded in ggml_flash_attn_ext as:
2242 // ne = { v->ne[0], q->ne[2], q->ne[1], q->ne[3] }
2243 // i.e. output dim 0 <- v dim 0 (head_size, static)
2244 // output dim 1 <- q dim 2 (n_heads, static)
2245 // output dim 2 <- q dim 1 (n_tokens, potentially dynamic)
2246 // output dim 3 <- q dim 3 (batch, static)
2247 // Using the fixed q-dim -> output-dim mapping table.
2248 // q is src[0]; the mapping from q's dynamic dim to the output dim is:
2249 // q dim 1 -> output dim 2
2250 // q dim 2 -> output dim 1
2251 // q dim 3 -> output dim 3
2252 // q dim 0 -> output dim 0 (head_size axis, unlikely to be dynamic)
2253 constexpr int q_to_out[GGML_MAX_DIMS] = {0, 2, 1, 3};
2254 m_node_dynamic_dims[node] = -1;
2255 if (m_node_dynamic_dims[node->src[0]] != -1) {
2256 auto q_dynamic_dim = m_node_dynamic_dims[node->src[0]];
2257 m_node_dynamic_dims[node] = q_to_out[q_dynamic_dim];
2258 }
2259 break;
2260 }
2261 case GGML_OP_CONT:
2262 m_node_dynamic_dims[node] = -1;
2263 if (m_node_dynamic_dims[node->src[0]] != -1) {
2264 auto dynamic_dim_idx = m_node_dynamic_dims[node->src[0]];
2265 if (ggml_are_same_shape(node, node->src[0])) {
2266 m_node_dynamic_dims[node] = dynamic_dim_idx;
2267 } else {
2268 size_t src_logical_nb[GGML_MAX_DIMS];
2269 src_logical_nb[0] = ggml_type_size(node->src[0]->type);
2270 src_logical_nb[1] = src_logical_nb[0] * (node->src[0]->ne[0] / ggml_blck_size(node->src[0]->type));
2271 for (int i = 2; i < GGML_MAX_DIMS; i++) {
2272 src_logical_nb[i] = src_logical_nb[i - 1] * node->src[0]->ne[i - 1];
2273 }
2274
2275 auto dynamic_dim_stride = src_logical_nb[dynamic_dim_idx] / ggml_type_size(node->src[0]->type) *
2276 ggml_type_size(node->type);
2277 int matched_dim_count = 0;
2278 int first_matched_dim = -1;
2279 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2280 if (node->nb[i] == dynamic_dim_stride && node->ne[i] == node->src[0]->ne[dynamic_dim_idx]) {
2281 if (first_matched_dim == -1) {
2282 first_matched_dim = i;
2283 }
2284 m_node_dynamic_dims[node] = i;
2285 matched_dim_count++;
2286 }
2287 }
2288 if (matched_dim_count > 1 && node->src[0]->ne[dynamic_dim_idx] == 1) {
2289 // Single-token capture: every trailing dim is size 1 with the same stride, so
2290 // the match is ambiguous. The lowest index is the real axis; the rest are
2291 // ggml's size-1 padding. Bailing out here would bake the captured token count
2292 // into the static prefill model, which then runs with a different one.
2293 m_node_dynamic_dims[node] = first_matched_dim;
2294 } else if (matched_dim_count != 1) {
2295 m_node_dynamic_dims[node] = -1;
2296 GGML_LOG_WARN("ggml-openvino: cannot determine dynamic dim for CONT node '%s', src[0]: '%s'\n",
2297 node->name, node->src[0]->name);
2298 }
2299 }
2300 }
2301 break;
2302 case GGML_OP_CONCAT:
2303 for (int i = 0; i < GGML_MAX_DIMS; i++) {
2304 if (node->src[0]->ne[i] != node->ne[i]) {
2305 m_node_dynamic_dims[node] = i;
2306 break;
2307 }
2308 }
2309 break;
2310 case GGML_OP_SSM_CONV:
2311 case GGML_OP_GATED_DELTA_NET:
2312 m_node_dynamic_dims[node] = 1;
2313 break;
2314 case GGML_OP_RMS_NORM:
2315 case GGML_OP_L2_NORM:
2316 case GGML_OP_NORM:
2317 case GGML_OP_ADD:
2318 case GGML_OP_SUB:
2319 case GGML_OP_GLU:
2320 case GGML_OP_ROPE:
2321 case GGML_OP_SCALE:
2322 case GGML_OP_SOFT_MAX:
2323 case GGML_OP_ARGSORT:
2324 case GGML_OP_ADD_ID:
2325 case GGML_OP_UNARY:
2326 case GGML_OP_CUMSUM:
2327 case GGML_OP_FILL:
2328 case GGML_OP_SET:
2329 case GGML_OP_DIAG:
2330 case GGML_OP_TRI:
2331 case GGML_OP_REPEAT:
2332 case GGML_OP_DUP:
2333 // Shape-preserving elementwise ops: the dynamic dim is unchanged from src[0].
2334 // DIV/CLAMP are used in the MoE routing-weight normalization
2335 // (sum_rows -> clamp -> div). If they are left untracked here the dynamic
2336 // (token) dim is lost there, the captured prefill token count gets baked into
2337 // the downstream reshapes, and every decoder layer after layer 0 turns static
2338 // (which then triggers the GPU in-place-concat KV-cache corruption).
2339 case GGML_OP_DIV:
2340 case GGML_OP_CLAMP:
2341 case GGML_OP_PAD:
2342 case GGML_OP_UPSCALE:
2343 case GGML_OP_SIN:
2344 case GGML_OP_COS:
2345 case GGML_OP_LOG:
2346 case GGML_OP_ROLL:
2347 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[0]];
2348 break;
2349 case GGML_OP_SUM_ROWS:
2350 // SUM_ROWS reduces ggml axis 0 to size 1 and preserves all other axes, so the
2351 // dynamic dim is preserved unless it was axis 0 (then it is summed away).
2352 m_node_dynamic_dims[node] =
2353 (m_node_dynamic_dims[node->src[0]] == 0) ? -1 : m_node_dynamic_dims[node->src[0]];
2354 break;
2355 case GGML_OP_MUL_MAT_ID:
2356 case GGML_OP_SOLVE_TRI:
2357 m_node_dynamic_dims[node] = m_node_dynamic_dims[node->src[1]];
2358 break;
2359 case GGML_OP_CPY:
2360 case GGML_OP_SET_ROWS:
2361 case GGML_OP_SUM:
2362 case GGML_OP_MEAN:
2363 m_node_dynamic_dims[node] = -1;
2364 break;
2365 case GGML_OP_IM2COL: {
2366 m_node_dynamic_dims[node] = -1;
2367 if (m_node_dynamic_dims[node->src[1]] != -1) {
2368 const bool is_2D = node->op_params[6] == 1;
2369 const int src_dyn = m_node_dynamic_dims[node->src[1]];
2370 if (is_2D) {
2371 if (src_dyn == 0) {
2372 m_node_dynamic_dims[node] = 1; // IW -> OW
2373 } else if (src_dyn == 1) {
2374 m_node_dynamic_dims[node] = 2; // IH -> OH
2375 } else if (src_dyn == 3) {
2376 m_node_dynamic_dims[node] = 3; // N -> N
2377 }
2378 } else {
2379 if (src_dyn == 0) {
2380 m_node_dynamic_dims[node] = 1; // IW -> OW
2381 } else if (src_dyn == 2) {
2382 m_node_dynamic_dims[node] = 2; // N -> N (1D: b->ne[2] is the batch/channel dim)
2383 }
2384 }
2385 if (m_node_dynamic_dims[node] != -1) {
2386 OPENVINO_ASSERT(node->src[1]->ne[src_dyn] == node->ne[m_node_dynamic_dims[node]],
2387 "Dynamic dim value mismatch for IM2COL node: " + std::string(node->name) +
2388 " and its src[1]: " + std::string(node->src[1]->name));
2389 }
2390 }
2391 break;
2392 }
2393 case GGML_OP_IM2COL_3D: {
2394 m_node_dynamic_dims[node] = -1;
2395 if (m_node_dynamic_dims[node->src[1]] != -1) {
2396 const int src_dyn = m_node_dynamic_dims[node->src[1]];
2397 if (src_dyn == 0) {
2398 m_node_dynamic_dims[node] = 1; // IW -> OW
2399 } else if (src_dyn == 1) {
2400 m_node_dynamic_dims[node] = 2; // IH -> OH
2401 } else if (src_dyn == 3) {
2402 m_node_dynamic_dims[node] = 3; // N -> N
2403 }
2404 if (m_node_dynamic_dims[node] != -1) {
2405 OPENVINO_ASSERT(node->src[1]->ne[src_dyn] == node->ne[m_node_dynamic_dims[node]],
2406 "Dynamic dim value mismatch for IM2COL_3D node: " + std::string(node->name) +
2407 " and its src[1]: " + std::string(node->src[1]->name));
2408 }
2409 }
2410 break;
2411 }
2412 default:
2413 GGML_LOG_DEBUG("ggml-openvino: compute_node_dynamic_dims: unhandled op %s for node '%s'\n",
2414 ggml_op_name(node->op), node->name);
2415 break;
2416 }
2417 };
2418
2419 for (int i = 0; i < m_cgraph->n_nodes; i++) {
2420 ggml_tensor * node = m_cgraph->nodes[i];
2421 visit_node(visit_node, node);
2422 }
2423
2424 // print the nodes in m_cgraph name & shape with the dynamic dim (the dynamic dim is the dimension with -1 in m_node_dynamic_dims) for debugging
2425 if (0) {
2426 for (int i = 0; i < m_cgraph->n_nodes; i++) {
2427 ggml_tensor * node = m_cgraph->nodes[i];
2428 int dynamic_dim = m_node_dynamic_dims[node];
2429 std::cout << "[" << i << "] " << "node_name: " << node->name << " op: " << ggml_op_name(node->op)
2430 << " shape: [";
2431 for (int j = 0; j < 4; j++) {
2432 if (j == dynamic_dim) {
2433 std::cout << "*";
2434 } else {
2435 std::cout << node->ne[j];
2436 }
2437 if (j < 3) {
2438 std::cout << ", ";
2439 }
2440 }
2441 std::cout << "]" << '\n';
2442 // print the src name & shape with the dynamic dim for debugging
2443 for (int j = 0; j < GGML_MAX_SRC; j++) {
2444 ggml_tensor * src = node->src[j];
2445 if (src == nullptr) {
2446 continue;
2447 }
2448 int src_dynamic_dim = m_node_dynamic_dims[src];
2449 std::cout << " [" << j << "] src_name: " << src->name << " [";
2450 for (int k = 0; k < 4; k++) {
2451 if (k == src_dynamic_dim) {
2452 std::cout << "*";
2453 } else {
2454 std::cout << src->ne[k];
2455 }
2456 if (k < 3) {
2457 std::cout << ", ";
2458 }
2459 }
2460 std::cout << "]" << '\n';
2461 }
2462 std::cout << '\n';
2463 }
2464 }
2465}