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] SplitDimensionM unification (#34508)
Vladislav Golubev061573302177
diff --git a/src/common/snippets/docs/mha_optimization_guide.md b/src/common/snippets/docs/mha_optimization_guide.mdindex 51bccbd23cd..879567d613c 100644--- a/src/common/snippets/docs/mha_optimization_guide.md+++ b/src/common/snippets/docs/mha_optimization_guide.md@@ -61,60 +61,16 @@ The supported by decomposition Transpose orders are defined by `TokenizeMHASnipp**Please note: the "unsupported" Transpose actually can be executed via Snippets decomposition, however CPU plugin implementation is expected to work faster in this particular case.**-### SplitDimensionM+## MHAParallelWAOptimizer: Parallel Work Amount Optimization-[SplitDimensionM](../src/pass/split_dimension_m.cpp) splits M dimension of MHA in 2 parts (`batch_m` and `new_m`) by inserting Reshape on A input of the first Matmul and output of the second Matmul (the rest Subgraph's inputs are reshaped by Unsqueeze-like reshapes in order not to break subgraph semantic).-This optimization increases parallel work amount by `batch_m` times thus enabling a more efficient parallel execution in some cases.-The splitting is performed based on heuristic algorithm which can be found in `SplitDimensionM::split` method.--Let's consider an example of the transformation:--```mermaid- graph LR- subgraph left[" "]- direction TB- MM0A_1[Matmul0 Input A]- MM0B_1[Matmul0 Input B]- MM1B_1[Matmul1 Input B]- S_1["Subgraph"]- MM1C_1[Matmul1 Output]-- MM0A_1-->|"[1, M, K1]"|S_1- MM0B_1-->|"[1, K1, N1]"|S_1- MM1B_1-->|"[1, N1, N2]"|S_1- S_1-->|"[1, M, N2]"|MM1C_1- end- subgraph middle[" "]- direction TB- MM0A_2[Matmul0 Input A]- Reshape1["Input SplitM Reshape"]- MM0B_2[Matmul0 Input B]- Reshape2["Unsqueeze-like Reshape 1"]- MM1B_2[Matmul1 Input B]- Reshape3["Unsqueeze-like Reshape 2"]- S_2["Subgraph"]- Reshape4["Output SplitM Reshape"]- MM1C_2[Matmul1 Output]-- MM0A_2-->|"[1, M, K1]"|Reshape1- Reshape1-->|"[1, batch_M, new_M, K1]"|S_2- MM0B_2-->|"[1, K1, N1]"|Reshape2- Reshape2-->|"[1, 1, K1, N1]"|S_2- MM1B_2-->|"[1, N1, N2]"|Reshape3- Reshape3-->|"[1, 1, N1, N2]"|S_2- S_2-->|"[1, batch_M, new_M, N2]"|Reshape4- Reshape4-->|"[1, M, N2]"|MM1C_2- end- left-->|SplitDimensionM|middle-%% middle-->|<font size=+1>Attach Add\n to Subgraph</font>|right- classDef no-bg-color fill:none,stroke-width:0px- class left,middle,right no-bg-color-```+[MHAParallelWAOptimizer](../src/lowered/pass/mha_parallel_wa_optimizer.cpp) increases the parallel work amount for MHA by logically splitting the M dimension into `batch_m` and `new_m` parts.+Unlike graph-level transformations, it **does not modify the model graph**: it operates entirely at the runtime level by adjusting loop work amounts and tensor layouts inside the `RuntimeConfigurator`.+The heuristic algorithm is implemented in `MHAParallelWAOptimizer::split`.**Important notes:**-- Since `SplitDimensionM` depends on parallel concurrency, the transformation result depends not only on the HW platform, but on number of streams used during model inference as well.-For instance, this might lead to different result in throughput and latency hint modes.-- `SplitDimensionM::can_be_optimized` is used in CPU plugin callback: if this method reports that appropriate parallel work amount can not be set for the MHA, the tokenization doesn't happen.+- Since `MHAParallelWAOptimizer` depends on parallel concurrency, the result depends not only on the HW platform, but also on the number of streams used during inference.+For instance, this may lead to different behavior in throughput and latency hint modes.+- `MHAParallelWAOptimizer::can_be_optimized` is used in the CPU plugin callback: if this method reports that an appropriate parallel work amount cannot be achieved for the MHA, tokenization is skipped.## Brgemm Blocking@@ -140,7 +96,7 @@ Based on previously discussed information, we provide the following recommendati2. Check how the graph was changed by [CommonOptimizations](#snippets-common-optimizations).In local experiments, some transformations might be worth to change:- Disable [ExtractUnsupportedTransposes](#extractunsupportedtransposes) transformation in order to benchmark Snippets Transpose implementation.- - Adjust [SplitDimensionM](#splitdimensionm) heuristics in order to benchmark another splitting, or disable the pass at all.+ - Adjust [MHAParallelWAOptimizer](#mhaparallelwaoptimizer-parallel-work-amount-optimization) heuristics in order to benchmark another splitting, or disable the optimization at all.3. [Blocking parameters](#blocking-parameters): adjust blocking heuristics in `BrgemmCPUBlocking`.- Please note that there are 2 Matmul nodes inside a single MHA, and each Matmul can have his own optimal K, N blocking params.M block is better to keep the same since the corresponding blocking loop is shared between both Matmuls.diff --git a/src/common/snippets/include/snippets/lowered/linear_ir.hpp b/src/common/snippets/include/snippets/lowered/linear_ir.hppindex de9a59ab5ea..090e1678f39 100644--- a/src/common/snippets/include/snippets/lowered/linear_ir.hpp+++ b/src/common/snippets/include/snippets/lowered/linear_ir.hpp@@ -206,6 +206,11 @@ public:bool is_dynamic() const;+ /**+ * @brief Updates m_is_dynamic flag by checking parameter/result shapes and loop work amounts.+ */+ void update_dynamic_state();+void enumerate_expressions() const;void sort_results();diff --git a/src/common/snippets/include/snippets/lowered/pass/mha_parallel_wa_optimizer.hpp b/src/common/snippets/include/snippets/lowered/pass/mha_parallel_wa_optimizer.hppindex 35ef1809697..0414ddef60d 100644--- a/src/common/snippets/include/snippets/lowered/pass/mha_parallel_wa_optimizer.hpp+++ b/src/common/snippets/include/snippets/lowered/pass/mha_parallel_wa_optimizer.hpp@@ -8,6 +8,7 @@#include <unordered_set>#include <vector>+#include "openvino/core/node.hpp"#include "openvino/core/rtti.hpp"#include "snippets/lowered/expression.hpp"#include "snippets/lowered/linear_ir.hpp"@@ -20,9 +21,8 @@ namespace ov::snippets::lowered::pass {class SetDynamicWAToOuterMostLoop;/*** @class MHAParallelWAOptimizer- * @brief Optimizes the dynamic MHA execution increasing parallel work amount dy dividing Brgemm's "M" dimension to- * "parallel_m" and "kernel_m". Uses heuristics from snippets::pass::SplitDimensionM for dimension splitting. The- * optimizer performs the following steps:+ * @brief Optimizes the MHA execution increasing parallel work amount by dividing Brgemm's "M" dimension to+ * "parallel_m" and "kernel_m". The optimizer performs the following steps:* - Identifies applicable Brgemm operations within the LinearIR.* - Finds parameters whose shapes and layouts need to be adjusted after the split.* - Determines loops that should be adjusted.@@ -40,7 +40,49 @@ public:return !m_loops_to_split.empty();}+ /**+ * @brief Tries to split M dimension in "shape" in accordance to optimal parallel work amount+ * @param shape Original shape+ * @param optimal_parallelism_work_amount Optimal work amount+ * @param batch_m_dim reference on batch's part of the split M+ * @param new_m_dim reference on new M dim after the split+ * @return true if split was successfull, otherwise false+ */+ static bool split(const ov::Shape& shape,+ size_t optimal_parallelism_work_amount,+ size_t& batch_m_dim,+ size_t& new_m_dim);++ /**+ * @brief Returns true if the parallel work amount can be increased by splitting the M dimension+ * @param node MatMul node to check (must be static)+ * @param concurrency Target parallelism work amount+ * @return true if M dimension can be split to improve parallelism, otherwise false+ */+ static bool can_be_optimized(const std::shared_ptr<const ov::Node>& node, size_t concurrency);+private:+ /**+ * @brief Contains splitM approaches allowing to get the batch ideally divisible by+ * optimal_parallelism_work_amount+ */+ static std::pair<size_t, size_t> split_ideally(size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount);+ /**+ * @brief Splits m_dim to minimize kernel_m in order to reduce waiting time for idle threads at the last+ * parallel loop iteration.+ */+ static std::pair<size_t, size_t> split_minimize_kernel_wa(size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount);+ /**+ * @brief Splits m_dim to get the batch in (optimal_parallelism_work_amount, 2 *+ * optimal_parallelism_work_amount) interval+ */+ static std::pair<size_t, size_t> split_fallback_increase_parallel_wa(size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount);static std::unordered_set<lowered::ExpressionPtr> find_applicable_brgemms(const lowered::LinearIRCPtr& linear_ir,bool check_dynamic_wa = true);@@ -58,6 +100,7 @@ private:size_t m_concurrency = 0;static const size_t m_dim_M_idx;+ static const size_t m_min_kernel_m;};} // namespace ov::snippets::lowered::passdiff --git a/src/common/snippets/include/snippets/op/subgraph.hpp b/src/common/snippets/include/snippets/op/subgraph.hppindex 9b66ba037b8..814a3ff9965 100644--- a/src/common/snippets/include/snippets/op/subgraph.hpp+++ b/src/common/snippets/include/snippets/op/subgraph.hpp@@ -145,6 +145,8 @@ public:}void set_virtual_port_count(size_t count);+ bool is_dynamic() const override;+void print() const;IShapeInferSnippets::Result shape_infer(const std::vector<VectorDimsRef>& input_shapes);diff --git a/src/common/snippets/include/snippets/pass/common_optimizations.hpp b/src/common/snippets/include/snippets/pass/common_optimizations.hppindex 535a2ede656..d4ace54c2d5 100644--- a/src/common/snippets/include/snippets/pass/common_optimizations.hpp+++ b/src/common/snippets/include/snippets/pass/common_optimizations.hpp@@ -17,7 +17,6 @@ class CommonOptimizations : public ov::pass::MatcherPass {class SubgraphManager;friend class ExtractConstants;friend class ExtractUnsupportedTransposes;- friend class SplitDimensionM;public:OPENVINO_MATCHER_PASS_RTTI("snippets::pass::CommonOptimizations");@@ -30,9 +29,7 @@ public:struct Config {using TransposeSupportCallback = std::function<bool(const std::shared_ptr<const ov::Node>&)>;- Config(size_t concurrency, bool split_m_dimension)- : m_concurrency(concurrency),- m_split_m_dimension(split_m_dimension) {+ explicit Config(size_t concurrency) : m_concurrency(concurrency) {OPENVINO_ASSERT(concurrency > 0, "Concurrency should be greater than 0");}@@ -45,10 +42,6 @@ public:return m_concurrency;}- [[nodiscard]] bool get_split_m_dimension() const {- return m_split_m_dimension;- }-void set_transpose_support_callback(TransposeSupportCallback cb) {m_transpose_support_cb = std::move(cb);}@@ -59,8 +52,6 @@ public:private:size_t m_concurrency = 0;- // True if "SplitDimensionM" optimization is enabled.- bool m_split_m_dimension = true;// Callback to determine whether a given Transpose is supported inside Subgraph.// If empty, all Transposes are treated as unsupported.TransposeSupportCallback m_transpose_support_cb = [](const std::shared_ptr<const ov::Node>&) {diff --git a/src/common/snippets/include/snippets/pass/split_dimension_m.hpp b/src/common/snippets/include/snippets/pass/split_dimension_m.hppdeleted file mode 100644index 96276c085a8..00000000000--- a/src/common/snippets/include/snippets/pass/split_dimension_m.hpp+++ /dev/null@@ -1,124 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#pragma once--#include <cstddef>-#include <memory>-#include <utility>-#include <vector>--#include "openvino/core/node.hpp"-#include "openvino/core/rtti.hpp"-#include "openvino/core/shape.hpp"-#include "openvino/op/matmul.hpp"-#include "snippets/op/subgraph.hpp"-#include "snippets/pass/common_optimizations.hpp"-#include "snippets/shape_types.hpp"-#include "subgraph_pass.hpp"--namespace ov::snippets::pass {--/**- * @interface SplitDimensionM- * @brief Inserts Reshape nodes before inputs and after outputs of Subgraphs with MatMul inside- * to split dimension M for MatMuls. It allows to increase work amount for parallelism- * @attention This pass works only for MHA with static shapes.- * For dynamic shapes, parallel work amount is optimized in RuntimeConfigurator.- * @todo Ticket 148805: Move static cases handling in RuntimeConfigurator as well.- * @ingroup snippets- */-class SplitDimensionM : public CommonOptimizations::SubgraphPass {-public:- OPENVINO_RTTI("SplitDimensionM", "0");- explicit SplitDimensionM(size_t concurrency) : SubgraphPass("SplitDimensionM"), m_concurrency(concurrency) {}-- bool run_on_subgraph(const std::shared_ptr<op::Subgraph>& subgraph) override;-- // Return True if the MatMul node is supported by this optimization- static bool is_supported_matmul(const std::shared_ptr<const ov::Node>& node);- // Returns True if parallelism work amount (concurrency) can be increased by this optimization- static bool can_be_optimized(const std::shared_ptr<const ov::Node>& node, size_t concurrency);-- /**- * @brief Tries to split M dimension in "shape" in accordance to optimal parallel work amount- * @param shape Original shape- * @param optimal_parallelism_work_amount Optimal work amount- * @param batch_m_dim reference on batch's part of the split M- * @param new_m_dim reference on new M dim after the split- * @return true if split was successfull, otherwise false- */- static bool split(const ov::Shape& shape,- size_t optimal_parallelism_work_amount,- size_t& batch_m_dim,- size_t& new_m_dim);-- /**- * @brief Splits m dimension in order- * @param order Original order- * @param m_index M dimension index- * @return updated order with the split M dimension- */- static std::vector<size_t> get_updated_order(const std::vector<size_t>& order, size_t m_index);- /**- * @brief Reshapes m dimension in "shape": separates M in two parts: "batch_m_dim" and "new_m_dim"- * @param shape Shape to split- * @param m_index M dimension index- * @param batch_m_dim batch's part of the split M- * @param new_m_dim new M dim after the split- * @return the updated shape- */- static ov::snippets::VectorDims reshape_m_dim(ov::snippets::VectorDims shape,- size_t m_index,- size_t batch_m_dim,- size_t new_m_dim);- /**- * @brief Unsqueezes m dimension in "shape" (inserts "1" before the dimension)- * @param shape Shape to split- * @param m_index M dimension index- * @return the updated shape- */- static ov::snippets::VectorDims unsqueeze_m_dim(ov::snippets::VectorDims shape, size_t m_index);--private:- static std::shared_ptr<ov::op::v0::MatMul> get_matmul(const std::shared_ptr<op::Subgraph>& subgraph);- /**- * @brief Contains splitM approaches allowing to get the batch ideally divisible by optimal_parallelism_work_amount- */- static std::pair<size_t, size_t> split_ideally(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount);- /**- * @brief Splits m_dim to minimize kernel_m in order to reduce waiting time for idle threads at the last parallel- * loop iteration.- */- static std::pair<size_t, size_t> split_minimize_kernel_wa(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount);- /**- * @brief Splits m_dim to get the batch in (optimal_parallelism_work_amount, 2 * optimal_parallelism_work_amount)- * interval- */- static std::pair<size_t, size_t> split_fallback_increase_parallel_wa(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount);-- static void reshape_subgraph(const std::shared_ptr<op::Subgraph>& subgraph,- const ov::Shape& shape,- size_t batch_m_dim,- size_t new_m_dim);-- static size_t get_dim_M(const ov::Shape& shape) {- if (shape.size() < dim_M_index + 1) {- return 1;- }- return *(shape.rbegin() + dim_M_index);- }-- size_t m_concurrency;-- static const size_t min_kernel_m;- static const size_t dim_M_index;-};-} // namespace ov::snippets::passdiff --git a/src/common/snippets/include/snippets/pass/tokenization.hpp b/src/common/snippets/include/snippets/pass/tokenization.hppindex 6f83f932cdc..e7b1be2bc37 100644--- a/src/common/snippets/include/snippets/pass/tokenization.hpp+++ b/src/common/snippets/include/snippets/pass/tokenization.hpp@@ -65,7 +65,7 @@ public:* Naming policy:* - During tokenization new Subgraph op takes the name of the last tokenized op.* It's needed to save output names of model in cases when tokenized op was before model Result.- * - If some transformation (for example, SplitDimensionM) insert new op after Subgraph,+ * - If some transformation inserts a new op after Subgraph,* the op should be called as this Subgraph to save output name. The Subgraph name is updated using suffix* "_original".* @ingroup snippetsdiff --git a/src/common/snippets/src/lowered/linear_ir.cpp b/src/common/snippets/src/lowered/linear_ir.cppindex d37dd085af3..82d7778d39b 100644--- a/src/common/snippets/src/lowered/linear_ir.cpp+++ b/src/common/snippets/src/lowered/linear_ir.cpp@@ -80,13 +80,7 @@ LinearIR::LinearIR(const std::shared_ptr<ov::Model>& model,last_param = it;}}- for (const auto& param_expr : m_parameter_expressions) {- m_is_dynamic = m_is_dynamic || utils::is_dynamic_vdims(param_expr->get_output_port_descriptor(0)->get_shape());- }- for (const auto& result_expr : m_result_expressions) {- m_is_dynamic = m_is_dynamic || utils::is_dynamic_vdims(result_expr->get_input_port_descriptor(0)->get_shape());- }-+ update_dynamic_state();enumerate_expressions();}@@ -161,6 +155,20 @@ bool LinearIR::is_dynamic() const {return m_is_dynamic;}+void LinearIR::update_dynamic_state() {+ bool is_dynamic = false;+ for (const auto& param_expr : m_parameter_expressions) {+ is_dynamic = is_dynamic || utils::is_dynamic_vdims(param_expr->get_output_port_descriptor(0)->get_shape());+ }+ for (const auto& result_expr : m_result_expressions) {+ is_dynamic = is_dynamic || utils::is_dynamic_vdims(result_expr->get_input_port_descriptor(0)->get_shape());+ }+ for (const auto& [loop_id, loop_info] : m_loop_manager->get_map()) {+ is_dynamic = is_dynamic || loop_info->is_dynamic();+ }+ m_is_dynamic = is_dynamic;+}+void LinearIR::debug_print(bool tds_as_pointers) const {auto print_rinfo = [](const RegInfo& rinfo) {std::cerr << " : {";diff --git a/src/common/snippets/src/lowered/pass/mha_parallel_wa_optimizer.cpp b/src/common/snippets/src/lowered/pass/mha_parallel_wa_optimizer.cppindex f327bf375a1..4b4c4883286 100644--- a/src/common/snippets/src/lowered/pass/mha_parallel_wa_optimizer.cpp+++ b/src/common/snippets/src/lowered/pass/mha_parallel_wa_optimizer.cpp@@ -5,14 +5,22 @@#include "snippets/lowered/pass/mha_parallel_wa_optimizer.hpp"#include <algorithm>+#include <cmath>#include <cstddef>+#include <functional>#include <iterator>+#include <memory>+#include <numeric>#include <set>+#include <tuple>#include <unordered_set>+#include <utility>#include <vector>#include "openvino/core/except.hpp"+#include "openvino/core/node.hpp"#include "openvino/core/type.hpp"+#include "openvino/op/matmul.hpp"#include "openvino/op/parameter.hpp"#include "snippets/itt.hpp"#include "snippets/lowered/expression.hpp"@@ -22,14 +30,67 @@#include "snippets/lowered/loop_port.hpp"#include "snippets/lowered/pass/runtime_optimizer.hpp"#include "snippets/op/brgemm.hpp"-#include "snippets/pass/split_dimension_m.hpp"#include "snippets/runtime_configurator.hpp"+#include "snippets/shape_types.hpp"#include "snippets/utils/loop_utils.hpp"#include "snippets/utils/utils.hpp"namespace ov::snippets::lowered::pass {+namespace {+std::vector<size_t> get_updated_order(const std::vector<size_t>& order, size_t m_index) {+ std::vector<size_t> new_order(order.size() + 1, 0);+ size_t shift_idx = 0;+ for (size_t i = 0; i < order.size(); ++i) {+ if (order[i] < m_index) {+ new_order[i + shift_idx] = order[i];+ } else if (order[i] == m_index) {+ new_order[i + shift_idx++] = order[i];+ new_order[i + shift_idx] = order[i] + 1;+ } else {+ new_order[i + shift_idx] = order[i] + 1;+ }+ }+ return new_order;+}++ov::snippets::VectorDims unsqueeze_m_dim(ov::snippets::VectorDims shape, size_t m_index) {+ OPENVINO_ASSERT(m_index < shape.size(), "m_index must be less than shape size");+ shape.insert(shape.begin() + m_index, 1);+ return shape;+}++ov::snippets::VectorDims reshape_m_dim(ov::snippets::VectorDims shape,+ size_t m_index,+ size_t batch_m_dim,+ size_t new_m_dim) {+ OPENVINO_ASSERT(m_index < shape.size(), "m_index must be less than shape size");+ if (shape[m_index] == 1) {+ return unsqueeze_m_dim(std::move(shape), m_index);+ }+ shape[m_index] = new_m_dim;+ shape.insert(shape.begin() + m_index, batch_m_dim);+ return shape;+}++bool is_prime_number(size_t value) {+ if (value == 2LU || value == 3LU) {+ return true;+ }+ if (value == 1 || value % 2 == 0 || value % 3 == 0) {+ return false;+ }+ const auto root = std::sqrt(value) + 1;+ for (size_t divisor = 5; divisor < root; divisor += 6) {+ if ((value % divisor == 0) || (value % (divisor + 2) == 0)) {+ return false;+ }+ }+ return true;+}+} // namespaceconst size_t MHAParallelWAOptimizer::m_dim_M_idx = 1;+const size_t MHAParallelWAOptimizer::m_min_kernel_m = 32;MHAParallelWAOptimizer::MHAParallelWAOptimizer(const lowered::LinearIRCPtr& linear_ir,const RuntimeConfigurator* configurator)@@ -56,7 +117,7 @@ MHAParallelWAOptimizer::MHAParallelWAOptimizer(const lowered::LinearIRCPtr& line: utils::get_output_dim_idx(layout, m_dim_M_idx);m_dim_M_idces[i] = dim_idx;const auto m_idx = i < configurator->get_in_num() ? dim_idx : layout.size() - 2;- m_optimized_layouts[i] = ov::snippets::pass::SplitDimensionM::get_updated_order(layout, m_idx);+ m_optimized_layouts[i] = get_updated_order(layout, m_idx);}}@@ -64,10 +125,7 @@ bool MHAParallelWAOptimizer::run(const lowered::LinearIR& linear_ir) {OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::MHAParallelWAOptimizer")const auto& config = m_configurator->get_config();size_t new_batch_dim = 0, new_kernel_dim = 0;- if (!ov::snippets::pass::SplitDimensionM::split(config->master_shape,- m_concurrency,- new_batch_dim,- new_kernel_dim)) {+ if (!split(config->master_shape, m_concurrency, new_batch_dim, new_kernel_dim)) {return false;}auto& master_shape = config->master_shape;@@ -100,11 +158,8 @@ bool MHAParallelWAOptimizer::run(const lowered::LinearIR& linear_ir) {for (size_t i = 0; i < m_configurator->get_io_num(); ++i) {config->io_shapes[i] =m_unsqueezed_params.count(i)- ? ov::snippets::pass::SplitDimensionM::unsqueeze_m_dim(config->io_shapes[i], m_dim_M_idces[i])- : ov::snippets::pass::SplitDimensionM::reshape_m_dim(config->io_shapes[i],- m_dim_M_idces[i],- new_batch_dim,- new_kernel_dim);+ ? unsqueeze_m_dim(config->io_shapes[i], m_dim_M_idces[i])+ : reshape_m_dim(config->io_shapes[i], m_dim_M_idces[i], new_batch_dim, new_kernel_dim);}config->io_layouts = m_optimized_layouts;return true;@@ -211,4 +266,124 @@ std::vector<lowered::ExpandedLoopInfoPtr> MHAParallelWAOptimizer::find_loops_to_return loops_to_split;}+bool MHAParallelWAOptimizer::split(const ov::Shape& shape,+ size_t optimal_parallelism_work_amount,+ size_t& batch_m_dim,+ size_t& new_m_dim) {+ // Shape must have at least 2 dimensions (M and K); shapes like [] or [K] are not splittable+ if (shape.size() < 2) {+ return false;+ }+ const auto batch_dim =+ std::accumulate(shape.rbegin() + 2, shape.rend(), static_cast<size_t>(1), std::multiplies<>());+ const auto m_dim = *(shape.rbegin() + 1);+ if (is_prime_number(m_dim)) {+ return false;+ }++ // We skip optimization if the current batch is optimal for concurrency+ if (batch_dim % optimal_parallelism_work_amount == 0) {+ return false;+ }++ auto split_is_done = [&batch_m_dim]() {+ return batch_m_dim != 1;+ };++ std::tie(batch_m_dim, new_m_dim) = split_ideally(batch_dim, m_dim, optimal_parallelism_work_amount);+ if (split_is_done()) {+ return true;+ }++ std::tie(batch_m_dim, new_m_dim) = split_minimize_kernel_wa(batch_dim, m_dim, optimal_parallelism_work_amount);+ if (split_is_done()) {+ return true;+ }+ // If all the previous heuristics failed, fallback heuristic is used, which reflects the old splitting behavior+ if (batch_dim < optimal_parallelism_work_amount) {+ std::tie(batch_m_dim, new_m_dim) =+ split_fallback_increase_parallel_wa(batch_dim, m_dim, optimal_parallelism_work_amount);+ }+ return split_is_done();+}++bool MHAParallelWAOptimizer::can_be_optimized(const std::shared_ptr<const ov::Node>& node, size_t concurrency) {+ const auto matmul = ov::as_type_ptr<const ov::op::v0::MatMul>(node);+ if (!matmul || matmul->get_transpose_a() || matmul->is_dynamic()) {+ return false;+ }+ size_t batch_m_dim = 0, new_m_dim = 0;+ return split(node->get_shape(), concurrency, batch_m_dim, new_m_dim);+}++std::pair<size_t, size_t> MHAParallelWAOptimizer::split_ideally(size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount) {+ // Ideal case #1: M can be split on the parts one of which complements the batch dimension to the optimal parallel+ // work amount In this case, each thread will execute the Snippets kernel once+ const size_t lower_bound = optimal_parallelism_work_amount / batch_dim;+ if (lower_bound * batch_dim == optimal_parallelism_work_amount && m_dim % lower_bound == 0) {+ return std::make_pair(lower_bound, m_dim / lower_bound);+ }++ // Ideal case #2: M is divisible by optimal parallel work amount, and the new_m_dim is big enough+ // In this case, each thread will execute the Snippets kernel 'batch_dim' times+ if (m_dim % optimal_parallelism_work_amount == 0) {+ const auto new_m_dim = m_dim / optimal_parallelism_work_amount;+ if (new_m_dim >= m_min_kernel_m) {+ return std::make_pair(optimal_parallelism_work_amount, new_m_dim);+ }+ }++ return std::make_pair(1, m_dim);+}++std::pair<size_t, size_t> MHAParallelWAOptimizer::split_fallback_increase_parallel_wa(+ size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount) {+ std::pair<size_t, size_t> splited = {1, m_dim};+ const size_t upper_bound = utils::div_up(2 * optimal_parallelism_work_amount, batch_dim);+ for (size_t divisor_0 = upper_bound - 1; divisor_0 > 1; divisor_0--) {+ size_t divisor_1 = m_dim / divisor_0;+ if (divisor_1 * divisor_0 == m_dim) {+ return divisor_0 * batch_dim >= optimal_parallelism_work_amount ? std::make_pair(divisor_0, divisor_1)+ : splited;+ }+ }+ return splited;+}++std::pair<size_t, size_t> MHAParallelWAOptimizer::split_minimize_kernel_wa(size_t batch_dim,+ size_t m_dim,+ size_t optimal_parallelism_work_amount) {+ // This heuristic minimizes 'm_kernel' (=> maximizes 'm_batch') with a limitation that 'm_kernel >= min_kernel_m'.+ // In other words, it tries to find 'm_kernel' bigger than 'm_min_kernel_m' and at the same time as close as+ // possible to this value.+ std::pair<size_t, size_t> best_result = {1, m_dim};+ for (size_t divisor = 2; divisor < std::sqrt(m_dim); ++divisor) {+ if (m_dim % divisor != 0) {+ continue;+ }+ // If divisor is more than 'm_min_kernel_m', divisor becomes 'm_kernel',+ // guaranteeing the most optimal implementation from 'm_kernel' minimization perspective.+ if (divisor >= m_min_kernel_m) {+ return std::make_pair(m_dim / divisor, divisor);+ }++ // If divisor is less than 'm_min_kernel_m', divisor becomes m_batch.+ // However, it is not guaranteed that the current 'm_kernel = m_dim / divisor' is minimized, as one of the next+ // divisors can be more optimal. So in this case the best result is remembered+ const size_t m_kernel = m_dim / divisor;+ if (m_kernel >= m_min_kernel_m) {+ best_result.first = divisor;+ best_result.second = m_kernel;+ }+ }+ if (best_result.first * batch_dim >= optimal_parallelism_work_amount) {+ return best_result;+ }+ return std::make_pair(1, m_dim);+}+} // namespace ov::snippets::lowered::passdiff --git a/src/common/snippets/src/lowered/pass/set_dynamic_wa_to_outermost_loop.cpp b/src/common/snippets/src/lowered/pass/set_dynamic_wa_to_outermost_loop.cppindex 0b119a8620a..0daf856db2b 100644--- a/src/common/snippets/src/lowered/pass/set_dynamic_wa_to_outermost_loop.cpp+++ b/src/common/snippets/src/lowered/pass/set_dynamic_wa_to_outermost_loop.cpp@@ -23,7 +23,7 @@ namespace ov::snippets::lowered::pass {bool SetDynamicWAToOuterMostLoop::run(LinearIR& linear_ir) {OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::SetDynamicWAToOuterMostLoop")- if (linear_ir.empty() || !linear_ir.is_dynamic() || linear_ir.get_config().m_enable_domain_optimization) {+ if (linear_ir.empty() || linear_ir.get_config().m_enable_domain_optimization) {return false;}@@ -72,6 +72,11 @@ bool SetDynamicWAToOuterMostLoop::run(LinearIR& linear_ir) {}}+ if (modified) {+ // Note: we need to update dynamic state of Linear IR after loop work amount modification+ linear_ir.update_dynamic_state();+ }+return modified;}diff --git a/src/common/snippets/src/op/subgraph.cpp b/src/common/snippets/src/op/subgraph.cppindex 6725b9ef3d7..d16f5e56d72 100644--- a/src/common/snippets/src/op/subgraph.cpp+++ b/src/common/snippets/src/op/subgraph.cpp@@ -115,6 +115,11 @@ void Subgraph::set_virtual_port_count(const size_t count) {m_virtual_port_count = count;}+bool Subgraph::is_dynamic() const {+ // Note: some control flow optimizations may introduce dynamism to the Subgraph+ return ov::Node::is_dynamic() || (m_linear_ir != nullptr && m_linear_ir->is_dynamic());+}+auto Subgraph::is_domain_sensitive_op(const std::shared_ptr<ov::Node>& op) -> bool {// Broadcast is domain sensetive op because the output shape depends on// the both input and broadcast shapes (the both - are inputs of op). Note: is used only in MHA patterndiff --git a/src/common/snippets/src/pass/common_optimizations.cpp b/src/common/snippets/src/pass/common_optimizations.cppindex 798a19c8ae1..73831f907f6 100644--- a/src/common/snippets/src/pass/common_optimizations.cpp+++ b/src/common/snippets/src/pass/common_optimizations.cpp@@ -18,7 +18,6 @@#include "snippets/pass/extract_unsupported_transposes.hpp"#include "snippets/pass/fq_decomposition.hpp"#include "snippets/pass/softmax_reshape_elimination.hpp"-#include "snippets/pass/split_dimension_m.hpp"#include "snippets/pass/subgraph_manager.hpp"#include "snippets/pass/transform_convert.hpp"#include "snippets/pass/validate.hpp"@@ -60,10 +59,6 @@ CommonOptimizations::CommonOptimizations(const CommonOptimizations::Config& confov::snippets::pass::ExtractUnsupportedTransposes,is_domain_sensitive,config.get_transpose_support_callback());- REGISTER_SNIPPETS_PASS(subgraph_manager,- ov::snippets::pass::SplitDimensionM,- is_domain_sensitive && config.get_split_m_dimension(),- config.get_concurrency());subgraph_manager.run_passes(subgraph);// Validate the body after all common optimizationsdiff --git a/src/common/snippets/src/pass/split_dimension_m.cpp b/src/common/snippets/src/pass/split_dimension_m.cppdeleted file mode 100644index 13014daf41c..00000000000--- a/src/common/snippets/src/pass/split_dimension_m.cpp+++ /dev/null@@ -1,425 +0,0 @@-// Copyright (C) 2018-2026 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include "snippets/pass/split_dimension_m.hpp"--#include <algorithm>-#include <cmath>-#include <cstddef>-#include <functional>-#include <iterator>-#include <memory>-#include <numeric>-#include <set>-#include <tuple>-#include <utility>-#include <vector>--#include "openvino/core/except.hpp"-#include "openvino/core/node.hpp"-#include "openvino/core/shape.hpp"-#include "openvino/core/type.hpp"-#include "openvino/core/type/element_type.hpp"-#include "openvino/op/broadcast.hpp"-#include "openvino/op/constant.hpp"-#include "openvino/op/matmul.hpp"-#include "openvino/op/parameter.hpp"-#include "openvino/op/reshape.hpp"-#include "openvino/op/result.hpp"-#include "openvino/op/softmax.hpp"-#include "openvino/op/transpose.hpp"-#include "snippets/itt.hpp"-#include "snippets/op/subgraph.hpp"-#include "snippets/shape_types.hpp"-#include "snippets/utils/utils.hpp"--namespace {-bool is_prime_number(size_t value) {- if (ov::snippets::utils::any_of(value, 2LU, 3LU)) {- return true;- }- if (value == 1 || value % 2 == 0 || value % 3 == 0) {- return false;- }- const auto root = std::sqrt(value) + 1;- for (size_t divisor = 5; divisor < root; divisor += 6) {- if (ov::snippets::utils::any_of(0U, value % divisor, value % (divisor + 2))) {- return false;- }- }- return true;-}-} // namespace--namespace ov::snippets::pass {--const size_t SplitDimensionM::min_kernel_m = 32;-const size_t SplitDimensionM::dim_M_index = 1;--bool SplitDimensionM::is_supported_matmul(const std::shared_ptr<const ov::Node>& node) {- const auto matmul = ov::as_type_ptr<const ov::op::v0::MatMul>(node);- return matmul && !matmul->get_transpose_a() && !matmul->is_dynamic();-}--std::pair<size_t, size_t> SplitDimensionM::split_ideally(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount) {- // Ideal case #1: M can be split on the parts one of which complements the batch dimension to the optimal parallel- // work amount In this case, each thread will execute the Snippets kernel once- const size_t lower_bound = optimal_parallelism_work_amount / batch_dim;- if (lower_bound * batch_dim == optimal_parallelism_work_amount && m_dim % lower_bound == 0) {- return std::make_pair(lower_bound, m_dim / lower_bound);- }-- // Ideal case #2: M is divisible by optimal parallel work amount, and the new_m_dim is big enough- // In this case, each thread will execute the Snippets kernel 'batch_dim' times- if (m_dim % optimal_parallelism_work_amount == 0) {- const auto new_m_dim = m_dim / optimal_parallelism_work_amount;- if (new_m_dim >= min_kernel_m) {- return std::make_pair(optimal_parallelism_work_amount, new_m_dim);- }- }-- return std::make_pair(1, m_dim);-}--std::pair<size_t, size_t> SplitDimensionM::split_fallback_increase_parallel_wa(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount) {- std::pair<size_t, size_t> splited = {1, m_dim};- const size_t upper_bound = utils::div_up(2 * optimal_parallelism_work_amount, batch_dim);- for (size_t divisor_0 = upper_bound - 1; divisor_0 > 1; divisor_0--) {- size_t divisor_1 = m_dim / divisor_0;- if (divisor_1 * divisor_0 == m_dim) {- return divisor_0 * batch_dim >= optimal_parallelism_work_amount ? std::make_pair(divisor_0, divisor_1)- : splited;- }- }- return splited;-}--std::pair<size_t, size_t> SplitDimensionM::split_minimize_kernel_wa(size_t batch_dim,- size_t m_dim,- size_t optimal_parallelism_work_amount) {- // This heuristic minimizes 'm_kernel' (=> maximizes 'm_batch') with a limitation that 'm_kernel >= min_kernel_m'.- // In other words, it tries to find 'm_kernel' bigger than 'min_kernel_m' and at the same time as close as possible- // to this value.- std::pair<size_t, size_t> best_result = {1, m_dim};- for (size_t divisor = 2; divisor < std::sqrt(m_dim); ++divisor) {- if (m_dim % divisor != 0) {- continue;- }- // If divisor is more than 'min_kernel_m', divisor becomes 'm_kernel',- // guaranteeing the most optimal implementation from 'm_kernel' minimization perspective.- if (divisor >= min_kernel_m) {- return std::make_pair(m_dim / divisor, divisor);- }-- // If divisor is less than 'min_kernel_m', divisor becomes m_batch.- // However, it is not guaranteed that the current 'm_kernel = m_dim / divisor' is minimized, as one of the next- // divisors can be more optimal. So in this case the best result is remembered- const size_t m_kernel = m_dim / divisor;- if (m_kernel >= min_kernel_m) {- best_result.first = divisor;- best_result.second = m_kernel;- }- }- if (best_result.first * batch_dim >= optimal_parallelism_work_amount) {- return best_result;- }- return std::make_pair(1, m_dim);-}--bool SplitDimensionM::can_be_optimized(const std::shared_ptr<const ov::Node>& node, size_t concurrency) {- if (!is_supported_matmul(node)) {- return false;- }- size_t batch_m_dim = 0, new_m_dim = 0;- return split(node->get_shape(), concurrency, batch_m_dim, new_m_dim);-}--std::vector<size_t> SplitDimensionM::get_updated_order(const std::vector<size_t>& order, size_t m_index) {- std::vector<size_t> new_order(order.size() + 1, 0);- size_t shift_idx = 0;- for (size_t i = 0; i < order.size(); ++i) {- if (order[i] < m_index) {- new_order[i + shift_idx] = order[i];- } else if (order[i] == m_index) {- new_order[i + shift_idx++] = order[i];- new_order[i + shift_idx] = order[i] + 1;- } else {- new_order[i + shift_idx] = order[i] + 1;- }- }- return new_order;-}--ov::snippets::VectorDims SplitDimensionM::reshape_m_dim(ov::snippets::VectorDims shape,- size_t m_index,- size_t batch_m_dim,- size_t new_m_dim) {- OPENVINO_ASSERT(m_index < shape.size(), "Incorrect M index: it should be less than target shape rank");- if (shape[m_index] == 1) {- return unsqueeze_m_dim(std::move(shape), m_index);- }- shape[m_index] = new_m_dim;- shape.insert(shape.begin() + m_index, batch_m_dim);- return shape;-}-ov::snippets::VectorDims SplitDimensionM::unsqueeze_m_dim(ov::snippets::VectorDims shape, size_t m_index) {- OPENVINO_ASSERT(m_index < shape.size(), "Incorrect M index: it should be less than target shape rank");- shape.insert(shape.begin() + m_index, 1);- return shape;-}--std::shared_ptr<ov::op::v0::MatMul> SplitDimensionM::get_matmul(const std::shared_ptr<op::Subgraph>& subgraph) {- const auto& body = subgraph->body_ptr();- const auto& parameters = body->get_parameters();- // [107806]: If count of Parameters isn't equal to Subgraph inputs (it's possible case in general),- // we cannot garantee correct extraction since we don't have correct connections between body I/O and- // Subgraph I/O.- OPENVINO_ASSERT(parameters.size() == subgraph->input_values().size(),- "Failed to extract unsupported transposes: the count of Parameters isn't equal to Subgraph inputs");-- // Need to find MatMul0 and check output shape- const auto& ops = body->get_ordered_ops();- const auto mm_it = std::find_if(ops.cbegin(), ops.cend(), [](const std::shared_ptr<ov::Node>& node) {- return ov::is_type<ov::op::v0::MatMul>(node);- });- if (mm_it == ops.end()) {- return nullptr;- }-- const auto& matmul0 = *mm_it;- return is_supported_matmul(matmul0) ? ov::as_type_ptr<ov::op::v0::MatMul>(matmul0) : nullptr;-}--bool SplitDimensionM::split(const ov::Shape& shape,- size_t optimal_parallelism_work_amount,- size_t& batch_m_dim,- size_t& new_m_dim) {- size_t batch_dim = 1;- if (shape.size() > 2) {- batch_dim = std::accumulate(shape.rbegin() + 2, shape.rend(), batch_dim, std::multiplies<>()); // B (batch)- }- const auto m_dim = get_dim_M(shape); // M- if (is_prime_number(m_dim)) {- return false;- }-- // We skip optimization if the current batch is optimal for concurrency- if (batch_dim % optimal_parallelism_work_amount == 0) {- return false;- }-- auto split_is_done = [&batch_m_dim]() {- return batch_m_dim != 1;- };-- std::tie(batch_m_dim, new_m_dim) = split_ideally(batch_dim, m_dim, optimal_parallelism_work_amount);- if (split_is_done()) {- return true;- }-- std::tie(batch_m_dim, new_m_dim) = split_minimize_kernel_wa(batch_dim, m_dim, optimal_parallelism_work_amount);- if (split_is_done()) {- return true;- }- // If all the previous heuristics failed, fallback heuristic is used, which reflects the old splitting behavior- if (batch_dim < optimal_parallelism_work_amount) {- std::tie(batch_m_dim, new_m_dim) =- split_fallback_increase_parallel_wa(batch_dim, m_dim, optimal_parallelism_work_amount);- }- return split_is_done();-}--void SplitDimensionM::reshape_subgraph(const std::shared_ptr<op::Subgraph>& subgraph,- const ov::Shape& shape,- size_t batch_m_dim,- size_t new_m_dim) {- const auto& body = subgraph->body_ptr();- const auto& parameters = body->get_parameters();- const auto& results = body->get_results();- const auto ops = body->get_ordered_ops();- const auto m_dim = get_dim_M(shape);-- // There are two Parameter variants:- // - Parameter on branches for Second input of MatMul - the shape should be only unsqueezed (add just 1)- // - Other Parameters (on First input of MatMuls and between) - the shape should be splitted on M dimension-- std::set<std::shared_ptr<ov::op::v0::Parameter>> reshaped_params;-- auto insert_reshape = [&](const std::shared_ptr<ov::op::v0::Parameter>& param, const ov::Shape& new_shape) {- const auto index = std::distance(parameters.begin(), std::find(parameters.begin(), parameters.end(), param));- const auto shape_const =- std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{new_shape.size()}, new_shape);- const auto reshape = std::make_shared<ov::op::v1::Reshape>(subgraph->input_value(index), shape_const, false);- subgraph->input(index).replace_source_output(reshape);- param->set_partial_shape(new_shape);- reshaped_params.insert(param);- };-- auto get_updated_shape = [&](const ov::snippets::VectorDims& shape, size_t m_index, bool split_m_dim) {- OPENVINO_ASSERT(m_index < shape.size(), "Dimension index must be less than shape rank");- const auto current_m_dim = shape[m_index];- OPENVINO_ASSERT(!split_m_dim || current_m_dim == 1 || current_m_dim == m_dim, "Incorrect shape for splitting!");- const auto new_shape =- split_m_dim ? reshape_m_dim(shape, m_index, batch_m_dim, new_m_dim) : unsqueeze_m_dim(shape, m_index);- OPENVINO_ASSERT(ov::shape_size(new_shape) == ov::shape_size(shape), "Incorrect shape splitting!");- return new_shape;- };-- auto reshape_transpose = [&](const std::shared_ptr<ov::Node>& transpose, bool is_input) -> size_t {- const auto order_constant = ov::as_type_ptr<ov::op::v0::Constant>(transpose->get_input_node_shared_ptr(1));- OPENVINO_ASSERT(order_constant != nullptr, "Transpose must have Constant order");- const auto order = order_constant->cast_vector<size_t>();- const auto forward_index = order.size() - 1 - dim_M_index;- const auto m_index =- is_input ? order[forward_index] : forward_index; // Index of M dimension in the previous order- const auto new_order = get_updated_order(order, m_index);- transpose->set_argument(1,- std::make_shared<ov::op::v0::Constant>(order_constant->get_element_type(),- ov::Shape{new_order.size()},- new_order));- return m_index;- };-- auto reshape_parameter = [&](const std::shared_ptr<ov::Node>& node, bool split_m_dim = true) {- const auto param = ov::as_type_ptr<ov::op::v0::Parameter>(node);- if (!param || reshaped_params.count(param) > 0) {- return;- }-- const auto shape = param->get_partial_shape().get_shape();- // if the index of dimension M is equal or greater than Shape rank, no need to reshape it.- if (shape.size() <= dim_M_index) {- return;- }-- const auto consumers = param->get_output_target_inputs(0);- const auto shared_consumer = consumers.begin()->get_node()->shared_from_this();- auto m_index = shape.size() - 1 - dim_M_index;- if (ov::is_type<ov::op::v1::Transpose>(shared_consumer)) {- m_index = reshape_transpose(shared_consumer, true);- }- insert_reshape(param, get_updated_shape(shape, m_index, split_m_dim));- };-- auto update_matmul_second_branch = [&](const std::shared_ptr<ov::op::v0::MatMul>& node) {- auto parent = node->get_input_node_shared_ptr(1);- while (!ov::is_type<ov::op::v0::Parameter>(parent)) {- if (parent->get_input_size() > 1) {- for (const auto& input_source : parent->input_values()) {- reshape_parameter(input_source.get_node_shared_ptr(), false);- }- }-- // [107731]: It's covered my MHA tokenization- parent = parent->get_input_node_shared_ptr(0);- }- reshape_parameter(parent, false);- };-- // Firstly, Unsqueeze parameters on second branches of MatMuls- for (const auto& op : ops) {- if (const auto matmul = ov::as_type_ptr<ov::op::v0::MatMul>(op)) {- update_matmul_second_branch(matmul);- } else if (const auto softmax_v8 = ov::as_type_ptr<ov::op::v8::Softmax>(op)) {- softmax_v8->set_axis(-1);- } else if (const auto softmax_v1 = ov::as_type_ptr<ov::op::v1::Softmax>(op)) {- softmax_v1->set_axis(- softmax_v1->get_output_partial_shape(0).size()); // since new_shape.size() = old_shape.size() + 1- } else if (const auto broadcast = ov::as_type_ptr<ov::op::v1::Broadcast>(op)) {- // Broadcast is tokenized only between MatMuls -> Split M dimension- const auto shape_const = ov::as_type_ptr<ov::op::v0::Constant>(broadcast->get_input_node_shared_ptr(1));- OPENVINO_ASSERT(shape_const, "SplitDimensionM expects Broadcast with Constant output shape");- const auto m_dim_idx = broadcast->get_output_partial_shape(0).size() - 2;- const auto new_shape = get_updated_shape(shape_const->cast_vector<size_t>(), m_dim_idx, true);- broadcast->set_argument(1,- std::make_shared<ov::op::v0::Constant>(shape_const->get_element_type(),- ov::Shape{new_shape.size()},- new_shape));- }- }-- // Secondly, Update All M dimensions for remaining parameters- for (const auto& param : parameters) {- if (reshaped_params.count(param) == 0) {- reshape_parameter(param, true);- }- }-- // Update Transpose order on Result- for (const auto& res : results) {- const auto parent = res->get_input_node_shared_ptr(0);- if (ov::is_type<ov::op::v1::Transpose>(parent)) {- reshape_transpose(parent, false);- }- }-- // Return the previous shape on outputs- for (size_t i = 0; i < subgraph->get_output_size(); ++i) {- const auto output_shape = subgraph->get_output_shape(i);- if (is_scalar(output_shape)) {- continue;- }-- const auto& target_inputs = subgraph->get_output_target_inputs(i);- const auto shape_const =- std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{output_shape.size()}, output_shape);- const auto reshape = std::make_shared<ov::op::v1::Reshape>(subgraph->output(i), shape_const, false);- // Save output name- const auto original_output = body->get_results()[i]->get_input_node_shared_ptr(0);- const auto original_name = original_output->get_friendly_name();- reshape->set_friendly_name(original_name);- original_output->set_friendly_name(original_name + "_original");-- for (const auto& input : target_inputs) {- input.replace_source_output(reshape);- // Result input tensor name was changed, the name has to be restored- if (ov::is_type<ov::op::v0::Result>(input.get_node())) {- input.get_tensor_ptr()->add_names(subgraph->output(i).get_tensor_ptr()->get_names());- }- }- subgraph->output(i).get_tensor_ptr()->set_names({});- }- subgraph->set_friendly_name(subgraph->get_friendly_name() + "_original");- // Need to update inner Shapes and Softmax Axis- subgraph->validate_and_infer_types();-}--bool SplitDimensionM::run_on_subgraph(const std::shared_ptr<op::Subgraph>& subgraph) {- OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::SplitDimensionM");- // To increase parallelism work in MHA pattern,- // we split 1st dimension (starting from 0th) into 2 new dimensions to get 4D Shapes where- // - 0th and 1st dimensions are used in parallel scheduling,- // - 2nd and 3rd dimensions are used in kernel-- // It's needed only for MHA patterns. Need to add support for common patterns- if (!subgraph->has_domain_sensitive_ops()) {- return false;- }-- // The pass supports only static shapes on Subgraph inputs due to static `Reshape` insertion around Subgraph.- const auto& params = subgraph->body_ptr()->get_parameters();- const auto is_dynamic = [](const std::shared_ptr<ov::Node>& p) {- return p->get_output_partial_shape(0).is_dynamic();- };- if (std::any_of(params.cbegin(), params.cend(), is_dynamic)) {- return false;- }-- if (const auto matmul0 = get_matmul(subgraph)) {- const auto mm_shape = matmul0->get_shape();- size_t batch_m_dim = 0, new_m_dim = 0;- if (!split(mm_shape, m_concurrency, batch_m_dim, new_m_dim)) {- return false;- }-- reshape_subgraph(subgraph, mm_shape, batch_m_dim, new_m_dim);- return true;- }- return false;-}-} // namespace ov::snippets::passdiff --git a/src/common/snippets/tests/include/utils/split_dim_m.hpp b/src/common/snippets/tests/include/utils/split_dim_m.hppindex 07fbf3fbd1e..aefce91d030 100644--- a/src/common/snippets/tests/include/utils/split_dim_m.hpp+++ b/src/common/snippets/tests/include/utils/split_dim_m.hpp@@ -23,14 +23,14 @@ struct ReferenceData {size_t kernel_m;};-struct SplitDimensionMParams {+struct MHAParallelWASplitParams {InputData input;ReferenceData reference;};-class SplitDimensionMTest : public testing::TestWithParam<SplitDimensionMParams> {+class MHAParallelWASplitTest : public testing::TestWithParam<MHAParallelWASplitParams> {public:- static std::string getTestCaseName(testing::TestParamInfo<SplitDimensionMParams> obj);+ static std::string getTestCaseName(testing::TestParamInfo<MHAParallelWASplitParams> obj);};} // namespace snippetsdiff --git a/src/common/snippets/tests/src/pass/mha_tokenization.cpp b/src/common/snippets/tests/src/pass/mha_tokenization.cppindex e6d85987416..c3b90bdb7ba 100644--- a/src/common/snippets/tests/src/pass/mha_tokenization.cpp+++ b/src/common/snippets/tests/src/pass/mha_tokenization.cpp@@ -128,7 +128,7 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_Partially_Dynamic_Disabletrue,false);model = f.getOriginal();- common_config = ov::snippets::pass::CommonOptimizations::Config(1, true);+ common_config = ov::snippets::pass::CommonOptimizations::Config(1);mha_config = ov::snippets::pass::TokenizeMHASnippets::Config(ov::snippets::pass::TokenizationConfig(std::numeric_limits<size_t>::max()),true,@@ -146,7 +146,7 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_Partially_Dynamic_Disabletrue,true);model = f.getOriginal();- common_config = ov::snippets::pass::CommonOptimizations::Config(1, true);+ common_config = ov::snippets::pass::CommonOptimizations::Config(1);mha_config = ov::snippets::pass::TokenizeMHASnippets::Config(ov::snippets::pass::TokenizationConfig(std::numeric_limits<size_t>::max()),true,@@ -286,184 +286,6 @@ TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_Dynamic_Transpose_fusion) {execute_and_validate_function(*this, f);}-TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA3D_SplitM) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{128, 12, 64}, {128, 12, 64}, {12, 128, 128}, {128, 12, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{2, 64, 12, 64}, {12, 1, 64, 128}, {12, 2, 64, 128}, {1, 128, 12, 64}, {128, 12, 64}},- false);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(24);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA3D_SplitM_Const_B) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{128, 12, 64}, {128, 12, 64}, {12, 128, 128}, {128, 12, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{2, 64, 12, 64}, {12, 1, 64, 128}, {12, 2, 64, 128}, {1, 128, 12, 64}, {128, 12, 64}},- false);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(24);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA3D_SplitM_withMul) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{128, 12, 64}, {128, 12, 64}, {12, 128, 128}, {128, 12, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{4, 32, 12, 64}, {12, 1, 64, 128}, {12, 4, 32, 128}, {1, 128, 12, 64}, {128, 12, 64}},- true);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(16);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA3D_SplitM_withMul_Const_B) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{128, 12, 64}, {128, 12, 64}, {12, 128, 128}, {128, 12, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{4, 32, 12, 64}, {12, 1, 64, 128}, {12, 4, 32, 128}, {1, 128, 12, 64}, {128, 12, 64}},- true);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(16);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA4D_SplitM) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{1, 384, 16, 64}, {1, 384, 16, 64}, {1, 1, 1, 384}, {1, 384, 16, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{1, 12, 32, 16, 64},- {1, 16, 1, 64, 384},- {1, 1, 1, 1, 384},- {1, 1, 384, 16, 64},- {1, 384, 16, 64}},- false);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(60);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA4D_SplitM_Const_B) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{1, 384, 16, 64}, {1, 384, 16, 64}, {1, 1, 1, 384}, {1, 384, 16, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{1, 12, 32, 16, 64},- {1, 16, 1, 64, 384},- {1, 1, 1, 1, 384},- {1, 1, 384, 16, 64},- {1, 384, 16, 64}},- false);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(60);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA4D_SplitM_withMul) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{1, 384, 16, 64}, {1, 384, 16, 64}, {1, 1, 1, 384}, {1, 384, 16, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{1, 12, 32, 16, 64},- {1, 16, 1, 64, 384},- {1, 1, 1, 1, 384},- {1, 1, 384, 16, 64},- {1, 384, 16, 64}},- true);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(60);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA4D_SplitM_withMul_Const_B) {- const auto& f = MHASplitMFunction(- std::vector<PartialShape>{{1, 384, 16, 64}, {1, 384, 16, 64}, {1, 1, 1, 384}, {1, 384, 16, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{1, 12, 32, 16, 64},- {1, 16, 1, 64, 384},- {1, 1, 1, 1, 384},- {1, 1, 384, 16, 64},- {1, 384, 16, 64}},- true);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(60);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHAWOTranspose_SplitM) {- const auto& f = MHAWOTransposeSplitMFunction(- std::vector<PartialShape>{{10, 9216, 128}, {10, 128, 9216}, {10, 9216, 128}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{10, 18, 512, 128}, {10, 1, 128, 9216}, {10, 1, 9216, 128}, {10, 9216, 128}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(18);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHAWOTranspose_SplitM_Const_B) {- const auto& f = MHAWOTransposeSplitMFunction(- std::vector<PartialShape>{{10, 9216, 128}, {10, 128, 9216}, {10, 9216, 128}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{10, 18, 512, 128}, {10, 1, 128, 9216}, {10, 1, 9216, 128}, {10, 9216, 128}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(18);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_SplitM_AlmostAllThreads) {- const auto& f = MHAWOTransposeSplitMFunction(- std::vector<PartialShape>{{5, 30, 32}, {5, 32, 30}, {5, 30, 32}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{5, 10, 3, 32}, {5, 1, 32, 30}, {5, 1, 30, 32}, {5, 30, 32}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(32);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_SplitM_AlmostAllThreads_Const_B) {- const auto& f = MHAWOTransposeSplitMFunction(- std::vector<PartialShape>{{5, 30, 32}, {5, 32, 30}, {5, 30, 32}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32}),- std::vector<Shape>{{5, 10, 3, 32}, {5, 1, 32, 30}, {5, 1, 30, 32}, {5, 30, 32}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(32);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_4D_SplitM_DynamicParameter) {- const auto& f = MHAFunction(- std::vector<PartialShape>{{1, 128, 16, 64}, {1, 128, 16, 64}, {1, 16, 128, -1}, {1, 128, 16, 64}},- std::vector<ov::element::Type>({ov::element::f32, ov::element::f32, ov::element::f32, ov::element::f32}),- false,- false);- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(32);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHASelect_SplitM) {- const auto& f = MHASelectSplitMFunction(- std::vector<PartialShape>{{8, 512, 18}, {8, 18, 64}, {1, 512, 64}, {1, 1, 64}, {8, 64, 512}},- std::vector<Shape>{{8, 2, 256, 18},- {8, 1, 18, 64},- {1, 2, 256, 64},- {1, 1, 1, 64},- {8, 1, 64, 512},- {8, 512, 512}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(16);- execute_and_validate_function(*this, f);-}--TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHASelect_SplitM_ScalarParams) {- const auto& f = MHASelectSplitMFunction(- std::vector<PartialShape>{{8, 512, 18}, {8, 18, 64}, {1}, {64}, {8, 64, 512}},- std::vector<Shape>{{8, 2, 256, 18}, {8, 1, 18, 64}, {}, {}, {8, 1, 64, 512}, {8, 512, 512}});- common_config = get_default_common_optimizations_config();- common_config.set_concurrency(16);- execute_and_validate_function(*this, f);-}-TEST_F(TokenizeMHASnippetsTests, smoke_Snippets_MHA_Reshape_extraction) {const auto& f = MHAWithExtractedReshapeFunction(std::vector<PartialShape>{{400, 196, 80},{400, 80, 196},diff --git a/src/common/snippets/tests/src/utils.cpp b/src/common/snippets/tests/src/utils.cppindex bcdf2f17cbd..34de10afb15 100644--- a/src/common/snippets/tests/src/utils.cpp+++ b/src/common/snippets/tests/src/utils.cpp@@ -23,7 +23,7 @@ TokenizationConfig get_default_tokenization_config() {}CommonOptimizations::Config get_default_common_optimizations_config() {- static CommonOptimizations::Config conf(1, true);+ static CommonOptimizations::Config conf(1);static bool initialized = false;if (!initialized) {conf.set_transpose_support_callback(ov::snippets::utils::make_transpose_support_callback(true));diff --git a/src/common/snippets/tests/src/utils/split_dim_m.cpp b/src/common/snippets/tests/src/utils/split_dim_m.cppindex c65423a5091..b1dc49fcfee 100644--- a/src/common/snippets/tests/src/utils/split_dim_m.cpp+++ b/src/common/snippets/tests/src/utils/split_dim_m.cpp@@ -5,14 +5,14 @@#include "utils/split_dim_m.hpp"#include "common_test_utils/ov_test_utils.hpp"-#include "snippets/pass/split_dimension_m.hpp"+#include "snippets/lowered/pass/mha_parallel_wa_optimizer.hpp"#include "snippets/utils/utils.hpp"namespace ov {namespace test {namespace snippets {-std::string SplitDimensionMTest::getTestCaseName(testing::TestParamInfo<SplitDimensionMParams> obj) {+std::string MHAParallelWASplitTest::getTestCaseName(testing::TestParamInfo<MHAParallelWASplitParams> obj) {const auto& input = obj.param.input;const auto& reference = obj.param.reference;std::ostringstream result;@@ -29,11 +29,11 @@ std::string SplitDimensionMTest::getTestCaseName(testing::TestParamInfo<SplitDimreturn result.str();}-TEST_P(SplitDimensionMTest, SplitDimensionM) {+TEST_P(MHAParallelWASplitTest, MHAParallelWASplit) {const auto& input = GetParam().input;const auto& reference = GetParam().reference;- // last_dim is fixed since it doesn't affect the SplitDimensionM result.+ // last_dim is fixed since it doesn't affect the MHAParallelWAOptimizer::split result.static const size_t last_dim = 1024;ov::Shape shape;if (input.cur_batch.has_value()) {@@ -42,10 +42,10 @@ TEST_P(SplitDimensionMTest, SplitDimensionM) {shape = {input.cur_m, last_dim};}size_t batch_m_dim, new_m_dim;- bool result = ov::snippets::pass::SplitDimensionM::split(shape,- input.concurrency,- batch_m_dim,- new_m_dim);+ bool result = ov::snippets::lowered::pass::MHAParallelWAOptimizer::split(shape,+ input.concurrency,+ batch_m_dim,+ new_m_dim);ASSERT_EQ(result, reference.is_split);if (result) {@@ -54,8 +54,8 @@ TEST_P(SplitDimensionMTest, SplitDimensionM) {}}-namespace SplitDimensionMInstantiation {-const std::vector<SplitDimensionMParams> split_dimension_cases = {+namespace MHAParallelWASplitInstantiation {+const std::vector<MHAParallelWASplitParams> split_dimension_cases = {// Negative test cases: split is not needed{InputData{{40} /*cur_batch*/, 32 /*cur_m*/, 40 /*concurrency*/}, ReferenceData{false /*is_split*/}},{InputData{{65}, 32, 40}, ReferenceData{false}},@@ -84,12 +84,12 @@ const std::vector<SplitDimensionMParams> split_dimension_cases = {{InputData{std::nullopt, 4097, 32}, ReferenceData{false, 4097, 32}},};-INSTANTIATE_TEST_SUITE_P(smoke_Snippets_SplitDimensionM,- SplitDimensionMTest,+INSTANTIATE_TEST_SUITE_P(smoke_Snippets_MHAParallelWASplit,+ MHAParallelWASplitTest,::testing::ValuesIn(split_dimension_cases),- SplitDimensionMTest::getTestCaseName);+ MHAParallelWASplitTest::getTestCaseName);-} // namespace SplitDimensionMInstantiation+} // namespace MHAParallelWASplitInstantiation} // namespace snippets} // namespace test} // namespace ov\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/nodes/subgraph.cpp b/src/plugins/intel_cpu/src/nodes/subgraph.cppindex 94080a637cf..7a28c186d11 100644--- a/src/plugins/intel_cpu/src/nodes/subgraph.cpp+++ b/src/plugins/intel_cpu/src/nodes/subgraph.cpp@@ -156,7 +156,7 @@ struct SubgraphKey {struct SubgraphCodeGeneratorKey {SubgraphCodeGeneratorKey(std::shared_ptr<SubgraphAttrs> attrs_,uint32_t broadcasting_mask_,- uint32_t constant_repacked_mask_ = 0)+ uint32_t constant_repacked_mask_): attrs(std::move(attrs_)),broadcasting_mask(broadcasting_mask_),constant_repacked_mask(constant_repacked_mask_) {}@@ -447,6 +447,10 @@ void Subgraph::createPrimitive() {initPluginBlockedShapes();initAttributes();optimizeIR();+ // Note: some control flow optimizations may introduce dynamism to the Subgraph,+ // so `is_dynamic` state has to be updated.+ updateIsDynamic();+ initConstantRepackedMask();// Init starts offsets should be after `prepareWeights`initStartOffsets();}@@ -534,6 +538,22 @@ void Subgraph::initPluginBlockedShapes() const {}}+void Subgraph::updateIsDynamic() {+ is_dynamic = is_dynamic || subgraph_attrs->snippet->is_dynamic();+}++void Subgraph::initConstantRepackedMask() {+#if defined(OPENVINO_ARCH_X86_64)+ // Compute the mask while input_repackers is fully populated after data-flow passes.+ // This value must be stable across repeated prepareParams() calls: BrgemmExternalRepackingAdjuster+ // erases already-repacked entries from input_repackers at runtime, so a later call to+ // getConstantRepackedMask() would incorrectly return 0 instead of the compile-time mask.+ m_constant_repacked_mask = getConstantRepackedMask();+#else+ m_constant_repacked_mask = 0;+#endif+}+Subgraph::DataFlowPasses Subgraph::getDataFlowPasses() {DataFlowPasses backend_passes;@@ -852,7 +872,7 @@ void Subgraph::prepareParams() {// configuration// 3. Create SubgraphDynamicSpecializedExecutorconst auto code_gen_result = cache->getOrCreate(- SubgraphCodeGeneratorKey(subgraph_attrs, getBroadcastingMask(in_shapes)),+ SubgraphCodeGeneratorKey(subgraph_attrs, getBroadcastingMask(in_shapes), key.constant_repacked_mask),[this](const SubgraphCodeGeneratorKey& key) -> std::shared_ptr<SubgraphCodeGenerator> {return std::make_shared<SubgraphCodeGenerator>(key.attrs,std::make_shared<CPURuntimeConfig>(),@@ -897,16 +917,10 @@ void Subgraph::prepareParams() {cache);};- // In the static case, io_data_offsets are baked into the JIT kernel, so two nodes with identical+ // io_data_offsets may be baked into the JIT kernel, so two nodes with identical// body structure and input shapes but different weight packing states produce different kernels- // and must be cached separately. In the dynamic case, offsets are recomputed at runtime, so the- // packing state has no effect on the generated code-# if defined(OPENVINO_ARCH_X86_64)- const auto constant_repacked_mask = is_dynamic ? 0U : getConstantRepackedMask();-# else- constexpr uint32_t constant_repacked_mask = 0;-# endif- const auto result = cache->getOrCreate(SubgraphKey(subgraph_attrs, in_shapes, constant_repacked_mask), builder);+ // and must be cached separately.+ const auto result = cache->getOrCreate(SubgraphKey(subgraph_attrs, in_shapes, m_constant_repacked_mask), builder);execPtr = result.first;#endifCPU_NODE_ASSERT(execPtr, "Executor is not created for node ", getName(), ".");diff --git a/src/plugins/intel_cpu/src/nodes/subgraph.h b/src/plugins/intel_cpu/src/nodes/subgraph.hindex 1675c1424ba..17c2046a219 100644--- a/src/plugins/intel_cpu/src/nodes/subgraph.h+++ b/src/plugins/intel_cpu/src/nodes/subgraph.h@@ -66,6 +66,7 @@ private:void initAttributes();void initStartOffsets();void initPluginBlockedShapes() const;+ void updateIsDynamic();void optimizeIR();snippets::op::Subgraph::BlockedShapeVector getSnippetsBlockedShapes() const;@@ -73,6 +74,7 @@ private:static uint64_t getBodyHash(const std::shared_ptr<snippets::op::Subgraph>& snippet);uint32_t getBroadcastingMask(const std::vector<VectorDims>& input_shapes);+ void initConstantRepackedMask();#if defined(OPENVINO_ARCH_X86_64)uint32_t getConstantRepackedMask() const;#endif@@ -114,6 +116,10 @@ private:std::set<size_t> external_ptrs_idces;bool is_dynamic = false;+ // Bitmask of inputs pre-packed at compile time (constant weights via RepackMatMulWeights).+ // Cached once in initConstantRepackedMask() right after optimizeIR(), because+ // BrgemmExternalRepackingAdjuster erases already-repacked entries from input_repackers at runtime.+ uint32_t m_constant_repacked_mask = 0;// Input shapes that are used in PrepareParams and ShapeInfer to avoid frequent memory allocationmutable std::vector<VectorDims> in_shapes;diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex b484bceaf4c..7b2ee3251ea 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -200,8 +200,8 @@# include "openvino/op/multiply.hpp"# include "openvino/op/softmax.hpp"# include "openvino/op/subtract.hpp"+# include "snippets/lowered/pass/mha_parallel_wa_optimizer.hpp"# include "snippets/pass/common_optimizations.hpp"-# include "snippets/pass/split_dimension_m.hpp"# include "transformations/common_optimizations/rms_fusion.hpp"# include "transformations/cpu_opset/common/op/sdpa.hpp"# include "transformations/cpu_opset/common/pass/causal_mask_preprocess_fusion.hpp"@@ -1241,11 +1241,7 @@ void Transformations::MainSnippets() {if (concurrency == 0) {concurrency = parallel_get_max_threads();}- // The optimization "SplitDimensionM" depends on target machine (thread count).- // To avoid uncontrolled behavior in tests, we disabled the optimization when there is- // Config::SnippetsMode::IgnoreCallback- bool split_m_dimension = !ignoreCallback;- CommonOptimizations::Config common_optimizations_config(concurrency, split_m_dimension);+ CommonOptimizations::Config common_optimizations_config(concurrency);#if defined(OPENVINO_ARCH_X86_64) || defined(OPENVINO_ARCH_ARM64)common_optimizations_config.set_transpose_support_callback(ov::snippets::utils::make_transpose_support_callback(true));@@ -1383,7 +1379,7 @@ void Transformations::MainSnippets() {};auto is_unsupported_parallel_work_amount = [&](const std::shared_ptr<const ov::Node>& n,const ov::PartialShape& shape) {- // SplitDimensionM transformation doesn't support dynamic shapes, so M dim is split in runtime configurator+ // Dynamic shapes are handled at runtime by MHAParallelWAOptimizerif (shape.is_dynamic()) {return false;}@@ -1395,7 +1391,9 @@ void Transformations::MainSnippets() {// Ticket 160154: enable tokenization for MHA with insufficient parallel work amountconst auto is_unsupported_parallel_work_amount =static_cast<size_t>(parallel_work_amount.get_length()) < common_optimizations_config.get_concurrency() &&- !SplitDimensionM::can_be_optimized(n, common_optimizations_config.get_concurrency());+ !snippets::lowered::pass::MHAParallelWAOptimizer::can_be_optimized(+ n,+ common_optimizations_config.get_concurrency());return is_unsupported_parallel_work_amount;};#endif // OPENVINO_ARCH_X86_64diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cppindex a20c163387b..88be4b1738e 100644--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/skip_tests_config.cpp@@ -132,8 +132,6 @@ const std::vector<std::regex>& disabled_test_patterns() {std::regex(R"(.*FakeConvertLayerTest.*dataPrecision=bf16.*)"),// Need to generate sequence exactly in the i64 data type. Enable in scope of i64 enabling.std::regex(R"(.*RandomUniformLayerTestCPU.*OutPrc=i64.*)"),- // Issue: 123815 (Tests are sensintive to available thread count on testing machines)- std::regex(R"(.*smoke_Snippets_MHA_.?D_SplitDimensionM_static.*)"),// Issue: 126095std::regex(R"(^smoke_Multinomial(?:Static|Dynamic)+(?:Log)*.*seed_g=0_seed_o=0.*device=CPU.*)"),// Issue: 129931diff --git a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_split_dim_m.cpp b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_split_dim_m.cppindex f26644548cb..77da1cac706 100644--- a/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_split_dim_m.cpp+++ b/src/plugins/intel_cpu/tests/functional/shared_tests_instances/snippets/mha_split_dim_m.cpp@@ -9,45 +9,19 @@namespace ov {namespace test {namespace snippets {-namespace {-static ov::AnyMap enable_callback(size_t num_threads) {- return ov::AnyMap({ov::intel_cpu::snippets_mode(ov::intel_cpu::SnippetsMode::ENABLE),- ov::inference_num_threads(num_threads)});-}-static ov::AnyMap set_num_threads(size_t num_threads) {return ov::AnyMap({ov::inference_num_threads(num_threads)});}-INSTANTIATE_TEST_SUITE_P(- smoke_Snippets_MHA_4D_SplitDimensionM_static,- MHAWithThreadCount,- ::testing::Combine(::testing::ValuesIn(SNIPPETS_TESTS_STATIC_SHAPES({{1, 128, 2, 64}, {1, 128, 2, 64}, {1, 1, 1, 1}, {1, 128, 2, 64}})),- ::testing::ValuesIn(precision_f32(4)),- ::testing::Values(ov::element::f32),- ::testing::Values(true),- ::testing::Values(7), // Subgraph + 4 Reshapes, Transpose1 on inputs and 1 Reshape on output- ::testing::Values(2),- ::testing::Values(ov::test::utils::DEVICE_CPU),- ::testing::Values(enable_callback(4))), // 4 Threads- MHAWithThreadCount::getTestCaseName);--INSTANTIATE_TEST_SUITE_P(- smoke_Snippets_MHA_3D_SplitDimensionM_static,- MHAWithThreadCount,- ::testing::Combine(::testing::ValuesIn(SNIPPETS_TESTS_STATIC_SHAPES({{384, 2, 64}, {384, 2, 64}, {1, 384, 384}, {384, 2, 64}})),- ::testing::ValuesIn(precision_f32(4)),- ::testing::Values(ov::element::f32),- ::testing::Values(true),- ::testing::Values(10), // Subgraph + 4 Reshapes on inputs and 1 Reshape on output + 4 Transposes- ::testing::Values(1), // MHA- ::testing::Values(ov::test::utils::DEVICE_CPU),- ::testing::Values(enable_callback(4))), // 4 Threads- MHAWithThreadCount::getTestCaseName);--std::vector<std::vector<ov::test::InputShape>> splitm_dynamic_shapes_4d = {+std::vector<std::vector<ov::test::InputShape>> splitm_shapes_4d = {+ {+ {PartialShape{}, {{1, 128, 2, 64}}},+ {PartialShape{}, {{1, 128, 2, 64}}},+ {PartialShape{}, {{1, 1, 1, 1}}},+ {PartialShape{}, {{1, 128, 2, 64}}},+ },{{PartialShape{-1, -1, -1, -1}, {{1, 128, 2, 64}, {1, 17, 2, 64}, {1, 128, 2, 64}}},{PartialShape{-1, -1, -1, -1}, {{1, 128, 2, 64}, {1, 17, 2, 64}, {1, 128, 2, 64}}},@@ -77,19 +51,25 @@ std::vector<std::vector<ov::test::InputShape>> splitm_dynamic_shapes_4d = {static constexpr size_t expected_nodes_mha_splitm_4d_dyn = 2;INSTANTIATE_TEST_SUITE_P(- smoke_Snippets_MHA_4D_SplitDimensionM_dynamic,+ smoke_Snippets_MHA_4D_MHAParallelWAOptimizer,MHAWithThreadCount,- ::testing::Combine(::testing::ValuesIn(splitm_dynamic_shapes_4d),+ ::testing::Combine(::testing::ValuesIn(splitm_shapes_4d),::testing::ValuesIn(precision_f32(4)),::testing::Values(ov::element::f32),::testing::Values(false),::testing::Values(expected_nodes_mha_splitm_4d_dyn),::testing::Values(2), // Transpose1 + MHA::testing::Values(ov::test::utils::DEVICE_CPU),- ::testing::Values(set_num_threads(4))), // 4 Threads+ ::testing::Values(set_num_threads(4))),MHAWithThreadCount::getTestCaseName);-std::vector<std::vector<ov::test::InputShape>> splitm_dynamic_shapes_3d = {+std::vector<std::vector<ov::test::InputShape>> splitm_shapes_3d = {+ {+ {PartialShape{}, {{384, 2, 64}}},+ {PartialShape{}, {{384, 2, 64}}},+ {PartialShape{}, {{1, 384, 384}}},+ {PartialShape{}, {{384, 2, 64}}},+ },{{PartialShape{-1, -1, -1}, {{128, 2, 64}, {17, 2, 64}, {128, 2, 64}}},{PartialShape{-1, -1, -1}, {{128, 2, 64}, {17, 2, 64}, {128, 2, 64}}},@@ -105,16 +85,16 @@ std::vector<std::vector<ov::test::InputShape>> splitm_dynamic_shapes_3d = {};INSTANTIATE_TEST_SUITE_P(- smoke_Snippets_MHA_3D_SplitDimensionM_dynamic,+ smoke_Snippets_MHA_3D_MHAParallelWAOptimizer,MHAWithThreadCount,- ::testing::Combine(::testing::ValuesIn(splitm_dynamic_shapes_3d),+ ::testing::Combine(::testing::ValuesIn(splitm_shapes_3d),::testing::ValuesIn(precision_f32(4)),::testing::Values(ov::element::f32),::testing::Values(false),::testing::Values(5), // Subgraph + 4 Transpose::testing::Values(2), // MHA + one of the transposes is executed via Subgraph (because callback is disabled)::testing::Values(ov::test::utils::DEVICE_CPU),- ::testing::Values(set_num_threads(4))), // 4 Threads+ ::testing::Values(set_num_threads(4))),MHAWithThreadCount::getTestCaseName);} // namespacediff --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 57fa1b5b621..0ad42c45a26 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@@ -144,19 +144,6 @@ protected:const std::vector<ov::element::Type> precisions;};-class MHASplitMFunction : public MHAFunction {-public:- explicit MHASplitMFunction(const std::vector<PartialShape>& inputShapes, const std::vector<ov::element::Type>& precisions,- const std::vector<Shape>& reshapes, bool with_mul = true)- : MHAFunction(inputShapes, precisions, with_mul), reshapes(reshapes) {- OPENVINO_ASSERT(reshapes.size() == 5, "Got invalid number of Reshape shapes");- }-protected:- std::shared_ptr<ov::Model> initReference() const override;-- std::vector<ov::Shape> reshapes;-};-/* Graph:* Transpose1[0,2,3,1] Parameter* \ /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 25ca8882296..a8ad0274af3 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@@ -360,69 +360,6 @@ std::shared_ptr<ov::Model> MHA2DFunction::initReference() const {return std::make_shared<ov::Model>(OutputVector{subgraph}, ngraphParams);}-std::shared_ptr<ov::Model> MHASplitMFunction::initReference() const {- auto data0 = std::make_shared<ov::opset1::Parameter>(precisions[0], input_shapes[0]);- auto data1 = std::make_shared<ov::opset1::Parameter>(precisions[1], input_shapes[1]);- auto data2 = std::make_shared<ov::opset1::Parameter>(precisions[2], input_shapes[2]);- auto data3 = std::make_shared<ov::opset1::Parameter>(precisions[3], input_shapes[3]);- ov::ParameterVector ngraphParams = {data0, data1, data2, data3};-- const auto rank_before = input_shapes[1].size();- const auto transpose1Const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank_before}, get_decomposed_order(rank_before));- const auto transpose1 = std::make_shared<ov::op::v1::Transpose>(data1, transpose1Const);-- std::shared_ptr<ov::Node> subgraph_parent1 = transpose1;- if (with_mul) {- ov::Shape shape(rank_before, 1);- if (transpose1->get_output_partial_shape(0).is_static()) {- shape[rank_before - 3] = transpose1->get_output_shape(0)[rank_before - 3];- }- const auto mulConst = ov::test::utils::make_constant(precisions[1], shape);- subgraph_parent1 = std::make_shared<ov::op::v1::Multiply>(transpose1, mulConst);- }-- auto make_reshape = [](const std::shared_ptr<ov::Node>& node, const ov::Shape& new_shape) {- auto shape_const = ov::op::v0::Constant::create(ov::element::i32, {new_shape.size()}, new_shape);- return std::make_shared<ov::op::v1::Reshape>(node, shape_const, true);- };-- auto reshape0 = make_reshape(data0, reshapes[0]);- auto reshape1 = make_reshape(subgraph_parent1, reshapes[1]);- auto reshape2 = make_reshape(data2, reshapes[2]);- auto reshape3 = make_reshape(data3, reshapes[3]);- OutputVector subgraph_inputs = {reshape0, reshape1, reshape2, reshape3};-- auto transpose0Param = std::make_shared<ov::opset1::Parameter>(precisions[0], reshape0->get_shape());- auto brgemm1Param = std::make_shared<ov::opset1::Parameter>(precisions[1], reshape1->get_shape());- auto addParam = std::make_shared<ov::opset1::Parameter>(precisions[2], reshape2->get_shape());- auto transpose2Param = std::make_shared<ov::opset1::Parameter>(precisions[3], reshape3->get_shape());- ov::ParameterVector subgraph_params = {transpose0Param, brgemm1Param, addParam, transpose2Param};-- const auto rank = input_shapes[0].size() + 1;- const auto transpose0Const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, get_fusion_order_after_split_m(rank, true));- const auto transpose2Const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, get_fusion_order_after_split_m(rank, true));- const auto transpose3Const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{rank}, get_fusion_order_after_split_m(rank, false));-- const auto transpose0 = std::make_shared<ov::op::v1::Transpose>(transpose0Param, transpose0Const);-- const auto matMul0 = std::make_shared<ov::op::v0::MatMul>(transpose0, brgemm1Param);- const auto add = std::make_shared<ov::op::v1::Add>(matMul0, addParam);- const auto softMax = std::make_shared<ov::opset1::Softmax>(add, rank - 1);- const auto transpose2 = std::make_shared<ov::op::v1::Transpose>(transpose2Param, transpose2Const);- const auto matMul1 = std::make_shared<ov::op::v0::MatMul>(softMax, transpose2);- const auto transpose3 = std::make_shared<ov::op::v1::Transpose>(matMul1, transpose3Const);-- const auto snippets_result = std::make_shared<ov::snippets::op::Result>(transpose3);-- const auto subgraph = std::make_shared<ov::snippets::op::Subgraph>(subgraph_inputs,- std::make_shared<ov::Model>(ov::OutputVector{snippets_result},- subgraph_params));-- auto reshape4 = make_reshape(subgraph, reshapes[4]);- ov::ResultVector results{std::make_shared<ov::opset1::Result>(reshape4)};- return std::make_shared<ov::Model>(results, ngraphParams, "mha");-}-std::shared_ptr<ov::Model> MHAWithDynamicMulFunction::initOriginal() const {auto transpose0Param = std::make_shared<ov::opset1::Parameter>(precisions[0], input_shapes[0]);auto transpose1Param = std::make_shared<ov::opset1::Parameter>(precisions[1], input_shapes[1]);