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
[Transformations][Core] Implement output index matching (#37232)
Andrii Staikova2e9901dc61d
diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_gated_delta_net.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_gated_delta_net.cppindex d3819e8881a..c955ecb4ed5 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_gated_delta_net.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_gated_delta_net.cpp@@ -144,11 +144,10 @@ ov::pass::RemoveConcatSliceAfterLoop::RemoveConcatSliceAfterLoop() {init_state,pattern::any_input()};- auto loop_output0 = pattern::wrap_type<ov::op::v5::Loop>(loop_inputs, pattern::output_index_matches(0));- auto loop_output1 = pattern::wrap_type<ov::op::v5::Loop>(loop_inputs, pattern::output_index_matches(1));+ auto loop = pattern::wrap_type_strict_index<ov::op::v5::Loop>(loop_inputs);- auto reshape_core_attn = pattern::wrap_type<v1::Reshape>({loop_output0, {-1}});- auto reshape_core_state = pattern::wrap_type<v1::Reshape>({loop_output1, {-1}});+ auto reshape_core_attn = pattern::wrap_type<v1::Reshape>({loop->output(0), {-1}});+ auto reshape_core_state = pattern::wrap_type<v1::Reshape>({loop->output(1), {-1}});auto concat_loop = pattern::wrap_type<v0::Concat>({reshape_core_attn, reshape_core_state}, {{"axis", 0}});auto out_numel = pattern::any_input(pattern::has_static_shape());auto slice_attn = pattern::wrap_type<ov::op::v8::Slice>({concat_loop, {0}, out_numel, {1}, {0}});@@ -161,7 +160,7 @@ ov::pass::RemoveConcatSliceAfterLoop::RemoveConcatSliceAfterLoop() {ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();bool changed = false;- auto loop_node = pattern_map.at(loop_output0).get_node_shared_ptr();+ auto loop_node = m.get_pattern_map().at(loop);if (pattern_map.count(reshape_attn)) {auto reshape_attn_out = pattern_map.at(reshape_attn);if (!ov::replace_output_update_name(pattern_map.at(reshape_attn), loop_node->output(0))) {diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cppindex fe4e794a5d8..2ec356ef28f 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_moe_experts.cpp@@ -109,10 +109,9 @@ std::shared_ptr<ov::pass::pattern::op::Block> mlp3_no_bias_swiglu_block({select_Gather_1, pattern::wrap_type<v0::Constant>(pattern::value_matches("0"))});// NonZero output_type relaxed to accept both i32 and i64auto ListUnpack_NonZero_1 = pattern::wrap_type<v3::NonZero>({squeeze_Squeeze_1});- auto ListUnpack_Split_1 = pattern::wrap_type<v1::Split>(+ auto ListUnpack_Split_1 = pattern::wrap_type_strict_index<v1::Split>({ListUnpack_NonZero_1, pattern::wrap_type<v0::Constant>(pattern::value_matches("0"))},{{"num_splits", 2}});- ListUnpack_Split_1->set_output_size(2);auto ListUnpack_Squeeze_0_1 = pattern::wrap_type<v0::Squeeze>({ListUnpack_Split_1->output(1), pattern::wrap_type<v0::Constant>(pattern::value_matches("0"))});// Convert is optional - pattern matches both with and without type conversion@@ -214,10 +213,9 @@ std::pair<std::shared_ptr<Node>, std::shared_ptr<Node>> create_router_pattern()auto transpose_perm = pattern::wrap_type<v0::Constant>(pattern::value_matches("2, 1, 0"));auto softmax = pattern::wrap_type<v8::Softmax>({linear_MatMul}, {{"axis", 1}});- auto topk = pattern::wrap_type<ov::op::v11::TopK>(+ auto topk = pattern::wrap_type_strict_index<ov::op::v11::TopK>({softmax, num_topk},{{"axis", -1}, {"mode", "max"}, {"sort", "value"}, {"index_element_type", "i64"}, {"stable", false}});- topk->set_output_size(2);auto one_hot =pattern::wrap_type<v1::OneHot>({topk->output(1), expert_num, one_hot_on, one_hot_off}, {{"axis", 2}});auto permute = pattern::wrap_type<v1::Transpose>({one_hot, transpose_perm});@@ -234,8 +232,7 @@ std::shared_ptr<Node> create_expert_indexing_pattern(const std::shared_ptr<Node>auto squeeze = pattern::wrap_type<v0::Squeeze>({select_gather, axes.axis0});// NonZero output_type relaxed to accept both i32 and i64auto non_zero = pattern::wrap_type<v3::NonZero>({squeeze});- auto split = pattern::wrap_type<v1::Split>({non_zero, axes.axis0}, {{"num_splits", 2}});- split->set_output_size(2);+ auto split = pattern::wrap_type_strict_index<v1::Split>({non_zero, axes.axis0}, {{"num_splits", 2}});auto squeeze_indices = pattern::wrap_type<v0::Squeeze>({split->output(1), axes.axis0});// Convert is optional - pattern matches both with and without type conversionauto convert = pattern::wrap_type<v0::Convert>({squeeze_indices}) | squeeze_indices;@@ -253,8 +250,7 @@ std::tuple<std::shared_ptr<Node>, std::shared_ptr<Node>> create_routing_weights_{{"auto_broadcast", "numpy"}, {"m_pythondiv", true}});auto unsqueeze = pattern::wrap_type<v0::Unsqueeze>({normalized, axes.axis2});auto shape_of = pattern::wrap_type<v3::ShapeOf>({unsqueeze}, {{"output_type", "i32"}});- auto split = pattern::wrap_type<v1::Split>({shape_of, axes.axis0}, {{"num_splits", 3}});- split->set_output_size(3);+ auto split = pattern::wrap_type_strict_index<v1::Split>({shape_of, axes.axis0}, {{"num_splits", 3}});auto reshape = pattern::wrap_type<v1::Reshape>({unsqueeze, pattern::any_input()});return {split, reshape};diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cppindex df822a7e8c0..c3f737359fc 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_rotary_positional_embeddings.cpp@@ -113,8 +113,7 @@ RoPEFusionFlux::RoPEFusionFlux(bool num_heads_transposed) {auto x1 = pattern::wrap_type<opset1::Reshape>({x, pattern::any_input()},pattern::shape_matches("[" + num_heads_pattern + ", ?, 2]"));- auto split = pattern::wrap_type<opset1::Split>({x1, -1}, {{"num_splits", 2}});- split->set_output_size(2);+ auto split = pattern::wrap_type_strict_index<opset1::Split>({x1, -1}, {{"num_splits", 2}});// 3 versions of mulitply by -1 depending on transformations execution prior to this passauto opt_squeeze = pattern::optional<opset1::Squeeze>({split->output(1), -1});@@ -158,7 +157,7 @@ RoPEFusionFlux::RoPEFusionFlux(bool num_heads_transposed) {auto new_node = std::make_shared<ov::op::internal::RoPE>(new_args, config);new_node->set_friendly_name(old_node->get_friendly_name());ov::copy_runtime_info({pattern_map.at(x1).get_node_shared_ptr(),- pattern_map.at(split).get_node_shared_ptr(),+ m.get_pattern_map().at(split),pattern_map.at(x2).get_node_shared_ptr(),pattern_map.at(x3).get_node_shared_ptr(),pattern_map.at(y1).get_node_shared_ptr(),@@ -194,8 +193,7 @@ RoPEFusionGPTNEOX::RoPEFusionGPTNEOX(int rank) {auto x_or_cos2 = pattern::any_input(pattern::rank_equals(rank));auto t_sin = pattern::any_input(pattern::rank_equals(rank));- auto varsplit = pattern::wrap_type<v1::VariadicSplit>({x, rank - 1, {"half_ndims", "?"}});- varsplit->set_output_size(2);+ auto varsplit = pattern::wrap_type_strict_index<v1::VariadicSplit>({x, rank - 1, {"half_ndims", "?"}});auto int32_max = std::numeric_limits<std::int32_t>::max();@@ -348,8 +346,7 @@ RoPEFusionIOSlicing::RoPEFusionIOSlicing() {MATCHER_SCOPE(RoPEFusionIOSlicing);auto int32_max = std::numeric_limits<std::int32_t>::max();auto data = pattern::any_input(pattern::rank_equals(4));- auto varsplit = pattern::wrap_type<v1::VariadicSplit>({data, 3, {"ndims", "?"}});- varsplit->set_output_size(2);+ auto varsplit = pattern::wrap_type_strict_index<v1::VariadicSplit>({data, 3, {"ndims", "?"}});auto x = op_util::NewGenSlice(data, 0, "ndims", 1, 3);auto y = op_util::NewGenSlice(data, "ndims", int32_max, 1, 3);@@ -467,16 +464,15 @@ RoPEFusionGPTJ::RoPEFusionGPTJ() {MATCHER_SCOPE(RoPEFusionGPTJ);auto gather_sin_cos = pattern::any_input(pattern::type_matches(ov::element::f32));- auto varsplit = pattern::wrap_type<opset1::VariadicSplit>({gather_sin_cos, -1, {"ndims/2", "-1"}});- varsplit->set_output_size(2);+ auto varsplit = pattern::wrap_type_strict_index<opset1::VariadicSplit>({gather_sin_cos, -1, {"ndims/2", "-1"}});auto repeat_interleave_sin = repeat_interleave_pattern(varsplit->output(0));auto repeat_interleave_cos = repeat_interleave_pattern(varsplit->output(1));auto view_Reshape = pattern::any_input(pattern::rank_equals(4));auto slice_Slice_965 = op_util::NewGenSlice(view_Reshape, 0, "ndims", 1, 3);// view_Reshape : B,L,H,S- auto varsplit_view_Reshape = pattern::wrap_type<opset1::VariadicSplit>({view_Reshape, 3, {"ndims", "end"}});- varsplit_view_Reshape->set_output_size(2);+ auto varsplit_view_Reshape =+ pattern::wrap_type_strict_index<opset1::VariadicSplit>({view_Reshape, 3, {"ndims", "end"}});// x interleave (-x[:,:,:, 1::2], x[:,:,:, 0::2])auto slice_Slice_1174 = op_util::NewGenSlice(slice_Slice_965 | varsplit_view_Reshape->output(0), 1, INT_MAX, 2, 3);@@ -530,7 +526,7 @@ RoPEFusionGPTJ::RoPEFusionGPTJ() {ov::op::internal::RoPE::Config config;OutputVector new_args;- NodeVector rt_from = {pattern_map.at(varsplit).get_node_shared_ptr(),+ NodeVector rt_from = {m.get_pattern_map().at(varsplit),pattern_map.at(repeat_interleave_sin).get_node_shared_ptr(),pattern_map.at(repeat_interleave_cos).get_node_shared_ptr(),pattern_map.at(neg_Multiply_1177).get_node_shared_ptr(),@@ -617,8 +613,7 @@ RoPEFusionChatGLM::RoPEFusionChatGLM(const bool support_2d_rope) {}auto slice0 = op_util::NewGenSlice(input_key, 0, "ndims", 1, 3);- auto var_split0 = pattern::wrap_type<v1::VariadicSplit>({input_key, 3, {"ndims", "end"}});- var_split0->set_output_size(2);+ auto var_split0 = pattern::wrap_type_strict_index<v1::VariadicSplit>({input_key, 3, {"ndims", "end"}});// rotate halfstd::shared_ptr<ov::Node> reshape0 = nullptr;@@ -641,8 +636,7 @@ RoPEFusionChatGLM::RoPEFusionChatGLM(const bool support_2d_rope) {auto x_even = pattern::wrap_type<v8::Gather>({reshape0, 0, -1}, {{"batch_dims", 0}});auto x_odd = pattern::wrap_type<v8::Gather>({reshape0, 1, -1}, {{"batch_dims", 0}});- auto var_split1 = pattern::wrap_type<v1::VariadicSplit>({cos_sin_cache, 0, {"0", "end"}});- var_split1->set_output_size(2);+ auto var_split1 = pattern::wrap_type_strict_index<v1::VariadicSplit>({cos_sin_cache, 0, {"0", "end"}});std::shared_ptr<ov::Node> reshape1 = nullptr;if (support_2d_rope) {@@ -802,13 +796,10 @@ RoPEFusionChatGLMHF::RoPEFusionChatGLMHF() {pattern::shape_matches("[?, head_cnt, 1, head_size]"),{{"special_zero", false}});- auto vsplit_out0 = pattern::wrap_type<op::v1::VariadicSplit>(- {reshape, 3, pattern::any_input()},- pattern::output_index_matches(0) && pattern::shape_matches("[?, head_cnt, 1, ndims]"));- auto vsplit_out1 = pattern::wrap_type<op::v1::VariadicSplit>(- {reshape, 3, pattern::any_input()},- pattern::output_index_matches(1) && pattern::shape_matches("[?, head_cnt, 1, ndims]"));- auto slice_1 = op_util::NewGenSlice(reshape, 0, "ndims", 1, 3) | vsplit_out0;+ auto vsplit =+ pattern::wrap_type_strict_index<op::v1::VariadicSplit>({reshape, 3, pattern::any_input()},+ pattern::shape_matches("[?, head_cnt, 1, ndims]"));+ auto slice_1 = op_util::NewGenSlice(reshape, 0, "ndims", 1, 3) | vsplit->output(0);auto repeat_interleave_cos = build_ChatGLMHF_interleave_pattern(cos);auto repeat_interleave_sin = build_ChatGLMHF_interleave_pattern(sin);@@ -830,7 +821,7 @@ RoPEFusionChatGLMHF::RoPEFusionChatGLMHF() {auto multiply_1 = pattern::wrap_type<v1::Multiply>({flatten, repeat_interleave_sin}, {{"auto_broadcast", "numpy"}});auto add = pattern::wrap_type<v1::Add>({multiply, multiply_1}, {{"auto_broadcast", "numpy"}});- auto slice_5 = op_util::NewGenSlice(reshape, "ndims", INT_MAX, 1, 3) | vsplit_out1;+ auto slice_5 = op_util::NewGenSlice(reshape, "ndims", INT_MAX, 1, 3) | vsplit->output(1);auto result = pattern::wrap_type<v0::Concat>({add, slice_5}, {{"axis", -1}});matcher_pass_callback callback = [=](pattern::Matcher& m) {@@ -936,8 +927,8 @@ RoPEFusionQwen::RoPEFusionQwen() {{{"special_zero", true}});auto ListUnpack_586_Split =- pattern::wrap_type<v1::Split>({reshape_opt1(slice_Slice_543) | reshape_special, -2}, {{"num_splits", 2}});- ListUnpack_586_Split->set_output_size(2);+ pattern::wrap_type_strict_index<v1::Split>({reshape_opt1(slice_Slice_543) | reshape_special, -2},+ {{"num_splits", 2}});auto Multiply_567527 =pattern::wrap_type<v1::Multiply>({ListUnpack_586_Split->output(1), -1.0f}, {{"auto_broadcast", "numpy"}});auto ListUnpack_586_Squeeze_0 = pattern::wrap_type<v0::Squeeze>({Multiply_567527, -2});@@ -1148,19 +1139,20 @@ RoPEFusionGPTOSS::RoPEFusionGPTOSS() {auto t_cos = pattern::any_input(pattern::shape_matches("[?, 1, ?, half_ndims]"));auto t_sin = pattern::any_input(pattern::shape_matches("[?, 1, ?, half_ndims]"));- auto vsplit_out0 = pattern::wrap_type<op::v1::VariadicSplit>(+ auto vsplit = pattern::wrap_type_strict_index<op::v1::VariadicSplit>({x, pattern::wrap_type<v0::Constant>(), {"half_ndims", "?"}},- pattern::output_index_matches(0) && pattern::shape_matches("[?, ?, ?, half_ndims]"));- auto vsplit_out1 = pattern::wrap_type<op::v1::VariadicSplit>(- {x, pattern::wrap_type<v0::Constant>(), {"half_ndims", "?"}},- pattern::output_index_matches(1) && pattern::shape_matches("[?, ?, ?, half_ndims]"));- auto first_half_mul_cos = pattern::wrap_type<v1::Multiply>({vsplit_out0, t_cos}, {{"auto_broadcast", "numpy"}});- auto second_half_mul_sin = pattern::wrap_type<v1::Multiply>({vsplit_out1, t_sin}, {{"auto_broadcast", "numpy"}});+ pattern::shape_matches("[?, ?, ?, half_ndims]"));+ auto first_half_mul_cos =+ pattern::wrap_type<v1::Multiply>({vsplit->output(0), t_cos}, {{"auto_broadcast", "numpy"}});+ auto second_half_mul_sin =+ pattern::wrap_type<v1::Multiply>({vsplit->output(1), t_sin}, {{"auto_broadcast", "numpy"}});auto neg = pattern::wrap_type<v1::Multiply>({second_half_mul_sin, -1.0f}, {{"auto_broadcast", "numpy"}});auto sub_Subtract = pattern::wrap_type<v1::Add>({first_half_mul_cos, neg}, {{"auto_broadcast", "numpy"}});- auto second_half_mul_cos = pattern::wrap_type<v1::Multiply>({vsplit_out1, t_cos}, {{"auto_broadcast", "numpy"}});- auto first_half_mul_sin = pattern::wrap_type<v1::Multiply>({vsplit_out0, t_sin}, {{"auto_broadcast", "numpy"}});+ auto second_half_mul_cos =+ pattern::wrap_type<v1::Multiply>({vsplit->output(1), t_cos}, {{"auto_broadcast", "numpy"}});+ auto first_half_mul_sin =+ pattern::wrap_type<v1::Multiply>({vsplit->output(0), t_sin}, {{"auto_broadcast", "numpy"}});auto add_Add =pattern::wrap_type<v1::Add>({second_half_mul_cos, first_half_mul_sin}, {{"auto_broadcast", "numpy"}});auto concat_result = pattern::wrap_type<opset1::Concat>({sub_Subtract, add_Add});@@ -1185,7 +1177,8 @@ RoPEFusionGPTOSS::RoPEFusionGPTOSS() {return false;// Verify VariadicSplit axis is the last dimension (accepts both -1 and positive equivalent)- auto vsplit_node = pattern_map.at(vsplit_out0).get_node_shared_ptr();+ // Node-to-node map: the strict split is bound to a single producer, so the index is irrelevant here.+ auto vsplit_node = m.get_pattern_map().at(vsplit);auto axis_const = ov::as_type_ptr<v0::Constant>(vsplit_node->input_value(1).get_node_shared_ptr());if (!axis_const)return false;@@ -1253,13 +1246,10 @@ RoPEFusionLtxVideo::RoPEFusionLtxVideo() {pattern::shape_matches("[?, ?, half_rotary_ndims, 2]"));// Split along axis=-1 into real (out0) and imag (out1)- auto split_out0 = pattern::wrap_type<v1::Split>({x_reshape, pattern::wrap_type<v0::Constant>()},- pattern::output_index_matches(0));- auto split_out1 = pattern::wrap_type<v1::Split>({x_reshape, pattern::wrap_type<v0::Constant>()},- pattern::output_index_matches(1));+ auto split = pattern::wrap_type_strict_index<v1::Split>({x_reshape, pattern::wrap_type<v0::Constant>()});// Negate imaginary: Multiply(-1)- auto neg_imag_mul = pattern::wrap_type<v1::Multiply>({split_out1, pattern::wrap_type<v0::Constant>()});+ auto neg_imag_mul = pattern::wrap_type<v1::Multiply>({split->output(1), pattern::wrap_type<v0::Constant>()});// Squeeze and Unsqueeze are optional (may be optimized away by NopElimination)auto squeeze_imag = pattern::optional<v0::Squeeze>({neg_imag_mul, pattern::wrap_type<v0::Constant>()});@@ -1268,7 +1258,7 @@ RoPEFusionLtxVideo::RoPEFusionLtxVideo() {// Concat [-imag, real] along axis=-1auto neg_imag_final = neg_imag_unsqueeze | squeeze_imag | neg_imag_mul;- auto x_rotated_concat = pattern::wrap_type<v0::Concat>({neg_imag_final, split_out0},+ auto x_rotated_concat = pattern::wrap_type<v0::Concat>({neg_imag_final, split->output(0)},pattern::shape_matches("[?, ?, half_rotary_ndims, 2]"));// Reshape back to [batch, seq_len, rotary_ndims]diff --git a/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp b/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cppindex 9294ac97b55..7a2e0c712d2 100644--- a/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/fuse_ssm.cpp@@ -117,11 +117,10 @@ ov::pass::RemoveConcatSliceAfterLoopSSM::RemoveConcatSliceAfterLoopSSM() {init_state,pattern::any_input()};- auto loop_output0 = pattern::wrap_type<ov::op::v5::Loop>(loop_inputs, pattern::output_index_matches(0));- auto loop_output1 = pattern::wrap_type<ov::op::v5::Loop>(loop_inputs, pattern::output_index_matches(1));+ auto loop = pattern::wrap_type_strict_index<ov::op::v5::Loop>(loop_inputs);- auto reshape_output = pattern::wrap_type<v1::Reshape>({loop_output0, {-1}});- auto reshape_state = pattern::wrap_type<v1::Reshape>({loop_output1, {-1}});+ auto reshape_output = pattern::wrap_type<v1::Reshape>({loop->output(0), {-1}});+ auto reshape_state = pattern::wrap_type<v1::Reshape>({loop->output(1), {-1}});auto concat_loop = pattern::wrap_type<v0::Concat>({reshape_output, reshape_state}, {{"axis", 0}});auto out_numel = pattern::any_input(pattern::has_static_shape());auto slice_output = pattern::wrap_type<ov::op::v8::Slice>({concat_loop, {0}, out_numel, {1}, {0}});@@ -137,7 +136,7 @@ ov::pass::RemoveConcatSliceAfterLoopSSM::RemoveConcatSliceAfterLoopSSM() {ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();bool changed = false;- auto loop_node = pattern_map.at(loop_output0).get_node_shared_ptr();+ auto loop_node = m.get_pattern_map().at(loop);if (pattern_map.count(restored_output)) {auto restored_output_out = pattern_map.at(restored_output);if (!ov::replace_output_update_name(restored_output_out, loop_node->output(0))) {diff --git a/src/common/transformations/src/transformations/common_optimizations/pack_multi_head_attention.cpp b/src/common/transformations/src/transformations/common_optimizations/pack_multi_head_attention.cppindex f78934e2a69..d2ffc425bb6 100644--- a/src/common/transformations/src/transformations/common_optimizations/pack_multi_head_attention.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/pack_multi_head_attention.cpp@@ -1,5 +1,6 @@// Copyright (C) 2018-2026 Intel Corporation// SPDX-License-Identifier: Apache-2.0+//#include "transformations/common_optimizations/pack_multi_head_attention.hpp"@@ -337,10 +338,10 @@ MergeUnrolledRoPE::MergeUnrolledRoPE() {pattern_nodes nodes;auto input = pattern::any_input();nodes.input = pattern::wrap_type<v1::Reshape>({input, pattern::any_input()});- nodes.split = pattern::wrap_type<v1::VariadicSplit>({nodes.input, pattern::any_input(), pattern::any_input()});- nodes.split->set_output_size(2);- nodes.angle_r = pattern::wrap_type<v0::Negative>({nodes.split});- nodes.concat = pattern::wrap_type<v0::Concat>({nodes.angle_r, nodes.split});+ nodes.split = pattern::wrap_type_strict_index<v1::VariadicSplit>(+ {nodes.input, pattern::any_input(), pattern::any_input()});+ nodes.angle_r = pattern::wrap_type<v0::Negative>({nodes.split->output(1)});+ nodes.concat = pattern::wrap_type<v0::Concat>({nodes.angle_r, nodes.split->output(0)});nodes.mul_r = pattern::wrap_type<v1::Multiply>({nodes.concat, pattern::any_input()});nodes.mul_l = pattern::wrap_type<v1::Multiply>({nodes.input, pattern::any_input()});nodes.add = pattern::wrap_type<v1::Add>({nodes.mul_l, nodes.mul_r});diff --git a/src/common/transformations/src/transformations/common_optimizations/sdpa_fusion.cpp b/src/common/transformations/src/transformations/common_optimizations/sdpa_fusion.cppindex 5196e380094..a606b99f120 100644--- a/src/common/transformations/src/transformations/common_optimizations/sdpa_fusion.cpp+++ b/src/common/transformations/src/transformations/common_optimizations/sdpa_fusion.cpp@@ -39,6 +39,7 @@ using ov::pass::pattern::consumers_count;using ov::pass::pattern::Matcher;using ov::pass::pattern::rank_equals;using ov::pass::pattern::wrap_type;+using ov::pass::pattern::wrap_type_strict_index;namespace v0 = ov::op::v0;namespace v1 = ov::op::v1;@@ -653,13 +654,10 @@ SDPASplitAttentionFusionMatcher::SDPASplitAttentionFusionMatcher() {auto split_axis = any_input();auto split_sizes = any_input();- auto vsplit_out0 =- wrap_type<v1::VariadicSplit>({softmax, split_axis, split_sizes}, ov::pass::pattern::output_index_matches(0));- auto vsplit_out1 =- wrap_type<v1::VariadicSplit>({softmax, split_axis, split_sizes}, ov::pass::pattern::output_index_matches(1));+ auto vsplit = wrap_type_strict_index<v1::VariadicSplit>({softmax, split_axis, split_sizes});- auto attn_cache = wrap_type<v0::MatMul>({vsplit_out0, v_cache_input}, consumers_count(1));- auto attn_new = wrap_type<v0::MatMul>({vsplit_out1, v_new_input}, consumers_count(1));+ auto attn_cache = wrap_type<v0::MatMul>({vsplit->output(0), v_cache_input}, consumers_count(1));+ auto attn_new = wrap_type<v0::MatMul>({vsplit->output(1), v_new_input}, consumers_count(1));auto output_add = wrap_type<v1::Add>({attn_cache, attn_new});ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {@@ -671,7 +669,7 @@ SDPASplitAttentionFusionMatcher::SDPASplitAttentionFusionMatcher() {auto add_node = pattern_map.at(output_add).get_node_shared_ptr();auto matmul_cache = ov::as_type_ptr<v0::MatMul>(pattern_map.at(attn_cache).get_node_shared_ptr());auto matmul_new = ov::as_type_ptr<v0::MatMul>(pattern_map.at(attn_new).get_node_shared_ptr());- auto vsplit_node = ov::as_type_ptr<v1::VariadicSplit>(pattern_map.at(vsplit_out0).get_node_shared_ptr());+ auto vsplit_node = ov::as_type_ptr<v1::VariadicSplit>(m.get_pattern_map().at(vsplit));auto softmax_node = ov::as_type_ptr<v8::Softmax>(pattern_map.at(softmax).get_node_shared_ptr());auto concat_node = ov::as_type_ptr<v0::Concat>(pattern_map.at(scores_concat).get_node_shared_ptr());auto qk_cache_node = ov::as_type_ptr<v0::MatMul>(pattern_map.at(qk_cache).get_node_shared_ptr());diff --git a/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp b/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cppindex 0acb517b81d..562e63229bb 100644--- a/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp+++ b/src/common/transformations/src/transformations/paged_attention/state_management_pattern.cpp@@ -48,6 +48,7 @@ namespace pattern = ov::pass::pattern;using ov::pass::pattern::any_input;using ov::pass::pattern::Matcher;using ov::pass::pattern::wrap_type;+using ov::pass::pattern::wrap_type_strict_index;using ov::pass::pattern::op::Or;namespace v0 = ov::op::v0;@@ -395,13 +396,11 @@ ov::pass::StateManagementPattern::StateManagementPattern(PaParams& pa_params,// TODO: Consider not specifying VariadicSplit as an input for Concat, it is not really used in the pattern, but// just sets more strict requirement for the graph. The risk with not specifying VariadicSplit is that it can be// ambiguous which part the matcher should take: KV merged part or where K and V are separate, requires experiments.- auto qkv_current_split_node = wrap_type<v1::VariadicSplit>({any_input(), any_input(), any_input()});- qkv_current_split_node->set_output_size(2);+ auto qkv_current_split_node = wrap_type_strict_index<v1::VariadicSplit>({any_input(), any_input(), any_input()});auto kv_current = qkv_current_split_node->output(1);std::shared_ptr<ov::Node> kv_past_var, kv_current2, kv_concat, kv_current_reshaped;std::tie(kv_past_var, kv_current2, kv_current_reshaped, kv_concat) = kv_read_and_concat(kv_current);- auto kv_concat_split = wrap_type<v1::VariadicSplit>({kv_concat, any_input(), any_input()});- kv_concat_split->set_output_size(2);+ auto kv_concat_split = wrap_type_strict_index<v1::VariadicSplit>({kv_concat, any_input(), any_input()});k_concat = std::make_shared<Or>(OutputVector{kv_concat_split->output(0), k_concat});v_concat = std::make_shared<Or>(OutputVector{kv_concat_split->output(1), v_concat});@@ -564,15 +563,15 @@ ov::pass::StateManagementPattern::StateManagementPattern(PaParams& pa_params,std::make_shared<v1::Reshape>(q_transpose, v0::Constant::create(element::i64, Shape{2}, {0, -1}), true);ov::Output<ov::Node> k_target_layout, v_target_layout;- if (pattern_map.count(qkv_current_split_node)) {+ if (m.get_pattern_map().count(qkv_current_split_node)) {// Fast track for merged K/V caches, based on the currently observed models topologies we don't need to// change layout and there is no point in the graph where it is in 4D. So `else` branch below is not// applicable for this case. + std::to_string(m_layer_index)- auto qkv_split = pattern_map.at(qkv_current_split_node).get_node_shared_ptr();+ auto qkv_split = m.get_pattern_map().at(qkv_current_split_node);// TODO: Consider handling Q part as well as KV here, requires more changes in the code and sets// VariadicSplit before Concat as essential part of the patternauto kv_split_part = qkv_split->output(1);- auto real_kv_concat_split = pattern_map.at(kv_concat_split).get_node_shared_ptr();+ auto real_kv_concat_split = m.get_pattern_map().at(kv_concat_split);// Reaply VariadicSplit from the model after the Concat with KV merged tensor to current KV merged tensor// before the Concatauto kv_current_split = real_kv_concat_split->clone_with_new_inputs(diff --git a/src/core/include/openvino/core/node.hpp b/src/core/include/openvino/core/node.hppindex 511bea3489a..ff40bcdd574 100644--- a/src/core/include/openvino/core/node.hpp+++ b/src/core/include/openvino/core/node.hpp@@ -442,6 +442,12 @@ protected:/// \return true if constant folding disabled otherwise false.bool is_const_fold_disabled() const;+ /// \brief Make `output_index` addressable, called only by the non-const output().+ virtual void on_output_access(size_t output_index);++ /// \brief Throw if `output_index` is not addressable.+ virtual void validate_output_index(size_t output_index) const;+private:friend class ov::NodeAccessor;std::vector<Node*> m_control_dependents;diff --git a/src/core/include/openvino/pass/pattern/op/pattern.hpp b/src/core/include/openvino/pass/pattern/op/pattern.hppindex 18108609650..18767cf9270 100644--- a/src/core/include/openvino/pass/pattern/op/pattern.hpp+++ b/src/core/include/openvino/pass/pattern/op/pattern.hpp@@ -6,6 +6,7 @@#include <functional>+#include "openvino/core/deprecated.hpp"#include "openvino/core/node.hpp"#include "openvino/pass/pattern/op/predicate.hpp"@@ -67,7 +68,11 @@ OPENVINO_API op::Predicate attrs_match(const Attributes& expected_attrs);OPENVINO_API op::Predicate shape_matches(const std::string& shape_notation);OPENVINO_API op::Predicate value_matches(const std::string& value_notation);+OPENVINO_DEPRECATED("Use wrap_type_strict_index<T>() and reference the output directly, e.g. node->output(0). "+ "`output_index_matches()` will be removed in 2028.0 release.")OPENVINO_API op::Predicate output_index_matches(size_t expected_index);+OPENVINO_DEPRECATED("Use wrap_type_strict_index<T>() and reference the output directly, e.g. node->output(0). "+ "`output_index_matches()` will be removed in 2028.0 release.")OPENVINO_API op::Predicate output_index_matches(const std::vector<size_t>& expected_indices);namespace op {diff --git a/src/core/include/openvino/pass/pattern/op/wrap_type.hpp b/src/core/include/openvino/pass/pattern/op/wrap_type.hppindex 257cd1e3090..a53007111fa 100644--- a/src/core/include/openvino/pass/pattern/op/wrap_type.hpp+++ b/src/core/include/openvino/pass/pattern/op/wrap_type.hpp@@ -15,7 +15,10 @@ class OPENVINO_API WrapType : public Pattern {public:OPENVINO_RTTI("WrapType");- explicit WrapType(const std::vector<NodeTypeInfo>& wrapped_types) : Pattern(), m_wrapped_types(wrapped_types) {+ explicit WrapType(const std::vector<NodeTypeInfo>& wrapped_types)+ : Pattern(),+ m_wrapped_types(wrapped_types),+ m_strict_output_index(false) {set_output_type(0, element::Type_t::dynamic, PartialShape::dynamic());}@@ -24,18 +27,23 @@ public:const TPredicate& pred,const OutputVector& input_values = {}): Pattern(input_values, Predicate(pred)),- m_wrapped_types(wrapped_types) {+ m_wrapped_types(wrapped_types),+ m_strict_output_index(false) {set_output_type(0, element::Type_t::dynamic, PartialShape::dynamic());}- explicit WrapType(NodeTypeInfo wrapped_type) : Pattern(), m_wrapped_types({wrapped_type}) {+ explicit WrapType(NodeTypeInfo wrapped_type)+ : Pattern(),+ m_wrapped_types({wrapped_type}),+ m_strict_output_index(false) {set_output_type(0, element::Type_t::dynamic, PartialShape::dynamic());}template <typename TPredicate>WrapType(NodeTypeInfo wrapped_type, const TPredicate& pred, const OutputVector& input_values = {}): Pattern(input_values, Predicate(pred)),- m_wrapped_types({wrapped_type}) {+ m_wrapped_types({wrapped_type}),+ m_strict_output_index(false) {set_output_type(0, element::Type_t::dynamic, PartialShape::dynamic());}@@ -48,8 +56,17 @@ public:const std::vector<NodeTypeInfo>& get_wrapped_types() const;std::ostream& write_type_description(std::ostream& out) const override;+ void set_strict_output_index(bool strict) {+ m_strict_output_index = strict;+ }++protected:+ void on_output_access(size_t output_index) override;+ void validate_output_index(size_t output_index) const override;+private:std::vector<NodeTypeInfo> m_wrapped_types;+ bool m_strict_output_index;};} // namespace op@@ -94,5 +111,22 @@ std::shared_ptr<Node> wrap_type(std::initializer_list<std::pair<const std::strinreturn wrap_type<Args...>(PatternOps{}, Attributes(attrs));}+template <class... Args,+ typename TPredicate,+ typename std::enable_if_t<std::is_constructible_v<op::Predicate, TPredicate>>* = nullptr>+std::shared_ptr<Node> wrap_type_strict_index(const PatternOps& inputs,+ const TPredicate& pred,+ const Attributes& attrs = {}) {+ auto node = wrap_type<Args...>(inputs, op::Predicate(pred), attrs);+ auto wrap = ov::as_type_ptr<op::WrapType>(node);+ wrap->set_strict_output_index(true);+ return node;+}++template <class... Args>+std::shared_ptr<Node> wrap_type_strict_index(const PatternOps& inputs = {}, const Attributes& attrs = {}) {+ return wrap_type_strict_index<Args...>(inputs, (attrs.empty() ? op::Predicate() : attrs_match(attrs)));+}+OPENVINO_API std::shared_ptr<Node> wrap_const();} // namespace ov::pass::patterndiff --git a/src/core/src/node.cpp b/src/core/src/node.cppindex 0088ecac0ea..d2e27623219 100644--- a/src/core/src/node.cpp+++ b/src/core/src/node.cpp@@ -596,21 +596,23 @@ ov::Input<const ov::Node> ov::Node::input(size_t input_index) const {return {this, input_index};}-ov::Output<ov::Node> ov::Node::output(size_t output_index) {+void ov::Node::on_output_access(size_t output_index) {}++void ov::Node::validate_output_index(size_t output_index) const {// All nodes will have at least 1 outputif (output_index > 0 && output_index >= m_outputs.size()) {OPENVINO_THROW(node_idx_out_of_range_txt);}+}+ov::Output<ov::Node> ov::Node::output(size_t output_index) {+ on_output_access(output_index);+ validate_output_index(output_index);return {this, output_index};}ov::Output<const ov::Node> ov::Node::output(size_t output_index) const {- // All nodes will have at least 1 output- if (output_index > 0 && output_index >= m_outputs.size()) {- OPENVINO_THROW(node_idx_out_of_range_txt);- }-+ validate_output_index(output_index);return Output<const Node>(this, output_index);}diff --git a/src/core/src/pattern/op/pattern.cpp b/src/core/src/pattern/op/pattern.cppindex ba586358afc..3e88142aa68 100644--- a/src/core/src/pattern/op/pattern.cpp+++ b/src/core/src/pattern/op/pattern.cpp@@ -612,6 +612,7 @@ op::Predicate value_matches(const std::string& value_notation) {"value_matches('" + value_notation + "')");}+OPENVINO_SUPPRESS_DEPRECATED_STARTop::Predicate output_index_matches(size_t expected_index) {return op::Predicate([=](const Output<Node>& output) -> bool {@@ -628,5 +629,6 @@ op::Predicate output_index_matches(const std::vector<size_t>& expected_indices)},"output_index_matches({" + ov::util::join(expected_indices) + "})");}+OPENVINO_SUPPRESS_DEPRECATED_END} // namespace ov::pass::patterndiff --git a/src/core/src/pattern/op/wrap_type.cpp b/src/core/src/pattern/op/wrap_type.cppindex 7dc9d55dc81..b21d68bae84 100644--- a/src/core/src/pattern/op/wrap_type.cpp+++ b/src/core/src/pattern/op/wrap_type.cpp@@ -12,6 +12,11 @@bool ov::pass::pattern::op::WrapType::match_value(Matcher* matcher,const Output<Node>& pattern_value,const Output<Node>& graph_value) {+ if (m_strict_output_index && pattern_value.get_index() != graph_value.get_index()) {+ OPENVINO_LOG_WRAPTYPE2(matcher);+ return false;+ }+if (std::none_of(m_wrapped_types.begin(), m_wrapped_types.end(), [&](const NodeTypeInfo& type_info) {return graph_value.get_node_shared_ptr()->get_type_info().is_castable(type_info);})) {@@ -25,6 +30,14 @@ bool ov::pass::pattern::op::WrapType::match_value(Matcher* matcher,}auto& pattern_map = matcher->get_pattern_value_map();+ // Opt-in: bind this node to a single physical producer across all edges. On a+ // repeat visit the node is already validated, so skip re-matching its arguments.+ if (m_strict_output_index) {+ auto it = pattern_map.find(shared_from_this());+ if (it != pattern_map.end()) {+ return it->second.get_node() == graph_value.get_node();+ }+ }pattern_map[shared_from_this()] = graph_value;matcher->add_node(graph_value);OPENVINO_LOG_WRAPTYPE3(matcher, get_input_size());@@ -35,6 +48,21 @@ bool ov::pass::pattern::op::WrapType::match_value(Matcher* matcher,return res;}+void ov::pass::pattern::op::WrapType::on_output_access(size_t output_index) {+ if (m_strict_output_index && output_index >= get_output_size()) {+ set_output_size(output_index + 1);+ }+}++void ov::pass::pattern::op::WrapType::validate_output_index(size_t output_index) const {+ if (output_index > 0 && output_index >= get_output_size()) {+ OPENVINO_THROW("Output ",+ output_index,+ " is not available on WrapType, use ",+ m_strict_output_index ? "the non-const output()" : "wrap_type_strict_index<T>()");+ }+}+ov::NodeTypeInfo ov::pass::pattern::op::WrapType::get_wrapped_type() const {if (m_wrapped_types.size() > 1) {OPENVINO_THROW("get_wrapped_type() called on WrapType with more than one type");diff --git a/src/core/tests/pattern.cpp b/src/core/tests/pattern.cppindex 49d20ec9d8a..0f98e2f897f 100644--- a/src/core/tests/pattern.cpp+++ b/src/core/tests/pattern.cpp@@ -18,6 +18,7 @@#include "openvino/op/abs.hpp"#include "openvino/op/add.hpp"#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/cos.hpp"#include "openvino/op/cosh.hpp"@@ -1580,115 +1581,181 @@ TEST(pattern, predicate_syntactic_sugar) {ASSERT_NO_THROW(pattern::wrap_type<op::v0::Relu>("[-1,0,1]"));}-TEST(pattern, output_index_matches_predicate) {+TEST(pattern, multi_output_edge_index_honored) {TestMatcher tm;- // Create a VariadicSplit with 3 outputsauto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{10, 20, 30});auto axis = op::v0::Constant::create(element::i64, {}, {-1});auto split_lengths = op::v0::Constant::create(element::i64, {3}, {5, 10, 15});auto variadic_split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);- // Set output size to match the number of split lengths.variadic_split->set_output_size(3);- // Test basic output_index_matches predicate functionality- auto pred_0 = pattern::output_index_matches(0);- auto pred_1 = pattern::output_index_matches(1);- auto pred_2 = pattern::output_index_matches(2);-- // Test predicates directly- ASSERT_TRUE(pred_0(variadic_split->output(0)));- ASSERT_FALSE(pred_0(variadic_split->output(1)));- ASSERT_FALSE(pred_0(variadic_split->output(2)));-- ASSERT_FALSE(pred_1(variadic_split->output(0)));- ASSERT_TRUE(pred_1(variadic_split->output(1)));- ASSERT_FALSE(pred_1(variadic_split->output(2)));-- ASSERT_FALSE(pred_2(variadic_split->output(0)));- ASSERT_FALSE(pred_2(variadic_split->output(1)));- ASSERT_TRUE(pred_2(variadic_split->output(2)));-- // Test vector version- auto pred_multi = pattern::output_index_matches({0, 2});- ASSERT_TRUE(pred_multi(variadic_split->output(0)));- ASSERT_FALSE(pred_multi(variadic_split->output(1)));- ASSERT_TRUE(pred_multi(variadic_split->output(2)));-- // Test pattern matching specific output index- auto pattern_out0 = pattern::any_input(pattern::output_index_matches(0));- auto pattern_out1 = pattern::any_input(pattern::output_index_matches(1));- auto pattern_out2 = pattern::any_input(pattern::output_index_matches(2));- auto pattern_out3 = pattern::any_input(pattern::output_index_matches(3)); // non-existent output-- // Test matching different outputs using match_value- ASSERT_TRUE(tm.match_value(pattern_out0, variadic_split->output(0)));- ASSERT_FALSE(tm.match_value(pattern_out0, variadic_split->output(1)));- ASSERT_FALSE(tm.match_value(pattern_out0, variadic_split->output(2)));-- ASSERT_FALSE(tm.match_value(pattern_out1, variadic_split->output(0)));- ASSERT_TRUE(tm.match_value(pattern_out1, variadic_split->output(1)));- ASSERT_FALSE(tm.match_value(pattern_out1, variadic_split->output(2)));-- ASSERT_FALSE(tm.match_value(pattern_out2, variadic_split->output(0)));- ASSERT_FALSE(tm.match_value(pattern_out2, variadic_split->output(1)));- ASSERT_TRUE(tm.match_value(pattern_out2, variadic_split->output(2)));-- ASSERT_FALSE(tm.match_value(pattern_out3, variadic_split->output(0)));- ASSERT_FALSE(tm.match_value(pattern_out3, variadic_split->output(1)));- ASSERT_FALSE(tm.match_value(pattern_out3, variadic_split->output(2)));-- // Test pattern matching multiple output indices - simplified test- auto pattern_multi = pattern::any_input(pattern::output_index_matches({0, 2}));-- // Test with regular Matcher instead of TestMatcher- ov::pass::pattern::Matcher m1(pattern_multi);- ASSERT_TRUE(m1.match(variadic_split->output(0)));-- ov::pass::pattern::Matcher m2(pattern_multi);- ASSERT_FALSE(m2.match(variadic_split->output(1)));-- ov::pass::pattern::Matcher m3(pattern_multi);- ASSERT_TRUE(m3.match(variadic_split->output(2)));+ auto reshape_shape = op::v0::Constant::create(element::i64, {2}, {-1, 5});+ auto reshape0 = std::make_shared<op::v1::Reshape>(variadic_split->output(0), reshape_shape, false);+ auto reshape1 = std::make_shared<op::v1::Reshape>(variadic_split->output(1), reshape_shape, false);++ auto split_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>(+ {pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto reshape_p = pattern::wrap_type<op::v1::Reshape>({split_p->output(1), pattern::any_input()});++ // A pattern edge pinned to producer->output(1) must NOT match a graph value+ // that is physical output(0).+ ASSERT_FALSE(tm.match(reshape_p, reshape0));+ ASSERT_TRUE(tm.match(reshape_p, reshape1));}-TEST(pattern, wrap_type_with_output_index_constraint) {- TestMatcher tm;+TEST(pattern, multi_output_shared_producer_identity_enforced) {+ auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{10, 20, 30});+ auto axis = op::v0::Constant::create(element::i64, {}, {0});+ auto split_lengths = op::v0::Constant::create(element::i64, {2}, {5, 5});++ // Pattern: ONE split node, both outputs referenced by index.+ auto split_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>();+ auto concat_p = pattern::wrap_type<op::v0::Concat>({split_p->output(1), split_p->output(0)});++ // Positive control: both concat inputs come from the SAME split -> matches.+ {+ auto split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{split->output(1), split->output(0)}, 0);+ TestMatcher tm;+ ASSERT_TRUE(tm.match(concat_p, concat));+ }++ // A single pattern node cannot bind to two different physical producers.+ {+ auto split_a = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ auto split_b = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{split_b->output(1), split_a->output(0)}, 0);+ TestMatcher tm;+ ASSERT_FALSE(tm.match(concat_p, concat));+ }+}++TEST(pattern, multi_output_single_node_index_honored) {+ auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{10, 20, 30});+ auto axis = op::v0::Constant::create(element::i64, {}, {0});+ auto split_lengths = op::v0::Constant::create(element::i64, {2}, {5, 5});+ auto scale = op::v0::Constant::create(element::f32, Shape{}, {-1.0f});++ /*+ Pattern: ONE split node, outputs referenced by index.+ split_p+ / \+ out1 out0+ | |+ Multiply(out1, *) |+ \ /+ Concat(neg_p, out0)+ */+ auto build_pattern = []() {+ auto split_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>(+ {pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto neg_p = pattern::wrap_type<op::v1::Multiply>({split_p->output(1), pattern::any_input()});+ auto concat_p = pattern::wrap_type<op::v0::Concat>({neg_p, split_p->output(0)});+ return concat_p;+ };++ // Correctly-wired graph: neg uses output(1), concat uses output(0) -> matches.+ {+ auto split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ split->set_output_size(2);+ auto neg = std::make_shared<op::v1::Multiply>(split->output(1), scale);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{neg, split->output(0)}, 0);- // Create a VariadicSplit with 3 outputs+ TestMatcher tm;+ ASSERT_TRUE(tm.match(build_pattern(), concat));+ }++ // Swapped-wired graph: neg uses output(0), concat uses output(1) -> must NOT match.+ {+ auto split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ split->set_output_size(2);+ auto neg = std::make_shared<op::v1::Multiply>(split->output(0), scale);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{neg, split->output(1)}, 0);++ TestMatcher tm;+ ASSERT_FALSE(tm.match(build_pattern(), concat));+ }+}++TEST(pattern, multi_output_callback_map_access) {+ auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{10, 20, 30});+ auto axis = op::v0::Constant::create(element::i64, {}, {0});+ auto split_lengths = op::v0::Constant::create(element::i64, {2}, {5, 5});+ auto scale = op::v0::Constant::create(element::f32, Shape{}, {-1.0f});++ auto graph_split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ graph_split->set_output_size(2);+ auto neg = std::make_shared<op::v1::Multiply>(graph_split->output(1), scale);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{neg, graph_split->output(0)}, 0);++ auto split_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>(+ {pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto neg_p = pattern::wrap_type<op::v1::Multiply>({split_p->output(1), pattern::any_input()});+ auto concat_p = pattern::wrap_type<op::v0::Concat>({neg_p, split_p->output(0)});++ bool callback_ran = false;+ auto callback = [&](pattern::Matcher& m) {+ callback_ran = true;++ const auto& node_map = m.get_pattern_map();+ EXPECT_EQ(node_map.at(split_p), graph_split);++ // It's possible to retrieve the matched output value for a+ // multi-output node from the pattern-value map, but the outputs+ // are not guaranteed to be in any particular order, so it's important+ // to use this output with care. I.e. taking the graph node from it.+ const auto& value_map = m.get_pattern_value_map();+ Output<Node> stored = value_map.at(split_p);+ EXPECT_EQ(stored.get_node(), graph_split.get());++ // To obtain a SPECIFIC physical output, index into the matched producer's+ // outputs directly; the index stored in the map is traversal-dependent.+ auto producer = stored.get_node_shared_ptr();+ EXPECT_EQ(producer->output(0), graph_split->output(0));+ EXPECT_EQ(producer->output(1), graph_split->output(1));+ };++ pattern::Matcher m(concat_p, "MultiOutputCallback");+ ASSERT_TRUE(m.match(concat->output(0)));+ callback(m);+ EXPECT_TRUE(callback_ran);+}++TEST(pattern, wrap_type_strict_index_matches_subset_of_outputs) {auto input = std::make_shared<op::v0::Parameter>(element::f32, Shape{10, 20, 30});auto axis = op::v0::Constant::create(element::i64, {}, {-1});- auto split_lengths = op::v0::Constant::create(element::i64, {3}, {5, 10, 15});- auto variadic_split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);- // Explicitly set output size to 3 to ensure the VariadicSplit node produces the expected number of outputs.- // Although split_lengths has 3 elements, set_output_size(3) may be required for correct behavior in some cases.- variadic_split->set_output_size(3);+ auto split_lengths = op::v0::Constant::create(element::i64, {3}, {10, 10, 10});+ auto scale = op::v0::Constant::create(element::f32, Shape{}, {2.0f});- // Create reshapes that use different outputs- auto reshape_shape = op::v0::Constant::create(element::i64, {2}, {-1, 5});- auto reshape0 = std::make_shared<op::v1::Reshape>(variadic_split->output(0), reshape_shape, false);- auto reshape1 = std::make_shared<op::v1::Reshape>(variadic_split->output(1), reshape_shape, false);- auto reshape2 = std::make_shared<op::v1::Reshape>(variadic_split->output(2), reshape_shape, false);+ // Graph node has THREE outputs; output(2) feeds a consumer the pattern+ // does not describe, but still matches. This is ok.+ auto split = std::make_shared<op::v1::VariadicSplit>(input, axis, split_lengths);+ split->set_output_size(3);+ ASSERT_EQ(split->get_output_size(), 3);+ auto ignored = std::make_shared<op::v1::Multiply>(split->output(2), scale);- // Create patterns that match Reshape with specific VariadicSplit output- auto vsplit_out0 = pattern::wrap_type<op::v1::VariadicSplit>(pattern::output_index_matches(0));- auto vsplit_out1 = pattern::wrap_type<op::v1::VariadicSplit>(pattern::output_index_matches(1));- auto vsplit_out2 = pattern::wrap_type<op::v1::VariadicSplit>(pattern::output_index_matches(2));+ auto neg = std::make_shared<op::v1::Multiply>(split->output(1), scale);+ auto concat = std::make_shared<op::v0::Concat>(OutputVector{neg, split->output(0)}, 0);- auto pattern_reshape_out0 = pattern::wrap_type<op::v1::Reshape>({vsplit_out0, pattern::any_input()});- auto pattern_reshape_out1 = pattern::wrap_type<op::v1::Reshape>({vsplit_out1, pattern::any_input()});- auto pattern_reshape_out2 = pattern::wrap_type<op::v1::Reshape>({vsplit_out2, pattern::any_input()});+ // Pattern producer only references output(0)/output(1).+ auto split_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>(+ {pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto neg_p = pattern::wrap_type<op::v1::Multiply>({split_p->output(1), pattern::any_input()});+ auto concat_p = pattern::wrap_type<op::v0::Concat>({neg_p, split_p->output(0)});- // Test that patterns match only corresponding reshapes- ASSERT_TRUE(tm.match(pattern_reshape_out0, reshape0));- ASSERT_FALSE(tm.match(pattern_reshape_out0, reshape1));- ASSERT_FALSE(tm.match(pattern_reshape_out0, reshape2));+ TestMatcher tm;+ ASSERT_TRUE(tm.match(concat_p, concat));+}- ASSERT_FALSE(tm.match(pattern_reshape_out1, reshape0));- ASSERT_TRUE(tm.match(pattern_reshape_out1, reshape1));- ASSERT_FALSE(tm.match(pattern_reshape_out1, reshape2));+TEST(pattern, wrap_type_strict_index_output_grows_through_base_handle) {+ std::shared_ptr<ov::Node> strict_p = pattern::wrap_type_strict_index<op::v1::VariadicSplit>();+ EXPECT_EQ(strict_p->get_output_size(), 1);+ EXPECT_NO_THROW(strict_p->output(3));+ EXPECT_EQ(strict_p->get_output_size(), 4);- ASSERT_FALSE(tm.match(pattern_reshape_out2, reshape0));- ASSERT_FALSE(tm.match(pattern_reshape_out2, reshape1));- ASSERT_TRUE(tm.match(pattern_reshape_out2, reshape2));+ // Non-strict pattern nodes keep the base out-of-range check.+ std::shared_ptr<ov::Node> plain_p = pattern::wrap_type<op::v1::VariadicSplit>();+ EXPECT_THROW(plain_p->output(1), ov::Exception);+ EXPECT_EQ(plain_p->get_output_size(), 1);}diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cppindex 97d34f73d1f..991eecde120 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/x64/pass/mlp_fusion.cpp@@ -5,7 +5,6 @@#include "mlp_fusion.hpp"#include <memory>-#include <utility>#include "openvino/cc/pass/itt.hpp"#include "openvino/core/graph_util.hpp"@@ -14,6 +13,7 @@#include "openvino/core/partial_shape.hpp"#include "openvino/core/rt_info.hpp"#include "openvino/core/shape.hpp"+#include "openvino/core/type.hpp"#include "openvino/core/type/element_type.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/convert.hpp"@@ -25,6 +25,7 @@#include "openvino/pass/matcher_pass.hpp"#include "openvino/pass/pattern/matcher.hpp"#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/optional.hpp"#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "openvino/util/pp.hpp"@@ -59,13 +60,13 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {auto input = any_input(rank_equals(3));auto gate_proj_weight_compressed = wrap_type<Constant>(); // [up_size, down_size]- auto gate_proj_weight = wrap_type<Convert>(gate_proj_weight_compressed, {{"destination_type", "f32"}});+ auto gate_proj_weight = optional<Convert>(gate_proj_weight_compressed, {{"destination_type", "f32"}});auto up_proj_weight_compressed = wrap_type<Constant>(); // [up_size, down_size]- auto up_proj_weight = wrap_type<Convert>(up_proj_weight_compressed, {{"destination_type", "f32"}});+ auto up_proj_weight = optional<Convert>(up_proj_weight_compressed, {{"destination_type", "f32"}});auto down_proj_weight_compressed = wrap_type<Constant>(); // [down_size, up_size]- auto down_proj_weight = wrap_type<Convert>(down_proj_weight_compressed, {{"destination_type", "f32"}});+ auto down_proj_weight = optional<Convert>(down_proj_weight_compressed, {{"destination_type", "f32"}});// symmetrically INT8 quantized version// all 3 layers must be quantized at the same time (checked in callback)@@ -89,7 +90,7 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {// gate-up weights are combinedauto gate_up_proj_weight = wrap_type<Constant>(type_matches(element::f16) && rank_equals(2));- auto gate_up_proj_weight_f32 = wrap_type<Convert>(gate_up_proj_weight, {{"destination_type", "f32"}});+ auto gate_up_proj_weight_f32 = optional<Convert>(gate_up_proj_weight, {{"destination_type", "f32"}});auto gate_up_proj_weight_const_i8 = wrap_type<Constant>(type_matches(element::i8) && rank_equals(2));auto gate_up_proj_weight_cvt_f32 = wrap_type<Convert>(gate_up_proj_weight_const_i8, {{"destination_type", "f32"}});@@ -103,21 +104,16 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {auto gate_up_proj_split = wrap_type<VariadicSplit>({gate_up_proj, -1, gate_up_split_lengths});gate_up_proj_split->set_output_size(2);- auto mlp_gate_proj =- wrap_type<MatMul>({input, gate_proj_weight | gate_proj_weight_compressed | gate_proj_weight_deq},- {{"transpose_a", false}, {"transpose_b", true}});- auto mlp_silu_gate = wrap_type<Swish>({mlp_gate_proj | gate_up_proj_split});- auto mlp_gelu_gate = wrap_type<Gelu>({mlp_gate_proj | gate_up_proj_split});- auto mlp_up_proj = wrap_type<MatMul>({input, up_proj_weight | up_proj_weight_compressed | up_proj_weight_deq},+ auto mlp_gate_proj = wrap_type<MatMul>({input, gate_proj_weight | gate_proj_weight_deq},+ {{"transpose_a", false}, {"transpose_b", true}});+ auto mlp_gate_act = wrap_type<Swish, Gelu>({mlp_gate_proj | gate_up_proj_split});+ auto mlp_up_proj = wrap_type<MatMul>({input, up_proj_weight | up_proj_weight_deq},{{"transpose_a", false}, {"transpose_b", true}});- auto mlp_gated_up = wrap_type<Multiply>({mlp_silu_gate | mlp_gelu_gate, mlp_up_proj | gate_up_proj_split},- {{"auto_broadcast", "numpy"}});- auto down_proj =- wrap_type<MatMul>({mlp_gated_up, down_proj_weight | down_proj_weight_compressed | down_proj_weight_deq},- {{"transpose_a", false}, {"transpose_b", true}});-- auto result = down_proj;+ auto mlp_gated_up =+ wrap_type<Multiply>({mlp_gate_act, mlp_up_proj | gate_up_proj_split}, {{"auto_broadcast", "numpy"}});+ auto down_proj = wrap_type<MatMul>({mlp_gated_up, down_proj_weight | down_proj_weight_deq},+ {{"transpose_a", false}, {"transpose_b", true}});matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();@@ -125,19 +121,11 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {// Determine gate_up_type based on pattern matchingLLMMLPNode::GATE_UP_TYPE gate_up_type = LLMMLPNode::GATE_UP_TYPE::SEPARATE;- if (pattern_map.find(gate_up_proj_split) != pattern_map.end()) {- auto mlp_gated_up_node = pattern_map.at(mlp_gated_up).get_node_shared_ptr();- auto input0 = mlp_gated_up_node->input_value(0);- auto input1 = mlp_gated_up_node->input_value(1);-- // Check if VariadicSplit output[0] connects to Multiply (swapped case)- // Since pattern matching succeeded, we know one of the outputs connects to Multiply- if ((input0.get_node() == pattern_map.at(gate_up_proj_split).get_node() && input0.get_index() == 0) ||- (input1.get_node() == pattern_map.at(gate_up_proj_split).get_node() && input1.get_index() == 0)) {- gate_up_type = LLMMLPNode::GATE_UP_TYPE::COMBINED_UP_GATE; // swapped case- } else {- gate_up_type = LLMMLPNode::GATE_UP_TYPE::COMBINED_GATE_UP; // normal combined case- }+ if (pattern_map.count(gate_up_proj_split)) {+ // The gate half feeds the activation: gate at split output(0) is the normal layout, otherwise swapped.+ auto gate_src = pattern_map.at(mlp_gate_act).get_node_shared_ptr()->input_value(0);+ gate_up_type = (gate_src.get_index() == 0) ? LLMMLPNode::GATE_UP_TYPE::COMBINED_GATE_UP+ : LLMMLPNode::GATE_UP_TYPE::COMBINED_UP_GATE;}auto src = pattern_map.at(input);@@ -237,37 +225,16 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {return false;}- auto [config, gate_act] = [&]() -> std::pair<LLMMLPNode::Config, std::shared_ptr<Node>> {- LLMMLPNode::Config cfg{};-- cfg.gate_up_quantized = is_gate_up_quantized_int8;- cfg.down_quantized = is_down_proj_int8;- cfg.hidden_size = static_cast<int>(down_size);- cfg.up_size = static_cast<int>(up_size);- cfg.gate_up_type = gate_up_type;-- if (pattern_map.count(mlp_silu_gate) > 0) {- cfg.act = LLMMLPNode::ACT_FN::SILU;- return {cfg, mlp_silu_gate};- }-- if (pattern_map.count(mlp_gelu_gate) > 0) {- cfg.act = LLMMLPNode::ACT_FN::GELU;- return {cfg, mlp_gelu_gate};- }-- return {cfg, nullptr};- }();-- if (!gate_act) {- return false;- }+ LLMMLPNode::Config config{};+ config.act = ov::is_type<Swish>(pattern_map.at(mlp_gate_act).get_node()) ? LLMMLPNode::ACT_FN::SILU+ : LLMMLPNode::ACT_FN::GELU;+ config.gate_up_quantized = is_gate_up_quantized_int8;+ config.down_quantized = is_down_proj_int8;+ config.hidden_size = static_cast<int>(down_size);+ config.up_size = static_cast<int>(up_size);+ config.gate_up_type = gate_up_type;- OutputVector new_args;- new_args.push_back(src);- new_args.push_back(gate_proj_w);- new_args.push_back(up_proj_w);- new_args.push_back(down_proj_w);+ OutputVector new_args{src, gate_proj_w, up_proj_w, down_proj_w};if (is_gate_up_quantized_int8) {if (gate_up_type != LLMMLPNode::GATE_UP_TYPE::SEPARATE) {new_args.push_back(pattern_map.at(gate_up_proj_weight_scales_per_OC));@@ -285,7 +252,7 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {auto new_node = std::make_shared<LLMMLPNode>(new_args, config);new_node->set_friendly_name(old_node->get_friendly_name());ov::copy_runtime_info(- {pattern_map.at(gate_act).get_node_shared_ptr(), pattern_map.at(down_proj).get_node_shared_ptr()},+ {pattern_map.at(mlp_gate_act).get_node_shared_ptr(), pattern_map.at(down_proj).get_node_shared_ptr()},new_node);if (gate_up_type != LLMMLPNode::GATE_UP_TYPE::SEPARATE) {ov::copy_runtime_info({pattern_map.at(gate_up_proj).get_node_shared_ptr()}, new_node);@@ -303,6 +270,6 @@ ov::intel_cpu::MLPFusionPass::MLPFusionPass() {return true;};- auto m = std::make_shared<ov::pass::pattern::Matcher>(result, matcher_name);+ auto m = std::make_shared<ov::pass::pattern::Matcher>(down_proj, matcher_name);this->register_matcher(m, callback);}diff --git a/src/plugins/intel_gpu/src/plugin/transformations/disable_fp16_comp_gated_residual.cpp b/src/plugins/intel_gpu/src/plugin/transformations/disable_fp16_comp_gated_residual.cppindex cd83cd90e36..c9fd6ac8ddb 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/disable_fp16_comp_gated_residual.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/disable_fp16_comp_gated_residual.cpp@@ -21,13 +21,13 @@namespace ov::intel_gpu {DisableFP16CompForQwenImageGatedResidualPattern::DisableFP16CompForQwenImageGatedResidualPattern() {+ using namespace ov::pass;using namespace ov::pass::pattern;- auto outer_split_out0 = wrap_type<ov::op::v1::VariadicSplit>({any_input(), any_input(), any_input()}, output_index_matches(0));- auto outer_split_out1 = wrap_type<ov::op::v1::VariadicSplit>({any_input(), any_input(), any_input()}, output_index_matches(1));- auto outer_split = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{outer_split_out0, outer_split_out1});- auto inner_split = wrap_type<ov::op::v1::VariadicSplit>({outer_split, any_input(), any_input()}, output_index_matches(2));- auto gate = wrap_type<ov::op::v0::Unsqueeze>({inner_split, any_input()}, type_matches(element::f32));+ auto outer_split = wrap_type_strict_index<ov::op::v1::VariadicSplit>({any_input(), any_input(), any_input()});+ auto outer_split_out = outer_split->output(0) | outer_split->output(1);+ auto inner_split = wrap_type_strict_index<ov::op::v1::VariadicSplit>({outer_split_out, any_input(), any_input()});+ auto gate = wrap_type<ov::op::v0::Unsqueeze>({inner_split->output(2), any_input()}, type_matches(element::f32));auto branch_matmul = wrap_type<ov::op::v0::MatMul>({any_input(), any_input()}, type_matches(element::f32));auto linear_add0 = wrap_type<ov::op::v1::Add>({branch_matmul, any_input()}, type_matches(element::f32));diff --git a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cppindex 1dbe7119a26..17a3c90c647 100644--- a/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp+++ b/src/plugins/intel_gpu/src/plugin/transformations/fuse_moe_router.cpp@@ -42,8 +42,7 @@ FuseMoESoftmaxRouter::FuseMoESoftmaxRouter() {auto softmax_m = wrap_type<ov::op::v8::Softmax>({routing_matmul}, consumers_count(1));auto topk_k_m = wrap_const();- auto topk_m = wrap_type<ov::op::v11::TopK>({softmax_m, topk_k_m});- topk_m->set_output_size(2);+ auto topk_m = wrap_type_strict_index<ov::op::v11::TopK>({softmax_m, topk_k_m});auto reduce_m = wrap_type<ov::op::v1::ReduceSum>({topk_m->output(0), any_input()}, consumers_count(1));auto norm_m = wrap_type<ov::op::v1::Divide>({topk_m->output(0), reduce_m});@@ -54,7 +53,7 @@ FuseMoESoftmaxRouter::FuseMoESoftmaxRouter() {}const auto& pattern_map = m.get_pattern_value_map();const auto& topk_in_shape = pattern_map.at(softmax_m).get_partial_shape();- const auto& topk_out_shape = pattern_map.at(topk_m).get_partial_shape();+ const auto& topk_out_shape = m.get_pattern_map().at(topk_m)->output(0).get_partial_shape();for (const auto& shape : {topk_in_shape, topk_out_shape}) {if (shape.rank().is_dynamic() || shape.size() == 0 || shape.rbegin()->is_dynamic()) {return false;@@ -96,9 +95,7 @@ FuseMoESigmoidRouter::FuseMoESigmoidRouter() {auto sigmoid_m = wrap_type<ov::op::v0::Sigmoid>({routing_matmul});auto routing_bias_m = any_input();auto add_m = wrap_type<ov::op::v1::Add>({sigmoid_m, routing_bias_m}, consumers_count(1));- auto topk_k_m = wrap_const();- auto topk_m = wrap_type<ov::op::v11::TopK>({add_m, topk_k_m});- topk_m->set_output_size(2);+ auto topk_m = wrap_type_strict_index<ov::op::v11::TopK>({add_m, wrap_const()});auto convert_topk_m = wrap_type<ov::op::v0::Convert>({topk_m->output(1)});auto indices_m = convert_topk_m | topk_m->output(1);@@ -118,7 +115,7 @@ FuseMoESigmoidRouter::FuseMoESigmoidRouter() {}const auto& pattern_map = m.get_pattern_value_map();const auto& topk_in_shape = pattern_map.at(add_m).get_partial_shape();- const auto& topk_out_shape = pattern_map.at(topk_m).get_partial_shape();+ const auto& topk_out_shape = m.get_pattern_map().at(topk_m)->output(1).get_partial_shape();for (const auto& shape : {topk_in_shape, topk_out_shape}) {if (shape.rank().is_dynamic() || shape.size() == 0 || shape.rbegin()->is_dynamic()) {return false;