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 / openvino / utils.cpp

987 lines · 50466 bytes Raw Blame History
1#include "utils.h"
2
3#include <cmath>
4#include <cstddef>
5#include <ctime>
6#include <memory>
7#include <openvino/op/add.hpp>
8#include <openvino/op/clamp.hpp>
9#include <openvino/op/convert.hpp>
10#include <openvino/op/cos.hpp>
11#include <openvino/op/divide.hpp>
12#include <openvino/op/gather.hpp>
13#include <openvino/op/maximum.hpp>
14#include <openvino/op/multiply.hpp>
15#include <openvino/op/reshape.hpp>
16#include <openvino/op/shape_of.hpp>
17#include <openvino/op/sin.hpp>
18#include <openvino/op/slice.hpp>
19#include <openvino/op/split.hpp>
20#include <openvino/op/squeeze.hpp>
21#include <openvino/op/subtract.hpp>
22#include <openvino/op/transpose.hpp>
23#include <string>
24
25namespace ov {
26namespace frontend {
27namespace ggml {
28
29void num_inputs_check(const NodeContext & context, size_t min_inputs, size_t max_inputs) {
30 auto input_size = context.get_input_size();
31 FRONT_END_OP_CONVERSION_CHECK(input_size >= min_inputs, "Got less inputs than expected");
32 FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");
33}
34
35int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {
36 int dim = nb.size() - 1;
37 size_t bytes = nb[dim];
38 for (int i = dim; i > 0; i--) {
39 bytes *= ne[i];
40 if (bytes != nb[i - 1]) {
41 return i;
42 }
43 }
44 return 0;
45}
46
47std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::op::v3::ShapeOf> & shape,
48 const std::vector<int> & dims) {
49 using namespace ov::op;
50 const auto zero = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});
51 const auto dims_const = v0::Constant::create(ov::element::i32, ov::Shape{dims.size()}, dims);
52 return std::make_shared<v8::Gather>(shape, dims_const, zero);
53}
54
55std::shared_ptr<ov::Node> get_dimensions(const std::shared_ptr<ov::Node> & node, const std::vector<int> & dims) {
56 return get_dimensions(std::make_shared<ov::op::v3::ShapeOf>(node), dims);
57}
58
59OutputVector rename_outputs_with_suffix(const OutputVector & outputs, const std::string & suffix) {
60 for (const auto & output : outputs) {
61 auto node = output.get_node_shared_ptr();
62 std::string name = node->get_friendly_name();
63 name += "_";
64 name += suffix;
65 node->set_friendly_name(name);
66 // Uncomment to dump every node's inferred shape (used to hunt down dynamic dims on NPU).
67 // std::cout << name << " " << output.get_partial_shape() << std::endl;
68 }
69 return outputs;
70}
71
72namespace {
73ov::Output<ov::Node> rope_yarn_ramp_mix(int num_elements, const float corr_dims[2], float ext_factor) {
74 std::vector<float> dim_ids_vec(num_elements);
75 std::iota(dim_ids_vec.begin(), dim_ids_vec.end(), 0.0f);
76 auto dim_ids = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, (size_t) num_elements}, dim_ids_vec);
77 auto corr_low = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[0]});
78 auto corr_high = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {corr_dims[1]});
79 auto denom = std::make_shared<ov::op::v1::Maximum>(
80 std::make_shared<ov::op::v1::Subtract>(corr_high, corr_low),
81 ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {0.001f}));
82 auto ramp_y =
83 std::make_shared<ov::op::v1::Divide>(std::make_shared<ov::op::v1::Subtract>(dim_ids, corr_low), denom);
84 auto ramp_clamped = std::make_shared<ov::op::v0::Clamp>(ramp_y, 0.0f, 1.0f);
85 // rope_yarn_ramp returns (1 - clamp(y)), so invert before scaling
86 auto one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
87 auto ramp_inverted = std::make_shared<ov::op::v1::Subtract>(one, ramp_clamped);
88 auto ext_factor_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {ext_factor});
89 auto ramp_mix = std::make_shared<ov::op::v1::Multiply>(ramp_inverted, ext_factor_node);
90 return ramp_mix;
91}
92
93float ggml_rope_yarn_corr_dim(int n_dims, int n_ctx_orig, float n_rot, float base) {
94#ifndef M_PI
95# define M_PI 3.14159265358979323846
96#endif
97 return n_dims * logf(n_ctx_orig / (n_rot * 2 * (float) M_PI)) / (2 * logf(base));
98}
99
100void ggml_rope_yarn_corr_dims(int n_dims,
101 int n_ctx_orig,
102 float freq_base,
103 float beta_fast,
104 float beta_slow,
105 float dims[2]) {
106 float start = floorf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_fast, freq_base));
107 float end = ceilf(ggml_rope_yarn_corr_dim(n_dims, n_ctx_orig, beta_slow, freq_base));
108 dims[0] = std::max(0.0f, start);
109 dims[1] = std::min(static_cast<float>(n_dims - 1), end);
110}
111} // namespace
112
113std::pair<ov::Output<Node>, ov::Output<Node>> make_sin_cos(int32_t * rope_params,
114 std::shared_ptr<ov::Node> inp_pos,
115 std::shared_ptr<ov::Node> rope_freqs_weight,
116 int mode,
117 bool stateful,
118 int64_t head_dim) {
119 constexpr int TYPE_IMROPE = 2;
120 constexpr int TYPE_VISION = 3;
121 constexpr int TYPE_MROPE = 4;
122
123 const bool is_imrope = (mode == TYPE_IMROPE);
124 const bool is_vision = (mode == TYPE_VISION);
125 const bool is_mrope = (mode == TYPE_MROPE);
126 const bool is_multi = is_imrope || is_vision || is_mrope;
127
128 if (stateful) {
129 inp_pos =
130 std::make_shared<ov::op::v0::Squeeze>(inp_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {0}));
131 inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
132 auto pos_perm =
133 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{3}, std::vector<int64_t>{2, 1, 0});
134 inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_perm);
135 } else if (is_multi) {
136 inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
137 auto pos_shape = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{5}, {0, 0, 0, 4, -1});
138 inp_pos = std::make_shared<ov::op::v1::Reshape>(inp_pos, pos_shape, true);
139 auto pos_transpose_shape =
140 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{5}, std::vector<int64_t>{0, 1, 2, 4, 3});
141 inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_transpose_shape);
142 } else {
143 inp_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::f32);
144 auto pos_perm =
145 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{4}, std::vector<int64_t>{0, 3, 1, 2});
146 inp_pos = std::make_shared<ov::op::v1::Transpose>(inp_pos, pos_perm);
147 }
148
149 float freq_base;
150 float freq_scale;
151 float ext_factor;
152 float attn_factor;
153 float beta_fast;
154 float beta_slow;
155 const int n_dims = rope_params[1];
156 const size_t n_dims_half = n_dims >> 1;
157 const int n_ctx_orig = rope_params[4];
158 memcpy(&freq_base, rope_params + 5, sizeof(float));
159 memcpy(&freq_scale, rope_params + 6, sizeof(float));
160 memcpy(&ext_factor, rope_params + 7, sizeof(float));
161 memcpy(&attn_factor, rope_params + 8, sizeof(float));
162 memcpy(&beta_fast, rope_params + 9, sizeof(float));
163 memcpy(&beta_slow, rope_params + 10, sizeof(float));
164
165 const float theta_scale = powf(freq_base, -2.0f / n_dims);
166
167 Output<Node> theta;
168 float mscale = attn_factor;
169 if (is_multi) {
170 const size_t num_pairs = is_vision ? (n_dims > 0 ? (size_t) n_dims : (size_t) (head_dim / 2)) : n_dims_half;
171 int sections[4];
172 memcpy(sections, rope_params + 11, sizeof(int) * 4);
173 int sect_dims = sections[0] + sections[1] + sections[2] + sections[3];
174 if (sect_dims <= 0) {
175 sect_dims = num_pairs;
176 }
177 int sec_w = sections[0] + sections[1];
178 int sec_e = sec_w + sections[2];
179 std::vector<int64_t> gather_indices(num_pairs);
180 std::vector<float> factor(num_pairs);
181 for (size_t j = 0; j < num_pairs; j++) {
182 int sector = j % sect_dims;
183 int plane = 0;
184 if (is_imrope) {
185 if (sector % 3 == 1 && sector < 3 * sections[1]) {
186 plane = 1;
187 } else if (sector % 3 == 2 && sector < 3 * sections[2]) {
188 plane = 2;
189 } else if (sector % 3 == 0 && sector < 3 * sections[0]) {
190 plane = 0;
191 } else {
192 plane = 3;
193 }
194 factor[j] = std::pow(theta_scale, j);
195 } else if (is_vision) {
196 int p_idx = 0;
197 if (sector < sections[0]) {
198 plane = 0;
199 p_idx = sector;
200 } else if (sector < sections[0] + sections[1]) {
201 plane = 1;
202 p_idx = sector - sections[0];
203 } else if (sector < sec_w + sections[2]) {
204 plane = 2;
205 p_idx = sector - sec_w;
206 } else {
207 plane = 3;
208 p_idx = sector - sec_e;
209 }
210 factor[j] = std::pow(theta_scale, p_idx);
211 } else {
212 if (sector >= sections[0] && sector < sec_w) {
213 plane = 1;
214 } else if (sector >= sec_w && sector < sec_e) {
215 plane = 2;
216 } else if (sector >= sec_e) {
217 plane = 3;
218 } else {
219 plane = 0;
220 }
221 factor[j] = std::pow(theta_scale, j);
222 }
223 gather_indices[j] = plane;
224 }
225 auto gather_indices_const =
226 std::make_shared<ov::op::v0::Constant>(ov::element::i64, ov::Shape{num_pairs}, gather_indices);
227 auto gather_axis = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {4});
228 inp_pos = std::make_shared<ov::op::v8::Gather>(inp_pos, gather_indices_const, gather_axis);
229 Output<Node> factor_node =
230 std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{num_pairs}, factor);
231 if (rope_freqs_weight) {
232 Output<Node> rope_factors = std::make_shared<ov::op::v8::Slice>(
233 rope_freqs_weight,
234 ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),
235 ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) num_pairs}),
236 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
237 ov::op::v0::Constant::create(ov::element::i64, {1}, {rope_freqs_weight->get_output_partial_shape(0).rank().get_length() - 1}));
238 rope_factors = std::make_shared<ov::op::v1::Reshape>(
239 rope_factors,
240 ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) num_pairs}),
241 false);
242 factor_node = std::make_shared<ov::op::v1::Divide>(factor_node, rope_factors);
243 }
244 auto theta_extrap = std::make_shared<ov::op::v1::Multiply>(inp_pos, factor_node);
245 auto theta_interp = std::make_shared<ov::op::v1::Multiply>(
246 theta_extrap, ov::op::v0::Constant::create(ov::element::f32, {1}, {freq_scale}));
247 if (ext_factor == 0.0f) {
248 theta = theta_interp;
249 } else {
250 float corr_dims[2];
251 ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
252 auto ramp_mix = rope_yarn_ramp_mix(num_pairs, corr_dims, ext_factor);
253 Output<Node> one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
254 auto one_minus_ramp = std::make_shared<ov::op::v1::Subtract>(one, ramp_mix);
255 theta = std::make_shared<ov::op::v1::Add>(
256 std::make_shared<ov::op::v1::Multiply>(theta_interp, one_minus_ramp),
257 std::make_shared<ov::op::v1::Multiply>(theta_extrap, ramp_mix));
258 mscale *= (1.0f + 0.1f * std::log(1.0f / freq_scale));
259 }
260 } else {
261 std::vector<float> factor(n_dims_half);
262 Output<Node> freq_factors;
263 float corr_dims[2];
264 ggml_rope_yarn_corr_dims(n_dims, n_ctx_orig, freq_base, beta_fast, beta_slow, corr_dims);
265 factor[0] = 1.0f;
266 for (size_t i = 1; i < factor.size(); i++) {
267 factor[i] = theta_scale * factor[i - 1];
268 }
269 if (stateful) {
270 freq_factors =
271 std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, 1, factor.size()}, factor);
272 } else {
273 freq_factors =
274 std::make_shared<ov::op::v0::Constant>(ov::element::f32, ov::Shape{1, 1, 1, factor.size()}, factor);
275 }
276 if (rope_freqs_weight) {
277 Output<Node> rope_factors = std::make_shared<ov::op::v8::Slice>(
278 rope_freqs_weight,
279 ov::op::v0::Constant::create(ov::element::i64, {1}, {0}),
280 ov::op::v0::Constant::create(ov::element::i64, {1}, {(int64_t) n_dims_half}),
281 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
282 ov::op::v0::Constant::create(ov::element::i64, {1}, {rope_freqs_weight->get_output_partial_shape(0).rank().get_length() - 1}));
283 if (stateful) {
284 rope_factors = std::make_shared<ov::op::v1::Reshape>(
285 rope_factors,
286 ov::op::v0::Constant::create(ov::element::i64, {3}, {(int64_t) 1, (int64_t) 1, (int64_t) n_dims_half}),
287 false);
288 } else {
289 rope_factors = std::make_shared<ov::op::v1::Reshape>(
290 rope_factors,
291 ov::op::v0::Constant::create(ov::element::i64, {4}, {(int64_t) 1, (int64_t) 1, (int64_t) 1, (int64_t) n_dims_half}),
292 false);
293 }
294 freq_factors = std::make_shared<ov::op::v1::Divide>(freq_factors, rope_factors);
295 }
296
297 auto theta_extrap = std::make_shared<ov::op::v1::Multiply>(freq_factors, inp_pos);
298 auto theta_interp = std::make_shared<ov::op::v1::Multiply>(
299 theta_extrap, ov::op::v0::Constant::create(ov::element::f32, {1}, {freq_scale}));
300
301 if (ext_factor == 0.0f) {
302 theta = theta_interp;
303 } else {
304 auto ramp_mix = rope_yarn_ramp_mix(n_dims_half, corr_dims, ext_factor);
305 Output<Node> one;
306 if (stateful) {
307 one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1}, {1.0f});
308 } else {
309 one = ov::op::v0::Constant::create(ov::element::f32, Shape{1, 1, 1, 1}, {1.0f});
310 }
311 auto one_minus_ramp = std::make_shared<ov::op::v1::Subtract>(one, ramp_mix);
312
313 theta =
314 std::make_shared<ov::op::v1::Add>(std::make_shared<ov::op::v1::Multiply>(theta_interp, one_minus_ramp),
315 std::make_shared<ov::op::v1::Multiply>(theta_extrap, ramp_mix));
316 mscale *= (1.0f + 0.1f * std::log(1.0f / freq_scale));
317 }
318 }
319
320 Output<Node> cos_theta = std::make_shared<ov::op::v0::Cos>(theta);
321 Output<Node> sin_theta = std::make_shared<ov::op::v0::Sin>(theta);
322
323 if (mscale != 1.0f) {
324 auto mscale_node = ov::op::v0::Constant::create(ov::element::f32, Shape{}, {mscale});
325
326 cos_theta = std::make_shared<ov::op::v1::Multiply>(cos_theta, mscale_node);
327 sin_theta = std::make_shared<ov::op::v1::Multiply>(sin_theta, mscale_node);
328 }
329
330 return std::make_pair(sin_theta, cos_theta);
331}
332
333ov::Output<ov::Node> process_view_input(const NodeContext & context, int input_index, int slice_len, int axis) {
334 // Only works for VIEW operations that does a non-strided slice with optinal reshape on the slice result.
335 // The function only does the slice part, the reshape (if any) should be handled by the caller.
336 // Default axis is -1, which means slicing the last dimension.
337 // If the VIEW reshapes the result, `slice_len` should be provided
338 auto input = context.get_input(input_index);
339 auto * op_params = (size_t *) context.get_input_op_params(input_index);
340 auto src_stride = context.get_input_stride(input_index);
341
342 int64_t slice_start = op_params[0] / src_stride[3];
343 if (slice_len == 0) {
344 slice_len = context.get_input_shape(input_index)[3].get_length();
345 }
346 int64_t slice_end = slice_start + slice_len;
347
348 auto begin = ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_start});
349 auto end = ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_end});
350 auto stride = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
351 ov::Output<ov::Node> axes;
352 if (axis == -1) {
353 axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {context.is_stateful() ? 2 : 3});
354 } else {
355 axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});
356 }
357 auto sliced = std::make_shared<ov::op::v8::Slice>(input, begin, end, stride, axes);
358 return sliced;
359}
360
361ov::Output<ov::Node> process_view_input_new(const NodeContext & context, int input_index) {
362 auto input = context.get_input(input_index);
363
364 // Check if this input has view inputs
365 size_t view_input_size = context.get_view_input_size(input_index);
366 if (view_input_size == 0) {
367 // No view inputs, return the input as is
368 return input;
369 }
370
371 // If translate_view already resolved this VIEW (produced a Slice), the input
372 // will already have the expected shape — skip re-slicing.
373 //
374 // Two notions of "matches" are accepted per axis:
375 // - both dims static and equal, OR
376 // - both dims dynamic.
377 // The dynamic case matters for the MoE expert-plane views: translate_view now emits a
378 // DYNAMIC-token slice (so the token dim is not frozen). An all-static-only check would
379 // see the dynamic token dim, decide the shapes "don't match", and fall through to
380 // re-slice/flatten the already-resolved view (a Reshape to the full flattened
381 // n_expert_used*n_embd tail, which then conflicts with the single-plane input). Treat a
382 // dynamic-vs-dynamic axis as matching so the already-resolved view is reused as-is.
383 //
384 // A third case matters for split-model MoE fragments: translate_view resolves the
385 // expert-plane view against the fragment's INPUT parameter. When the graph is split
386 // the token axis of that parameter may already be concrete (static n_tokens) even
387 // though get_view_input_ov_shape() still reports it as dynamic (-1). The resolved
388 // view is then static [1,1,n_tokens,n_embd] while `expected` is [1,1,?,n_embd].
389 // An "expected dynamic, actual static" axis is a valid concretization of the SAME
390 // resolved view, so treat it as matching too. Falling through to process_single_view
391 // here would re-slice/re-flatten the already-resolved single-plane view against the
392 // recorded (multi-plane) source strides and emit a constant-target Reshape whose baked
393 // dims no longer divide the concretized input -> "dimensions do not evenly divide".
394 // A fourth case matters for stateful execution: `expected` comes from ggml metadata and is
395 // always GGML_MAX_DIMS ranks, but stateful drops the leading size-1 batch dim, so the
396 // resolved view is one rank lower. Compare the common trailing dims and require the
397 // leading expected dims we skip to be 1. Without this the rank test below never matches on
398 // the stateful path and every already-resolved MoE expert-plane view is re-sliced.
399 auto expected_ov_shape = context.get_view_input_ov_shape(input_index, 0);
400 auto actual_shape = input.get_partial_shape();
401 if (expected_ov_shape.rank().is_static() && actual_shape.rank().is_static() &&
402 expected_ov_shape.rank().get_length() >= actual_shape.rank().get_length()) {
403 const int64_t n_actual = actual_shape.rank().get_length();
404 const int64_t shift = expected_ov_shape.rank().get_length() - n_actual;
405 bool shapes_match = true;
406 for (int64_t i = 0; i < shift; ++i) {
407 if (!expected_ov_shape[i].is_static() || expected_ov_shape[i].get_length() != 1) {
408 shapes_match = false;
409 break;
410 }
411 }
412 for (int64_t i = 0; i < n_actual && shapes_match; ++i) {
413 const auto & exp = expected_ov_shape[i + shift];
414 const bool both_dynamic = exp.is_dynamic() && actual_shape[i].is_dynamic();
415 const bool both_static_equal =
416 exp.is_static() && actual_shape[i].is_static() && exp == actual_shape[i];
417 // expected dynamic, actual static: the resolved view already carries the
418 // concrete size for this fragment; reuse it rather than re-materializing.
419 const bool expected_dyn_actual_static = exp.is_dynamic() && actual_shape[i].is_static();
420 if (!both_dynamic && !both_static_equal && !expected_dyn_actual_static) {
421 shapes_match = false;
422 break;
423 }
424 }
425 if (shapes_match) {
426 return input;
427 }
428 }
429
430 // In static mode, use Split instead of Slice for single-dimension reductions.
431 // This ensures NPUW's FOLD doesn't parametrize per-layer slice indices (which
432 // would introduce dynamic shapes). A shared Split node sits outside the repeated
433 // subgraph boundary; each layer receives one of its output ports.
434 if (context.is_static() && view_input_size == 1) {
435 auto view_stride_v = context.get_view_input_stride(input_index, 0);
436 auto view_src_stride_v = context.get_view_input_src_stride(input_index, 0);
437 auto view_ggml_shape = context.get_view_input_ggml_shape(input_index, 0);
438 auto view_src_ggml_shape = context.get_view_input_src_ggml_shape(input_index, 0);
439 auto view_offset = context.get_view_input_offset(input_index, 0);
440 auto view_src_offset = context.get_view_input_src_offset(input_index, 0);
441
442 size_t ndims = view_ggml_shape.size();
443 std::vector<int> diff_dims;
444 if (view_src_ggml_shape.size() == ndims) {
445 for (size_t i = 0; i < ndims; ++i) {
446 if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
447 diff_dims.push_back(static_cast<int>(i));
448 }
449 }
450 }
451
452 if (diff_dims.size() == 1) {
453 int split_dim = diff_dims[0];
454 int64_t num_splits = static_cast<int64_t>(view_src_ggml_shape[split_dim]);
455 int64_t chunk_size = static_cast<int64_t>(view_ggml_shape[split_dim]);
456
457 // Only apply when slicing exactly 1 element from a multi-element dimension
458 if (chunk_size == 1 && num_splits > 1) {
459 // Check suffix strides match (dimensions after split_dim)
460 bool suffix_ok = view_stride_v.size() == view_src_stride_v.size();
461 if (suffix_ok) {
462 for (size_t i = static_cast<size_t>(split_dim) + 1; i < ndims; ++i) {
463 if (view_stride_v[i] != view_src_stride_v[i]) {
464 suffix_ok = false;
465 break;
466 }
467 }
468 }
469
470 if (suffix_ok && view_src_stride_v[split_dim] > 0) {
471 size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;
472 int64_t split_index = static_cast<int64_t>(relative_offset / view_src_stride_v[split_dim]);
473
474 if (split_index >= 0 && split_index < num_splits) {
475 auto src_node = input.get_node_shared_ptr();
476 std::string rt_key = "split_dim_" + std::to_string(split_dim);
477 auto & rt_info = src_node->get_rt_info();
478
479 if (rt_info.find(rt_key) == rt_info.end()) {
480 auto axis_const =
481 ov::op::v0::Constant::create(ov::element::i64, {}, {static_cast<int64_t>(split_dim)});
482 auto split_node =
483 std::make_shared<ov::op::v1::Split>(input, axis_const, static_cast<size_t>(num_splits));
484 split_node->set_friendly_name(src_node->get_friendly_name() + "_split");
485 rt_info[rt_key] = split_node;
486 }
487
488 auto split_node = rt_info[rt_key].as<std::shared_ptr<ov::op::v1::Split>>();
489 return split_node->output(static_cast<size_t>(split_index));
490 }
491 }
492 }
493 }
494 }
495
496 // Lambda function to process a single view operation
497 auto process_single_view =
498 [](ov::Output<ov::Node> current, size_t view_offset, const std::vector<size_t> & view_stride,
499 const ov::Shape & view_ggml_shape, const ov::PartialShape & view_ov_shape, const std::string & view_name,
500 size_t view_src_offset, const std::vector<size_t> & view_src_stride, const ov::Shape & view_src_ggml_shape,
501 const ov::PartialShape & view_src_ov_shape, const std::string & view_src_name) -> ov::Output<ov::Node> {
502 // Stateful execution drops a leading size-1 axis, so `current` can be one rank lower
503 // than the ggml shape metadata (view_stride/view_ggml_shape, always GGML_MAX_DIMS
504 // entries) assumes. Shift any axis index built from that metadata down by the
505 // difference before using it as an OV Slice axis.
506 const auto current_rank = current.get_partial_shape().rank();
507 const int axis_shift = current_rank.is_static() ?
508 static_cast<int>(view_stride.size()) - static_cast<int>(current_rank.get_length()) :
509 0;
510
511 auto build_reshape_pattern = [](const ov::PartialShape & target_ov_shape,
512 const ov::Shape & target_ggml_shape) -> std::vector<int64_t> {
513 const size_t ndims = target_ggml_shape.size();
514 std::vector<int64_t> reshape_pattern(ndims);
515 size_t dynamic_dims = 0;
516
517 if (target_ov_shape.rank().is_static() &&
518 target_ov_shape.rank().get_length() == static_cast<int64_t>(ndims)) {
519 for (size_t i = 0; i < ndims; ++i) {
520 if (target_ov_shape[i].is_static()) {
521 reshape_pattern[i] = target_ov_shape[i].get_length();
522 } else {
523 reshape_pattern[i] = -1;
524 ++dynamic_dims;
525 }
526 }
527 } else {
528 dynamic_dims = 2;
529 }
530
531 if (dynamic_dims > 1) {
532 for (size_t i = 0; i < ndims; ++i) {
533 reshape_pattern[i] = static_cast<int64_t>(target_ggml_shape[i]);
534 }
535 }
536
537 return reshape_pattern;
538 };
539
540 auto build_prefix_tail_reshape_pattern = [](const ov::PartialShape & target_ov_shape,
541 const ov::Shape & target_ggml_shape, size_t prefix_dims,
542 int64_t tail_dim) -> std::vector<int64_t> {
543 std::vector<int64_t> reshape_pattern(prefix_dims + 1);
544 size_t dynamic_dims = 0;
545
546 if (target_ov_shape.rank().is_static() &&
547 target_ov_shape.rank().get_length() == static_cast<int64_t>(target_ggml_shape.size())) {
548 for (size_t i = 0; i < prefix_dims; ++i) {
549 if (target_ov_shape[i].is_static()) {
550 reshape_pattern[i] = target_ov_shape[i].get_length();
551 } else {
552 reshape_pattern[i] = -1;
553 ++dynamic_dims;
554 }
555 }
556 } else {
557 dynamic_dims = 2;
558 }
559
560 if (dynamic_dims > 1) {
561 for (size_t i = 0; i < prefix_dims; ++i) {
562 reshape_pattern[i] = static_cast<int64_t>(target_ggml_shape[i]);
563 }
564 }
565
566 reshape_pattern[prefix_dims] = tail_dim;
567 return reshape_pattern;
568 };
569
570 bool same_stride = view_stride.size() == view_src_stride.size();
571 if (same_stride) {
572 for (size_t i = 0; i < view_stride.size(); ++i) {
573 if (view_stride[i] != view_src_stride[i]) {
574 same_stride = false;
575 break;
576 }
577 }
578 }
579
580 bool same_ggml_shape = view_ggml_shape.size() == view_src_ggml_shape.size();
581 if (same_ggml_shape) {
582 for (size_t i = 0; i < view_ggml_shape.size(); ++i) {
583 if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
584 same_ggml_shape = false;
585 break;
586 }
587 }
588 }
589
590 if (same_stride && same_ggml_shape) {
591 return current;
592 }
593
594 if (same_stride) {
595 const size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;
596 const size_t ndims = view_stride.size();
597
598 std::vector<int> diff_dims;
599 if (view_ggml_shape.size() == ndims && view_src_ggml_shape.size() == ndims) {
600 for (size_t i = 0; i < ndims; ++i) {
601 if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
602 diff_dims.push_back(static_cast<int>(i));
603 }
604 }
605 }
606
607 if (diff_dims.size() == 1) {
608 const int slice_dim = diff_dims[0];
609 const int64_t dim_size = static_cast<int64_t>(view_src_ggml_shape[slice_dim]);
610
611 if (view_stride[slice_dim] > 0 && relative_offset % view_stride[slice_dim] == 0) {
612 const int64_t begin_val = static_cast<int64_t>((relative_offset / view_stride[slice_dim]) %
613 static_cast<size_t>(dim_size));
614 const int64_t end_val = begin_val + static_cast<int64_t>(view_ggml_shape[slice_dim]);
615
616 if (begin_val >= 0 && end_val <= dim_size) {
617 auto sliced = std::make_shared<ov::op::v8::Slice>(
618 current, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_val}),
619 ov::op::v0::Constant::create(ov::element::i64, {1}, {end_val}),
620 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
621 ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim - axis_shift}));
622
623 if (view_ov_shape.is_static()) {
624 auto reshaped = std::make_shared<ov::op::v1::Reshape>(
625 sliced,
626 ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()),
627 false);
628 reshaped->set_friendly_name(view_name);
629 return reshaped;
630 }
631
632 sliced->set_friendly_name(view_name);
633 return sliced;
634 }
635 }
636
637 int64_t tail_src_elems = 1;
638 int64_t tail_dst_elems = 1;
639 for (size_t i = slice_dim; i < ndims; ++i) {
640 tail_src_elems *= static_cast<int64_t>(view_src_ggml_shape[i]);
641 tail_dst_elems *= static_cast<int64_t>(view_ggml_shape[i]);
642 }
643
644 const size_t elem_stride = view_stride[ndims - 1];
645 int64_t tail_begin = 0;
646 if (elem_stride > 0) {
647 tail_begin =
648 static_cast<int64_t>((relative_offset / elem_stride) % static_cast<size_t>(tail_src_elems));
649 }
650 const int64_t tail_end = tail_begin + tail_dst_elems;
651
652 if (tail_begin >= 0 && tail_end <= tail_src_elems) {
653 std::vector<int64_t> flat_shape;
654 flat_shape.reserve(slice_dim);
655 for (int i = 0; i < slice_dim; ++i) {
656 flat_shape.push_back(static_cast<int64_t>(view_src_ggml_shape[i]));
657 }
658 flat_shape.push_back(tail_src_elems);
659 const size_t flat_ndims = flat_shape.size();
660
661 auto flat = std::make_shared<ov::op::v1::Reshape>(
662 current, ov::op::v0::Constant::create(ov::element::i64, {flat_ndims}, flat_shape), false);
663
664 auto sliced = std::make_shared<ov::op::v8::Slice>(
665 flat, ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_begin}),
666 ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_end}),
667 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
668 ov::op::v0::Constant::create(ov::element::i64, {1}, {slice_dim}));
669
670 if (view_ov_shape.is_static()) {
671 auto reshaped = std::make_shared<ov::op::v1::Reshape>(
672 sliced, ov::op::v0::Constant::create(ov::element::i64, {ndims}, view_ov_shape.to_shape()),
673 false);
674 reshaped->set_friendly_name(view_name);
675 return reshaped;
676 }
677
678 sliced->set_friendly_name(view_name);
679 return sliced;
680 }
681 }
682
683 std::vector<int64_t> begin(ndims, 0);
684 std::vector<int64_t> end(ndims, 0);
685 std::vector<int64_t> step(ndims, 1);
686 std::vector<int64_t> axes(ndims, 0);
687
688 size_t remaining_offset = relative_offset;
689 for (size_t i = 0; i < ndims; ++i) {
690 axes[i] = static_cast<int64_t>(i);
691 if (view_stride[i] > 0) {
692 begin[i] = static_cast<int64_t>(remaining_offset / view_stride[i]);
693 remaining_offset %= view_stride[i];
694 }
695 end[i] = begin[i] + static_cast<int64_t>(view_ggml_shape[i]);
696 }
697
698 bool in_bounds = view_src_ggml_shape.size() == ndims && view_ggml_shape.size() == ndims;
699 if (in_bounds) {
700 for (size_t i = 0; i < ndims; ++i) {
701 if (end[i] > static_cast<int64_t>(view_src_ggml_shape[i])) {
702 in_bounds = false;
703 break;
704 }
705 }
706 }
707
708 if (in_bounds && remaining_offset == 0) {
709 auto sliced = std::make_shared<ov::op::v8::Slice>(
710 current, ov::op::v0::Constant::create(ov::element::i64, {ndims}, begin),
711 ov::op::v0::Constant::create(ov::element::i64, {ndims}, end),
712 ov::op::v0::Constant::create(ov::element::i64, {ndims}, step),
713 ov::op::v0::Constant::create(ov::element::i64, {ndims}, axes));
714
715 sliced->set_friendly_name(view_name);
716 return sliced;
717 }
718 } else {
719 bool same_rank = view_stride.size() == view_src_stride.size() &&
720 view_ggml_shape.size() == view_src_ggml_shape.size() &&
721 view_stride.size() == view_ggml_shape.size();
722 const size_t relative_offset = view_offset >= view_src_offset ? view_offset - view_src_offset : 0;
723
724 if (same_rank) {
725 const size_t ndims = view_ggml_shape.size();
726 std::vector<int> diff_dims;
727 for (size_t i = 0; i < ndims; ++i) {
728 if (view_ggml_shape[i] != view_src_ggml_shape[i]) {
729 diff_dims.push_back(static_cast<int>(i));
730 }
731 }
732
733 if (diff_dims.size() == 1) {
734 const size_t slice_dim = static_cast<size_t>(diff_dims[0]);
735 bool suffix_stride_match = true;
736 for (size_t i = slice_dim + 1; i < ndims; ++i) {
737 if (view_stride[i] != view_src_stride[i]) {
738 suffix_stride_match = false;
739 break;
740 }
741 }
742
743 if (suffix_stride_match && view_src_stride[slice_dim] > 0 &&
744 relative_offset % view_src_stride[slice_dim] == 0) {
745 const int64_t begin_val = static_cast<int64_t>(relative_offset / view_src_stride[slice_dim]);
746 const int64_t end_val = begin_val + static_cast<int64_t>(view_ggml_shape[slice_dim]);
747 const int64_t dim_size = static_cast<int64_t>(view_src_ggml_shape[slice_dim]);
748
749 if (begin_val >= 0 && end_val <= dim_size) {
750 auto sliced = std::make_shared<ov::op::v8::Slice>(
751 current, ov::op::v0::Constant::create(ov::element::i64, {1}, {begin_val}),
752 ov::op::v0::Constant::create(ov::element::i64, {1}, {end_val}),
753 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
754 ov::op::v0::Constant::create(ov::element::i64, {1}, {static_cast<int64_t>(slice_dim)}));
755 sliced->set_friendly_name(view_name);
756 return sliced;
757 }
758 }
759 }
760 }
761
762 size_t view_elems = 1;
763 size_t src_elems = 1;
764 if (same_rank) {
765 for (size_t i = 0; i < view_ggml_shape.size(); ++i) {
766 view_elems *= view_ggml_shape[i];
767 src_elems *= view_src_ggml_shape[i];
768 }
769 }
770
771 bool same_num_elements = same_rank && view_elems == src_elems;
772
773 if (same_rank && relative_offset == 0 && same_num_elements) {
774 auto reshape_pattern = build_reshape_pattern(view_ov_shape, view_ggml_shape);
775
776 auto reshaped = std::make_shared<ov::op::v1::Reshape>(
777 current, ov::op::v0::Constant::create(ov::element::i64, {reshape_pattern.size()}, reshape_pattern),
778 false);
779 reshaped->set_friendly_name(view_name);
780 return reshaped;
781 }
782
783 if (same_rank) {
784 const size_t ndims = view_ggml_shape.size();
785
786 // Match views that can be expressed as a regular strided slice over the
787 // already reconstructed source tensor, e.g. offset on one axis plus step > 1
788 // on another axis.
789 bool is_regular_slice = view_src_ggml_shape.size() == ndims;
790 std::vector<int64_t> begin(ndims, 0);
791 std::vector<int64_t> end(ndims, 0);
792 std::vector<int64_t> step(ndims, 1);
793 std::vector<int64_t> axes(ndims, 0);
794 size_t remaining_offset = relative_offset;
795
796 if (is_regular_slice) {
797 for (size_t i = 0; i < ndims; ++i) {
798 axes[i] = static_cast<int64_t>(i);
799
800 if (view_src_stride[i] == 0 || view_stride[i] == 0 ||
801 view_stride[i] % view_src_stride[i] != 0) {
802 is_regular_slice = false;
803 break;
804 }
805
806 step[i] = static_cast<int64_t>(view_stride[i] / view_src_stride[i]);
807 if (step[i] <= 0) {
808 is_regular_slice = false;
809 break;
810 }
811
812 begin[i] = static_cast<int64_t>(remaining_offset / view_src_stride[i]);
813 remaining_offset %= view_src_stride[i];
814
815 if (view_ggml_shape[i] == 0) {
816 end[i] = begin[i];
817 continue;
818 }
819
820 end[i] = begin[i] + step[i] * static_cast<int64_t>(view_ggml_shape[i] - 1) + 1;
821
822 if (begin[i] < 0 || end[i] > static_cast<int64_t>(view_src_ggml_shape[i])) {
823 is_regular_slice = false;
824 break;
825 }
826 }
827 }
828
829 if (is_regular_slice && remaining_offset == 0) {
830 auto sliced = std::make_shared<ov::op::v8::Slice>(
831 current, ov::op::v0::Constant::create(ov::element::i64, {ndims}, begin),
832 ov::op::v0::Constant::create(ov::element::i64, {ndims}, end),
833 ov::op::v0::Constant::create(ov::element::i64, {ndims}, step),
834 ov::op::v0::Constant::create(ov::element::i64, {ndims}, axes));
835
836 sliced->set_friendly_name(view_name);
837 return sliced;
838 }
839
840 const size_t elem_stride = view_src_stride.back();
841 const bool aligned_offset = elem_stride > 0 && relative_offset % elem_stride == 0;
842
843 if (aligned_offset) {
844 size_t suffix_start = 0;
845 size_t expected_stride = elem_stride;
846 for (int i = static_cast<int>(ndims) - 1; i >= 0; --i) {
847 if (view_stride[i] != expected_stride) {
848 suffix_start = static_cast<size_t>(i + 1);
849 break;
850 }
851 expected_stride *= view_ggml_shape[i];
852 }
853
854 size_t prefix_elems = 1;
855 size_t suffix_elems = 1;
856 for (size_t i = 0; i < suffix_start; ++i) {
857 prefix_elems *= view_ggml_shape[i];
858 }
859 for (size_t i = suffix_start; i < ndims; ++i) {
860 suffix_elems *= view_ggml_shape[i];
861 }
862
863 if (prefix_elems > 0 && src_elems % prefix_elems == 0) {
864 const size_t src_tail_elems = src_elems / prefix_elems;
865 const int64_t tail_begin = static_cast<int64_t>(relative_offset / elem_stride);
866 const int64_t tail_end = tail_begin + static_cast<int64_t>(suffix_elems);
867
868 if (tail_begin >= 0 && tail_end <= static_cast<int64_t>(src_tail_elems)) {
869 auto prefix_tail_pattern = build_prefix_tail_reshape_pattern(
870 view_ov_shape, view_ggml_shape, suffix_start, static_cast<int64_t>(src_tail_elems));
871
872 auto prefix_tail = std::make_shared<ov::op::v1::Reshape>(
873 current,
874 ov::op::v0::Constant::create(ov::element::i64, {prefix_tail_pattern.size()},
875 prefix_tail_pattern),
876 false);
877
878 ov::Output<ov::Node> selected = prefix_tail;
879 if (tail_begin != 0 || tail_end != static_cast<int64_t>(src_tail_elems)) {
880 selected = std::make_shared<ov::op::v8::Slice>(
881 prefix_tail, ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_begin}),
882 ov::op::v0::Constant::create(ov::element::i64, {1}, {tail_end}),
883 ov::op::v0::Constant::create(ov::element::i64, {1}, {1}),
884 ov::op::v0::Constant::create(ov::element::i64, {1},
885 {static_cast<int64_t>(suffix_start)}));
886 }
887
888 auto reshape_pattern = build_reshape_pattern(view_ov_shape, view_ggml_shape);
889 auto reshaped = std::make_shared<ov::op::v1::Reshape>(
890 selected,
891 ov::op::v0::Constant::create(ov::element::i64, {reshape_pattern.size()},
892 reshape_pattern),
893 false);
894 reshaped->set_friendly_name(view_name);
895 return reshaped;
896 }
897 }
898 }
899 }
900
901 return current;
902 }
903
904 (void) view_name;
905 (void) view_src_ov_shape;
906 (void) view_src_name;
907
908 return current;
909 };
910
911 // Special case: ggml collapses VIEW-of-VIEW chains so that `view_offs` is always an
912 // ABSOLUTE offset from the true root allocation, regardless of how many VIEW levels
913 // are in between (see ggml_new_tensor_impl). `src[0]` is still the immediate op-graph
914 // parent though, which can be a DIFFERENT (already narrowed) VIEW with the SAME ggml
915 // shape as this one but a different absolute offset -- e.g. a per-layer deepstack
916 // slice `view_2d(embd, n_embd, n_tokens, embd->nb[1], layer*n_embd*sizeof(float))`
917 // whose src[0] ("embd") is itself already a zero-offset VIEW of the true root (the
918 // padded embedding). Chaining through "embd" here would try to re-slice an already
919 // 2-narrowed tensor using a root-relative offset, going out of bounds and silently
920 // falling back to a no-op (returning the wrong, already-resolved sibling slice).
921 // Detect this (same shape as the immediate src, but different absolute offset) and
922 // re-slice directly from the untouched root using the innermost view's absolute
923 // offset against the ROOT's own shape/stride instead of chaining through src[0].
924 {
925 auto innermost_offset = context.get_view_input_offset(input_index, 0);
926 auto innermost_src_offset = context.get_view_input_src_offset(input_index, 0);
927 auto innermost_shape = context.get_view_input_ggml_shape(input_index, 0);
928 auto innermost_src_shape = context.get_view_input_src_ggml_shape(input_index, 0);
929 if (innermost_offset != innermost_src_offset && innermost_shape == innermost_src_shape) {
930 size_t root_view_idx = view_input_size - 1;
931 auto root_ggml_shape = context.get_view_input_src_ggml_shape(input_index, root_view_idx);
932 auto root_stride = context.get_view_input_src_stride(input_index, root_view_idx);
933 auto root_offset = context.get_view_input_src_offset(input_index, root_view_idx);
934 auto root_ov_shape = context.get_view_input_src_ov_shape(input_index, root_view_idx);
935 auto root_name = context.get_view_input_src_name(input_index, root_view_idx);
936 auto innermost_stride = context.get_view_input_stride(input_index, 0);
937 auto innermost_ov_shape = context.get_view_input_ov_shape(input_index, 0);
938 auto innermost_name = context.get_view_input_name(input_index, 0);
939
940 return process_single_view(input, innermost_offset, innermost_stride, innermost_shape, innermost_ov_shape,
941 innermost_name, root_offset, root_stride, root_ggml_shape, root_ov_shape,
942 root_name);
943 }
944 }
945
946 // Process views from the base tensor (last) to the current view (first)
947 // Start with the base tensor
948 ov::Output<ov::Node> current = input;
949
950 // Process each view in reverse order (from base to current)
951 for (int view_idx = view_input_size - 1; view_idx >= 0; view_idx--) {
952 auto view_offset = context.get_view_input_offset(input_index, view_idx);
953 auto view_stride = context.get_view_input_stride(input_index, view_idx);
954 auto view_ggml_shape = context.get_view_input_ggml_shape(input_index, view_idx);
955 auto view_ov_shape = context.get_view_input_ov_shape(input_index, view_idx);
956 auto view_name = context.get_view_input_name(input_index, view_idx);
957
958 // print view info
959 // std::cout << "View " << view_idx << ": name = " << view_name << ", offset = " << view_offset << ", stride = ["
960 // << view_stride[0] << "," << view_stride[1] << "," << view_stride[2] << "," << view_stride[3]
961 // << "], ggml shape = [" << view_ggml_shape[0] << "," << view_ggml_shape[1] << ","
962 // << view_ggml_shape[2] << "," << view_ggml_shape[3] << "], ov shape = " << view_ov_shape << std::endl;
963
964 auto view_src_offset = context.get_view_input_src_offset(input_index, view_idx);
965 auto view_src_stride = context.get_view_input_src_stride(input_index, view_idx);
966 auto view_src_ggml_shape = context.get_view_input_src_ggml_shape(input_index, view_idx);
967 auto view_src_ov_shape = context.get_view_input_src_ov_shape(input_index, view_idx);
968 auto view_src_name = context.get_view_input_src_name(input_index, view_idx);
969 // print source view info
970 // std::cout << "View " << view_idx << ": source name = " << view_src_name
971 // << ", source offset = " << view_src_offset << ", source stride = [" << view_src_stride[0] << ","
972 // << view_src_stride[1] << "," << view_src_stride[2] << "," << view_src_stride[3]
973 // << "], source ggml shape = [" << view_src_ggml_shape[0] << "," << view_src_ggml_shape[1] << ","
974 // << view_src_ggml_shape[2] << "," << view_src_ggml_shape[3]
975 // << "], source ov shape = " << view_src_ov_shape << std::endl;
976
977 current = process_single_view(current, view_offset, view_stride, view_ggml_shape, view_ov_shape, view_name,
978 view_src_offset, view_src_stride, view_src_ggml_shape, view_src_ov_shape,
979 view_src_name);
980 }
981
982 return current;
983}
984
985} // namespace ggml
986} // namespace frontend
987} // namespace ov