OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[GGUF] Simplify GGUFMakeStateful and AdaptToGenAI passes (#37813)
Maxim Vafinc13c670d775e
diff --git a/src/frontends/gguf/src/pass/adapt_to_genai.cpp b/src/frontends/gguf/src/pass/adapt_to_genai.cppindex f37ac639f66..a9908d6f0c6 100644--- a/src/frontends/gguf/src/pass/adapt_to_genai.cpp+++ b/src/frontends/gguf/src/pass/adapt_to_genai.cpp@@ -5,7 +5,6 @@#include "openvino/frontend/gguf/adapt_to_genai.hpp"#include <memory>-#include <unordered_map>#include "openvino/core/rt_info.hpp"#include "openvino/frontend/gguf/make_stateful.hpp"@@ -30,12 +29,12 @@#include "openvino/op/squeeze.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/tile.hpp"-#include "openvino/op/transpose.hpp"#include "openvino/op/unsqueeze.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "openvino/runtime/properties.hpp"+#include "utils.hpp"namespace ov {namespace frontend {@@ -49,10 +48,6 @@ using std::make_shared;// f16 lowest, matches genai's causal-mask "-inf" fill.constexpr float NEG_INF = -65504.0f;-std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t>& values) {- return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);-}-// translate_get_rows's embedding-table lookup restores ggml's rank-4 form with a fixed// Unsqueeze(axis=0), pinning the residual stream's leading axis to a literal 1 regardless of// backend -- correct for SDPA, but wrong once SDPAToPagedAttention rewrites input_ids to rank-1@@ -73,7 +68,8 @@ std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t>& valuclass FixEmbdAxis : public ov::pass::MatcherPass {public:FixEmbdAxis() {- auto p_unsqueeze = ov::pass::pattern::wrap_type<ov::op::v0::Unsqueeze>();+ using namespace ov::op;+ auto p_unsqueeze = ov::pass::pattern::wrap_type<v0::Unsqueeze>();ov::matcher_pass_callback callback = [](ov::pass::pattern::Matcher& m) {auto unsqueeze = m.get_match_root();@@ -82,10 +78,10 @@ public:// Unsqueeze (output dtype mismatch); look through it structurally instead of// relying on naming.auto node = unsqueeze->input_value(0).get_node_shared_ptr();- if (auto convert = ov::as_type_ptr<ov::op::v0::Convert>(node)) {+ if (auto convert = ov::as_type_ptr<v0::Convert>(node)) {node = convert->input_value(0).get_node_shared_ptr();}- auto gather = ov::as_type_ptr<ov::op::v8::Gather>(node);+ auto gather = ov::as_type_ptr<v8::Gather>(node);if (!gather) {return false;}@@ -95,16 +91,17 @@ public:// actually rooted at the "inp_tokens" parameter, not some unrelated Gather/Unsqueeze// pair elsewhere in the graph (e.g. FixInpOutIdsRowSelect's call sites).auto indices_node = gather->input_value(1).get_node_shared_ptr();- if (auto squeeze = ov::as_type_ptr<ov::op::v0::Squeeze>(indices_node)) {+ if (auto squeeze = ov::as_type_ptr<v0::Squeeze>(indices_node)) {indices_node = squeeze->input_value(0).get_node_shared_ptr();}- auto param = ov::as_type_ptr<ov::op::v0::Parameter>(indices_node);+ auto param = ov::as_type_ptr<v0::Parameter>(indices_node);if (!param || param->output(0).get_names().count("inp_tokens") == 0) {return false;}auto res = unsqueeze->input_value(0); // Gather's (or Convert's) output, rank 3- auto fixed = make_shared<ov::op::v0::Unsqueeze>(res, const_i64({1}));+ auto axis_1 = v0::Constant::create(ov::element::i64, {1}, {1});+ auto fixed = make_shared<v0::Unsqueeze>(res, axis_1);fixed->set_friendly_name(unsqueeze->get_friendly_name());ov::copy_runtime_info(unsqueeze, fixed);unsqueeze->output(0).replace(fixed->output(0));@@ -123,16 +120,17 @@ public:class FixInpOutIdsRowSelect : public ov::pass::MatcherPass {public:FixInpOutIdsRowSelect() {+ using namespace ov::op;using ov::pass::pattern::any_input;using ov::pass::pattern::wrap_type;- auto p_inp_out_ids = wrap_type<ov::op::v0::Parameter>([](const ov::Output<ov::Node>& output) -> bool {+ auto p_inp_out_ids = wrap_type<v0::Parameter>([](const ov::Output<ov::Node>& output) -> bool {return output.get_names().count("inp_out_ids") != 0;});- auto p_indices_squeeze = wrap_type<ov::op::v0::Squeeze>({p_inp_out_ids, any_input()});- auto p_data_squeeze = wrap_type<ov::op::v0::Squeeze>({any_input(), any_input()});- auto p_gather = wrap_type<ov::op::v8::Gather>({p_data_squeeze, p_indices_squeeze, any_input()});- auto p_unsqueeze = wrap_type<ov::op::v0::Unsqueeze>({p_gather, any_input()});+ auto p_indices_squeeze = wrap_type<v0::Squeeze>({p_inp_out_ids, any_input()});+ auto p_data_squeeze = wrap_type<v0::Squeeze>({any_input(), any_input()});+ auto p_gather = wrap_type<v8::Gather>({p_data_squeeze, p_indices_squeeze, any_input()});+ auto p_unsqueeze = wrap_type<v0::Unsqueeze>({p_gather, any_input()});ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {const auto& pm = m.get_pattern_value_map();@@ -142,11 +140,13 @@ public:auto data = data_squeeze->input_value(0); // the original, un-squeezed activationconst int64_t hidden = data.get_partial_shape()[3].get_length();- auto data_flat = make_shared<ov::op::v1::Reshape>(data, const_i64({-1, hidden}), false);- auto indices_flat =- make_shared<ov::op::v1::Reshape>(indices_squeeze->input_value(0), const_i64({-1, 1}), false);- auto fixed_res = make_shared<ov::op::v8::Gather>(data_flat, indices_flat, const_i64({0}));- auto fixed_unsqueeze = make_shared<ov::op::v0::Unsqueeze>(fixed_res, const_i64({0}));+ auto data_flat_shape = v0::Constant::create(ov::element::i64, {2}, std::vector<int64_t>{-1, hidden});+ auto data_flat = make_shared<v1::Reshape>(data, data_flat_shape, false);+ auto indices_flat_shape = v0::Constant::create(ov::element::i64, {2}, {-1, 1});+ auto indices_flat = make_shared<v1::Reshape>(indices_squeeze->input_value(0), indices_flat_shape, false);+ auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});+ auto fixed_res = make_shared<v8::Gather>(data_flat, indices_flat, axis0);+ auto fixed_unsqueeze = make_shared<v0::Unsqueeze>(fixed_res, axis0);fixed_unsqueeze->set_friendly_name(unsqueeze->get_friendly_name());ov::copy_runtime_info(unsqueeze, fixed_unsqueeze);unsqueeze->output(0).replace(fixed_unsqueeze->output(0));@@ -157,17 +157,6 @@ public:}};-// Find a Parameter whose output tensor names (or friendly name) match `name`.-std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model, const std::string& name) {- for (const auto& p : model->get_parameters()) {- const auto& names = p->output(0).get_names();- if (names.count(name) || p->get_friendly_name() == name) {- return p;- }- }- return nullptr;-}-void name_output(const ov::Output<ov::Node>& out, const std::string& name) {out.get_node_shared_ptr()->set_friendly_name(name);out.get_node_shared_ptr()->output(0).set_names({name});@@ -196,6 +185,7 @@ int64_t max_kv_cache_head_size(const std::shared_ptr<ov::Model>& model) {} // namespacebool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {+ using namespace ov::op;OPENVINO_ASSERT(m_mode == InputMode::IDS_TO_LOGITS,"[gguf] AdaptToGenAI: only InputMode::IDS_TO_LOGITS is implemented; ""EMBEDS_TO_LOGITS (VLM language model) is reserved for future work.");@@ -203,10 +193,10 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// The gguf inputs we rewire. inp_tokens/inp_pos/self_kq_mask/token_len_per_seq are// required; if they are absent the model is not a gguf-IO model (e.g. already adapted),// so this pass is a no-op.- auto inp_tokens = find_param(model, "inp_tokens");- auto inp_pos = find_param(model, "inp_pos");- auto self_kq_mask = find_param(model, "self_kq_mask");- auto token_len_per_seq = find_param(model, "token_len_per_seq");+ auto inp_tokens = find_parameter(model, "inp_tokens");+ auto inp_pos = find_parameter(model, "inp_pos");+ auto self_kq_mask = find_parameter(model, "self_kq_mask");+ auto token_len_per_seq = find_parameter(model, "token_len_per_seq");if (!inp_tokens || !inp_pos || !self_kq_mask || !token_len_per_seq) {return false;}@@ -219,17 +209,17 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {self_correcting_axis_manager.run_passes(model);// ---- new genai inputs: input_ids / attention_mask / position_ids [b, seq] i64 ----- auto input_ids = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ auto input_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});name_output(input_ids, "input_ids");- auto attention_mask = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ auto attention_mask = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});name_output(attention_mask, "attention_mask");- auto position_ids = make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ auto position_ids = make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});name_output(position_ids, "position_ids");// beam_idx (i32 [D]) is added by the make-stateful pass, next to the Gather that reads it; genai// sets it via set_tensor("beam_idx"). Keep that Parameter so its wiring is preserved. Its absence// means the model is not stateful, which the genai contract requires.- auto beam_idx = find_param(model, "beam_idx");+ auto beam_idx = find_parameter(model, "beam_idx");OPENVINO_ASSERT(beam_idx,"[gguf] AdaptToGenAI: model has no 'beam_idx' input, so it is not stateful. ""Register a make-stateful transformation extension (e.g. "@@ -241,8 +231,9 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// and splices an Unsqueeze(axis=1) in front of its consumers, making it [tokens, 1]. Reading// dim 1 would then yield 1 for every prompt, collapsing the causal mask and the logits to a// single token; reading dim 0 breaks the un-rewritten case. ReduceProd is correct under both.- auto ids_shape = make_shared<ov::op::v3::ShapeOf>(input_ids, ov::element::i64);- auto seq_len = make_shared<ov::op::v1::ReduceProd>(ids_shape, const_i64({0}), true); // [1]+ auto ids_shape = make_shared<v3::ShapeOf>(input_ids, ov::element::i64);+ auto reduce_axis_0 = v0::Constant::create(ov::element::i64, {1}, {0});+ auto seq_len = make_shared<v1::ReduceProd>(ids_shape, reduce_axis_0, true); // [1]token_len_per_seq->output(0).replace(seq_len->output(0));// The two gguf rank-4 input kinds carry the (batch, tokens) pair on different axes, so they get@@ -255,66 +246,71 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// indices must present exactly the Parameter's own [batch, seq]: prepend two 1s.// SDPA: [1,1,1,tokens] -> squeeze -> [1,tokens] -> embd [1,tokens,n_embd]// PA : [1,1,tokens,1] -> squeeze -> [tokens,1] -> embd [tokens,1,n_embd]- const auto shape_1_1_batch_seq = make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), ids_shape}, 0);+ auto ones_1_1 = v0::Constant::create(ov::element::i64, {2}, {1, 1});+ const auto shape_1_1_batch_seq = make_shared<v0::Concat>(ov::OutputVector{ones_1_1, ids_shape}, 0);// ACTIVATION-like inputs (inp_pos): consumed by make_sin_cos, which transposes {0,3,1,2} to put// the token axis at 1, yielding cos/sin [batch, tokens, 1, n_rot/2] that broadcast against the// roped [batch, heads, tokens, head_size]. special_zero's 0 copies dim 0 and -1 absorbs the rest.// SDPA: [1,1,1,tokens] -> cos/sin [1,tokens,1,half]// PA : [tokens,1,1,1] -> cos/sin [tokens,1,1,half], which broadcasts against [tokens,H,1,S]- const auto shape_keep0_1_1_rest = const_i64({0, 1, 1, -1});+ const auto shape_keep0_1_1_rest = v0::Constant::create(ov::element::i64, {4}, {0, 1, 1, -1});- auto tokens_i32 = make_shared<ov::op::v0::Convert>(input_ids, ov::element::i32);- auto tokens_4d = make_shared<ov::op::v1::Reshape>(tokens_i32, shape_1_1_batch_seq, false);+ auto tokens_i32 = make_shared<v0::Convert>(input_ids, ov::element::i32);+ auto tokens_4d = make_shared<v1::Reshape>(tokens_i32, shape_1_1_batch_seq, false);inp_tokens->output(0).replace(tokens_4d->output(0));- ov::Output<ov::Node> pos_i32 = make_shared<ov::op::v0::Convert>(position_ids, ov::element::i32);+ ov::Output<ov::Node> pos_i32 = make_shared<v0::Convert>(position_ids, ov::element::i32);// M-RoPE (qwen35): inp_pos carries FOUR position sections per token, laid out section-major --// make_sin_cos reshapes it to {..,4,tokens} and transposes. GenAI supplies one position per// token, so tile it 4x along the token axis. All four sections hold the same value here: the// per-section split only differs for image/video input, and a text-only prompt has no spatial// axes to differ on (llama.cpp fills all sections with the text position likewise).if (model->get_rt_info().count(gguf_imrope_key())) {- auto tile_repeats = const_i64({1, 4});- pos_i32 = make_shared<ov::op::v0::Tile>(pos_i32, tile_repeats);+ auto tile_repeats = v0::Constant::create(ov::element::i64, {2}, {1, 4});+ pos_i32 = make_shared<v0::Tile>(pos_i32, tile_repeats);}- auto pos_4d = make_shared<ov::op::v1::Reshape>(pos_i32, shape_keep0_1_1_rest, true);+ auto pos_4d = make_shared<v1::Reshape>(pos_i32, shape_keep0_1_1_rest, true);inp_pos->output(0).replace(pos_4d->output(0));// ---- self_kq_mask [1,1,seq,kv_len] f32: 0 where attended, -inf above causal ----// kv_len = attention_mask length (= past + seq). query absolute positions = position_ids[0].- auto am_shape = make_shared<ov::op::v3::ShapeOf>(attention_mask, ov::element::i64);- auto kv_len = make_shared<ov::op::v8::Gather>(am_shape, const_i64({1}), const_i64({0})); // [1]+ auto am_shape = make_shared<v3::ShapeOf>(attention_mask, ov::element::i64);+ ov::Output<ov::Node> kv_len = get_dimensions(am_shape, {1}); // [1]// Flatten position_ids to [seq] via a shape-independent Reshape({-1}) rather than Squeeze(axis=0):// PA also rewrites position_ids to rank-1 and Unsqueezes it to [seq,1], where squeezing axis 0// would fail (or drop the wrong axis).- auto q_pos =- make_shared<ov::op::v0::Convert>(make_shared<ov::op::v1::Reshape>(position_ids, const_i64({-1}), false),- ov::element::i32); // [seq]- auto q_pos_col =- make_shared<ov::op::v1::Reshape>(q_pos,- make_shared<ov::op::v0::Concat>(ov::OutputVector{seq_len, const_i64({1})}, 0),- false); // [seq, 1]-- auto zero_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});- auto one_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});- auto kv_len_i32 = make_shared<ov::op::v0::Squeeze>(make_shared<ov::op::v0::Convert>(kv_len, ov::element::i32),- const_i64({0})); // scalar- auto k_range = make_shared<ov::op::v4::Range>(zero_i32, kv_len_i32, one_i32, ov::element::i32); // [kv_len]- auto k_row =- make_shared<ov::op::v1::Reshape>(k_range,- make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1}), kv_len}, 0),- false); // [1, kv_len]-- auto allowed = make_shared<ov::op::v1::LessEqual>(k_row, q_pos_col); // [seq, kv_len] bool- auto zero_f = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});- auto neg_f = ov::op::v0::Constant::create(ov::element::f32, ov::Shape{}, {NEG_INF});- auto mask2d = make_shared<ov::op::v1::Select>(allowed, zero_f, neg_f); // [seq, kv_len] f32- auto mask_4d = make_shared<ov::op::v1::Reshape>(- mask2d,- make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), seq_len, kv_len}, 0),- false); // [1, 1, seq, kv_len]+ auto flat_shape = v0::Constant::create(ov::element::i64, {1}, {-1});+ auto q_pos = make_shared<v0::Convert>(make_shared<v1::Reshape>(position_ids, flat_shape, false),+ ov::element::i32); // [seq]+ auto one_1 = v0::Constant::create(ov::element::i64, {1}, {1});+ auto q_pos_col = make_shared<v1::Reshape>(q_pos,+ make_shared<v0::Concat>(ov::OutputVector{seq_len, one_1}, 0),+ false); // [seq, 1]++ auto zero_i32 = v0::Constant::create(ov::element::i32, ov::Shape{}, {0});+ auto one_i32 = v0::Constant::create(ov::element::i32, ov::Shape{}, {1});+ auto squeeze_axis_0 = v0::Constant::create(ov::element::i64, {1}, {0});+ auto kv_len_i32 = make_shared<v0::Squeeze>(make_shared<v0::Convert>(kv_len, ov::element::i32),+ squeeze_axis_0); // scalar+ auto k_range = make_shared<v4::Range>(zero_i32, kv_len_i32, one_i32, ov::element::i32); // [kv_len]+ auto k_row = make_shared<v1::Reshape>(k_range,+ make_shared<v0::Concat>(ov::OutputVector{one_1, kv_len}, 0),+ false); // [1, kv_len]++ auto zero_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {0.0f});+ auto neg_f = v0::Constant::create(ov::element::f32, ov::Shape{}, {NEG_INF});+ // [seq, kv_len] boolean predicate -> [1, 1, seq, kv_len] f32 mask (0 where attended, -inf elsewhere).+ auto to_mask_4d = [&](const ov::Output<ov::Node>& allowed_pred) {+ auto mask2d = make_shared<v1::Select>(allowed_pred, zero_f, neg_f); // [seq, kv_len] f32+ return make_shared<v1::Reshape>(mask2d,+ make_shared<v0::Concat>(ov::OutputVector{ones_1_1, seq_len, kv_len}, 0),+ false); // [1, 1, seq, kv_len]+ };++ auto allowed = make_shared<v1::LessEqual>(k_row, q_pos_col); // [seq, kv_len] bool+ auto mask_4d = to_mask_4d(allowed);self_kq_mask->output(0).replace(mask_4d->output(0));// Sliding-window mask: for prompts within the window this equals the full causal mask, but@@ -325,22 +321,17 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// [q - window + 1, q]. Absent a recorded length (e.g. gpt-oss/gemma4, whose SWA is described// by sinks / a per-layer pattern with no accompanying token count here), fall back to the// full causal mask, matching the previous behavior.- if (auto self_kq_mask_swa = find_param(model, "self_kq_mask_swa")) {+ if (auto self_kq_mask_swa = find_parameter(model, "self_kq_mask_swa")) {ov::Output<ov::Node> swa_mask_4d = mask_4d->output(0);const auto& rt_info = model->get_rt_info();const auto swa_it = rt_info.find(gguf_swa_window_key());if (swa_it != rt_info.end()) {const auto window = swa_it->second.as<int64_t>();- auto window_m1 =- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {static_cast<int32_t>(window - 1)});- auto window_start = make_shared<ov::op::v1::Subtract>(q_pos_col, window_m1); // [seq, 1]- auto within_window = make_shared<ov::op::v1::GreaterEqual>(k_row, window_start); // [seq, kv_len]- auto allowed_swa = make_shared<ov::op::v1::LogicalAnd>(allowed, within_window); // [seq, kv_len]- auto mask2d_swa = make_shared<ov::op::v1::Select>(allowed_swa, zero_f, neg_f); // [seq, kv_len]- swa_mask_4d = make_shared<ov::op::v1::Reshape>(- mask2d_swa,- make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), seq_len, kv_len}, 0),- false); // [1, 1, seq, kv_len]+ auto window_m1 = v0::Constant::create(ov::element::i32, ov::Shape{}, {static_cast<int32_t>(window - 1)});+ auto window_start = make_shared<v1::Subtract>(q_pos_col, window_m1); // [seq, 1]+ auto within_window = make_shared<v1::GreaterEqual>(k_row, window_start); // [seq, kv_len]+ auto allowed_swa = make_shared<v1::LogicalAnd>(allowed, within_window); // [seq, kv_len]+ swa_mask_4d = to_mask_4d(allowed_swa);}self_kq_mask_swa->output(0).replace(swa_mask_4d);}@@ -355,33 +346,28 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// (batch_dim=1), giving the single global index tokens - 1. Under SDPAToPagedAttention it is// [tokens, 1] (batch_dim=tokens, seq_dim=1), giving indices [0, 1, .., tokens - 1] -- the// identity that layout needs, since it already carries one token per row.- if (auto inp_out_ids = find_param(model, "inp_out_ids")) {- auto batch_dim =- make_shared<ov::op::v8::Gather>(ids_shape, const_i64({0}), const_i64({0})); // [1]: ids_shape[0]- auto seq_dim = make_shared<ov::op::v8::Gather>(ids_shape, const_i64({1}), const_i64({0})); // [1]: ids_shape[1]- auto seq_dim_i32 = make_shared<ov::op::v0::Convert>(seq_dim, ov::element::i32);- auto last_index = make_shared<ov::op::v1::Subtract>(- seq_dim_i32,- ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1})); // [1]: seq_dim - 1+ if (auto inp_out_ids = find_parameter(model, "inp_out_ids")) {+ ov::Output<ov::Node> batch_dim = get_dimensions(ids_shape, {0}); // [1]: ids_shape[0]+ auto seq_dim = get_dimensions(ids_shape, {1}); // [1]: ids_shape[1]+ auto seq_dim_i32 = make_shared<v0::Convert>(seq_dim, ov::element::i32);+ auto last_index =+ make_shared<v1::Subtract>(seq_dim_i32,+ v0::Constant::create(ov::element::i32, ov::Shape{1}, {1})); // [1]: seq_dim - 1auto batch_dim_scalar =- make_shared<ov::op::v0::Squeeze>(make_shared<ov::op::v0::Convert>(batch_dim, ov::element::i32),- const_i64({0}));- auto zero_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {0});- auto one_i32 = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {1});- auto row_ids = make_shared<ov::op::v4::Range>(zero_i32,- batch_dim_scalar,- one_i32,- ov::element::i32); // [batch_dim]: 0 .. batch_dim - 1- auto global_index = make_shared<ov::op::v1::Add>(make_shared<ov::op::v1::Multiply>(row_ids, seq_dim_i32),- last_index); // [batch_dim]- auto out_grid = make_shared<ov::op::v1::Reshape>(- global_index,- make_shared<ov::op::v0::Concat>(ov::OutputVector{batch_dim, const_i64({1})}, 0),- false); // [batch, 1]- auto out_ids = make_shared<ov::op::v1::Reshape>(- out_grid,- make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, 1}), batch_dim, const_i64({1})}, 0),- false);+ make_shared<v0::Squeeze>(make_shared<v0::Convert>(batch_dim, ov::element::i32), squeeze_axis_0);+ auto row_ids = make_shared<v4::Range>(zero_i32,+ batch_dim_scalar,+ one_i32,+ ov::element::i32); // [batch_dim]: 0 .. batch_dim - 1+ auto global_index = make_shared<v1::Add>(make_shared<v1::Multiply>(row_ids, seq_dim_i32),+ last_index); // [batch_dim]+ auto out_grid = make_shared<v1::Reshape>(global_index,+ make_shared<v0::Concat>(ov::OutputVector{batch_dim, one_1}, 0),+ false); // [batch, 1]+ auto out_ids =+ make_shared<v1::Reshape>(out_grid,+ make_shared<v0::Concat>(ov::OutputVector{ones_1_1, batch_dim, one_1}, 0),+ false);inp_out_ids->output(0).replace(out_ids->output(0));}@@ -392,15 +378,13 @@ bool AdaptToGenAI::run_on_model(const std::shared_ptr<ov::Model>& model) {// contract this pass targets; token_len_per_seq above is likewise a whole-input token count.)auto old_result = model->get_results()[0];auto logits_src = old_result->input_value(0);- auto vocab = make_shared<ov::op::v8::Gather>(make_shared<ov::op::v3::ShapeOf>(logits_src, ov::element::i64),- const_i64({-1}),- const_i64({0})); // [1]- auto logits_3d = make_shared<ov::op::v1::Reshape>(- logits_src,- make_shared<ov::op::v0::Concat>(ov::OutputVector{const_i64({1, -1}), vocab}, 0),- false); // [1, seq, vocab]+ auto vocab = get_dimensions(logits_src, {-1}); // [1]+ auto batch_seq_flat = v0::Constant::create(ov::element::i64, {2}, {1, -1});+ auto logits_3d = make_shared<v1::Reshape>(logits_src,+ make_shared<v0::Concat>(ov::OutputVector{batch_seq_flat, vocab}, 0),+ false); // [1, seq, vocab]name_output(logits_3d, "logits");- auto new_result = make_shared<ov::op::v0::Result>(logits_3d);+ auto new_result = make_shared<v0::Result>(logits_3d);new_result->set_friendly_name("logits");model->add_results({new_result});diff --git a/src/frontends/gguf/src/pass/make_stateful.cpp b/src/frontends/gguf/src/pass/make_stateful.cppindex 043843f62f2..d80da4e4f3e 100644--- a/src/frontends/gguf/src/pass/make_stateful.cpp+++ b/src/frontends/gguf/src/pass/make_stateful.cpp@@ -19,18 +19,25 @@#include "openvino/op/reshape.hpp"#include "openvino/op/result.hpp"#include "openvino/op/util/variable.hpp"+#include "utils.hpp"namespace ov::frontend::gguf::pass {namespace {-std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model, const std::string& name) {- for (const auto& p : model->get_parameters()) {- if (p->get_friendly_name() == name || p->output(0).get_names().count(name)) {- return p;- }+// The cache is no longer part of the model's IO once rewritten: its Parameter is now a ReadValue+// and its Result an Assign sink. Results must go first so the Parameters have no consumers left.+void finalize_stateful_rewrite(const std::shared_ptr<ov::Model>& model,+ const ov::ResultVector& results_to_remove,+ const ov::SinkVector& new_sinks,+ const ov::ParameterVector& params_to_remove) {+ for (const auto& r : results_to_remove) {+ model->remove_result(r);+ }+ model->add_sinks(new_sinks);+ for (const auto& p : params_to_remove) {+ model->remove_parameter(p);}- return nullptr;}// The axis the cache grows along. An un-preallocated cache Parameter states it by construction: it@@ -98,6 +105,7 @@ const std::string& gguf_swa_window_key() {// Their shapes are fully static, so the init is a real zeros Constant. Zero is also the correct// initial value: ggml starts a sequence with a zeroed conv window and delta matrix.static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& model) {+ using namespace ov::op;auto it = model->get_rt_info().find(gguf_recurrent_states_key());if (it == model->get_rt_info().end()) {return false;@@ -115,7 +123,7 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& modconst std::string& in_name = flat[i];const std::string& out_name = flat[i + 1];- auto param = find_param(model, in_name);+ auto param = find_parameter(model, in_name);if (!param) {continue; // already rewritten (a second run of this pass)}@@ -129,7 +137,7 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& mod// The Result holding this state's new value: the one whose producing node carries the// state's output name. The builder names that node after the state (see the VIEW cases),// which is why those names have to survive translation.- std::shared_ptr<ov::op::v0::Result> state_result;+ std::shared_ptr<v0::Result> state_result;for (const auto& r : model->get_results()) {const auto producer = r->get_input_node_shared_ptr(0);if (producer->get_friendly_name().find(out_name) != std::string::npos) {@@ -141,12 +149,12 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& modconst auto et = param->get_element_type();auto var = std::make_shared<ov::op::util::Variable>(ov::op::util::VariableInfo{ps, et, in_name});- auto init = ov::op::v0::Constant::create(et, ps.to_shape(), std::vector<float>(1, 0.0f));- auto read_value = std::make_shared<ov::op::v6::ReadValue>(init, var);+ auto init = v0::Constant::create(et, ps.to_shape(), std::vector<float>(1, 0.0f));+ auto read_value = std::make_shared<v6::ReadValue>(init, var);read_value->set_friendly_name(in_name);ov::replace_node(param, read_value);- new_sinks.push_back(std::make_shared<ov::op::v6::Assign>(state_result->input_value(0), var));+ new_sinks.push_back(std::make_shared<v6::Assign>(state_result->input_value(0), var));model->add_variables({var});results_to_remove.push_back(state_result);params_to_remove.push_back(param);@@ -155,27 +163,22 @@ static bool make_recurrent_states_stateful(const std::shared_ptr<ov::Model>& modif (params_to_remove.empty()) {return false;}- for (const auto& r : results_to_remove) {- model->remove_result(r);- }- model->add_sinks(new_sinks);- for (const auto& p : params_to_remove) {- model->remove_parameter(p);- }+ finalize_stateful_rewrite(model, results_to_remove, new_sinks, params_to_remove);return true;}bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {+ using namespace ov::op;// beam_idx reorders the past cache along the batch axis for beam search (identity at batch 1 /// beam_idx [0], but emitting it is what lets CPU's stateful_sdpa_fusion match). It belongs to// the STATE, so this pass owns it: it indexes an OpenVINO cache that ggml has no equivalent// of, so no decoder should declare it. Created here, next to its only consumer (the Gather// below); a model that already has one (a caller that declared it, or a second run of this// pass) keeps it.- auto beam_idx = find_param(model, m_beam_idx_name);+ auto beam_idx = find_parameter(model, m_beam_idx_name);const bool created_beam_idx = beam_idx == nullptr;if (created_beam_idx) {- beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{ov::Dimension()});+ beam_idx = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{ov::Dimension()});beam_idx->set_friendly_name(m_beam_idx_name);beam_idx->output(0).set_names({m_beam_idx_name});}@@ -189,7 +192,7 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {if (!set_rows) {continue;}- auto dst = ov::as_type_ptr<ov::op::v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());+ auto dst = ov::as_type_ptr<v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());if (dst && !m_skip_caches.count(dst->get_friendly_name())) {cache_writes.push_back(set_rows);}@@ -203,10 +206,12 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {ov::ParameterVector params_to_remove;ov::ResultVector results_to_remove;ov::SinkVector new_sinks;+ // Same beam_idx Gather axis for every cache; hoisted out of the loop below.+ auto axis0 = v0::Constant::create(ov::element::i64, ov::Shape{}, {0});for (const auto& set_rows : cache_writes) {auto new_rows = set_rows->input_value(0);- auto cache_param = ov::as_type_ptr<ov::op::v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());+ auto cache_param = ov::as_type_ptr<v0::Parameter>(set_rows->input_value(2).get_node_shared_ptr());const auto& cache_name = cache_param->get_friendly_name();const auto& ps = cache_param->get_partial_shape();const auto et = cache_param->get_element_type();@@ -241,8 +246,8 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {}// Empty init: required, not cosmetic -- CPU's MemoryInputSDPA aborts on a MemoryInput with// zero parent edges (see the header note).- auto init = ov::op::v0::Constant::create(et, init_shape, std::vector<float>{});- auto read_value = std::make_shared<ov::op::v6::ReadValue>(init, var);+ auto init = v0::Constant::create(et, init_shape, std::vector<float>{});+ auto read_value = std::make_shared<v6::ReadValue>(init, var);// The SetRows placeholder presents the new rows flattened to [.., 1, tokens, row_size] (see// translate_set_rows), which need not be the cache's own split of those same elements -- e.g.@@ -254,17 +259,14 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {for (int64_t i = 0; i < ps.rank().get_length(); ++i) {split_pattern.push_back(i < axis ? 0 : (i == axis ? -1 : ps[i].get_length()));}- new_rows = std::make_shared<ov::op::v1::Reshape>(- new_rows,- ov::op::v0::Constant::create(ov::element::i64, {split_pattern.size()}, split_pattern),- true);+ auto split_shape = v0::Constant::create(ov::element::i64, {split_pattern.size()}, split_pattern);+ new_rows = std::make_shared<v1::Reshape>(new_rows, split_shape, true);// Reorder the past by beam_idx before appending, so each beam continues its own history.- auto axis0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {0});- auto past = std::make_shared<ov::op::v8::Gather>(read_value, beam_idx, axis0);- auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{past, new_rows}, axis);+ auto past = std::make_shared<v8::Gather>(read_value, beam_idx, axis0);+ auto concat = std::make_shared<v0::Concat>(ov::OutputVector{past, new_rows}, axis);concat->set_friendly_name(set_rows->get_friendly_name());- new_sinks.push_back(std::make_shared<ov::op::v6::Assign>(concat, var));+ new_sinks.push_back(std::make_shared<v6::Assign>(concat, var));// The stateless graph returns each updated cache as a Result; in the stateful form the Assign// sink above takes that role, so those Results go. Identify them as the Results reading THIS@@ -272,7 +274,7 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {// names a cache's write after the cache itself. Collect them before replace_node, while the// SetRows is still the node they read.for (const auto& consumer : set_rows->output(0).get_target_inputs()) {- if (auto r = ov::as_type_ptr<ov::op::v0::Result>(consumer.get_node()->shared_from_this())) {+ if (auto r = ov::as_type_ptr<v0::Result>(consumer.get_node()->shared_from_this())) {results_to_remove.push_back(r);}}@@ -285,20 +287,12 @@ bool GGUFMakeStateful::run_on_model(const std::shared_ptr<ov::Model>& model) {params_to_remove.push_back(cache_param);}- // The cache is no longer part of the model's IO: its Parameter is now a ReadValue and its Result- // an Assign sink. Remove the Results first so the Parameters have no consumers left.- for (const auto& r : results_to_remove) {- model->remove_result(r);- }- model->add_sinks(new_sinks);// Only now, having actually built the Gathers that read it -- so a pass that converted nothing// adds no input.if (created_beam_idx) {model->add_parameters({beam_idx});}- for (const auto& p : params_to_remove) {- model->remove_parameter(p);- }+ finalize_stateful_rewrite(model, results_to_remove, new_sinks, params_to_remove);// Recurrent states are independent of the KV caches; a hybrid stack (qwen35) has both.make_recurrent_states_stateful(model);diff --git a/src/frontends/gguf/src/utils.cpp b/src/frontends/gguf/src/utils.cppindex 127107510a8..4312943d5c9 100644--- a/src/frontends/gguf/src/utils.cpp+++ b/src/frontends/gguf/src/utils.cpp@@ -9,14 +9,17 @@#include <memory>#include <string>+#include "openvino/core/model.hpp"#include "openvino/op/add.hpp"#include "openvino/op/clamp.hpp"+#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/cos.hpp"#include "openvino/op/divide.hpp"#include "openvino/op/gather.hpp"#include "openvino/op/maximum.hpp"#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/shape_of.hpp"#include "openvino/op/sin.hpp"@@ -35,6 +38,16 @@ void num_inputs_check(const NodeContext& context, size_t min_inputs, size_t max_FRONT_END_OP_CONVERSION_CHECK(input_size <= max_inputs, "Got more inputs than expected");}+std::shared_ptr<ov::op::v0::Parameter> find_parameter(const std::shared_ptr<ov::Model>& model,+ const std::string& name) {+ for (const auto& p : model->get_parameters()) {+ if (p->get_friendly_name() == name || p->output(0).get_names().count(name)) {+ return p;+ }+ }+ return nullptr;+}+int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb) {const auto dim = static_cast<int>(nb.size() - 1);size_t bytes = nb[dim];diff --git a/src/frontends/gguf/src/utils.hpp b/src/frontends/gguf/src/utils.hppindex 251f5a47ae5..a645d62f0ac 100644--- a/src/frontends/gguf/src/utils.hpp+++ b/src/frontends/gguf/src/utils.hpp@@ -14,7 +14,11 @@#include "openvino/op/topk.hpp"namespace ov {+class Model;namespace op {+namespace v0 {+class Parameter;+} // namespace v0namespace v3 {class ShapeOf;} // namespace v3@@ -25,6 +29,10 @@ namespace gguf {void num_inputs_check(const NodeContext& context, size_t min_inputs, size_t max_inputs);+/// \brief Find a Parameter whose friendly name or output tensor names include `name`.+/// Returns nullptr if the model has no such Parameter.+std::shared_ptr<ov::op::v0::Parameter> find_parameter(const std::shared_ptr<ov::Model>& model, const std::string& name);+int non_cont_dim(std::vector<size_t> ne, std::vector<size_t> nb);template <typename T>diff --git a/src/frontends/gguf/tests/test_adapt_to_genai.cpp b/src/frontends/gguf/tests/test_adapt_to_genai.cppindex 492ae3bc915..92fe7606ee1 100644--- a/src/frontends/gguf/tests/test_adapt_to_genai.cpp+++ b/src/frontends/gguf/tests/test_adapt_to_genai.cpp@@ -34,25 +34,14 @@#include "openvino/op/util/variable.hpp"#include "openvino/pass/manager.hpp"#include "openvino/pass/sdpa_to_paged_attention.hpp"+#include "utils.hpp"using namespace ov_gguf_test;+using namespace ov::op;using ov::frontend::gguf::pass::AdaptToGenAI;namespace {-std::shared_ptr<ov::op::v0::Constant> const_i64(const std::vector<int64_t>& values) {- return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{values.size()}, values);-}--std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Model>& model, const std::string& name) {- for (const auto& p : model->get_parameters()) {- if (p->output(0).get_names().count(name) || p->get_friendly_name() == name) {- return p;- }- }- return nullptr;-}-// A minimal gguf-IO model: the four Parameters AdaptToGenAI requires, a token-embedding lookup// built exactly the way translate_get_rows builds it (Squeeze -> Gather -> Unsqueeze, friendly// name ending "_embd"), and a trivial rank-4 logits Result depending on it. `vocab`/`hidden` size@@ -64,9 +53,9 @@ std::shared_ptr<ov::op::v0::Parameter> find_param(const std::shared_ptr<ov::Mode// the same shape "attn_out_g"/"inpSA_g" have in a real model.struct MinimalGgufModel {std::shared_ptr<ov::Model> model;- std::shared_ptr<ov::op::v0::Parameter> inp_tokens;+ std::shared_ptr<v0::Parameter> inp_tokens;std::shared_ptr<ov::Node> embd; // Unsqueeze(Gather(vocab, Squeeze(inp_tokens)), axis=0)- std::shared_ptr<ov::op::v0::Parameter> inp_out_ids;+ std::shared_ptr<v0::Parameter> inp_out_ids;std::shared_ptr<ov::Node> row_select; // Unsqueeze(Gather(Squeeze(embd), Squeeze(inp_out_ids)), axis=0)// A second, independent embedding-table lookup keyed on the same inp_tokens indices, mirroring// Gemma4's per-layer "pe_tok_flat" (GET_ROWS(per_layer_token_embd.weight, inp_tokens)):@@ -81,42 +70,45 @@ MinimalGgufModel build_minimal_gguf_model(int64_t vocab = 4,bool with_second_inp_tokens_lookup = false) {MinimalGgufModel m;- m.inp_tokens = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});+ m.inp_tokens = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});m.inp_tokens->output(0).set_names({"inp_tokens"});- auto inp_pos = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});+ auto inp_pos = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});inp_pos->output(0).set_names({"inp_pos"});- auto self_kq_mask = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, -1});+ auto self_kq_mask = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, -1});self_kq_mask->output(0).set_names({"self_kq_mask"});- auto token_len_per_seq = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1});+ auto token_len_per_seq = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1});token_len_per_seq->output(0).set_names({"token_len_per_seq"});- auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});+ auto beam_idx = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{-1});beam_idx->output(0).set_names({"beam_idx"});std::vector<float> table_values(vocab * hidden);for (size_t i = 0; i < table_values.size(); ++i) {table_values[i] = static_cast<float>(i);}- auto vocab_table = ov::op::v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, table_values);+ auto vocab_table = v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, table_values);++ auto squeeze_01 = v0::Constant::create(ov::element::i64, {2}, {0, 1});+ auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});// Mirrors translate_get_rows's embedding-table ("else", rank-2 data) branch exactly:// Squeeze(indices, [0,1]) -> Gather(table, ., axis=0) -> Unsqueeze(., axis=0).- auto indices = std::make_shared<ov::op::v0::Squeeze>(m.inp_tokens, const_i64({0, 1}));- auto gather = std::make_shared<ov::op::v8::Gather>(vocab_table, indices, const_i64({0}));- m.embd = std::make_shared<ov::op::v0::Unsqueeze>(gather, const_i64({0}));+ auto indices = std::make_shared<v0::Squeeze>(m.inp_tokens, squeeze_01);+ auto gather = std::make_shared<v8::Gather>(vocab_table, indices, axis0);+ m.embd = std::make_shared<v0::Unsqueeze>(gather, axis0);m.embd->set_friendly_name("Unsqueeze_test_embd");ov::ParameterVector params{m.inp_tokens, inp_pos, self_kq_mask, token_len_per_seq, beam_idx};if (with_inp_out_ids) {- m.inp_out_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});+ m.inp_out_ids = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});m.inp_out_ids->output(0).set_names({"inp_out_ids"});params.push_back(m.inp_out_ids);// Mirrors translate_get_rows's rank-4/dim1==1 branch ("attn_out_g"/"inpSA_g" in a real// model): Squeeze(data,[0,1]) -> Gather(., Squeeze(indices,[0,1]), axis=0) -> Unsqueeze(0).- auto data_squeeze = std::make_shared<ov::op::v0::Squeeze>(m.embd, const_i64({0, 1}));- auto row_indices = std::make_shared<ov::op::v0::Squeeze>(m.inp_out_ids, const_i64({0, 1}));- auto row_gather = std::make_shared<ov::op::v8::Gather>(data_squeeze, row_indices, const_i64({0}));- m.row_select = std::make_shared<ov::op::v0::Unsqueeze>(row_gather, const_i64({0}));+ auto data_squeeze = std::make_shared<v0::Squeeze>(m.embd, squeeze_01);+ auto row_indices = std::make_shared<v0::Squeeze>(m.inp_out_ids, squeeze_01);+ auto row_gather = std::make_shared<v8::Gather>(data_squeeze, row_indices, axis0);+ m.row_select = std::make_shared<v0::Unsqueeze>(row_gather, axis0);m.row_select->set_friendly_name("Unsqueeze_test_row_select");}@@ -126,22 +118,22 @@ MinimalGgufModel build_minimal_gguf_model(int64_t vocab = 4,for (size_t i = 0; i < pe_table_values.size(); ++i) {pe_table_values[i] = static_cast<float>(1000 + i);}- auto pe_table =- ov::op::v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, pe_table_values);- auto pe_indices = std::make_shared<ov::op::v0::Squeeze>(m.inp_tokens, const_i64({0, 1}));- auto pe_gather = std::make_shared<ov::op::v8::Gather>(pe_table, pe_indices, const_i64({0}));- m.pe_tok = std::make_shared<ov::op::v0::Unsqueeze>(pe_gather, const_i64({0}));+ auto pe_table = v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, pe_table_values);+ auto pe_indices = std::make_shared<v0::Squeeze>(m.inp_tokens, squeeze_01);+ auto pe_gather = std::make_shared<v8::Gather>(pe_table, pe_indices, axis0);+ m.pe_tok = std::make_shared<v0::Unsqueeze>(pe_gather, axis0);m.pe_tok->set_friendly_name("Unsqueeze_test_pe_tok_flat");// Reachable from a Result: MatcherPass only visits nodes reachable from the model's// results/sinks, so an orphan branch would silently never be matched.- results.push_back(std::make_shared<ov::op::v0::Result>(m.pe_tok));+ results.push_back(std::make_shared<v0::Result>(m.pe_tok));}// A trivial rank-4 "logits" output so AdaptToGenAI's final logits reshape has something to// work on: reduce the hidden axis so the shape stays predictable regardless of vocab/hidden.auto logits_src = with_inp_out_ids ? m.row_select : m.embd;- auto logits = std::make_shared<ov::op::v1::ReduceSum>(logits_src, const_i64({3}), true);- results.insert(results.begin(), std::make_shared<ov::op::v0::Result>(logits));+ auto reduce_axis_3 = v0::Constant::create(ov::element::i64, {1}, {3});+ auto logits = std::make_shared<v1::ReduceSum>(logits_src, reduce_axis_3, true);+ results.insert(results.begin(), std::make_shared<v0::Result>(logits));m.model = std::make_shared<ov::Model>(results, params);return m;@@ -156,10 +148,10 @@ TEST(GGUFAdaptToGenAI, RewritesIOContract) {ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));- auto input_ids = find_param(m.model, "input_ids");- auto attention_mask = find_param(m.model, "attention_mask");- auto position_ids = find_param(m.model, "position_ids");- auto beam_idx = find_param(m.model, "beam_idx");+ auto input_ids = find_parameter(m.model, "input_ids");+ auto attention_mask = find_parameter(m.model, "attention_mask");+ auto position_ids = find_parameter(m.model, "position_ids");+ auto beam_idx = find_parameter(m.model, "beam_idx");ASSERT_NE(input_ids, nullptr);ASSERT_NE(attention_mask, nullptr);ASSERT_NE(position_ids, nullptr);@@ -175,8 +167,8 @@ TEST(GGUFAdaptToGenAI, RewritesIOContract) {// Without the required gguf inputs present, the pass is a no-op (e.g. a model already adapted, or// not a gguf-IO model at all).TEST(GGUFAdaptToGenAI, NoOpWithoutGgufInputs) {- auto input_ids = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});- auto result = std::make_shared<ov::op::v0::Result>(input_ids);+ auto input_ids = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{-1, -1});+ auto result = std::make_shared<v0::Result>(input_ids);auto model = std::make_shared<ov::Model>(ov::ResultVector{result}, ov::ParameterVector{input_ids});EXPECT_FALSE(AdaptToGenAI().run_on_model(model));@@ -204,7 +196,7 @@ TEST(GGUFAdaptToGenAI, FixesEmbdAxisStructurally) {ASSERT_EQ(fixed_embd->get_type_name(), std::string("Unsqueeze"));EXPECT_EQ(fixed_embd->input_value(0), embd_gather_input); // still the same Gather, unchanged- auto axis_const = ov::as_type_ptr<ov::op::v0::Constant>(fixed_embd->input_value(1).get_node_shared_ptr());+ auto axis_const = ov::as_type_ptr<v0::Constant>(fixed_embd->input_value(1).get_node_shared_ptr());ASSERT_NE(axis_const, nullptr);EXPECT_EQ(axis_const->cast_vector<int64_t>(), std::vector<int64_t>({1}));}@@ -239,7 +231,7 @@ TEST(GGUFAdaptToGenAI, FixesEmbdAxisStructurallyForSecondaryInpTokensLookup) {ASSERT_EQ(fixed_pe_tok->get_type_name(), std::string("Unsqueeze"));EXPECT_EQ(fixed_pe_tok->input_value(0), pe_tok_gather_input); // still the same Gather, unchanged- auto axis_const = ov::as_type_ptr<ov::op::v0::Constant>(fixed_pe_tok->input_value(1).get_node_shared_ptr());+ auto axis_const = ov::as_type_ptr<v0::Constant>(fixed_pe_tok->input_value(1).get_node_shared_ptr());ASSERT_NE(axis_const, nullptr);// Same axis (1) as embd's own fix, above -- the two branches must agree.EXPECT_EQ(axis_const->cast_vector<int64_t>(), std::vector<int64_t>({1}));@@ -255,7 +247,7 @@ TEST(GGUFAdaptToGenAI, EmbdLeadingAxisSelfCorrectsUnderBothLayouts) {auto m = build_minimal_gguf_model(/*vocab=*/8, hidden);// Add the probe Result *before* running the pass: FixEmbdAxis replaces embd's Unsqueeze, and// Output::replace() only rewires consumers that already exist at that point.- auto embd_result = std::make_shared<ov::op::v0::Result>(m.embd);+ auto embd_result = std::make_shared<v0::Result>(m.embd);m.model->add_results({embd_result});ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));m.model->validate_nodes_and_infer_types();@@ -325,12 +317,12 @@ TEST(GGUFAdaptToGenAI, FixesInpOutIdsRowSelectStructurally) {ASSERT_NE(fixed_embd, nullptr);ASSERT_EQ(fixed_row_select->get_type_name(), std::string("Unsqueeze"));- auto gather = ov::as_type_ptr<ov::op::v8::Gather>(fixed_row_select->input_value(0).get_node_shared_ptr());+ auto gather = ov::as_type_ptr<v8::Gather>(fixed_row_select->input_value(0).get_node_shared_ptr());ASSERT_NE(gather, nullptr);// Both the activation and the indices are now fed through a Reshape (flatten), not a Squeeze.- auto data_flat = ov::as_type_ptr<ov::op::v1::Reshape>(gather->input_value(0).get_node_shared_ptr());- auto indices_flat = ov::as_type_ptr<ov::op::v1::Reshape>(gather->input_value(1).get_node_shared_ptr());+ auto data_flat = ov::as_type_ptr<v1::Reshape>(gather->input_value(0).get_node_shared_ptr());+ auto indices_flat = ov::as_type_ptr<v1::Reshape>(gather->input_value(1).get_node_shared_ptr());ASSERT_NE(data_flat, nullptr);ASSERT_NE(indices_flat, nullptr);EXPECT_EQ(data_flat->input_value(0), fixed_embd->output(0)); // still fed by the (now-fixed) embd@@ -345,7 +337,7 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {const int64_t hidden = 3;auto m = build_minimal_gguf_model(/*vocab=*/8, hidden, /*with_inp_out_ids=*/true);// Add the probe Result before running the pass, same reasoning as the embd functional test.- auto row_result = std::make_shared<ov::op::v0::Result>(m.row_select);+ auto row_result = std::make_shared<v0::Result>(m.row_select);m.model->add_results({row_result});ASSERT_TRUE(AdaptToGenAI().run_on_model(m.model));m.model->validate_nodes_and_infer_types();@@ -394,7 +386,7 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {// Functional/structural regression test for the whole bug class FixEmbdAxis and// FixInpOutIdsRowSelect fix: a genai-adapted model whose residual stream (embd) feeds a REAL// attention block (Q/K/V projections, a stateful KV cache, and an actual-// ov::op::v13::ScaledDotProductAttention) must survive ov::pass::SDPAToPagedAttention -- the exact+// v13::ScaledDotProductAttention) must survive ov::pass::SDPAToPagedAttention -- the exact// transformation that rewrites input_ids to rank-1 [tokens] and is what actually exposed this bug// (see the class comment on FixEmbdAxis in adapt_to_genai.cpp). Unlike the tests above, which probe// embd/row-selection in isolation and hand-feed a [tokens, 1] tensor to simulate the post-PA@@ -410,15 +402,15 @@ TEST(GGUFAdaptToGenAI, InpOutIdsRowSelectionCorrectUnderBothLayouts) {namespace {std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hidden) {- auto inp_tokens = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});+ auto inp_tokens = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});inp_tokens->output(0).set_names({"inp_tokens"});- auto inp_pos = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});+ auto inp_pos = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{1, 1, 1, -1});inp_pos->output(0).set_names({"inp_pos"});- auto self_kq_mask = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, -1});+ auto self_kq_mask = std::make_shared<v0::Parameter>(ov::element::f32, ov::PartialShape{1, 1, -1, -1});self_kq_mask->output(0).set_names({"self_kq_mask"});- auto token_len_per_seq = std::make_shared<ov::op::v0::Parameter>(ov::element::i64, ov::PartialShape{1});+ auto token_len_per_seq = std::make_shared<v0::Parameter>(ov::element::i64, ov::PartialShape{1});token_len_per_seq->output(0).set_names({"token_len_per_seq"});- auto beam_idx = std::make_shared<ov::op::v0::Parameter>(ov::element::i32, ov::PartialShape{-1});+ auto beam_idx = std::make_shared<v0::Parameter>(ov::element::i32, ov::PartialShape{-1});beam_idx->output(0).set_names({"beam_idx"});// Token embedding table: row i is filled with value i (so the expected running-mean output@@ -429,33 +421,39 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hidtable_values[v * hidden + h] = static_cast<float>(v);}}- auto vocab_table = ov::op::v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, table_values);+ auto vocab_table = v0::Constant::create(ov::element::f32, {(size_t)vocab, (size_t)hidden}, table_values);++ auto squeeze_01 = v0::Constant::create(ov::element::i64, {2}, {0, 1});+ auto axis0 = v0::Constant::create(ov::element::i64, {1}, {0});// Mirrors translate_get_rows's embedding-table branch exactly, same as build_minimal_gguf_model.- auto indices = std::make_shared<ov::op::v0::Squeeze>(inp_tokens, const_i64({0, 1}));- auto gather = std::make_shared<ov::op::v8::Gather>(vocab_table, indices, const_i64({0}));- auto embd = std::make_shared<ov::op::v0::Unsqueeze>(gather, const_i64({0}));+ auto indices = std::make_shared<v0::Squeeze>(inp_tokens, squeeze_01);+ auto gather = std::make_shared<v8::Gather>(vocab_table, indices, axis0);+ auto embd = std::make_shared<v0::Unsqueeze>(gather, axis0);embd->set_friendly_name("embd");// Flatten to [1, tokens, hidden] regardless of which axis (0 pre-fix, 1 post-fix) carries the// real token count -- Reshape never reorders memory, so this is correct either way (same trick// FixInpOutIdsRowSelect itself uses).- auto embd_3d = std::make_shared<ov::op::v1::Reshape>(embd, const_i64({1, -1, hidden}), false);+ auto embd_3d_shape = v0::Constant::create(ov::element::i64, {3}, std::vector<int64_t>{1, -1, hidden});+ auto embd_3d = std::make_shared<v1::Reshape>(embd, embd_3d_shape, false);std::vector<float> zero_w(hidden * hidden, 0.0f);- auto w_zero = ov::op::v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, zero_w);+ auto w_zero = v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, zero_w);std::vector<float> identity_w(hidden * hidden, 0.0f);for (int64_t i = 0; i < hidden; ++i) {identity_w[i * hidden + i] = 1.0f;}- auto w_identity = ov::op::v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, identity_w);+ auto w_identity = v0::Constant::create(ov::element::f32, {(size_t)hidden, (size_t)hidden}, identity_w);// Single-head Q/K/V projection: MatMul -> reshape to [1, tokens, 1, head_size] -> transpose to// [1, 1, tokens, head_size].- auto make_projection = [&](const std::shared_ptr<ov::op::v0::Constant>& weight) {- auto matmul = std::make_shared<ov::op::v0::MatMul>(embd_3d, weight, false, true);- auto heads = std::make_shared<ov::op::v1::Reshape>(matmul, const_i64({0, 0, 1, hidden}), true);- return std::make_shared<ov::op::v1::Transpose>(heads, const_i64({0, 2, 1, 3}));+ auto transpose_0213 = v0::Constant::create(ov::element::i64, {4}, {0, 2, 1, 3});+ auto make_projection = [&](const std::shared_ptr<v0::Constant>& weight) {+ auto matmul = std::make_shared<v0::MatMul>(embd_3d, weight, false, true);+ auto heads_shape = v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{0, 0, 1, hidden});+ auto heads = std::make_shared<v1::Reshape>(matmul, heads_shape, true);+ return std::make_shared<v1::Transpose>(heads, transpose_0213);};auto q = make_projection(w_zero);auto k = make_projection(w_zero);@@ -464,33 +462,33 @@ std::shared_ptr<ov::Model> build_attention_gguf_model(int64_t vocab, int64_t hid// Stateful KV cache: ReadValue -> Gather(beam_idx) -> Concat(-2, cur) -> Assign, exactly what// ov::frontend::gguf::pass::MakeStateful emits for a real model.auto make_kv_cache = [&](const ov::Output<ov::Node>& cur, const std::string& var_id) {- auto var = std::make_shared<ov::op::util::Variable>(- ov::op::util::VariableInfo{ov::PartialShape{-1, 1, -1, hidden}, ov::element::f32, var_id});- auto init_shape = const_i64({1, 1, 0, hidden});- auto init = std::make_shared<ov::op::v3::Broadcast>(ov::op::v0::Constant::create(ov::element::f32, {}, {0.0f}),- init_shape);- auto read = std::make_shared<ov::op::v6::ReadValue>(init, var);- auto past = std::make_shared<ov::op::v8::Gather>(read, beam_idx, const_i64({0}), 0);- auto concat = std::make_shared<ov::op::v0::Concat>(ov::OutputVector{past, cur}, -2);- auto assign = std::make_shared<ov::op::v6::Assign>(concat, var);- return std::make_pair(ov::Output<ov::Node>(concat), std::static_pointer_cast<ov::op::Sink>(assign));+ auto var = std::make_shared<util::Variable>(+ util::VariableInfo{ov::PartialShape{-1, 1, -1, hidden}, ov::element::f32, var_id});+ auto init_shape = v0::Constant::create(ov::element::i64, {4}, std::vector<int64_t>{1, 1, 0, hidden});+ auto init = std::make_shared<v3::Broadcast>(v0::Constant::create(ov::element::f32, {}, {0.0f}), init_shape);+ auto read = std::make_shared<v6::ReadValue>(init, var);+ auto past = std::make_shared<v8::Gather>(read, beam_idx, axis0, 0);+ auto concat = std::make_shared<v0::Concat>(ov::OutputVector{past, cur}, -2);+ auto assign = std::make_shared<v6::Assign>(concat, var);+ return std::make_pair(ov::Output<ov::Node>(concat), std::static_pointer_cast<Sink>(assign));};auto [k_concat, k_assign] = make_kv_cache(k, "attn_k_cache.0");auto [v_concat, v_assign] = make_kv_cache(v, "attn_v_cache.0");- auto scale = ov::op::v0::Constant::create(ov::element::f32, {}, {1.0f});- auto sdpa = std::make_shared<ov::op::v13::ScaledDotProductAttention>(q,- k_concat,- v_concat,- self_kq_mask,- scale,- /*causal=*/false);+ auto scale = v0::Constant::create(ov::element::f32, {}, {1.0f});+ auto sdpa = std::make_shared<v13::ScaledDotProductAttention>(q,+ k_concat,+ v_concat,+ self_kq_mask,+ scale,+ /*causal=*/false);// Merge heads back and flatten to [1, tokens, hidden] -- the "logits"-shaped output// AdaptToGenAI's final reshape expects.- auto merged = std::make_shared<ov::op::v1::Transpose>(sdpa, const_i64({0, 2, 1, 3}));- auto merged_flat = std::make_shared<ov::op::v1::Reshape>(merged, const_i64({0, 0, -1}), true);- auto result = std::make_shared<ov::op::v0::Result>(merged_flat);+ auto merged = std::make_shared<v1::Transpose>(sdpa, transpose_0213);+ auto merged_flat_shape = v0::Constant::create(ov::element::i64, {3}, {0, 0, -1});+ auto merged_flat = std::make_shared<v1::Reshape>(merged, merged_flat_shape, true);+ auto result = std::make_shared<v0::Result>(merged_flat);return std::make_shared<ov::Model>(ov::ResultVector{result},@@ -517,9 +515,9 @@ TEST(GGUFAdaptToGenAI, SurvivesSDPAToPagedAttentionWithRealAttentionBlock) {ASSERT_NO_THROW(pass_manager.run_passes(model));ASSERT_NO_THROW(model->validate_nodes_and_infer_types());- std::shared_ptr<ov::op::PagedAttentionExtension> pa;+ std::shared_ptr<PagedAttentionExtension> pa;for (const auto& op : model->get_ordered_ops()) {- if (auto node = ov::as_type_ptr<ov::op::PagedAttentionExtension>(op)) {+ if (auto node = ov::as_type_ptr<PagedAttentionExtension>(op)) {pa = node;}}