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 / translate_session.cpp

546 lines · 27101 bytes Raw Blame History
1#include "translate_session.h"
2
3#include "ggml-impl.h"
4#include "ggml-openvino/ggml-openvino-extra.h"
5#include "ggml-openvino/openvino/node_context.h"
6#include "ggml-openvino/openvino/utils.h"
7#include "input_model.h"
8#include "pass/fuse_argsort_topk.h"
9#include "pass/fuse_moe_router.h"
10#include "pass/align_eltwise_ranks.h"
11#include "pass/fuse_moe_compressed.h"
12#include "pass/fuse_to_conv.h"
13#include "pass/kv_state_seq_axis.h"
14#include "pass/mark_decompression_convert_constant_folding.h"
15#include "pass/mark_dequantization_subgraph.h"
16#include "pass/squeeze_matmul.h"
17#include "rt_info/weightless_caching_attributes.hpp"
18
19#include <algorithm>
20#include <cstdint>
21#include <cstdlib>
22#include <map>
23#include <memory>
24#include <openvino/core/node.hpp>
25#include <openvino/core/preprocess/pre_post_process.hpp>
26#include <openvino/core/shape.hpp>
27#include <openvino/core/type.hpp>
28#include <openvino/core/type/element_type.hpp>
29#include <openvino/op/add.hpp>
30#include <openvino/op/broadcast.hpp>
31#include <openvino/op/concat.hpp>
32#include <openvino/op/constant.hpp>
33#include <openvino/op/convert.hpp>
34#include <openvino/op/convert_like.hpp>
35#include <openvino/op/cos.hpp>
36#include <openvino/op/divide.hpp>
37#include <openvino/op/gather.hpp>
38#include <openvino/op/greater_eq.hpp>
39#include <openvino/op/less.hpp>
40#include <openvino/op/logical_and.hpp>
41#include <openvino/op/multiply.hpp>
42#include <openvino/op/parameter.hpp>
43#include <openvino/op/range.hpp>
44#include <openvino/op/reshape.hpp>
45#include <openvino/op/result.hpp>
46#include <openvino/op/select.hpp>
47#include <openvino/op/sin.hpp>
48#include <openvino/op/slice.hpp>
49#include <openvino/op/squeeze.hpp>
50#include <openvino/op/strided_slice.hpp>
51#include <openvino/op/subtract.hpp>
52#include <openvino/op/transpose.hpp>
53#include <openvino/op/unsqueeze.hpp>
54#include <openvino/pass/constant_folding.hpp>
55#include <openvino/pass/make_stateful.hpp>
56#include <limits>
57#include <sstream>
58
59namespace ov {
60namespace frontend {
61namespace ggml {
62
63using namespace ov::op;
64
65namespace {
66
67std::shared_ptr<ov::op::v0::Parameter> create_parameter(const std::string & name,
68 const ModelInputInfo & input_info) {
69 auto param_node = std::make_shared<ov::op::v0::Parameter>(input_info.type, input_info.shape);
70 param_node->set_friendly_name(name);
71 param_node->output(0).get_tensor().set_names({name});
72 return param_node;
73}
74
75std::shared_ptr<ov::Node> create_extra_input(const std::string & name, const ModelExtraInputInfo & input_info) {
76 if (input_info.is_parameter) {
77 auto param_node = std::make_shared<ov::op::v0::Parameter>(input_info.type, input_info.shape);
78 param_node->set_friendly_name(name);
79 param_node->output(0).get_tensor().set_names({name});
80 return param_node;
81 }
82
83 auto constant = std::make_shared<ov::op::v0::Constant>(input_info.type, input_info.shape,
84 std::vector<int64_t>{input_info.value});
85 constant->set_friendly_name(name);
86 return constant;
87}
88
89ov::pass::MakeStateful::ParamResPairs get_kv_param_res_pairs(
90 const std::shared_ptr<ov::Model> & model,
91 const std::map<std::string, std::string> & kv_param_res_names) {
92 ov::pass::MakeStateful::ParamResPairs pairs;
93 const auto & params = model->get_parameters();
94 const auto & results = model->get_results();
95
96 for (const auto & param_res : kv_param_res_names) {
97 const auto & param_name = param_res.first;
98 const auto & res_name = param_res.second;
99
100 auto param_it = std::find_if(params.begin(), params.end(), [&](const std::shared_ptr<v0::Parameter> & node) {
101 return node->get_friendly_name() == param_name;
102 });
103
104 OPENVINO_ASSERT(param_it != params.end(), "The tensor name ", param_name,
105 " is not associated with any of "
106 "Parameters in the network.");
107
108 auto res_it = std::find_if(results.begin(), results.end(), [&](const std::shared_ptr<v0::Result> & node) {
109 return node->get_friendly_name() == res_name;
110 });
111
112 OPENVINO_ASSERT(res_it != results.end(), "The tensor name ", res_name,
113 " is not associated with any of "
114 "Results in the network.");
115
116 std::shared_ptr<ov::op::v0::Parameter> param = *param_it;
117 std::shared_ptr<ov::op::v0::Result> res = *res_it;
118 pairs.emplace_back(param, res);
119 }
120 return pairs;
121}
122
123void add_sliced_mask_stateful(TensorMap & tensor_map, bool imrope) {
124 auto create_sliced_mask = [&](const std::string & mask_name, const std::string & sliced_name) {
125 if ((tensor_map.find(mask_name) != tensor_map.end()) &&
126 (tensor_map.find("token_len_per_seq") != tensor_map.end()) &&
127 (tensor_map.find("inp_pos") != tensor_map.end())) {
128 auto token_len_per_seq = tensor_map.at("token_len_per_seq").get_node_shared_ptr();
129 auto mask = tensor_map.at(mask_name).get_node_shared_ptr();
130 std::shared_ptr<ov::Node> mask_sliced = mask;
131 auto one = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
132 auto zero = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
133 auto three = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
134 auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
135
136 auto step = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
137 auto axes = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
138
139 auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
140 // IMROPE's fourth position plane is zero for text; use the token's first plane.
141 ov::Output<ov::Node> last_index = neg_one;
142 if (imrope) {
143 last_index = std::make_shared<ov::op::v1::Add>(token_len_per_seq, neg_one);
144 }
145 auto last_inp_pos = std::make_shared<ov::op::v8::Gather>(inp_pos, last_index, three);
146 auto last_inp_pos_1d = std::make_shared<ov::op::v1::Reshape>(
147 last_inp_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {1}), false);
148 auto last_inp_pos_cvt = std::make_shared<ov::op::v0::Convert>(last_inp_pos_1d, ov::element::i64);
149 auto last_inp_pos_inc = std::make_shared<ov::op::v1::Add>(last_inp_pos_cvt, one);
150
151 mask_sliced = std::make_shared<ov::op::v8::Slice>(mask, zero, last_inp_pos_inc, step, axes);
152 mask_sliced = std::make_shared<ov::op::v0::Convert>(mask_sliced, ov::element::f16);
153 mask_sliced->set_friendly_name(sliced_name);
154
155 tensor_map.insert({sliced_name, mask_sliced->output(0)});
156 }
157 };
158
159 create_sliced_mask("self_kq_mask", "KQ_mask_sliced");
160 create_sliced_mask("KQ_mask", "KQ_mask_sliced");
161 create_sliced_mask("self_kq_mask_swa", "KQ_mask_swa_sliced");
162}
163
164// Rebuild the sliding-window mask from absolute positions.
165// ggml caps self_kq_mask_swa at the size of its own SWA cache, but the stateful KV state is
166// Concat-appended and grows without bound, so past that cap the two disagree on length and the
167// mask add fails. A pure-Concat state is ordered by position, so positions can rebuild the mask.
168// swa_window holds the real n_swa, read back from the ggml mask in ggml-decoder.cpp.
169// No-op when the graph has no SWA mask, or when the window could not be read back.
170void add_position_mask_stateful_swa(TensorMap & tensor_map) {
171 if (tensor_map.find("self_kq_mask_swa") == tensor_map.end() || tensor_map.find("inp_pos") == tensor_map.end() ||
172 tensor_map.find("swa_window") == tensor_map.end()) {
173 return;
174 }
175
176 auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
177
178 auto zero_i64 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
179 auto one_i64 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
180 auto three = ov::op::v0::Constant::create(ov::element::i64, {1}, {3});
181 auto neg_one = ov::op::v0::Constant::create(ov::element::i64, {1}, {-1});
182
183 auto query_pos = std::make_shared<ov::op::v0::Convert>(inp_pos, ov::element::i64);
184 auto query_pos_1d = std::make_shared<ov::op::v1::Reshape>(
185 query_pos, ov::op::v0::Constant::create(ov::element::i64, {1}, {-1}), false);
186
187 auto last_pos = std::make_shared<ov::op::v8::Gather>(inp_pos, neg_one, three);
188 auto last_pos_1d = std::make_shared<ov::op::v1::Reshape>(last_pos, one_i64, false);
189 auto last_pos_cvt = std::make_shared<ov::op::v0::Convert>(last_pos_1d, ov::element::i64);
190 auto total_len = std::make_shared<ov::op::v1::Add>(last_pos_cvt, one_i64);
191 auto total_len_scalar = std::make_shared<ov::op::v0::Squeeze>(total_len);
192
193 auto cached_pos = std::make_shared<ov::op::v4::Range>(
194 ov::op::v0::Constant::create(ov::element::i64, {}, {0}), total_len_scalar,
195 ov::op::v0::Constant::create(ov::element::i64, {}, {1}), ov::element::i64);
196
197 auto query_col = std::make_shared<ov::op::v1::Reshape>(
198 query_pos_1d, ov::op::v0::Constant::create(ov::element::i64, {2}, {-1, 1}), false);
199 auto cached_row = std::make_shared<ov::op::v1::Reshape>(
200 cached_pos, ov::op::v0::Constant::create(ov::element::i64, {2}, {1, -1}), false);
201 auto diff = std::make_shared<ov::op::v1::Subtract>(query_col, cached_row);
202
203 auto swa_window = tensor_map.at("swa_window").get_node_shared_ptr();
204 auto window = std::make_shared<ov::op::v0::Convert>(swa_window, ov::element::i64);
205 auto causal_ok = std::make_shared<ov::op::v1::GreaterEqual>(diff, zero_i64);
206 auto window_ok = std::make_shared<ov::op::v1::Less>(diff, window);
207 auto keep = std::make_shared<ov::op::v1::LogicalAnd>(causal_ok, window_ok);
208
209 auto zero_f = ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f});
210 auto neg_inf_f = ov::op::v0::Constant::create(ov::element::f32, {}, {-std::numeric_limits<float>::infinity()});
211 std::shared_ptr<ov::Node> mask = std::make_shared<ov::op::v1::Select>(keep, zero_f, neg_inf_f);
212
213 auto batch_axis = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
214 mask = std::make_shared<ov::op::v0::Unsqueeze>(mask, batch_axis);
215 mask = std::make_shared<ov::op::v0::Unsqueeze>(mask, batch_axis);
216 mask = std::make_shared<ov::op::v0::Convert>(mask, ov::element::f16);
217 mask->set_friendly_name("KQ_mask_swa_sliced");
218
219 tensor_map["KQ_mask_swa_sliced"] = mask->output(0);
220}
221
222void add_rope_sin_cos(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
223 // When ROPE ops in the graph have divergent op_params (e.g. gemma4's mixed
224 // SWA/non-SWA layers with different n_dims or freq_base), a shared sin/cos
225 // precompute cannot broadcast across every ROPE use. Skip it here and let
226 // translate_rope() build sin/cos per-op from its own op_params.
227 if (ggml_model_decoder.has_mixed_rope_params()) {
228 return;
229 }
230 int32_t * rope_params = ggml_model_decoder.get_rope_params();
231 if (tensor_map.find("inp_pos") == tensor_map.end() || rope_params == nullptr) {
232 return;
233 }
234 auto inp_pos = tensor_map.at("inp_pos").get_node_shared_ptr();
235 std::shared_ptr<ov::Node> rope_freqs_weight;
236 if (tensor_map.find("rope_freqs.weight") != tensor_map.end()) {
237 rope_freqs_weight = tensor_map.at("rope_freqs.weight").get_node_shared_ptr();
238 }
239
240 auto sin_cos = make_sin_cos(rope_params, inp_pos, rope_freqs_weight);
241 auto sin_theta = sin_cos.first;
242 auto cos_theta = sin_cos.second;
243
244 cos_theta.get_node_shared_ptr()->set_friendly_name("rope_cos");
245 sin_theta.get_node_shared_ptr()->set_friendly_name("rope_sin");
246 tensor_map.insert({"rope_cos", cos_theta});
247 tensor_map.insert({"rope_sin", sin_theta});
248}
249
250// Create common patterns
251void preprocess(TensorMap & tensor_map, GgmlDecoder & ggml_model_decoder) {
252 if (ggml_model_decoder.is_stateful()) {
253 add_sliced_mask_stateful(tensor_map, ggml_model_decoder.get_rope_params()[2] == GGML_ROPE_TYPE_IMROPE);
254 add_position_mask_stateful_swa(tensor_map);
255 }
256 // This optimization is error-prone
257 // add_rope_sin_cos(tensor_map, ggml_model_decoder);
258}
259
260} // namespace
261
262TranslateSession::TranslateSession(const frontend::InputModel::Ptr & input_model,
263 const std::unordered_map<std::string, CreatorFunction> & translator_map,
264 bool naive) :
265 m_input_model(input_model),
266 m_translator_map(translator_map),
267 m_ov_model(nullptr),
268 m_naive(naive) {}
269
270std::shared_ptr<Model> TranslateSession::get_converted_model() {
271 if (m_ov_model) {
272 return m_ov_model;
273 }
274 m_ov_model = translate_graph(m_input_model);
275 return m_ov_model;
276}
277
278std::shared_ptr<Model> TranslateSession::translate_graph(const frontend::InputModel::Ptr & input_model) {
279 ov::ParameterVector params;
280 ov::ResultVector results;
281 auto tensor_map = std::make_shared<TensorMap>();
282 std::shared_ptr<Model> resulting_model;
283
284 const auto & ggml_model = ov::as_type_ptr<InputModel>(input_model);
285 std::shared_ptr<GgmlDecoder> ggml_model_decoder = ggml_model->get_model_decoder();
286
287 for (const auto & it : ggml_model_decoder->get_model_inputs()) {
288 auto param_node = create_parameter(it.first, it.second);
289 params.push_back(param_node);
290 (*tensor_map)[it.first] = param_node;
291 }
292
293 for (const auto & it : ggml_model_decoder->get_model_extra_inputs()) {
294 auto input_node = create_extra_input(it.first, it.second);
295 if (it.second.is_parameter) {
296 params.push_back(ov::as_type_ptr<ov::op::v0::Parameter>(input_node));
297 }
298 (*tensor_map)[it.first] = input_node;
299 }
300
301 for (const auto & it : ggml_model_decoder->get_model_weights()) {
302 (*tensor_map)[it.first] = it.second;
303 }
304
305 auto translate_node = [&](const std::shared_ptr<GgmlDecoder> & decoder, int node_idx) {
306 auto operation_type = decoder->get_op_type(node_idx);
307 if (operation_type == "GGML_OP_NONE") {
308 return ov::OutputVector{};
309 }
310
311 const auto & node_output_names = decoder->get_output_names(node_idx);
312 if (operation_type == "GGML_OP_VIEW" && decoder->get_op_case(node_idx) == 2 && node_output_names.size() == 1) {
313 auto direct_output = tensor_map->find(node_output_names[0]);
314 if (direct_output != tensor_map->end()) {
315 // GDN publishes its native attention/state outputs under the two GGML VIEW names.
316 // Keep those mappings instead of rebuilding slices of a packed temporary.
317 return ov::OutputVector{direct_output->second};
318 }
319 }
320
321 auto it = m_translator_map.find(operation_type);
322 FRONT_END_OP_CONVERSION_CHECK(it != m_translator_map.end(), "Translation for operation type ", operation_type,
323 " is not implemented.");
324 NodeContext node_context(decoder, tensor_map, node_idx, this);
325 ov::OutputVector converted_outputs = it->second(node_context);
326
327 FRONT_END_OP_CONVERSION_CHECK(node_output_names.size() == converted_outputs.size(), "Number of ",
328 operation_type, " outputs greater than number of converted outputs, which are ",
329 node_output_names.size(), " and ", converted_outputs.size(), " respectively.");
330
331 for (size_t i = 0; i < node_output_names.size(); ++i) {
332 auto output_name = node_output_names[i];
333 if (i < converted_outputs.size() && converted_outputs[i].get_node_shared_ptr() != nullptr) {
334 (*tensor_map)[output_name] = converted_outputs[i];
335 }
336 }
337 return converted_outputs;
338 };
339
340 // To handle cases like this
341 // 3: [ 18432, 1, 1, 1] RESHAPE cache_r_l0 (reshaped)#3
342 // [ 18432, 1, 1, 1] 0: NONE cache_r_l0
343 // 4: [ 0, 1, 1, 1] VIEW cache_r_l0 (reshaped) (view)#4
344 // [ 18432, 1, 1, 1] 0: RESHAPE cache_r_l0 (reshaped)#3
345 // 5: [ 0, 1, 1, 1] SCALE cache_r_l0 (reshaped) (view) (view)#5
346 // [ 0, 1, 1, 1] 0: VIEW cache_r_l0 (reshaped) (view)#4
347 // 6: [ 1, 1, 1, 1] VIEW (view)#6
348 // [ 1, 1, 1, 1] 0: NONE leaf_5
349 // 7: [ 18432, 1, 1, 1] GET_ROWS conv_states-0#7
350 // [ 18432, 1, 1, 1] 0: RESHAPE cache_r_l0 (reshaped)#3
351 // [ 1, 1, 1, 1] 1: VIEW (view)#6
352 // The scale is in-place which modifies cache_r_l0 (reshaped)#3
353 // The translation of scale overwrites cache_r in the tensor_map,
354 // but we also need to overwrite the old cache_r_l0 (reshaped)#3
355 auto refresh_inplace_aliases = [&](const std::shared_ptr<GgmlDecoder> & decoder, int inplace_node_idx,
356 const std::string & view_src_name) {
357 for (int node_idx = 0; node_idx < inplace_node_idx; node_idx++) {
358 if (decoder->is_view_like_alias_of(node_idx, view_src_name)) {
359 translate_node(decoder, node_idx);
360 }
361 }
362 };
363
364 auto node_visitor = [&](const std::shared_ptr<GgmlDecoder> & decoder, int node_idx) {
365 auto converted_outputs = translate_node(decoder, node_idx);
366 if (converted_outputs.empty()) {
367 return;
368 }
369 const auto inplace_src = decoder->get_inplace_op_src(node_idx);
370 if (inplace_src.empty()) {
371 return;
372 }
373 if (converted_outputs[0].get_node_shared_ptr() != nullptr) {
374 (*tensor_map)[inplace_src] = converted_outputs[0];
375 }
376 refresh_inplace_aliases(decoder, node_idx, inplace_src);
377 };
378
379 if (!m_naive) {
380 preprocess(*tensor_map, *ggml_model_decoder);
381 }
382 ggml_model_decoder->visit_subgraph(node_visitor);
383
384 for (const auto & name : ggml_model_decoder->get_model_output_names()) {
385 FRONT_END_GENERAL_CHECK(tensor_map->find(name) != tensor_map->end(),
386 "Output name not found in tensor map: ", name);
387 auto result = std::make_shared<v0::Result>(tensor_map->at(name));
388 result->set_friendly_name(name);
389 results.push_back(result);
390 }
391
392 // Debug-only hook: GGML_OPENVINO_DEBUG_NODE=<name1>,<name2>,... adds extra
393 // Result nodes for arbitrary intermediate tensors (looked up by name in
394 // tensor_map), on top of the real model outputs above. These debug
395 // Results are deliberately NOT added to ggml_decoder's model outputs, so
396 // the caller (ov_graph_compute_dynamic in utils.cpp) will not bind them
397 // to any ggml tensor buffer -- OpenVINO allocates its own tensor for
398 // them. This avoids the risk of reading a ggml buffer that has since
399 // been overwritten by a later in-place op (ggml aggressively reuses
400 // buffers), which can happen if trying to inspect an intermediate value
401 // via GGML_OPENVINO_DEBUG_OUTPUT by hacking it into a real output.
402 //
403 // tensor_map keys are usually the plain ggml tensor name (e.g. "embd"),
404 // but tensors that are recomputed multiple times in the same cgraph
405 // (GGML_TENSOR_FLAG_COMPUTE) are disambiguated with a "#<hash>" suffix
406 // (e.g. "cache_k_l0#4853", see get_tensor_ov_name()) which is not
407 // predictable ahead of time. To keep the env var usable, a requested
408 // name is matched either exactly, or as the "name" part before "#" of a
409 // suffixed key (first match wins; ambiguous requests should include the
410 // full "name#hash" form seen in a previous run's log/dump).
411 if (const char * debug_nodes = ggml_openvino_getenv_str("GGML_OPENVINO_DEBUG_NODE")) {
412 std::stringstream ss(debug_nodes);
413 std::string name;
414 while (std::getline(ss, name, ',')) {
415 auto it = tensor_map->find(name);
416 if (it == tensor_map->end()) {
417 it = std::find_if(tensor_map->begin(), tensor_map->end(), [&](const auto & entry) {
418 return entry.first.compare(0, name.size(), name) == 0 && entry.first.size() > name.size() &&
419 entry.first[name.size()] == '#';
420 });
421 }
422 if (it == tensor_map->end()) {
423 GGML_LOG_WARN("GGML_OPENVINO_DEBUG_NODE: node '%s' not found in tensor map, skipping\n", name.c_str());
424 continue;
425 }
426 auto result = std::make_shared<v0::Result>(it->second);
427 result->set_friendly_name("__debug_" + it->first);
428 results.push_back(result);
429 }
430 }
431
432 ov::ParameterVector used_params;
433 for (const auto & param : params) {
434 if (!param->output(0).get_target_inputs().empty()) {
435 used_params.push_back(param);
436 }
437 }
438 // if (auto diff = params.size() - used_params.size()) {
439 // GGML_LOG_INFO("%zu parameters are not used in the model.", diff);
440 // }
441 resulting_model = std::make_shared<Model>(results, used_params);
442
443 apply_transformations(resulting_model);
444
445 // Set WeightlessCacheAttribute on large constants to avoid unnecessary memory copies
446 // in the NPUW plugin. Without this attribute, NPUW's LazyTensor constructor
447 // (lazy_tensor.cpp, op::Const::Const) will memcpy every constant "in case export
448 // occurs", doubling memory usage per compile_model call.
449 //
450 // The bin_offset field serves as a unique key (not a real file offset) — this is
451 // the same convention the GPU plugin uses for non-IR models (see
452 // Plugin::set_weightless_cache_attributes in intel_gpu/src/plugin/plugin.cpp).
453 // Each constant must have a distinct bin_offset, otherwise GPU's weightless cache
454 // import will map multiple constants to the same data.
455 //
456 // Small constants (< 16 elements) are excluded since they may be introduced by
457 // optimization patterns and the overhead is negligible.
458 //
459 // Note: use shape_size() rather than byte_size()/element_type().size() - GatherMatmul's default
460 // bias is a Constant(element::dynamic, Shape{0}), whose element_type().size() is 0 and would
461 // divide by zero.
462 size_t offset = 0;
463 for (auto & node : resulting_model->get_ordered_ops()) {
464 if (auto cnst = ov::as_type_ptr<ov::op::v0::Constant>(node); cnst && ov::shape_size(cnst->get_shape()) >= 16) {
465 auto & rt_info = cnst->get_rt_info();
466 if (rt_info.find(ov::WeightlessCacheAttribute::get_type_info_static()) == rt_info.end()) {
467 rt_info[ov::WeightlessCacheAttribute::get_type_info_static()] =
468 ov::WeightlessCacheAttribute(cnst->get_byte_size(), offset++, cnst->get_element_type());
469 }
470 }
471 }
472 return resulting_model;
473}
474
475std::shared_ptr<Model> TranslateSession::apply_transformations(std::shared_ptr<Model> model) {
476 auto ggml_model_decoder = ov::as_type_ptr<InputModel>(m_input_model)->get_model_decoder();
477 {
478 ov::pass::Manager manager;
479 manager.set_per_pass_validation(true);
480 manager.register_pass<ov::pass::MarkCompressedFloatConstants>();
481 // Marks the Convert/Subtract/Multiply nodes of our GatherMatmul dequantization chain
482 // (make_int4_weights/make_int8_weights, for_gather_matmul=true) with disable_constant_folding,
483 // so it survives ConstantFolding regardless of whether the target plugin's own
484 // is_decompression_multiply() recognizes GatherMatmul as a valid consumer.
485 manager.register_pass<ov::pass::MarkDequantization>(
486 std::vector<ov::element::Type>{ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4});
487 manager.register_pass<pass::FuseToConv>();
488 manager.register_pass<pass::FuseArgsortTopK>();
489
490 // MOECompressed has no CPU plugin implementation, so enable it by default only on GPU.
491 // GGML_OPENVINO_MOE_OP=0 keeps the unfused GatherMatmul path for fallback/debugging.
492 if (ggml_openvino_is_gpu() &&
493 ggml_openvino_getenv_int("GGML_OPENVINO_MOE_OP", 1) != 0) {
494 manager.register_pass<pass::FuseMoeRouter>();
495 manager.register_pass<pass::FuseMoeCompressed>();
496 // Same fusion for models whose gate and up projections share one fused expert
497 // weight (gemma-4). It only matches that shape and only when the experts carry an
498 // integer zero point, so it is a no-op on the separate-gate/up models above.
499 manager.register_pass<pass::FuseMoeCompressedFusedGateUp>();
500 }
501
502 // Workaround for an OpenVINO GPU-plugin defect: an eltwise op whose operands differ in
503 // rank is computed wrongly once the plugin fuses it as a post-op into `rms`. gemma-4
504 // dense under stateful execution adds a rank-3 residual to the rank-4 norm output and
505 // decodes garbage on GPU while CPU is correct. Equalising the ranks is a no-op for
506 // NUMPY broadcasting and makes the fused path correct.
507 // Remove once the plugin guards that fusion. Opt out with
508 // GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN=1.
509 if (ggml_openvino_is_gpu() && !ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_ELTWISE_RANK_ALIGN")) {
510 manager.register_pass<pass::AlignEltwiseOperandRanks>();
511 }
512
513 if (ggml_model_decoder->is_stateful()) {
514 const auto kv_param_res_names = ggml_model_decoder->get_kv_param_res_names();
515 const auto kv_param_res_pairs = get_kv_param_res_pairs(model, kv_param_res_names);
516 manager.register_pass<ov::pass::MakeStateful>(kv_param_res_pairs);
517 // Must run after MakeStateful, which is what creates the ReadValue/Assign pairs.
518 if (!ggml_openvino_getenv_int("GGML_OPENVINO_DISABLE_KV_STATE_RELAYOUT")) {
519 manager.register_pass<pass::KVStateSeqAxis>();
520 }
521 }
522
523 if (ggml_model_decoder->is_static()) {
524 manager.register_pass<pass::SqueezeMatmul>();
525 }
526 manager.run_passes(model);
527 if (ggml_model_decoder->is_stateful()) {
528 ov::preprocess::PrePostProcessor ppp(model);
529 for (size_t i = 0; i < model->get_output_size(); i++) {
530 auto model_output_shape = model->output(i).get_partial_shape();
531 if (model_output_shape.rank().is_static() && model_output_shape.rank().get_length() == 3) {
532 ppp.output(i).postprocess().custom([](const ov::Output<ov::Node>& node) {
533 auto axes = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0});
534 return std::make_shared<ov::op::v0::Unsqueeze>(node, axes);
535 });
536 }
537 }
538 model = ppp.build();
539 }
540 }
541 return model;
542}
543
544} // namespace ggml
545} // namespace frontend
546} // namespace ov