Skip to content

OpenVINO™ is an open source toolkit for optimizing and deploying AI inference

[Snippets] Shift rank upgrade reshape from mha body to rank reduction reshape in mha input branch (#29997)

Chenhu Wange6ad7da9c11a
diff --git a/src/common/snippets/include/snippets/pass/extract_reshapes_from_mha.hpp b/src/common/snippets/include/snippets/pass/extract_reshapes_from_mha.hpp
index 34bb95787f6..0683ddceb31 100644
--- a/src/common/snippets/include/snippets/pass/extract_reshapes_from_mha.hpp
+++ b/src/common/snippets/include/snippets/pass/extract_reshapes_from_mha.hpp
@@ -4,6 +4,7 @@
#pragma once
+#include "openvino/pass/graph_rewrite.hpp"
#include "openvino/pass/matcher_pass.hpp"
namespace ov {
@@ -11,8 +12,8 @@ namespace snippets {
namespace pass {
/**
- * @interface ExtractReshapesFromMHA
- * @brief This pass tries to extract unsupported reshape pairs around eltwise ops from MHA body
+ * @interface ExtractPairsAfterMatmul
+ * @brief This pass tries to extract unsupported reshape pairs around eltwise ops between MatMul and Softmax from MHA
* Subgraph inside the MHA body:
*
* matmul
@@ -29,10 +30,46 @@ namespace pass {
*
* @ingroup snippets
*/
-class ExtractReshapesFromMHA: public ov::pass::MatcherPass {
+class ExtractPairsAfterMatmul : public ov::pass::MatcherPass {
public:
- OPENVINO_MATCHER_PASS_RTTI("snippets::pass::ExtractReshapesFromMHA");
- ExtractReshapesFromMHA();
+ OPENVINO_MATCHER_PASS_RTTI("snippets::pass::ExtractPairsAfterMatmul");
+ ExtractPairsAfterMatmul();
+};
+
+/**
+ * @interface RankUpgradeToRankReduction
+ * @brief This pass tries to transfer rank upgrade reshape from MHA branch to rank reduction reshape in MHA input
+ * branch. This pass can be only applied to static shape, and Eltwise below means BinaryElementwiseArithmetic.
+ * Subgraph inside the MHA body:
+ * Matmul Matmul
+ * | input1 | input1 input2
+ * | / | / /
+ * Eltwise1 Eltwise1 /
+ * | ==> | reshape
+ * | | /
+ * Reshape Eltwise2
+ * | input2
+ * | /
+ * Eltwise2
+ * |
+ * |
+ * Reshape
+ *
+ * @ingroup snippets
+ */
+class RankUpgradeToRankReduction : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("snippets::pass::RankUpgradeToRankReduction");
+ RankUpgradeToRankReduction();
+};
+
+class ExtractReshapesFromMHA : public ov::pass::GraphRewrite {
+public:
+ OPENVINO_GRAPH_REWRITE_RTTI("ExtractReshapesFromMHA");
+ ExtractReshapesFromMHA() {
+ add_matcher<ExtractPairsAfterMatmul>();
+ add_matcher<RankUpgradeToRankReduction>();
+ }
};
} // namespace pass
diff --git a/src/common/snippets/src/pass/extract_reshapes_from_mha.cpp b/src/common/snippets/src/pass/extract_reshapes_from_mha.cpp
index 810d325dca7..45330517eb2 100644
--- a/src/common/snippets/src/pass/extract_reshapes_from_mha.cpp
+++ b/src/common/snippets/src/pass/extract_reshapes_from_mha.cpp
@@ -7,6 +7,8 @@
#include <openvino/opsets/opset1.hpp>
#include "openvino/core/rt_info.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/pass/pattern/op/optional.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "snippets/itt.hpp"
#include "snippets/pass/mha_tokenization.hpp"
@@ -14,8 +16,8 @@
using namespace ov::pass;
-ov::snippets::pass::ExtractReshapesFromMHA::ExtractReshapesFromMHA() {
- MATCHER_SCOPE(ExtractReshapesFromMHA);
+ov::snippets::pass::ExtractPairsAfterMatmul::ExtractPairsAfterMatmul() {
+ MATCHER_SCOPE(ExtractPairsAfterMatmul);
auto static_shape_single_consumer = [](const ov::Output<ov::Node>& out) {
return pattern::has_static_shape()(out) && pattern::consumers_count(1)(out);
};
@@ -28,7 +30,7 @@ ov::snippets::pass::ExtractReshapesFromMHA::ExtractReshapesFromMHA() {
auto reshape_2_m = pattern::wrap_type<opset1::Reshape>({add_2_m, pattern::wrap_type<opset1::Constant>()}, pattern::has_static_shape());
matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {
- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::op::ExtractReshapesFromMHA")
+ OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::op::ExtractPairsAfterMatmul")
const auto& pattern_map = m.get_pattern_value_map();
const auto& matmul = pattern_map.at(matmul_m);
const auto matmul_node = ov::as_type_ptr<opset1::MatMul>(matmul.get_node_shared_ptr());
@@ -66,3 +68,104 @@ ov::snippets::pass::ExtractReshapesFromMHA::ExtractReshapesFromMHA() {
auto m = std::make_shared<pattern::Matcher>(reshape_2_m, matcher_name);
register_matcher(m, callback);
}
+
+ov::snippets::pass::RankUpgradeToRankReduction::RankUpgradeToRankReduction() {
+ MATCHER_SCOPE(RankUpgradeToRankReduction);
+ auto static_shape_single_consumer = [](const ov::Output<ov::Node>& out) {
+ return pattern::has_static_shape()(out) && pattern::consumers_count(1)(out);
+ };
+ // reshape_1_m insert leading dimension of 1.
+ auto rank_upgrade_reshape = [&](const ov::Output<ov::Node>& out) {
+ if (!static_shape_single_consumer(out)) {
+ return false;
+ }
+ auto out_shape = out.get_shape();
+ if (out_shape.size() < 1 || out_shape[0] != 1) {
+ return false;
+ }
+ out_shape.erase(out_shape.begin());
+ const auto& in_shape_partial = out.get_node_shared_ptr()->get_input_partial_shape(0);
+ if (in_shape_partial.is_dynamic()) {
+ return false;
+ }
+ const auto& in_shape = in_shape_partial.to_shape();
+ return out_shape == in_shape;
+ };
+ // input_2_m has leading dimension of 1.
+ auto has_leading_dimension_one = [&](const ov::Output<ov::Node>& out) {
+ if (!static_shape_single_consumer(out)) {
+ return false;
+ }
+ const auto& out_shape = out.get_shape();
+ return ((out_shape.size() > 0) && (out_shape[0] == 1));
+ };
+ // reshape_2_m delete leading dimension of 1.
+ auto rank_reduction_reshape = [&](const ov::Output<ov::Node>& out) {
+ if (!static_shape_single_consumer(out)) {
+ return false;
+ }
+ auto in_shape_partial = out.get_node_shared_ptr()->get_input_partial_shape(0);
+ if (in_shape_partial.is_dynamic()) {
+ return false;
+ }
+ auto in_shape = in_shape_partial.to_shape();
+ if (in_shape.size() < 1 || in_shape[0] != 1) {
+ return false;
+ }
+ in_shape.erase(in_shape.begin());
+ const auto& out_shape = out.get_shape();
+ return out_shape == in_shape;
+ };
+
+ auto matmul_m = pattern::wrap_type<opset1::MatMul>(static_shape_single_consumer);
+ auto input_1_m = pattern::any_input(pattern::has_static_shape());
+ auto eltwise_1_m = pattern::optional<ov::op::util::BinaryElementwiseArithmetic>({matmul_m, input_1_m},
+ static_shape_single_consumer);
+ auto reshape_1_m = pattern::wrap_type<opset1::Reshape>({eltwise_1_m, pattern::wrap_type<opset1::Constant>()},
+ rank_upgrade_reshape);
+ auto input_2_m = pattern::any_input(has_leading_dimension_one);
+ auto eltwise_2_m = pattern::wrap_type<ov::op::util::BinaryElementwiseArithmetic>({reshape_1_m, input_2_m},
+ static_shape_single_consumer);
+ auto reshape_2_m = pattern::wrap_type<opset1::Reshape>({eltwise_2_m, pattern::wrap_type<opset1::Constant>()},
+ rank_reduction_reshape);
+
+ matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](pattern::Matcher& m) {
+ OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::op::RankUpgradeToRankReduction")
+ const auto& pattern_map = m.get_pattern_value_map();
+ const auto& matmul = pattern_map.at(matmul_m);
+ const auto matmul_node = ov::as_type_ptr<opset1::MatMul>(matmul.get_node_shared_ptr());
+ if (!ov::snippets::pass::TokenizeMHASnippets::is_matmul0_supported(matmul_node) ||
+ transformation_callback(matmul_node))
+ return false;
+ const auto& eltwise_2 = pattern_map.at(eltwise_2_m).get_node_shared_ptr();
+ const auto& shapes = ov::util::get_node_input_partial_shapes(*eltwise_2);
+ OPENVINO_ASSERT(shapes.size() > 0, "Eltwise node should has at least one input.");
+ auto equal_rank = [&](const PartialShape& p) {
+ return p.size() == shapes[0].size();
+ };
+ if (!std::all_of(shapes.cbegin(), shapes.cend(), equal_rank)) {
+ return false;
+ }
+
+ const auto& input_2 = pattern_map.at(input_2_m);
+ auto input_2_shape = input_2.get_shape();
+ input_2_shape.erase(input_2_shape.begin());
+ const auto target_shape = ov::opset1::Constant::create(ov::element::i32, {input_2_shape.size()}, input_2_shape);
+ const auto reshaped_input2 = std::make_shared<ov::opset1::Reshape>(input_2, target_shape, true);
+ const auto& reshape_1 = pattern_map.at(reshape_1_m).get_node_shared_ptr();
+ ov::copy_runtime_info(reshape_1, reshaped_input2);
+
+ auto first_input = pattern_map.at(matmul_m);
+ if (pattern_map.count(eltwise_1_m)) {
+ first_input = pattern_map.at(eltwise_1_m);
+ }
+
+ OutputVector new_args({first_input, reshaped_input2});
+ eltwise_2->set_arguments(new_args);
+ const auto& old_reshape = pattern_map.at(reshape_2_m);
+ return ov::replace_output_update_name(old_reshape, eltwise_2);
+ };
+
+ auto m = std::make_shared<pattern::Matcher>(reshape_2_m, matcher_name);
+ register_matcher(m, callback);
+}
diff --git a/src/common/snippets/tests/src/pass/mha_tokenization.cpp b/src/common/snippets/tests/src/pass/mha_tokenization.cpp
index 75de3d4af23..725c7bdef81 100644
--- a/src/common/snippets/tests/src/pass/mha_tokenization.cpp
+++ b/src/common/snippets/tests/src/pass/mha_tokenization.cpp
@@ -285,6 +285,17 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_Reshape_extraction) {
run();
}
+TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_Rank_Change_Reshape_extraction) {
+ const auto& f = MHARankUpgradeToReductionFunction(std::vector<PartialShape>{{100, 16, 100, 32},
+ {100, 16, 32, 100},
+ {1, 16, 100, 100},
+ {1, 100, 1, 100, 100},
+ {100, 16, 100, 32}});
+ model = f.getOriginal();
+ model_ref = f.getReference();
+ run();
+}
+
} // namespace snippets
} // namespace test
} // namespace ov
diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_extracted_reshape.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_extracted_reshape.cpp
index f3c14393956..4a757e77d89 100644
--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_extracted_reshape.cpp
+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_extracted_reshape.cpp
@@ -34,6 +34,23 @@ INSTANTIATE_TEST_SUITE_P(
::testing::Values(CPUTestUtils::empty_plugin_config)),
MHA::getTestCaseName);
+const auto& inputShapesRankChangeReshape = SNIPPETS_TESTS_STATIC_SHAPES(
+ {{3, 16, 10, 32}, {3, 16, 32, 10}, {1, 16, 10, 10}, {1, 3, 1, 10, 10}, {3, 16, 10, 16}},
+ {{1, 3, 16, 64}, {1, 3, 64, 8}, {1, 1, 1, 8}, {1, 3, 1, 16, 8}, {1, 3, 8, 4}});
+
+INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHARankUpgradeToReductionReshape,
+ MHARankUpgradeToReductionReshape,
+ ::testing::Combine(::testing::ValuesIn(inputShapesRankChangeReshape),
+ ::testing::Values(std::vector<element::Type>{}),
+ ::testing::Values(ov::element::f32),
+ ::testing::Values(false),
+ ::testing::Values(MHA::default_thread_count),
+ ::testing::Values(2), // MHA + reshape
+ ::testing::Values(1), // MHA subgraph
+ ::testing::Values(ov::test::utils::DEVICE_CPU),
+ ::testing::Values(CPUTestUtils::empty_plugin_config)),
+ MHA::getTestCaseName);
+
} // namespace
} // namespace snippets
} // namespace test
diff --git a/src/tests/functional/plugin/shared/include/snippets/mha.hpp b/src/tests/functional/plugin/shared/include/snippets/mha.hpp
index b8ce7ff31e9..22372cafd9a 100644
--- a/src/tests/functional/plugin/shared/include/snippets/mha.hpp
+++ b/src/tests/functional/plugin/shared/include/snippets/mha.hpp
@@ -119,6 +119,11 @@ protected:
std::shared_ptr<SnippetsFunctionBase> get_subgraph() const override;
};
+class MHARankUpgradeToReductionReshape : public MHA {
+protected:
+ std::shared_ptr<SnippetsFunctionBase> get_subgraph() const override;
+};
+
class MHAWithDynamicMul : public testing::WithParamInterface<ov::test::snippets::MHAWithDynamicMulParams>,
virtual public MHABase {
public:
diff --git a/src/tests/functional/plugin/shared/src/snippets/mha.cpp b/src/tests/functional/plugin/shared/src/snippets/mha.cpp
index 25b1acbff92..35463e507f8 100644
--- a/src/tests/functional/plugin/shared/src/snippets/mha.cpp
+++ b/src/tests/functional/plugin/shared/src/snippets/mha.cpp
@@ -249,6 +249,10 @@ std::shared_ptr<SnippetsFunctionBase> MHAWithExtractedReshape::get_subgraph() co
return std::make_shared<ov::test::snippets::MHAWithExtractedReshapeFunction>(inputDynamicShapes, false);
}
+std::shared_ptr<SnippetsFunctionBase> MHARankUpgradeToReductionReshape::get_subgraph() const {
+ return std::make_shared<ov::test::snippets::MHARankUpgradeToReductionFunction>(inputDynamicShapes);
+}
+
std::shared_ptr<SnippetsFunctionBase> MHAWithDynamicMul::get_subgraph() const {
return std::make_shared<ov::test::snippets::MHAWithDynamicMulFunction>(inputDynamicShapes, m_input_types);
}
@@ -326,6 +330,12 @@ TEST_P(MHAWithExtractedReshape, CompareWithRefImpl) {
validateNumSubgraphs();
}
+TEST_P(MHARankUpgradeToReductionReshape, CompareWithRefImpl) {
+ SKIP_IF_CURRENT_TEST_IS_DISABLED()
+ run();
+ validateNumSubgraphs();
+}
+
TEST_P(MHAWithDynamicMul, CompareWithRefImpl) {
SKIP_IF_CURRENT_TEST_IS_DISABLED()
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.hpp
index 57ad062463c..095c4e1c5f2 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
@@ -460,6 +460,40 @@ private:
bool add_2nd_reshape = false;
};
+/* Graph:
+ * input0 input1
+ * \ /
+ * MatMul0 input2
+ * | /
+ * Eltwise1
+ * |
+ * Reshape input3
+ * | /
+ * Eltwise2
+ * |
+ * Reshape
+ * |
+ * Softmax
+ * | input4
+ * \ /
+ * MatMul1
+ */
+class MHARankUpgradeToReductionFunction : public SnippetsFunctionBase {
+public:
+ explicit MHARankUpgradeToReductionFunction(const std::vector<PartialShape>& inputShapes)
+ : SnippetsFunctionBase(inputShapes) {
+ OPENVINO_ASSERT(input_shapes.size() == 5, "Got invalid number of input shapes");
+ bool are_static_shapes = std::all_of(input_shapes.cbegin(), input_shapes.cend(), [](const PartialShape& shape) {
+ return shape.is_static();
+ });
+ OPENVINO_ASSERT(are_static_shapes, "Expect static shape, got dynamic shape");
+ }
+
+protected:
+ std::shared_ptr<ov::Model> initOriginal() const override;
+ std::shared_ptr<ov::Model> initReference() const override;
+};
+
} // namespace snippets
} // namespace test
} // namespace ov
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.cpp
index 06cda869a11..4a815276c3f 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
@@ -1126,6 +1126,71 @@ std::shared_ptr<ov::Model> MHAWithExtractedReshapeFunction::initReference() cons
return std::make_shared<ov::Model>(results, ngraphParam, "mha");
}
+std::shared_ptr<ov::Model> MHARankUpgradeToReductionFunction::initOriginal() const {
+ const auto param_0 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[0]);
+ const auto param_1 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[1]);
+ const auto param_2 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[2]);
+ const auto param_3 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[3]);
+ const auto param_4 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[4]);
+ ov::ParameterVector parameters = {param_0, param_1, param_2, param_3, param_4};
+ const auto matmul_0 = std::make_shared<ov::opset1::MatMul>(param_0, param_1);
+ const auto add_0 = std::make_shared<ov::opset1::Add>(matmul_0, param_2);
+
+ auto add0_shape = add_0->get_output_shape(0);
+ add0_shape.emplace(add0_shape.begin(), 1);
+ const auto reshape_up_const = ov::opset1::Constant::create(ov::element::i32, {add0_shape.size()}, add0_shape);
+ const auto reshape_up = std::make_shared<ov::opset1::Reshape>(add_0, reshape_up_const, false);
+
+ const auto add_1 = std::make_shared<ov::opset1::Add>(reshape_up, param_3);
+
+ auto add1_shape = add_1->get_output_shape(0);
+ add1_shape.erase(add1_shape.begin());
+ const auto reshape_down_const = ov::opset1::Constant::create(ov::element::i32, {add1_shape.size()}, add1_shape);
+ const auto reshape_down = std::make_shared<ov::opset1::Reshape>(add_1, reshape_down_const, false);
+
+ const auto softmax = std::make_shared<ov::op::v8::Softmax>(reshape_down, -1);
+ const auto matmul_1 = std::make_shared<ov::opset1::MatMul>(softmax, param_4);
+
+ ov::ResultVector results{std::make_shared<ov::opset1::Result>(matmul_1)};
+ return std::make_shared<ov::Model>(results, parameters, "mha");
+}
+
+std::shared_ptr<ov::Model> MHARankUpgradeToReductionFunction::initReference() const {
+ const auto data_0 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[0]);
+ const auto data_1 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[1]);
+ const auto data_2 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[2]);
+ const auto data_3 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[3]);
+ const auto data_4 = std::make_shared<ov::opset1::Parameter>(precision, input_shapes[4]);
+ ov::ParameterVector parameters = {data_0, data_1, data_2, data_3, data_4};
+
+ auto input_reshape = input_shapes[3].to_shape();
+ input_reshape.erase(input_reshape.begin());
+ const auto input_reshape_down =
+ ov::opset1::Constant::create(ov::element::i32, {input_reshape.size()}, input_reshape);
+ const auto reshape = std::make_shared<ov::opset1::Reshape>(data_3, input_reshape_down, false);
+
+ const auto param_0 = std::make_shared<ov::opset1::Parameter>(precision, data_0->get_shape());
+ const auto param_1 = std::make_shared<ov::opset1::Parameter>(precision, data_1->get_shape());
+ const auto param_2 = std::make_shared<ov::opset1::Parameter>(precision, data_2->get_shape());
+ const auto param_3 = std::make_shared<ov::opset1::Parameter>(precision, reshape->get_shape());
+ const auto param_4 = std::make_shared<ov::opset1::Parameter>(precision, data_4->get_shape());
+
+ const auto matmul_0 = std::make_shared<ov::op::v0::MatMul>(param_0, param_1);
+ const auto add_0 = std::make_shared<ov::opset1::Add>(matmul_0, param_2);
+ const auto add_1 = std::make_shared<ov::opset1::Add>(add_0, param_3);
+ const auto softmax = std::make_shared<ov::op::v8::Softmax>(add_1, -1);
+ const auto matmul_1 = std::make_shared<ov::op::v0::MatMul>(softmax, param_4);
+
+ auto subgraph_body = std::make_shared<ov::Model>(NodeVector{matmul_1},
+ ov::ParameterVector{param_0, param_1, param_2, param_3, param_4});
+ auto subgraph =
+ std::make_shared<ov::snippets::op::Subgraph>(ov::NodeVector{data_0, data_1, data_2, reshape, data_4},
+ subgraph_body);
+
+ ov::ResultVector results{std::make_shared<ov::opset1::Result>(subgraph)};
+ return std::make_shared<ov::Model>(results, parameters, "mha");
+}
+
} // namespace snippets
} // namespace test
} // namespace ov