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
[Snippets] Support ShapeOf derived MHA Broadcast and Reshape (#37749)
Arseniy Obolenskiyfde316cf48b3
diff --git a/src/common/snippets/include/snippets/pass/softmax_reshape_elimination.hpp b/src/common/snippets/include/snippets/pass/softmax_reshape_elimination.hppindex 37d50fee802..44d67061574 100644--- a/src/common/snippets/include/snippets/pass/softmax_reshape_elimination.hpp+++ b/src/common/snippets/include/snippets/pass/softmax_reshape_elimination.hpp@@ -4,6 +4,9 @@#pragma once+#include <memory>++#include "openvino/op/reshape.hpp"#include "openvino/pass/matcher_pass.hpp"namespace ov::snippets::pass {@@ -17,6 +20,11 @@ class SoftmaxReshapeElimination : public ov::pass::MatcherPass {public:OPENVINO_MATCHER_PASS_RTTI("snippets::pass::SoftmaxReshapeElimination");SoftmaxReshapeElimination();++ /// Removes Reshape operations around Softmax when the transformation preserves the last dimension.+ static bool eliminate(const std::shared_ptr<ov::op::v1::Reshape>& reshape0,+ const std::shared_ptr<ov::Node>& softmax,+ const std::shared_ptr<ov::op::v1::Reshape>& reshape1);};} // namespace ov::snippets::passdiff --git a/src/common/snippets/src/pass/mha_tokenization.cpp b/src/common/snippets/src/pass/mha_tokenization.cppindex 9314dabe2cc..5985bc0b4dc 100644--- a/src/common/snippets/src/pass/mha_tokenization.cpp+++ b/src/common/snippets/src/pass/mha_tokenization.cpp@@ -26,6 +26,7 @@#include "openvino/op/select.hpp"#include "openvino/op/util/attr_types.hpp"#include "openvino/op/util/binary_elementwise_arithmetic.hpp"+#include "openvino/op/util/shape_of_base.hpp"#include "openvino/op/util/unary_elementwise_arithmetic.hpp"#include "openvino/opsets/opset1.hpp"#include "openvino/pass/pattern/matcher.hpp"@@ -35,6 +36,7 @@#include "snippets/op/brgemm.hpp"#include "snippets/pass/collapse_subgraph.hpp"#include "snippets/pass/explicit_transpose_matmul_inputs.hpp"+#include "snippets/pass/softmax_reshape_elimination.hpp"#include "snippets/pass/tokenization.hpp"#include "snippets/utils/tokenization_utils.hpp"#include "snippets/utils/utils.hpp"@@ -97,11 +99,15 @@ void tokenize_broadcast(const std::shared_ptr<ov::Node>& interm_op, ov::NodeVectconst auto broadcast = input.get_source_output().get_node_shared_ptr();// TODO: Can we reuse AppropriateForSubgraph here? Seems like it's huge check for Broadcastif (ov::snippets::utils::is_numpy_broadcast(broadcast) && broadcast->get_output_target_inputs(0).size() == 1) {- // TODO: Add support of Broadcast with ShapeOf subgraph on second input- if (!ov::is_type<ov::op::v0::Constant>(broadcast->input_value(1).get_node_shared_ptr())) {- continue;+ const auto target = broadcast->input_value(1).get_node_shared_ptr();+ if (!ov::is_type<ov::op::v0::Constant>(target)) {+ const auto shape_of = ov::as_type_ptr<ov::op::util::ShapeOfBase>(target);+ const auto inputs = interm_op->input_values();+ // The other operand must preserve the runtime batch expansion after Broadcast removal.+ if (!shape_of || std::find(inputs.begin(), inputs.end(), shape_of->input_value(0)) == inputs.end()) {+ continue;+ }}-broadcast_nodes.push_back(broadcast);const auto pshape = broadcast->get_input_partial_shape(0);@@ -127,22 +133,35 @@ void tokenize_broadcast(const std::shared_ptr<ov::Node>& interm_op, ov::NodeVect}}+bool is_shape_of_consumer(const ov::Input<ov::Node>& input) {+ return ov::is_type<ov::op::util::ShapeOfBase>(input.get_node());+}++bool has_shape_of_consumer(const std::shared_ptr<ov::Node>& node) {+ const auto& target_inputs = node->get_output_target_inputs(0);+ return target_inputs.size() == 2 && std::any_of(target_inputs.begin(), target_inputs.end(), is_shape_of_consumer);+}++std::shared_ptr<ov::Node> get_data_consumer(const std::shared_ptr<ov::Node>& node) {+ const auto& target_inputs = node->get_output_target_inputs(0);+ const auto it = std::find_if(target_inputs.begin(), target_inputs.end(), [](const ov::Input<ov::Node>& input) {+ return !is_shape_of_consumer(input);+ });+ return it == target_inputs.end() ? nullptr : it->get_node()->shared_from_this();+}++std::shared_ptr<ov::Node> get_shape_of_consumer(const std::shared_ptr<ov::Node>& node) {+ const auto& target_inputs = node->get_output_target_inputs(0);+ const auto it = std::find_if(target_inputs.begin(), target_inputs.end(), is_shape_of_consumer);+ return it == target_inputs.end() ? nullptr : it->get_node()->shared_from_this();+}+bool tokenize_reshape_around_softmax(std::shared_ptr<ov::Node>& interm_op,std::shared_ptr<ov::opset1::Reshape>& reshape,ov::NodeVector& ordered_ops) {reshape = ov::as_type_ptr<ov::opset1::Reshape>(interm_op);if (reshape) {- // TODO: Add support of Reshape with ShapeOf subgraph on second input- if (!ov::is_type<ov::op::v0::Constant>(reshape->input_value(1).get_node_shared_ptr())) {- return false;- }-- const auto in_shape = reshape->get_input_partial_shape(0);- const auto out_shape = reshape->get_output_partial_shape(0);- const auto in_last_dim = *in_shape.crbegin();- const auto out_last_dim = *out_shape.crbegin();- if (in_last_dim.is_dynamic() || out_last_dim.is_dynamic() || in_last_dim != out_last_dim ||- reshape->get_output_target_inputs(0).size() != 1) {+ if (reshape->get_output_target_inputs(0).size() != 1) {return false;}@@ -157,7 +176,7 @@ bool update_intermediate_supported_ops(std::shared_ptr<ov::Node>& interm_op,size_t& n_potential_body_params) {while (is_supported_intermediate_op(interm_op)) {// All supported intermediate ops have only one output port- if (interm_op->get_output_target_inputs(0).size() != 1) {+ if (interm_op->get_output_target_inputs(0).size() != 1 && !has_shape_of_consumer(interm_op)) {return false;}@@ -199,9 +218,12 @@ bool update_intermediate_supported_ops(std::shared_ptr<ov::Node>& interm_op,n_potential_body_params += get_potential_body_params(interm_op);ordered_ops.push_back(interm_op);- interm_op = interm_op->get_output_target_inputs(0).begin()->get_node()->shared_from_this();+ if (has_shape_of_consumer(interm_op)) {+ ordered_ops.push_back(get_shape_of_consumer(interm_op));+ }+ interm_op = get_data_consumer(interm_op);}- return true;+ return interm_op != nullptr;}std::vector<int32_t> get_rank_equivalent_order(std::vector<int32_t> default_order, size_t rank) {@@ -224,8 +246,9 @@ std::vector<int32_t> ov::snippets::pass::TokenizeMHASnippets::get_decomposed_tra}bool ov::snippets::pass::TokenizeMHASnippets::is_matmul0_supported(const std::shared_ptr<ov::opset1::MatMul>& matmul) {- if (!matmul || matmul->get_output_target_inputs(0).size() != 1 || matmul->get_transpose_a() ||- !is_supported_tensor(matmul->get_input_tensor(0)) || !is_supported_tensor(matmul->get_input_tensor(1))) {+ if (!matmul || (matmul->get_output_target_inputs(0).size() != 1 && !has_shape_of_consumer(matmul)) ||+ matmul->get_transpose_a() || !is_supported_tensor(matmul->get_input_tensor(0)) ||+ !is_supported_tensor(matmul->get_input_tensor(1))) {return false;}@@ -292,9 +315,16 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const Config& confiordered_ops.push_back(matmul0);+ if (has_shape_of_consumer(matmul0)) {+ ordered_ops.push_back(get_shape_of_consumer(matmul0));+ }+const auto pattern_rank = matmul0->get_output_partial_shape(0).size();- auto interm_op = matmul0->get_output_target_inputs(0).begin()->get_node()->shared_from_this();+ auto interm_op = get_data_consumer(matmul0);+ if (!interm_op) {+ return false;+ }// Add supported operations which are between MatMul0 and Softmax to ordered_opsif (!update_intermediate_supported_ops(interm_op, ordered_ops, n_potential_body_params)) {return false;@@ -305,9 +335,10 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const Config& confireturn false;}- const auto axis = ov::snippets::utils::get_softmax_axis(interm_op);- const auto rank = static_cast<int64_t>(interm_op->get_input_partial_shape(0).rank().get_length());- if (!axis || *axis != (rank - 1) || interm_op->get_output_target_inputs(0).size() != 1) {+ const auto softmax = interm_op;+ const auto axis = ov::snippets::utils::get_softmax_axis(softmax);+ if (!axis || *axis != softmax->get_input_partial_shape(0).rank().get_length() - 1 ||+ softmax->get_output_target_inputs(0).size() != 1) {return false;}@@ -319,9 +350,7 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const Config& confireturn false;}- if (((reshape0 == nullptr) != (reshape1 == nullptr)) ||- (reshape0 && reshape1 &&- (reshape0->get_input_partial_shape(0) != reshape1->get_output_partial_shape(0)))) {+ if ((reshape0 == nullptr) != (reshape1 == nullptr)) {return false;}@@ -466,6 +495,33 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const Config& confireturn false;}+ // ShapeOf must become unused when its shape-input consumer is removed.+ for (const auto& op : ordered_ops) {+ if (!ov::is_type<ov::op::util::ShapeOfBase>(op)) {+ continue;+ }+ const auto& consumers = op->get_output_target_inputs(0);+ if (consumers.size() != 1) {+ return false;+ }+ const auto& input = *consumers.begin();+ const auto consumer = input.get_node()->shared_from_this();+ if (input.get_index() != 1 ||+ (consumer != reshape0 && consumer != reshape1 &&+ (!is_numpy_broadcast(consumer) ||+ std::find(ordered_ops.begin(), ordered_ops.end(), consumer) == ordered_ops.end()))) {+ return false;+ }+ }++ if (reshape0 && reshape1) {+ if (!ov::snippets::pass::SoftmaxReshapeElimination::eliminate(reshape0, softmax, reshape1)) {+ return false;+ }+ ordered_ops.erase(std::find(ordered_ops.begin(), ordered_ops.end(), reshape0));+ ordered_ops.erase(std::find(ordered_ops.begin(), ordered_ops.end(), reshape1));+ }+const auto subgraph = tokenize_ordered_nodes(ordered_ops);// mark the Subgraph as Completed to not allow Snippets to include any nodes into the MHA Subgraph in common// Tokenizationdiff --git a/src/common/snippets/src/pass/softmax_reshape_elimination.cpp b/src/common/snippets/src/pass/softmax_reshape_elimination.cppindex 72904903bac..5a6e4125ad6 100644--- a/src/common/snippets/src/pass/softmax_reshape_elimination.cpp+++ b/src/common/snippets/src/pass/softmax_reshape_elimination.cpp@@ -4,21 +4,76 @@#include "snippets/pass/softmax_reshape_elimination.hpp"-#include <cstdint>+#include <algorithm>#include <memory>#include "openvino/core/graph_util.hpp"-#include "openvino/core/rt_info.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_input.hpp"+#include "openvino/core/node_output.hpp"#include "openvino/core/type.hpp"#include "openvino/op/constant.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/softmax.hpp"+#include "openvino/op/util/shape_of_base.hpp"#include "openvino/pass/pattern/matcher.hpp"#include "openvino/pass/pattern/op/label.hpp"#include "openvino/pass/pattern/op/pattern.hpp"#include "openvino/pass/pattern/op/wrap_type.hpp"#include "snippets/itt.hpp"#include "snippets/utils/utils.hpp"+#include "transformations/symbolic_transformations/utils.hpp"++bool ov::snippets::pass::SoftmaxReshapeElimination::eliminate(const std::shared_ptr<ov::op::v1::Reshape>& reshape0,+ const std::shared_ptr<ov::Node>& softmax,+ const std::shared_ptr<ov::op::v1::Reshape>& reshape1) {+ const auto input_shape = reshape0->get_input_partial_shape(0);+ const auto output_shape = reshape1->get_output_partial_shape(0);+ const auto softmax_shape = softmax->get_input_partial_shape(0);+ if (input_shape.rank().is_dynamic() || output_shape.rank().is_dynamic() || softmax_shape.rank().is_dynamic() ||+ input_shape.rank().get_length() == 0 || softmax_shape.rank().get_length() == 0 ||+ input_shape.rank() != output_shape.rank()) {+ return false;+ }++ const auto shape_of = ov::as_type_ptr<ov::op::util::ShapeOfBase>(reshape1->input_value(1).get_node_shared_ptr());+ const bool shape_of_input = shape_of && shape_of->input_value(0) == reshape0->input_value(0);+ const bool constant_patterns = ov::is_type<ov::op::v0::Constant>(reshape0->get_input_node_ptr(1)) &&+ ov::is_type<ov::op::v0::Constant>(reshape1->get_input_node_ptr(1));+ if (!shape_of_input && (!constant_patterns || input_shape != output_shape) &&+ !std::equal(input_shape.begin(), input_shape.end(), output_shape.begin(), ov::symbol::util::dims_are_equal)) {+ return false;+ }++ const auto axis = ov::snippets::utils::get_softmax_axis(softmax);+ // Supports only the last axis.+ if (!axis || *axis != softmax_shape.rank().get_length() - 1) {+ return false;+ }++ // An unknown reduction dimension is not proof that the reshape preserves it.+ const auto& in_last_dim = *input_shape.crbegin();+ if (!ov::symbol::util::dims_are_equal(in_last_dim, *softmax_shape.crbegin()) ||+ (!shape_of_input && !ov::symbol::util::dims_are_equal(in_last_dim, *output_shape.crbegin()))) {+ return false;+ }++ // Eliminate Reshape before Softmax.+ replace_output_update_name(reshape0->output(0), reshape0->input_value(0));++ // Eliminate Reshape after Softmax with name saving.+ replace_output_update_name(reshape1->output(0), reshape1->input_value(0));++ // Update axis.+ const auto new_axis = input_shape.rank().get_length() - 1;+ if (auto softmax_v8 = ov::as_type_ptr<ov::op::v8::Softmax>(softmax)) {+ softmax_v8->set_axis(new_axis);+ } else if (auto softmax_v1 = ov::as_type_ptr<ov::op::v1::Softmax>(softmax)) {+ softmax_v1->set_axis(new_axis);+ }++ return true;+}ov::snippets::pass::SoftmaxReshapeElimination::SoftmaxReshapeElimination() {MATCHER_SCOPE(SoftmaxReshapeElimination);@@ -31,55 +86,16 @@ ov::snippets::pass::SoftmaxReshapeElimination::SoftmaxReshapeElimination() {const auto m_reshape1 = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({m_softmax, ov::pass::pattern::wrap_type<ov::op::v0::Constant>()});- register_matcher(- std::make_shared<ov::pass::pattern::Matcher>(m_reshape1, matcher_name),- [=](ov::pass::pattern::Matcher& m) {- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::op::SoftmaxReshapeElimination")- auto& pattern_to_output = m.get_pattern_value_map();- auto reshape0 = pattern_to_output[m_reshape0].get_node_shared_ptr();- auto softmax = pattern_to_output[m_softmax].get_node_shared_ptr();- auto reshape1 = pattern_to_output[m_reshape1].get_node_shared_ptr();-- const auto input_shape = reshape0->get_input_partial_shape(0);- const auto output_shape = reshape1->get_output_partial_shape(0);- const auto softmax_shape = softmax->get_input_partial_shape(0);- if (input_shape != output_shape || input_shape.rank() != output_shape.rank()) {- return false;- }-- const auto softmax_rank = softmax_shape.rank();- const auto axis = ov::snippets::utils::get_softmax_axis(softmax);- // Supports only last axis- if (!axis || *axis != static_cast<int64_t>(softmax_rank.get_length()) - 1) {- return false;- }-- // Dimensions by reduction axis should be equal- const auto in_last_dim = *input_shape.crbegin();- const auto out_last_dim = *output_shape.crbegin();- const auto softmax_last_dim = *softmax_shape.crbegin();- if (in_last_dim.is_dynamic() || out_last_dim.is_dynamic() || softmax_last_dim.is_dynamic() ||- in_last_dim != out_last_dim || in_last_dim != softmax_last_dim) {- return false;- }-- // Eliminate Reshape before Softmax- reshape0->output(0).replace(reshape0->input_value(0));- copy_runtime_info(- {reshape0->input_value(0).get_node_shared_ptr(), reshape0->output(0).get_node_shared_ptr()},- reshape0->input_value(0).get_node_shared_ptr());-- // Eliminate Reshape after Softmax with name saving- replace_output_update_name(reshape1->output(0), reshape1->input_value(0));-- // update axis- const auto new_axis = input_shape.rank().get_length() - 1;- if (auto softmax_v8 = ov::as_type_ptr<ov::op::v8::Softmax>(softmax)) {- softmax_v8->set_axis(new_axis);- } else if (auto softmax_v1 = ov::as_type_ptr<ov::op::v1::Softmax>(softmax)) {- softmax_v1->set_axis(new_axis);- }-- return true;- });+ register_matcher(std::make_shared<ov::pass::pattern::Matcher>(m_reshape1, matcher_name),+ [=](ov::pass::pattern::Matcher& m) {+ OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform,+ "Snippets::op::SoftmaxReshapeElimination")+ auto& pattern_to_output = m.get_pattern_value_map();+ auto reshape0 = pattern_to_output[m_reshape0].get_node_shared_ptr();+ auto softmax = pattern_to_output[m_softmax].get_node_shared_ptr();+ auto reshape1 = pattern_to_output[m_reshape1].get_node_shared_ptr();+ return eliminate(ov::as_type_ptr<ov::op::v1::Reshape>(reshape0),+ softmax,+ ov::as_type_ptr<ov::op::v1::Reshape>(reshape1));+ });}diff --git a/src/common/snippets/tests/src/pass/mha_tokenization.cpp b/src/common/snippets/tests/src/pass/mha_tokenization.cppindex fe69e81f9a4..5e8ba64474c 100644--- a/src/common/snippets/tests/src/pass/mha_tokenization.cpp+++ b/src/common/snippets/tests/src/pass/mha_tokenization.cpp@@ -9,6 +9,14 @@#include <pass/mha_tokenization.hpp>#include <subgraph_mha.hpp>+#include "openvino/op/broadcast.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/opsets/opset1.hpp"+#include "snippets/op/result.hpp"+#include "snippets/op/subgraph.hpp"#include "snippets/pass/common_optimizations.hpp"#include "snippets/pass/extract_reshapes_from_mha.hpp"#include "snippets/pass/tokenization.hpp"@@ -68,6 +76,131 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D) {execute_and_validate_function(*this, f);}+TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_ShapeOf_Broadcast) {+ const auto& f = MHAFunction(+ std::vector<PartialShape>{{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 1, 128, 128}, {1, 128, 12, 64}},+ std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),+ true,+ false,+ true,+ true);+ execute_and_validate_function(*this, f);+}++TEST_F(TokenizeMHASnippetsTests, ShapeOfExternalConsumer) {+ const auto f = MHAFunction(+ std::vector<PartialShape>{{-1, 128, 12, 64}, {-1, 128, 12, 64}, {-1, 1, 128, 128}, {-1, 128, 12, 64}},+ std::vector<ov::element::Type>(4, ov::element::f32),+ false,+ false,+ true,+ true);+ model = f.getOriginal();+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v3::ShapeOf>(node)) {+ model->add_results({std::make_shared<ov::op::v0::Result>(node)});+ break;+ }+ }+ ASSERT_EQ(model->get_results().size(), 2);+ run();+}++class RuntimeBroadcastTarget : public TokenizeMHASnippetsTests, public testing::WithParamInterface<bool> {};++TEST_P(RuntimeBroadcastTarget, PreserveBatchExpansion) {+ const auto make_parameters = []() {+ return ParameterVector{+ std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic(4)),+ std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic(4)),+ std::make_shared<op::v0::Parameter>(element::f32, Shape{1, 1, 1, 1}),+ std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic(4)),+ std::make_shared<op::v0::Parameter>(GetParam() ? element::f32 : element::i64,+ GetParam() ? PartialShape::dynamic(4) : PartialShape{4})};+ };+ const auto make_broadcast = [](const ParameterVector& params) {+ const Output<Node> target =+ GetParam() ? Output<Node>(std::make_shared<op::v3::ShapeOf>(params[4])) : params[4]->output(0);+ return std::make_shared<op::v3::Broadcast>(params[2], target, op::BroadcastType::NUMPY);+ };+ const auto make_mha = [](const OutputVector& inputs) {+ const auto matmul0 = std::make_shared<op::v0::MatMul>(inputs[0], inputs[1]);+ const auto add = std::make_shared<op::v1::Add>(matmul0, inputs[2]);+ const auto softmax = std::make_shared<op::v1::Softmax>(add, 3);+ return std::make_shared<op::v0::MatMul>(softmax, inputs[3]);+ };++ const auto params = make_parameters();+ const auto broadcast = make_broadcast(params);+ model = std::make_shared<Model>(OutputVector{make_mha({params[0], params[1], broadcast, params[3]})}, params);++ const auto ref_params = make_parameters();+ const auto ref_broadcast = make_broadcast(ref_params);+ const OutputVector inputs{ref_params[0], ref_params[1], ref_broadcast, ref_params[3]};+ ParameterVector body_params;+ OutputVector body_inputs;+ for (const auto& input : inputs) {+ body_params.push_back(std::make_shared<op::v0::Parameter>(input.get_element_type(), input.get_partial_shape()));+ body_inputs.push_back(body_params.back());+ }+ const auto result = std::make_shared<ov::snippets::op::Result>(make_mha(body_inputs));+ const auto body = std::make_shared<Model>(ResultVector{result}, body_params);+ const auto subgraph = std::make_shared<ov::snippets::op::Subgraph>(inputs, body);+ model_ref = std::make_shared<Model>(OutputVector{subgraph}, ref_params);++ manager.register_pass<ov::snippets::pass::EnumerateNodes>();+ manager.register_pass<ov::snippets::pass::TokenizeMHASnippets>(mha_config);+ disable_rt_info_check();+}++INSTANTIATE_TEST_SUITE_P(smoke_Snippets, RuntimeBroadcastTarget, testing::Values(false, true));++TEST_F(TokenizeMHASnippetsTests, ShapeOfReshapeExternalConsumer) {+ const auto f = MHAFunction(+ std::vector<PartialShape>{{-1, 128, 12, 64}, {-1, 128, 12, 64}, {-1, 12, 128, 128}, {-1, 128, 12, 64}},+ std::vector<ov::element::Type>(4, ov::element::f32),+ false,+ true,+ false,+ true);+ model = f.getOriginal();+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<ov::op::v3::ShapeOf>(node)) {+ model->add_results({std::make_shared<ov::op::v0::Result>(node)});+ break;+ }+ }+ ASSERT_EQ(model->get_results().size(), 2);+ run();+}++TEST_F(TokenizeMHASnippetsTests, ShapeOfReshapeIndirectConsumer) {+ const auto f =+ MHAFunction(std::vector<PartialShape>{{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 12, 128, 128}, {1, 128, 12, 64}},+ std::vector<ov::element::Type>(4, ov::element::f32),+ false,+ true,+ false,+ true);+ model = f.getOriginal();+ for (const auto& node : model->get_ordered_ops()) {+ if (ov::is_type<op::v3::ShapeOf>(node)) {+ // Build Concat(-1, Gather(ShapeOf(add))) as the first Reshape target.+ const auto restore = *node->get_output_target_inputs(0).begin();+ const auto softmax = restore.get_node()->get_input_node_shared_ptr(0);+ const auto reshape0 = softmax->get_input_node_shared_ptr(0);+ const auto index = op::v0::Constant::create(element::i64, Shape{1}, {3});+ const auto axis = op::v0::Constant::create(element::i64, Shape{}, {0});+ const auto last_dim = std::make_shared<op::v1::Gather>(node, index, axis);+ const auto minus_one = op::v0::Constant::create(element::i64, Shape{1}, {-1});+ reshape0->set_argument(1, std::make_shared<op::v0::Concat>(OutputVector{minus_one, last_dim}, 0));+ restore.replace_source_output(op::v0::Constant::create(element::i64, Shape{4}, {1, 12, 128, 128}));+ break;+ }+ }+ run();+}+TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_V3_Broadcast) {const auto& f = MHAFunction(std::vector<PartialShape>{{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 1, 128, 128}, {1, 128, 12, 64}},@@ -78,6 +211,17 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_V3_Broadcast) {execute_and_validate_function(*this, f);}+TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_ShapeOf_Reshape) {+ const auto& f = MHAFunction(+ std::vector<PartialShape>{{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 12, 128, 128}, {1, 128, 12, 64}},+ std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),+ true,+ true,+ false,+ true);+ execute_and_validate_function(*this, f);+}+TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_Const_B) {const auto& f = MHAConstBFunction(std::vector<PartialShape>{{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 12, 128, 128}, {1, 128, 12, 64}},diff --git a/src/common/snippets/tests/src/pass/softmax_reshape_elimination.cpp b/src/common/snippets/tests/src/pass/softmax_reshape_elimination.cppindex a2e478a3a43..cb63039164a 100644--- a/src/common/snippets/tests/src/pass/softmax_reshape_elimination.cpp+++ b/src/common/snippets/tests/src/pass/softmax_reshape_elimination.cpp@@ -4,9 +4,9 @@#include <gtest/gtest.h>+#include <openvino/op/shape_of.hpp>#include <openvino/opsets/opset1.hpp>#include <snippets/pass/softmax_reshape_elimination.hpp>-#include <transformations/init_node_info.hpp>#include "common_test_utils/ov_test_utils.hpp"@@ -84,3 +84,27 @@ TEST_F(TransformationTestsF, SoftmaxV8ReshapeElimination_DynamicBatch) {model_ref = std::make_shared<Model>(OutputVector{softmax_v1}, ParameterVector{data});}}++TEST_F(TransformationTestsF, SoftmaxReshapeElimination_UnknownReductionDimension) {+ const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, 4});+ const auto pattern = std::make_shared<op::v0::Parameter>(element::i64, Shape{2});+ const auto reshape0 = std::make_shared<op::v1::Reshape>(data, pattern, false);+ const auto softmax = std::make_shared<op::v8::Softmax>(reshape0, -1);+ const auto restore = std::make_shared<op::v3::ShapeOf>(data);+ const auto reshape1 = std::make_shared<op::v1::Reshape>(softmax, restore, false);+ model = std::make_shared<Model>(OutputVector{reshape1}, ParameterVector{data, pattern});+ EXPECT_FALSE(snippets::pass::SoftmaxReshapeElimination::eliminate(reshape0, softmax, reshape1));+}++TEST_F(TransformationTestsF, SoftmaxReshapeElimination_ArbitraryRestoreShape) {+ const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, 4});+ const auto prefix = std::make_shared<op::v0::Parameter>(element::i64, Shape{2});+ const auto last_dim = op::v0::Constant::create(element::i64, Shape{1}, {4});+ const auto pattern = op::v0::Constant::create(element::i64, Shape{2}, {-1, 4});+ const auto reshape0 = std::make_shared<op::v1::Reshape>(data, pattern, false);+ const auto softmax = std::make_shared<op::v8::Softmax>(reshape0, -1);+ const auto restore = std::make_shared<op::v0::Concat>(OutputVector{prefix, last_dim}, 0);+ const auto reshape1 = std::make_shared<op::v1::Reshape>(softmax, restore, false);+ model = std::make_shared<Model>(OutputVector{reshape1}, ParameterVector{data, prefix});+ EXPECT_FALSE(snippets::pass::SoftmaxReshapeElimination::eliminate(reshape0, softmax, reshape1));+}diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha.cppindex 68ac4d1dc4b..38fcadead71 100644--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha.cpp+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha.cpp@@ -4,6 +4,8 @@#include "snippets/mha.hpp"+#include <algorithm>+#include "utils.hpp"namespace ov {@@ -60,6 +62,21 @@ std::vector<std::vector<InputShape>> transposedShape_4D_v3_broadcast() {return SNIPPETS_TESTS_STATIC_SHAPES({{1, 128, 12, 64}, {1, 128, 12, 64}, {1, 1, 128, 128}, {1, 128, 12, 64}});}+std::vector<std::vector<InputShape>> transposedShape_4D_shapeof_broadcast() {+ // Keep the batch dynamic so ShapeOf remains a runtime shape input.+ return {{{PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}},+ {PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}},+ {PartialShape{-1, 1, 128, 128}, {{1, 1, 128, 128}}},+ {PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}}}};+}++std::vector<std::vector<InputShape>> transposedShape_4D_shapeof_reshape() {+ return {{{PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}},+ {PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}},+ {PartialShape{-1, 12, 128, 128}, {{1, 12, 128, 128}}},+ {PartialShape{-1, 128, 12, 64}, {{1, 128, 12, 64}}}}};+}+std::vector<std::vector<InputShape>> twoConstBShape_4D() {return SNIPPETS_TESTS_STATIC_SHAPES({{1, 300, 8, 32}, // Q1{1, 300, 8, 32}, // K1@@ -145,6 +162,30 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHA_4D_V3_Broadcast,::testing::Values(CPUTestUtils::empty_plugin_config)),MHAWithBroadcast::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHA_4D_ShapeOf_Broadcast,+ MHAWithShapeOfBroadcast,+ ::testing::Combine(::testing::ValuesIn(transposedShape_4D_shapeof_broadcast()),+ ::testing::ValuesIn(precision_f32(4)),+ ::testing::Values(ov::element::f32),+ ::testing::Values(false),+ ::testing::Values(expected_nodes_mha_4d_f32),+ ::testing::Values(2), // decomposed Transpose + MHA+ ::testing::Values(ov::test::utils::DEVICE_CPU),+ ::testing::Values(CPUTestUtils::empty_plugin_config)),+ MHAWithShapeOfBroadcast::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHA_4D_ShapeOf_Reshape,+ MHAWithShapeOfReshape,+ ::testing::Combine(::testing::ValuesIn(transposedShape_4D_shapeof_reshape()),+ ::testing::ValuesIn(precision_f32(4)),+ ::testing::Values(ov::element::f32),+ ::testing::Values(false),+ ::testing::Values(expected_nodes_mha_4d_f32),+ ::testing::Values(2), // decomposed Transpose + MHA+ ::testing::Values(ov::test::utils::DEVICE_CPU),+ ::testing::Values(CPUTestUtils::empty_plugin_config)),+ MHAWithShapeOfReshape::getTestCaseName);+// Ticket: CVS-180477INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHA_4D_TwoConstB_StaticShapesCacheCollisionRegression,MHATwoConstB,diff --git a/src/tests/functional/plugin/shared/include/snippets/mha.hpp b/src/tests/functional/plugin/shared/include/snippets/mha.hppindex e13d0118f02..4b1eb35cd7c 100644--- a/src/tests/functional/plugin/shared/include/snippets/mha.hpp+++ b/src/tests/functional/plugin/shared/include/snippets/mha.hpp@@ -102,6 +102,16 @@ protected:std::shared_ptr<SnippetsFunctionBase> get_subgraph() const override;};+class MHAWithShapeOfBroadcast : public MHA {+protected:+ std::shared_ptr<SnippetsFunctionBase> get_subgraph() const override;+};++class MHAWithShapeOfReshape : public MHA {+protected:+ std::shared_ptr<SnippetsFunctionBase> get_subgraph() const override;+};+class MHASelect : public MHA {protected:void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override;diff --git a/src/tests/functional/plugin/shared/src/snippets/mha.cpp b/src/tests/functional/plugin/shared/src/snippets/mha.cppindex a602e6a7b48..0fdef9964d5 100644--- a/src/tests/functional/plugin/shared/src/snippets/mha.cpp+++ b/src/tests/functional/plugin/shared/src/snippets/mha.cpp@@ -277,6 +277,26 @@ std::shared_ptr<SnippetsFunctionBase> MHAWithBroadcast::get_subgraph() const {is_with_reshape);}+std::shared_ptr<SnippetsFunctionBase> MHAWithShapeOfBroadcast::get_subgraph() const {+ const auto with_mul = std::get<3>(this->GetParam());+ return std::make_shared<ov::test::snippets::MHAFunction>(inputDynamicShapes,+ m_input_types,+ with_mul,+ false,+ true,+ true);+}++std::shared_ptr<SnippetsFunctionBase> MHAWithShapeOfReshape::get_subgraph() const {+ const auto with_mul = std::get<3>(this->GetParam());+ return std::make_shared<ov::test::snippets::MHAFunction>(inputDynamicShapes,+ m_input_types,+ with_mul,+ true,+ false,+ true);+}+void MHASelect::generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) {inputs.clear();auto model_inputs = function->inputs();@@ -396,6 +416,14 @@ TEST_P(MHAWithBroadcast, CompareWithRefImpl) {validateNumSubgraphs();}+TEST_P(MHAWithShapeOfBroadcast, CompareWithRefImpl) {+ run();+}++TEST_P(MHAWithShapeOfReshape, CompareWithRefImpl) {+ run();+}+TEST_P(MHASelect, CompareWithRefImpl) {run();}diff --git a/src/tests/ov_helpers/ov_snippets_models/include/subgraph_mha.hpp b/src/tests/ov_helpers/ov_snippets_models/include/subgraph_mha.hppindex 199066dd9e8..19f8cc8a0fc 100644--- a/src/tests/ov_helpers/ov_snippets_models/include/subgraph_mha.hpp+++ b/src/tests/ov_helpers/ov_snippets_models/include/subgraph_mha.hpp@@ -49,11 +49,13 @@ public:const std::vector<ov::element::Type>& precisions,bool with_mul = true,bool with_reshape = true,- bool with_broadcast = false)+ bool with_broadcast = false,+ bool with_shape_of = false): SnippetsFunctionBase(inputShapes),with_mul(with_mul),with_reshape(with_reshape),with_broadcast(with_broadcast),+ with_shape_of(with_shape_of),precisions(precisions) {OPENVINO_ASSERT(input_shapes.size() == 4, "Got invalid number of input shapes");OPENVINO_ASSERT(precisions.size() == 4, "Got invalid number of input precisions");@@ -66,6 +68,7 @@ protected:const bool with_mul = true;const bool with_reshape = true;const bool with_broadcast = false;+ const bool with_shape_of = false;const std::vector<ov::element::Type> precisions;};diff --git a/src/tests/ov_helpers/ov_snippets_models/src/subgraph_mha.cpp b/src/tests/ov_helpers/ov_snippets_models/src/subgraph_mha.cppindex 17fe274a6ba..ce10005416e 100644--- a/src/tests/ov_helpers/ov_snippets_models/src/subgraph_mha.cpp+++ b/src/tests/ov_helpers/ov_snippets_models/src/subgraph_mha.cpp@@ -4,11 +4,16 @@#include "subgraph_mha.hpp"+#include <tuple>+#include <utility>+#include "common_test_utils/data_utils.hpp"#include "common_test_utils/node_builders/constant.hpp"#include "common_test_utils/node_builders/fake_quantize.hpp"#include "fake_quantize_helper.hpp"#include "openvino/op/broadcast.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/shape_of.hpp"#include "openvino/opsets/opset1.hpp"#include "ov_lpt_models/common/builders.hpp"#include "ov_ops/type_relaxed.hpp"@@ -51,7 +56,27 @@ std::vector<int64_t> get_decomposed_order_after_split_m(size_t rank) {}OPENVINO_THROW("Incorrect rank for testing");}-} // namespace++ov::Output<ov::Node> make_broadcast_shape(const ov::Output<ov::Node>& source, size_t rank, bool with_shape_of) {+ if (with_shape_of) {+ return std::make_shared<ov::op::v3::ShapeOf>(source, ov::element::i64);+ }++ OPENVINO_ASSERT(source.get_partial_shape().is_static(),+ "MHAFunction with broadcast requires a static MatMul output shape");+ return ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, source.get_shape());+}++std::pair<ov::Output<ov::Node>, ov::Output<ov::Node>> make_reshape_shapes(const ov::Output<ov::Node>& source,+ size_t rank) {+ const auto shape_of = std::make_shared<ov::op::v3::ShapeOf>(source, ov::element::i64);+ const auto last_dim = source.get_partial_shape()[rank - 1].get_length();+ const auto shape_before_softmax =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{-1, last_dim});+ return {shape_before_softmax, shape_of};+}++} // namespacestd::shared_ptr<ov::Model> init_mha_original(const std::vector<PartialShape>& input_shapes,const std::vector<ov::element::Type>& precisions,@@ -59,7 +84,8 @@ std::shared_ptr<ov::Model> init_mha_original(const std::vector<PartialShape>& inbool with_reshape,bool const_b_matmul0,bool const_b_matmul1,- bool with_broadcast) {+ bool with_broadcast,+ bool with_shape_of) {auto transpose0Param = std::make_shared<ov::opset1::Parameter>(precisions[0], input_shapes[0]);auto addParam = std::make_shared<ov::opset1::Parameter>(precisions[2], input_shapes[2]);ov::ParameterVector ngraphParam = {transpose0Param};@@ -106,25 +132,31 @@ std::shared_ptr<ov::Model> init_mha_original(const std::vector<PartialShape>& inconst auto matMul0 = std::make_shared<ov::op::v0::MatMul>(transpose0, matmul_parent1);auto add_input = addParam->output(0);if (with_broadcast) {- OPENVINO_ASSERT(matMul0->get_output_partial_shape(0).is_static(),- "MHAFunction with broadcast requires a static MatMul output shape");- const auto target_shape =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, matMul0->get_output_shape(0));- add_input = std::make_shared<ov::op::v3::Broadcast>(add_input, target_shape, ov::op::BroadcastType::NUMPY);+ add_input = std::make_shared<ov::op::v3::Broadcast>(+ add_input, make_broadcast_shape(matMul0, rank, with_shape_of), ov::op::BroadcastType::NUMPY);}const auto add = std::make_shared<ov::op::v1::Add>(matMul0, add_input);auto softmax_out = add->output(0);if (with_reshape) {- const auto interm_shape = add->get_output_shape(0);- const auto batch =- std::accumulate(interm_shape.cbegin(), interm_shape.cbegin() + (rank - 1), 1, std::multiplies<size_t>());- const auto reshape0ConstData = std::vector<int64_t>{batch, -1};- const auto reshape1ConstData = interm_shape;- const auto reshape0Const =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{reshape0ConstData.size()}, reshape0ConstData);- const auto reshape1Const =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{reshape1ConstData.size()}, reshape1ConstData);+ ov::Output<ov::Node> reshape0Const;+ ov::Output<ov::Node> reshape1Const;+ if (with_shape_of) {+ std::tie(reshape0Const, reshape1Const) = make_reshape_shapes(add, rank);+ } else {+ const auto shape_after_softmax = add->get_output_shape(0);+ const auto batch = std::accumulate(shape_after_softmax.cbegin(),+ shape_after_softmax.cbegin() + (rank - 1),+ size_t{1},+ std::multiplies<size_t>());+ const auto shape_before_softmax = std::vector<int64_t>{static_cast<int64_t>(batch), -1};+ reshape0Const = ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{shape_before_softmax.size()},+ shape_before_softmax);+ reshape1Const = ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{shape_after_softmax.size()},+ shape_after_softmax);+ }const auto reshape0 = std::make_shared<ov::opset1::Reshape>(add, reshape0Const, true);const auto softMax = std::make_shared<ov::opset1::Softmax>(reshape0, 1);@@ -148,7 +180,8 @@ std::shared_ptr<ov::Model> init_mha_reference(const std::vector<PartialShape>& ibool with_mul,bool const_b_matmul0,bool const_b_matmul1,- bool with_broadcast = false) {+ bool with_broadcast,+ bool with_shape_of) {auto data0 = std::make_shared<ov::opset1::Parameter>(precisions[0], input_shapes[0]);auto data2 = std::make_shared<ov::opset1::Parameter>(precisions[2], input_shapes[2]);ov::ParameterVector ngraphParams = {data0};@@ -207,11 +240,8 @@ std::shared_ptr<ov::Model> init_mha_reference(const std::vector<PartialShape>& iconst auto matMul0 = std::make_shared<ov::op::v0::MatMul>(transpose0, brgemm1Param);auto add_input = addParam->output(0);if (with_broadcast) {- OPENVINO_ASSERT(matMul0->get_output_partial_shape(0).is_static(),- "MHAFunction with broadcast requires a static MatMul output shape");- const auto target_shape =- ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, matMul0->get_output_shape(0));- add_input = std::make_shared<ov::op::v3::Broadcast>(add_input, target_shape, ov::op::BroadcastType::NUMPY);+ add_input = std::make_shared<ov::op::v3::Broadcast>(+ add_input, make_broadcast_shape(matMul0, rank, with_shape_of), ov::op::BroadcastType::NUMPY);}const auto add = std::make_shared<ov::op::v1::Add>(matMul0, add_input);const auto softMax = std::make_shared<ov::opset1::Softmax>(add, rank - 1);@@ -228,11 +258,18 @@ std::shared_ptr<ov::Model> init_mha_reference(const std::vector<PartialShape>& i}std::shared_ptr<ov::Model> MHAFunction::initOriginal() const {- return init_mha_original(input_shapes, precisions, with_mul, with_reshape, false, false, with_broadcast);+ return init_mha_original(input_shapes,+ precisions,+ with_mul,+ with_reshape,+ false,+ false,+ with_broadcast,+ with_shape_of);}std::shared_ptr<ov::Model> MHAFunction::initReference() const {- return init_mha_reference(input_shapes, precisions, with_mul, false, false, with_broadcast);+ return init_mha_reference(input_shapes, precisions, with_mul, false, false, with_broadcast, with_shape_of);}std::shared_ptr<ov::Model> MHAConstBFunction::initOriginal() const {@@ -242,11 +279,12 @@ std::shared_ptr<ov::Model> MHAConstBFunction::initOriginal() const {with_reshape,const_b_matmul0,const_b_matmul1,+ false,false);}std::shared_ptr<ov::Model> MHAConstBFunction::initReference() const {- return init_mha_reference(input_shapes, precisions, with_mul, const_b_matmul0, const_b_matmul1);+ return init_mha_reference(input_shapes, precisions, with_mul, const_b_matmul0, const_b_matmul1, false, false);}void MHAConstBFunction::validate_function(const std::shared_ptr<Model>& f) const {