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] Added dynamic memory sharing support (#27175)
Alexandra Sidorovaab71e5ba54e6
diff --git a/src/common/snippets/include/snippets/lowered/expressions/buffer_expression.hpp b/src/common/snippets/include/snippets/lowered/expressions/buffer_expression.hppindex 3dcd98ef0a9..9174d9866db 100644--- a/src/common/snippets/include/snippets/lowered/expressions/buffer_expression.hpp+++ b/src/common/snippets/include/snippets/lowered/expressions/buffer_expression.hpp@@ -38,6 +38,7 @@ public:size_t get_offset() const { return m_offset; }size_t get_allocation_size() const { return m_allocation_size; }size_t get_byte_size() const;+ ov::element::Type get_data_type() const;void set_reg_group(size_t reg_group) { m_reg_group = reg_group; }void set_cluster_id(size_t cluster) { m_cluster_id = cluster; }diff --git a/src/common/snippets/include/snippets/lowered/loop_info.hpp b/src/common/snippets/include/snippets/lowered/loop_info.hppindex cc66f5f6ffc..23e1f14a8b7 100644--- a/src/common/snippets/include/snippets/lowered/loop_info.hpp+++ b/src/common/snippets/include/snippets/lowered/loop_info.hpp@@ -211,13 +211,20 @@ public:int64_t data_size = 0;bool is_dynamic() const;+ bool is_static() const;++ friend bool operator==(const LoopPortDesc& lhs, const LoopPortDesc& rhs);+ friend bool operator!=(const LoopPortDesc& lhs, const LoopPortDesc& rhs);};// The structure describes full information about port// - TODO [140365] : UnifiedLoopInfo should have the map of LoopPorts and LoopDesc as class field// instead of the separate vectors with descriptors.struct LoopPortInfo {- LoopPort port;- LoopPortDesc desc;+ LoopPortInfo() = default;+ LoopPortInfo(LoopPort port_, LoopPortDesc desc_) : port(std::move(port_)), desc(std::move(desc_)) {}++ LoopPort port = {};+ LoopPortDesc desc = {};};UnifiedLoopInfo() = default;@@ -367,6 +374,12 @@ public:caller(m_output_ports[i], m_output_port_descs[i]);}+ /**+ * @brief Return loop port info of an expression port+ * @param expr_port - expression port.+ */+ LoopPortInfo get_loop_port_info(const ExpressionPort& expr_port);+protected:/*** @brief Clone LoopPortDesc[actual_port_idx] `new_count` times and insert on the place of current descdiff --git a/src/common/snippets/include/snippets/lowered/pass/define_buffer_clusters.hpp b/src/common/snippets/include/snippets/lowered/pass/define_buffer_clusters.hppindex 1597eaa2377..312abb02abf 100644--- a/src/common/snippets/include/snippets/lowered/pass/define_buffer_clusters.hpp+++ b/src/common/snippets/include/snippets/lowered/pass/define_buffer_clusters.hpp@@ -6,6 +6,8 @@#include "pass.hpp"+#include "snippets/lowered/loop_info.hpp"+namespace ov {namespace snippets {namespace lowered {@@ -45,7 +47,7 @@ public:private:using BufferCluster = std::set<BufferExpressionPtr>;using BufferClusters = std::vector<BufferCluster>;- using BufferPorts = std::unordered_map<BufferExpressionPtr, std::set<size_t>>;+ using BufferMap = std::unordered_map<BufferExpressionPtr, UnifiedLoopInfo::LoopPortInfo>;/*** @brief Finds Buffer cluster in set of clusters which contains the target expression with Buffer* @param target target expression with Buffer op@@ -58,76 +60,72 @@ private:* @param target_expr expression with target op - LoopEnd or MemoryAccess op* @return boolean value*/- bool is_direct_buffer(const BufferExpressionPtr& buffer_expr, const ExpressionPtr& target_expr) const;+ static bool is_direct_buffer(const BufferExpressionPtr& buffer_expr, const ExpressionPtr& target_expr);/*** @brief Creates new buffer cluster if buffer_exprs is missed in clusters. If buffer_exprs is already in clusters, do nothing* @param buffer_expr expression with Buffer op*/void create_new_cluster(const BufferExpressionPtr& buffer_expr);+ /**+ * @brief Add buffers to the existing clusters+ * @param existing_cluster existing clusters+ * @param buffers buffers which will be added to the existing cluster+ */+ static void add_buffers_to_cluster(BufferCluster& existing_cluster, const std::set<BufferExpressionPtr>& buffers);/*** @brief Returns common ID of cluster if all buffer inside have the same Buffer ID. Otherwise returns the default value SIZE_MAX* that means that Buffers in cluster have different IDs.* @param cluster set of Buffer expressions - cluster* @return common buffer ID or SIZE_MAX - size value*/- size_t get_cluster_buffer_id(const BufferCluster& cluster) const;+ static size_t get_cluster_buffer_id(const BufferCluster& cluster);/*** @brief Analyzes Loop: if Loop has Buffer ops on inputs and outputs, Loop can read and write from/to the same memory.+ * @param loop_manager loop manager* @param expr_it iterator of Linear IR which refers to the expression with LoopEnd*/- void parse_loop(const LinearIR::constExprIt& expr_it);+ void parse_loop(const LoopManagerPtr& loop_manager, const LinearIR::constExprIt& expr_it);/*** @brief Analyzes full MemoryAccess op: if the op has Buffer ops on I/O, the op can read and write from/to the same memory.* @param expr expression with full MemoryAccess op*/void parse_memory_access_op(const ExpressionPtr& expr);/**- * @brief Gets input outputs buffers of Loop- * @param loop_expr expression with LoopEnd op- * @return unordered map [Expression -> set of input ports] which represents input Buffers of Loop+ * @brief Find all direct buffers that are connected to the current Loop+ * @param loop_info current unified loop info+ * @param loop_expr the target LoopEnd expression+ * @return input and output buffer maps*/- BufferPorts get_input_buffers(const ExpressionPtr& loop_expr) const;- /**- * @brief Gets output buffers of Loop- * @param loop_expr expression with LoopEnd op- * @return unordered map [Expression -> set of input ports] which represents output Buffers of Loop- */- BufferPorts get_output_buffers(const ExpressionPtr& loop_expr) const;+ static std::pair<BufferMap, BufferMap> get_direct_buffers(const UnifiedLoopInfoPtr& loop_info, const ExpressionPtr& loop_expr);/*** @brief Analyzes nested Loops: unite nested buffer clusters if they can reproduce `window` sliding- * @param input_buffers unordered map [Expression -> set of input ports] which represents input Buffers of Loop- * @param output_buffers unordered map [Expression -> set of output ports (one)] which represents output Buffers of Loop+ * @param loop_manager loop manager+ * @param input_buffers unordered map [Expression -> LoopPortInfo] which represents input Buffers of Loop+ * @param output_buffers unordered map [Expression -> LoopPortInfo] which represents output Buffers of Loop* @param outer_loop_end_expr_it iterator of Linear IR which refers to the expression with outer LoopEnd*/- void parse_nested_loops(const BufferPorts& input_buffers, const BufferPorts& output_buffers, const LinearIR::constExprIt& outer_loop_end_expr_it);+ void parse_nested_loops(const LoopManagerPtr& loop_manager, const BufferMap& input_buffers, const BufferMap& output_buffers,+ const LinearIR::constExprIt& outer_loop_end_expr_it);/**- * @brief Finds the last connected Loop to the target Buffer and returns the corresponding finalization offset+ * @brief Finds the last connected Loop to the target Buffer and init the corresponding loop port info+ * @param loop_manager loop manager* @param buffer_expr expression with Buffer op- * @return finalization offset - int64_t value- */- int64_t get_buffer_finalization_offset(const BufferExpressionPtr& buffer_expr) const;- /**- * @brief Check if two Buffer expressions are connected to the same Loop. Set common LoopEnd as `loop` parameter and- * indexes of Loop ports `up_idx` and `down_idx` if Buffers are really neighbours- * @param up expression with upper Buffer op- * @param down expression with lower Buffer op- * @param loop expression with common LoopEnd op- * @param up_idx the reference to port index of upper Buffer op to the Loop- * @param down_idx the reference to port index of lower Buffer op to the Loop- * @return Return True if the Buffers are connected to the same Loop+ * @param port_info target loop port info to be initialized+ * @return status - True if loop port has been found. Otherwise, return false - not connected to the Loop.*/- static bool are_buffer_neighbours(const BufferExpressionPtr& up, const BufferExpressionPtr& down, ExpressionPtr& loop,- size_t& up_idx, size_t& down_idx);+ static bool init_buffer_last_loop_port_info(const LoopManagerPtr& loop_manager, const BufferExpressionPtr& buffer_expr,+ UnifiedLoopInfo::LoopPortInfo& port_info);/*** @brief Unite clusters+ * @param loop_manager loop manager* @param inner_cluster_it iterator to inner cluster - buffer cluster is in the loop* @param outer_cluster buffer clusters with buffers outside the Loop* @param outer_buffer target Buffer from outer_cluster* @param is_outer_up true if outer buffer is upper in Linear IR than inner Buffers* @return Return True if clusters have been united*/- bool unite_nested_clusters(const BufferClusters::iterator& inner_cluster_it, BufferCluster& outer_cluster,+ bool unite_nested_clusters(const LoopManagerPtr& loop_manager, const BufferClusters::iterator& inner_cluster_it, BufferCluster& outer_cluster,const BufferExpressionPtr& outer_buffer, bool is_outer_up);BufferClusters m_clusters;diff --git a/src/common/snippets/include/snippets/lowered/pass/mark_invariant_shape_path.hpp b/src/common/snippets/include/snippets/lowered/pass/mark_invariant_shape_path.hppnew file mode 100644index 00000000000..6a31a697bac--- /dev/null+++ b/src/common/snippets/include/snippets/lowered/pass/mark_invariant_shape_path.hpp@@ -0,0 +1,65 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "pass.hpp"++namespace ov {+namespace snippets {+namespace lowered {+namespace pass {++/**+ * @interface MarkInvariantShapePath+ * @brief The helper pass for BufferAllocation pipeline:+ * - Many buffer-relates passes (SetBufferRegGroup, DefineBufferClusters) depend on loop pointer increments.+ * The increments are unknown in dynamic case, so these passes can't set reg groups and clusters efficiently.+ * The current pass marks expressions port which will have the same shape. The shape and layout means+ * the same loop pointer arithmetic in runtime.+ * @ingroup snippets+ */+class MarkInvariantShapePath: public RangedPass {+public:+ OPENVINO_RTTI("MarkInvariantShapePath", "RangedPass")+ MarkInvariantShapePath() = default;++ /**+ * @brief Apply the pass to the Linear IR+ * @param linear_ir the target Linear IR+ * @return status of the pass+ */+ bool run(LinearIR& linear_ir, lowered::LinearIR::constExprIt begin, lowered::LinearIR::constExprIt end) override;++ /**+ * @brief Returns ID (color) of the current Invariant Shape path for the passed port.+ * Ports which have the same IDs of the paths - will have the same shapes in runtime.+ * Note: if passed port is input port, the method returns value for source of port connector+ * for the passed port. Because the shape is created by output ports of expressions.+ * @param port target expression port+ * @return ID+ */+ static size_t getInvariantPortShapePath(const ExpressionPort& port);++private:+ /**+ * @brief Sets ID (color) of the current Invariant Shape path for the passed output port.+ * Ports which have the same IDs of the paths - will have the same shapes in runtime.+ * @param port target expression port+ * @param value ID of the path (color)+ */+ static void SetInvariantPortShapePath(const ExpressionPort& port, size_t value);++ /**+ * @brief Return runtime info for the passed expression port+ * @param port target expression port+ * @return runtime info map+ */+ static ov::RTMap& get_rt_info(const ExpressionPort& port);+};++} // namespace pass+} // namespace lowered+} // namespace snippets+} // namespace ovdiff --git a/src/common/snippets/include/snippets/lowered/pass/set_buffer_reg_group.hpp b/src/common/snippets/include/snippets/lowered/pass/set_buffer_reg_group.hppindex cba3f28856b..dc22ce4beff 100644--- a/src/common/snippets/include/snippets/lowered/pass/set_buffer_reg_group.hpp+++ b/src/common/snippets/include/snippets/lowered/pass/set_buffer_reg_group.hpp@@ -6,6 +6,7 @@#include "pass.hpp"+#include "snippets/lowered/loop_info.hpp"#include "snippets/utils/utils.hpp"namespace ov {@@ -38,34 +39,19 @@ public:* @param linear_ir the target Linear IR* @return status of the pass*/- bool run(LinearIR& linear_ir, lowered::LinearIR::constExprIt begin, lowered::LinearIR::constExprIt end) override;-- struct ShiftPtrParams {- ShiftPtrParams() = default;- ShiftPtrParams(int64_t ds, int64_t pi, int64_t fo) : data_size(ds), ptr_increment(pi), finalization_offset(fo) {}- int64_t data_size = 0;- int64_t ptr_increment = 0;- int64_t finalization_offset = 0;-- inline bool is_static() const {- return !utils::is_dynamic_value(ptr_increment) && !utils::is_dynamic_value(finalization_offset);- }-- friend bool operator==(const ShiftPtrParams& lhs, const ShiftPtrParams& rhs);- friend bool operator!=(const ShiftPtrParams& lhs, const ShiftPtrParams& rhs);- };+ bool run(LinearIR& linear_ir, LinearIR::constExprIt begin, LinearIR::constExprIt end) override;/**- * @brief Check if two Buffers can be in one register group by ShiftPtrParams < data_size, ptr_increment, finalization_offset >- * @param lhs Data pointer shift params for first Buffer- * @param rhs Data pointer shift params for second Buffer+ * @brief Check if two Buffers can be in one register group by LoopDesc < data_size, ptr_increment, finalization_offset >+ * @param lhs LoopPortInfo (Port and Data pointer shift params for first Buffer)+ * @param rhs LoopPortInfo (Port and Data pointer shift params for second Buffer)* @return Returns True if params are valid to reuse one register. Otherwise returns False*/- static bool can_be_in_one_group(const ShiftPtrParams& lhs, const ShiftPtrParams& rhs);+ static bool can_be_in_one_reg_group(const UnifiedLoopInfo::LoopPortInfo& lhs, const UnifiedLoopInfo::LoopPortInfo& rhs);private:using BufferPool = std::vector<BufferExpressionPtr>;- using BufferMap = std::map<BufferExpressionPtr, ShiftPtrParams>;+ using BufferMap = std::map<BufferExpressionPtr, UnifiedLoopInfo::LoopPortInfo>;/*** @brief Get Buffer Index in Buffer set@@ -76,11 +62,14 @@ private:static size_t get_buffer_idx(const BufferExpressionPtr& target, const BufferPool& pool);/*** @brief Create adjacency matrix for Buffer system. See comment in the method for more details.- * @param linear_ir the target Linear IR+ * @param loop_manager the loop manager+ * @param begin begin iterator+ * @param end end iterator* @param pool set of Buffers from the Linear IR* @return adjacency matrix where True value means that Buffers are adjacent and cannot have the same ID*/- static std::vector<bool> create_adjacency_matrix(lowered::LinearIR::constExprIt begin, lowered::LinearIR::constExprIt end, const BufferPool& pool);+ static std::vector<bool> create_adjacency_matrix(const LoopManagerPtr& loop_manager, LinearIR::constExprIt begin, LinearIR::constExprIt end,+ const BufferPool& pool);/*** @brief Algorithm of Graph coloring where vertices are Buffers* @param buffers set of Buffers from the Linear IR@@ -99,25 +88,23 @@ private:* @param buffers set of Buffers from the Linear IR* @param adj Target adjacency matrix*/- static void update_adj_matrix(const std::pair<BufferExpressionPtr, ShiftPtrParams>& lhs,- const std::pair<BufferExpressionPtr, ShiftPtrParams>& rhs,- const BufferPool& buffers,+ static void update_adj_matrix(const BufferMap::value_type& lhs, const BufferMap::value_type& rhs, const BufferPool& buffers,std::vector<bool>& adj);+/*** @brief Check if two Buffers are adjacent and cannot have the same ID- * @param lhs Pair where first value is Expression with first Buffer and second value is data pointer shift params for it- * @param rhs Pair where first value is Expression with second Buffer and second value is data pointer shift params for it+ * @param lhs LoopPortInfo (Port and Data pointer shift params for first Buffer)+ * @param rhs LoopPortInfo (Port and Data pointer shift params for second Buffer)* @return Returns True if they are adjacent, otherwise returns False*/- static bool are_adjacent(const std::pair<BufferExpressionPtr, ShiftPtrParams>& lhs,- const std::pair<BufferExpressionPtr, ShiftPtrParams>& rhs);+ static bool are_adjacent(const BufferMap::value_type& lhs, const BufferMap::value_type& rhs);/**- * @brief Find all buffers that are connected to the current LoopEnd- * @param loop_end_expr expression of the target LoopEnd- * @return buffer map [buffer expr -> ShiftDataPtrs]+ * @brief Find all buffers that are connected to the current Loop+ * @param loop_info current unified loop info+ * @return buffer map*/- static BufferMap get_buffer_loop_neighbours(const ExpressionPtr& loop_end_expr);+ static BufferMap get_buffer_loop_neighbours(const UnifiedLoopInfoPtr& loop_info);/*** @brief Find all buffers that are inside the current Loop.* @param loop_end_it expression iterator in LinearIR of the target LoopEnddiff --git a/src/common/snippets/include/snippets/utils/utils.hpp b/src/common/snippets/include/snippets/utils/utils.hppindex f7e584d48a9..ff4646f24d0 100644--- a/src/common/snippets/include/snippets/utils/utils.hpp+++ b/src/common/snippets/include/snippets/utils/utils.hpp@@ -91,6 +91,12 @@ static inline auto rnd_up(const T lhs, const U rhs) -> decltype(div_up(lhs, rhs)return div_up_res * rhs;}+static inline bool is_planar_layout(const std::vector<size_t>& order) {+ for (size_t i = 0; i < order.size(); ++i)+ if (order[i] != i) return false;+ return true;+}+inline bool is_dynamic_vdims(const VectorDims& shape) {return std::any_of(shape.cbegin(), shape.cend(), [](size_t v){ return is_dynamic_value(v); });}diff --git a/src/common/snippets/src/lowered/expression.cpp b/src/common/snippets/src/lowered/expression.cppindex aaa71612cef..1952b93017a 100644--- a/src/common/snippets/src/lowered/expression.cpp+++ b/src/common/snippets/src/lowered/expression.cpp@@ -170,11 +170,6 @@ ExpressionPtr Expression::clone() const {}bool Expression::visit_attributes(AttributeVisitor &visitor) {- auto is_planar_layout = [](const std::vector<size_t>& layout) {- for (size_t i = 0; i < layout.size(); ++i)- if (layout[i] != i) return false;- return true;- };auto subtensor2str = [](const VectorDims& subtensor) {std::stringstream ss;for (size_t i = 0; i < subtensor.size(); ++i) {@@ -203,7 +198,7 @@ bool Expression::visit_attributes(AttributeVisitor &visitor) {subtensors.emplace_back("in_subtensor_" + std::to_string(i), subtensor2str(subtensor));const auto& layout = desc->get_layout();- if (!layout.empty() && !is_planar_layout(layout))+ if (!layout.empty() && !utils::is_planar_layout(layout))layouts.emplace_back("in_layout_" + std::to_string(i), layout);in_reg_types.emplace_back(regTypeToStr(desc->get_reg().type));@@ -220,7 +215,7 @@ bool Expression::visit_attributes(AttributeVisitor &visitor) {subtensors.emplace_back("out_subtensor_" + std::to_string(i), subtensor2str(subtensor));const auto& layout = desc->get_layout();- if (!layout.empty() && !is_planar_layout(layout))+ if (!layout.empty() && !utils::is_planar_layout(layout))layouts.emplace_back("out_layout_" + std::to_string(i), layout);out_reg_types.emplace_back(regTypeToStr(desc->get_reg().type));diff --git a/src/common/snippets/src/lowered/expressions/buffer_expression.cpp b/src/common/snippets/src/lowered/expressions/buffer_expression.cppindex acc742ff196..a8b3bb2034b 100644--- a/src/common/snippets/src/lowered/expressions/buffer_expression.cpp+++ b/src/common/snippets/src/lowered/expressions/buffer_expression.cpp@@ -25,12 +25,15 @@ ExpressionPtr BufferExpression::clone() const {}bool BufferExpression::visit_attributes(AttributeVisitor &visitor) {+ Expression::visit_attributes(visitor);auto allocation_size = utils::value2str(m_allocation_size);auto offset = utils::value2str(m_offset);+ auto prc = get_data_type();visitor.on_attribute("allocation_size", allocation_size);visitor.on_attribute("offset", offset);visitor.on_attribute("reg_group", m_reg_group);visitor.on_attribute("cluster_id", m_cluster_id);+ visitor.on_attribute("data_type", prc);return true;}@@ -38,9 +41,13 @@ bool BufferExpression::is_defined() const {return !utils::is_dynamic_value(m_allocation_size);}+ov::element::Type BufferExpression::get_data_type() const {+ return get_node()->get_output_element_type(0);+}+size_t BufferExpression::get_byte_size() const {if (is_defined())- return m_allocation_size * get_node()->get_output_element_type(0).size();+ return m_allocation_size * get_data_type().size();return utils::get_dynamic_value<size_t>();}diff --git a/src/common/snippets/src/lowered/loop_info.cpp b/src/common/snippets/src/lowered/loop_info.cppindex 954cc180a15..1c856869878 100644--- a/src/common/snippets/src/lowered/loop_info.cpp+++ b/src/common/snippets/src/lowered/loop_info.cpp@@ -99,7 +99,7 @@ template<>std::vector<LoopPort>::iterator LoopInfo::find_loop_port(const ExpressionPort& expr_port) {auto& ports = expr_port.get_type() == ExpressionPort::Input ? m_input_ports : m_output_ports;const auto it = std::find_if(ports.begin(), ports.end(),- [&expr_port](const LoopPort& port) { return *port.expr_port.get() == expr_port; });+ [&expr_port](const LoopPort& port) { return *port.expr_port == expr_port; });return it;}@@ -176,6 +176,19 @@ bool UnifiedLoopInfo::LoopPortDesc::is_dynamic() const {return utils::is_dynamic_value(ptr_increment) || utils::is_dynamic_value(finalization_offset);}+bool UnifiedLoopInfo::LoopPortDesc::is_static() const {+ return !is_dynamic();+}++bool operator==(const UnifiedLoopInfo::LoopPortDesc& lhs, const UnifiedLoopInfo::LoopPortDesc& rhs) {+ if (&lhs == &rhs)+ return true;+ return lhs.ptr_increment == rhs.ptr_increment && lhs.finalization_offset == rhs.finalization_offset && lhs.data_size == rhs.data_size;+}+bool operator!=(const UnifiedLoopInfo::LoopPortDesc& lhs, const UnifiedLoopInfo::LoopPortDesc& rhs) {+ return !(rhs == lhs);+}+UnifiedLoopInfo::UnifiedLoopInfo(size_t work_amount, size_t increment,const std::vector<LoopPort>& entries, const std::vector<LoopPort>& exits,const SpecificIterationHandlers& handlers)@@ -321,6 +334,18 @@ void UnifiedLoopInfo::sort_ports() {reorder(m_output_ports, m_output_port_descs);}+UnifiedLoopInfo::LoopPortInfo UnifiedLoopInfo::get_loop_port_info(const ExpressionPort& expr_port) {+ OPENVINO_ASSERT(is_loop_port(expr_port), "Failed get_loop_port: expr_port is not a loop port");+ const auto is_input = expr_port.get_type() == ExpressionPort::Input;+ const auto& ports = is_input ? m_input_ports : m_output_ports;+ const auto& descs = is_input ? m_input_port_descs : m_output_port_descs;+ const auto it = std::find_if(ports.begin(), ports.end(),+ [&expr_port](const LoopPort& port) { return *port.expr_port == expr_port; });+ const auto index = static_cast<size_t>(std::distance(ports.cbegin(), it));+ OPENVINO_ASSERT(index < ports.size() && index < descs.size(), "LoopPortInfo has not been found!");+ return {ports[index], descs[index]};+}+void UnifiedLoopInfo::replace_with_cloned_descs(size_t actual_port_idx, size_t new_count, bool is_input) {auto& descs = is_input ? m_input_port_descs : m_output_port_descs;std::vector<LoopPortDesc> target_shifts(new_count, descs[actual_port_idx]);diff --git a/src/common/snippets/src/lowered/pass/allocate_buffers.cpp b/src/common/snippets/src/lowered/pass/allocate_buffers.cppindex f76c4097b38..0269c65109b 100644--- a/src/common/snippets/src/lowered/pass/allocate_buffers.cpp+++ b/src/common/snippets/src/lowered/pass/allocate_buffers.cpp@@ -12,7 +12,7 @@#include "snippets/lowered/pass/define_buffer_clusters.hpp"#include "snippets/lowered/pass/normalize_buffer_reg_groups.hpp"#include "snippets/lowered/pass/propagate_buffer_offset.hpp"-#include "snippets/pass/tokenization.hpp"+#include "snippets/lowered/pass/mark_invariant_shape_path.hpp"#include "snippets/itt.hpp"#include "snippets/utils/utils.hpp"@@ -30,6 +30,7 @@ bool AllocateBuffers::run(lowered::LinearIR& linear_ir, lowered::LinearIR::constPassPipeline pipeline;pipeline.register_pass<ComputeBufferAllocationSize>();if (m_is_optimized_mode) {+ pipeline.register_pass<MarkInvariantShapePath>();pipeline.register_pass<SetBufferRegGroup>();pipeline.register_pass<DefineBufferClusters>();pipeline.register_pass<SolveBufferMemory>(buffer_scratchpad_size);diff --git a/src/common/snippets/src/lowered/pass/define_buffer_clusters.cpp b/src/common/snippets/src/lowered/pass/define_buffer_clusters.cppindex c43b5d63a35..e8132d62be0 100644--- a/src/common/snippets/src/lowered/pass/define_buffer_clusters.cpp+++ b/src/common/snippets/src/lowered/pass/define_buffer_clusters.cpp@@ -4,24 +4,42 @@#include "snippets/lowered/pass/define_buffer_clusters.hpp"+#include "snippets/lowered/pass/mark_invariant_shape_path.hpp"#include "snippets/lowered/pass/set_buffer_reg_group.hpp"+#include "snippets/lowered/loop_manager.hpp"#include "snippets/snippets_isa.hpp"#include "snippets/utils/utils.hpp"#include "snippets/itt.hpp"+namespace ov {namespace snippets {namespace lowered {namespace pass {-using ShiftPtrParams = SetBufferRegGroup::ShiftPtrParams;+namespace {++// Find Loops which are connected to the current `buffer_expr` (consumer of Buffer is port of these Loops)+std::vector<size_t> get_connected_loops(const BufferExpressionPtr& buffer_expr, const ExpressionPtr& consumer_expr) {+ // [133463] Remove it please+ if (ov::is_type<op::LoopEnd>(consumer_expr->get_node()))+ return {};+ const auto& buffer_loops_ids = buffer_expr->get_loop_ids();+ const auto& consumer_loop_ids = consumer_expr->get_loop_ids();+ OPENVINO_ASSERT(buffer_loops_ids.size() <= consumer_loop_ids.size(), "Buffer with consumer are in incorrect loops");+ const auto mismatched_its = std::mismatch(buffer_loops_ids.begin(), buffer_loops_ids.end(), consumer_loop_ids.begin());+ return {mismatched_its.second, consumer_loop_ids.cend()};+}+} // namespace++using LoopPortInfo = UnifiedLoopInfo::LoopPortInfo;DefineBufferClusters::BufferClusters::iterator DefineBufferClusters::find_cluster_by_expr(const BufferExpressionPtr& target) {return std::find_if(m_clusters.begin(), m_clusters.end(),[&target](const BufferCluster& cluster) { return cluster.count(target) > 0; });}-bool DefineBufferClusters::is_direct_buffer(const BufferExpressionPtr& buffer_expr, const ExpressionPtr& target_expr) const {+bool DefineBufferClusters::is_direct_buffer(const BufferExpressionPtr& buffer_expr, const ExpressionPtr& target_expr) {return buffer_expr && buffer_expr->get_loop_ids() == target_expr->get_loop_ids();}@@ -33,7 +51,16 @@ void DefineBufferClusters::create_new_cluster(const BufferExpressionPtr& buffer_}}-size_t DefineBufferClusters::get_cluster_buffer_id(const BufferCluster& cluster) const {+void DefineBufferClusters::add_buffers_to_cluster(BufferCluster& existing_cluster, const std::set<BufferExpressionPtr>& buffers) {+ existing_cluster.insert(buffers.cbegin(), buffers.cend());+ // All buffers in one cluster must be only static or dynamic (no mixes).+ if (std::any_of(existing_cluster.cbegin(), existing_cluster.cend(), [](const BufferExpressionPtr& buffer) { return !buffer->is_defined(); })) {+ for (const auto& buffer : existing_cluster)+ buffer->set_allocation_size(utils::get_dynamic_value<size_t>());+ }+}++size_t DefineBufferClusters::get_cluster_buffer_id(const BufferCluster& cluster) {OPENVINO_ASSERT(!cluster.empty(), "Buffer cluster is empty!");const auto id = cluster.cbegin()->get()->get_reg_group();if (std::all_of(cluster.cbegin(), cluster.cend(), [&id](const BufferExpressionPtr& expr) { return expr->get_reg_group() == id; })) {@@ -42,141 +69,121 @@ size_t DefineBufferClusters::get_cluster_buffer_id(const BufferCluster& cluster)return SIZE_MAX;}-DefineBufferClusters::BufferPorts DefineBufferClusters::get_input_buffers(const ExpressionPtr& loop_expr) const {- BufferPorts input_buffers;-- const auto loop_end = ov::as_type_ptr<op::LoopEnd>(loop_expr->get_node());- const auto in_count = loop_end->get_input_num();- const auto& connectors = loop_expr->get_input_port_connectors();-- // Input Buffers- for (size_t i = 0; i < in_count; ++i) {- const auto& source_expr = ov::as_type_ptr<BufferExpression>(connectors[i]->get_source().get_expr());- if (!is_direct_buffer(source_expr, loop_expr))+std::pair<DefineBufferClusters::BufferMap, DefineBufferClusters::BufferMap> DefineBufferClusters::get_direct_buffers(const UnifiedLoopInfoPtr& loop_info,+ const ExpressionPtr& loop_expr) {+ BufferMap input_buffers;+ const auto& loop_inputs = loop_info->get_input_ports_info();+ for (const auto& port_info : loop_inputs) {+ const auto& buffer_expr = ov::as_type_ptr<BufferExpression>(port_info.port.expr_port->get_port_connector_ptr()->get_source().get_expr());+ if (!is_direct_buffer(buffer_expr, loop_expr))+ continue;+ if (input_buffers.count(buffer_expr) > 0) {+ const auto& port_desc = port_info.desc;+ OPENVINO_ASSERT(input_buffers[buffer_expr].desc == port_desc,+ "Invalid data pointer shifts: If Buffer has several consumers, this consumers must have the same shifts or zero");continue;- // Save as input Buffer- const auto ret = input_buffers.insert(std::make_pair(source_expr, std::set<size_t>{ i })).second;- if (!ret)- input_buffers[source_expr].insert(i);+ }+ input_buffers[buffer_expr] = port_info;}- return input_buffers;-}--DefineBufferClusters::BufferPorts DefineBufferClusters::get_output_buffers(const ExpressionPtr& loop_expr) const {- BufferPorts output_buffers;- const auto loop_end = ov::as_type_ptr<op::LoopEnd>(loop_expr->get_node());- const auto in_count = loop_end->get_input_num();- const auto out_count = loop_end->get_output_num();- const auto& connectors = loop_expr->get_input_port_connectors();-- for (size_t i = in_count; i < in_count + out_count; ++i) {- for (const auto& consumer : connectors[i]->get_consumers()) {- const auto& consumer_expr = ov::as_type_ptr<BufferExpression>(consumer.get_expr());- if (!is_direct_buffer(consumer_expr, loop_expr))+ BufferMap output_buffers;+ const auto& loop_outputs = loop_info->get_output_ports_info();+ for (const auto& port_info : loop_outputs) {+ const auto& consumer_inputs = port_info.port.expr_port->get_port_connector_ptr()->get_consumers();+ for (const auto& consumer_input : consumer_inputs) {+ const auto& buffer_expr = ov::as_type_ptr<BufferExpression>(consumer_input.get_expr());+ if (!is_direct_buffer(buffer_expr, loop_expr))continue;- // Save as output Buffer- output_buffers[consumer_expr] = { i };+ OPENVINO_ASSERT(output_buffers.count(buffer_expr) == 0, "Only one Buffer can be on node output!");+ output_buffers[buffer_expr] = port_info;}}- return output_buffers;++ return std::make_pair(input_buffers, output_buffers);}-void DefineBufferClusters::parse_loop(const LinearIR::constExprIt& expr_it) {+void DefineBufferClusters::parse_loop(const LoopManagerPtr& loop_manager, const LinearIR::constExprIt& expr_it) {const auto& expr = *expr_it;- const auto loop_end = ov::as_type_ptr<op::LoopEnd>(expr->get_node());- const auto& ptr_increments = loop_end->get_ptr_increments();- const auto& final_offsets = loop_end->get_finalization_offsets();- const auto& data_sizes = loop_end->get_element_type_sizes();+ const auto& loop_end = ov::as_type_ptr<op::LoopEnd>(expr->get_node());+ const auto& loop_info = loop_manager->get_loop_info<UnifiedLoopInfo>(loop_end->get_id());- // [ Expression -> Port indexes ]- const auto input_buffers = get_input_buffers(expr);- const auto output_buffers = get_output_buffers(expr);+ BufferMap input_buffers, output_buffers;+ std::tie(input_buffers, output_buffers) = get_direct_buffers(loop_info, expr);for (const auto& in : input_buffers)create_new_cluster(in.first);std::set<ExpressionPtr> visited_buffers;for (const auto& out : output_buffers) {- const auto output_buffer_expr = out.first;- const auto output_buffer_port_idx = *(out.second.cbegin()); // Output port is always one+ const auto& output_buffer_expr = out.first;+ const auto& output_buffer_port_info = out.second;bool has_been_added = false;for (const auto& in : input_buffers) {const auto& input_buffer_expr = in.first;+ const auto& input_buffer_port_info = in.second;if (visited_buffers.count(input_buffer_expr) > 0)continue;- // If allocated sizes of buffers are unkown on compilation stage (dynamic),- // we cannot be sure that they're will be the same in runtime.- if (!input_buffer_expr->is_defined()|| !output_buffer_expr->is_defined())+ // Memory can be reused if reading and writing are executed proportionally:+ // - output buffer can have precision with data size less than input buffer+ if ((input_buffer_expr->get_data_type().size() < output_buffer_expr->get_data_type().size()))continue;- // Memory can be reused if reading and writing are executed proportionally:- // - the same reading/writing order- // - the same buffer memory sizes- if ((input_buffer_expr->get_byte_size() != output_buffer_expr->get_byte_size()) ||- (input_buffer_expr->get_output_port_descriptor(0)->get_layout() != output_buffer_expr->get_input_port_descriptor(0)->get_layout()))+ const auto in_path = MarkInvariantShapePath::getInvariantPortShapePath(*input_buffer_port_info.port.expr_port);+ const auto out_path = MarkInvariantShapePath::getInvariantPortShapePath(*output_buffer_port_info.port.expr_port);+ // - Memory can be reused if there are the same loop pointer increments (data size, final offsets, ptr increments).+ // For that, loop ports with buffers should be on the same shape-path and have the same value of `is_incremented`.+ if (in_path != out_path || input_buffer_port_info.port.is_incremented != output_buffer_port_info.port.is_incremented)continue;- // Also memory can be reused if there are the same ShiftPtrParams (data size, final offsets, ptr increments)- const auto& input_buffer_ports = in.second;- for (const auto& input_buffer_port_idx : input_buffer_ports) {- const auto input_params =- ShiftPtrParams(data_sizes[input_buffer_port_idx], ptr_increments[input_buffer_port_idx], final_offsets[input_buffer_port_idx]);- const auto output_params =- ShiftPtrParams(data_sizes[output_buffer_port_idx], ptr_increments[output_buffer_port_idx], final_offsets[output_buffer_port_idx]);-- // If data pointer shift parameters are unknown on model compilation stage (dynamic),- // we cannot be sure that these data pointers will be proportionally shifted in runtime.- if (input_params.is_static() && output_params.is_static() && input_params == output_params) {- const auto cluster_it = find_cluster_by_expr(input_buffer_expr);- OPENVINO_ASSERT(cluster_it != m_clusters.end(), "Buffer on inputs of Loop must be already saved in clusters");- // Add to the existing cluster- has_been_added = cluster_it->insert(output_buffer_expr).second;- OPENVINO_ASSERT(has_been_added, "Buffer has not been saved in cluster");- // Remove input buffer because we have already use its memory- visited_buffers.insert(input_buffer_expr);- break;- }+ // - Memory can be shared if Buffer has the same allocation size.+ if (input_buffer_expr->is_defined() && output_buffer_expr->is_defined()) {+ if (input_buffer_expr->get_allocation_size() != output_buffer_expr->get_allocation_size())+ continue;+ } else {+ // If allocation sizes are undefined, we can check if they have the same allocation sizes in runtime:+ // - they should calculate allocation size using the common algorithm from `BufferExpression::init_allocation_size`.+ if (!utils::everyone_is(BufferExpression::get_type_info_static(), input_buffer_expr->get_type_info(), output_buffer_expr->get_type_info()))+ continue;}- if (has_been_added) break;++ const auto cluster_it = find_cluster_by_expr(input_buffer_expr);+ OPENVINO_ASSERT(cluster_it != m_clusters.end(), "Buffer on inputs of Loop must be already saved in clusters");+ // Add to the existing cluster+ add_buffers_to_cluster(*cluster_it, {output_buffer_expr});+ // Remove input buffer because we have already use its memory+ visited_buffers.insert(input_buffer_expr);+ has_been_added = true;+ break;}if (!has_been_added) {- m_clusters.push_back(BufferCluster{output_buffer_expr});+ create_new_cluster(output_buffer_expr);}}// Check Buffers inside to possible memory reusing using `window` sliding- parse_nested_loops(input_buffers, output_buffers, expr_it);+ parse_nested_loops(loop_manager, input_buffers, output_buffers, expr_it);}-void DefineBufferClusters::parse_nested_loops(const BufferPorts& input_buffers, const BufferPorts& output_buffers,- const LinearIR::constExprIt& outer_loop_end_expr_it) {+void DefineBufferClusters::parse_nested_loops(const LoopManagerPtr& loop_manager, const BufferMap& input_buffers,+ const BufferMap& output_buffers, const LinearIR::constExprIt& outer_loop_end_expr_it) {if (input_buffers.empty() && output_buffers.empty())return;- // The inner Buffer can reuse memory of the outer Buffer using `window` sliding only if:- // - The finalization offset of the latest Loop connected to the inner Buffer is equal to pointer increment of outer Buffer to emulate `window` sliding- // - This outer Buffer should have the same Buffer ID as inner to move data ptr of inner Buffer after each outer Loop iteration.- // It's needed because all Loops reset data pointers of connected Buffer after full work.- // To avoid rewriting of outer Buffer data we have to have the same Buffer ID (GPR) to proportionally shift pointers both Buffers.-- auto can_be_data_ptr_proportionally_shifted = [](int64_t outer_buffer_ptr_increment, int64_t outer_buffer_data_size,- int64_t inner_buffer_final_offsets, int64_t inner_buffer_data_size) {- // If data pointer shift parameters are unknown on model compilation stage (dynamic),- // we cannot be sure that these data pointers will be proportionally shifted in runtime.- if (utils::is_dynamic_value(outer_buffer_ptr_increment) || utils::is_dynamic_value(inner_buffer_final_offsets))+ auto can_be_data_ptr_proportionally_shifted = [](const LoopPortInfo& outer_port_info, const LoopPortInfo& inner_port_info) {+ // Outer Buffer ptr should be shifted to emulate "window" sliding+ const auto& outer_desc = outer_port_info.desc;+ if (!outer_port_info.port.is_incremented || (!utils::is_dynamic_value(outer_desc.ptr_increment) && outer_desc.ptr_increment == 0))return false;- return (outer_buffer_ptr_increment != 0) &&- ((inner_buffer_data_size * inner_buffer_final_offsets * -1) == outer_buffer_ptr_increment * outer_buffer_data_size);- };- const auto outer_loop_end = ov::as_type_ptr<op::LoopEnd>(outer_loop_end_expr_it->get()->get_node());- const auto outer_loop_begin = outer_loop_end->get_loop_begin();- const auto& outer_ptr_increments = outer_loop_end->get_ptr_increments();- const auto& outer_data_sizes = outer_loop_end->get_element_type_sizes();+ OPENVINO_ASSERT(inner_port_info.port.expr_port && outer_port_info.port.expr_port, "Expression ports are nullptr!");+ // we can be sure that these data pointers will be proportionally shifted if they're on the same invariant shape path+ return MarkInvariantShapePath::getInvariantPortShapePath(*inner_port_info.port.expr_port) ==+ MarkInvariantShapePath::getInvariantPortShapePath(*outer_port_info.port.expr_port);+ };+ const auto outer_loop_begin = ov::as_type_ptr<op::LoopEnd>(outer_loop_end_expr_it->get()->get_node())->get_loop_begin();for (auto it = std::reverse_iterator<LinearIR::constExprIt>(outer_loop_end_expr_it); (*it)->get_node() != outer_loop_begin; ++it) {const auto& inner_expr = *it;if (const auto inner_buffer_expr = ov::as_type_ptr<BufferExpression>(inner_expr)) {@@ -185,9 +192,12 @@ void DefineBufferClusters::parse_nested_loops(const BufferPorts& input_buffers,const auto inner_cluster_id = get_cluster_buffer_id(*inner_cluster_it);if (inner_cluster_id == SIZE_MAX) continue;- const auto final_offset = get_buffer_finalization_offset(inner_buffer_expr);+ // If inner Buffer is not connected to the Loop - `window` sliding effect is not possible+ LoopPortInfo final_loop_info;+ if (!init_buffer_last_loop_port_info(loop_manager, inner_buffer_expr, final_loop_info))+ continue;- auto unite = [&](const BufferPorts& ports, const bool is_input) {+ auto unite = [&](const BufferMap& ports, const bool is_input) {bool applied = false;for (const auto& port : ports) {const auto cluster_it = find_cluster_by_expr(port.first);@@ -196,17 +206,15 @@ void DefineBufferClusters::parse_nested_loops(const BufferPorts& input_buffers,if (cluster_it == inner_cluster_it) continue;// Buffer from one cluster must be only defined (with known allocation_size) or dynamic (with unknown allocation_size)if (inner_buffer_expr->is_defined() != port.first->is_defined()) continue;-- bool can_be_reused = true;- for (const auto idx : port.second) {- can_be_reused = can_be_reused &&- can_be_data_ptr_proportionally_shifted(outer_ptr_increments[idx], outer_data_sizes[idx],- final_offset, inner_buffer_expr->get_node()->get_element_type().size());- }- if (!can_be_reused)- continue;-- applied = unite_nested_clusters(inner_cluster_it, *cluster_it, port.first, is_input);+ // The inner Buffer can reuse memory of the outer Buffer using `window` sliding only if:+ // - The finalization offset of the latest Loop connected to the inner Buffer is equal to+ // pointer increment of outer Buffer to emulate `window` sliding+ // - This outer Buffer should have the same Buffer ID as inner to move data ptr of inner Buffer after each outer Loop iteration.+ // It's needed because all Loops reset data pointers of connected Buffer after full work.+ // To avoid rewriting of outer Buffer data we have to have the same Buffer ID (GPR) to proportionally shift pointers both Buffers.+ if (!can_be_data_ptr_proportionally_shifted(port.second, final_loop_info)) continue;++ applied = unite_nested_clusters(loop_manager, inner_cluster_it, *cluster_it, port.first, is_input);if (applied) break;}return applied;@@ -218,101 +226,66 @@ void DefineBufferClusters::parse_nested_loops(const BufferPorts& input_buffers,}}-int64_t DefineBufferClusters::get_buffer_finalization_offset(const BufferExpressionPtr& buffer_expr) const {- auto index = [](const std::vector<PortConnectorPtr>& loop_inputs, const PortConnectorPtr& buffer_out) {- const auto it = std::find(loop_inputs.cbegin(), loop_inputs.cend(), buffer_out);- OPENVINO_ASSERT(it != loop_inputs.cend(), "Buffer output PortConnector has not been found in target LoopEnd inputs");- return std::distance(loop_inputs.cbegin(), it);+bool DefineBufferClusters::init_buffer_last_loop_port_info(const LoopManagerPtr& loop_manager, const BufferExpressionPtr& buffer_expr,+ UnifiedLoopInfo::LoopPortInfo& port_info) {+ auto get_direct_loop_for_buffer_out = [&](const BufferExpressionPtr& buffer_expr, const ExpressionPtr& consumer_expr) -> UnifiedLoopInfoPtr {+ const auto inner_loops = get_connected_loops(buffer_expr, consumer_expr);+ if (inner_loops.empty())+ return nullptr;+ return loop_manager->get_loop_info<UnifiedLoopInfo>(inner_loops.front());};- int64_t final_offset = 0;++ bool found = false;double last_loop_exec_order = -1 * std::numeric_limits<double>::max();const auto& buffer_outs = buffer_expr->get_output_port_connectors();for (const auto& buffer_out : buffer_outs) {const auto consumers = buffer_out->get_consumers();for (const auto& consumer : consumers) {- const auto consumer_expr = consumer.get_expr();- const auto loop_end = ov::as_type_ptr<ov::snippets::op::LoopEnd>(consumer_expr->get_node());- if (loop_end && consumer_expr->get_loop_ids() == buffer_expr->get_loop_ids()) {- const auto loop_order = consumer_expr->get_exec_num();+ if (const auto& direct_loop = get_direct_loop_for_buffer_out(buffer_expr, consumer.get_expr())) {+ const auto loop_order = direct_loop->get_output_ports().back().expr_port->get_expr()->get_exec_num();if (loop_order > last_loop_exec_order) {- const auto& loop_inputs = consumer_expr->get_input_port_connectors();- final_offset = loop_end->get_finalization_offsets()[index(loop_inputs, buffer_out)];+ OPENVINO_ASSERT(direct_loop->is_loop_port(consumer), "Consumer of Buffer from another loop must be loop port");+ port_info = direct_loop->get_loop_port_info(consumer);last_loop_exec_order = loop_order;+ found = true;}}}}- return final_offset;+ return found;}-bool DefineBufferClusters::unite_nested_clusters(const BufferClusters::iterator& inner_cluster_it,- BufferCluster& outer_cluster,- const BufferExpressionPtr& outer_buffer, bool is_outer_up) {+bool DefineBufferClusters::unite_nested_clusters(const LoopManagerPtr& loop_manager, const BufferClusters::iterator& inner_cluster_it,+ BufferCluster& outer_cluster, const BufferExpressionPtr& outer_buffer, bool is_outer_up) {for (const auto& inner_buffer : *inner_cluster_it) {- ExpressionPtr common_loop_end_expr = nullptr;- size_t outer_idx = SIZE_MAX, inner_idx = SIZE_MAX;- const auto& up_buffer = is_outer_up ? outer_buffer : inner_buffer;- const auto& down_buffer = is_outer_up ? inner_buffer : outer_buffer;- auto& up_idx = is_outer_up ? outer_idx : inner_idx;- auto& down_idx = is_outer_up ? inner_idx : outer_idx;- if (are_buffer_neighbours(up_buffer, down_buffer, common_loop_end_expr, up_idx, down_idx)) {- const auto common_loop_end = ov::as_type_ptr<op::LoopEnd>(common_loop_end_expr->get_node());- const auto& inner_ptr_increments = common_loop_end->get_ptr_increments();- const auto& inner_final_offsets = common_loop_end->get_finalization_offsets();- const auto& inner_data_sizes = common_loop_end->get_element_type_sizes();- if (SetBufferRegGroup::can_be_in_one_group({ inner_data_sizes[up_idx], inner_ptr_increments[up_idx], inner_final_offsets[up_idx] },- { inner_data_sizes[down_idx], inner_ptr_increments[down_idx], inner_final_offsets[down_idx] })) {- for (const auto& inner_buffer : *inner_cluster_it)- inner_buffer->set_reg_group(outer_buffer->get_reg_group());-- outer_cluster.insert(inner_cluster_it->cbegin(), inner_cluster_it->cend());- m_clusters.erase(inner_cluster_it);- return true;+ const auto& upper_buffer = is_outer_up ? outer_buffer : inner_buffer;+ const auto& lower_buffer = is_outer_up ? inner_buffer : outer_buffer;++ const auto& lower_buffer_source = lower_buffer->get_input_port_connector(0)->get_source();+ const auto& upper_buffer_consumers = upper_buffer->get_output_port_connector(0)->get_consumers();+ for (const auto& upper_buffer_consumer : upper_buffer_consumers) {+ const auto& connected_loops = get_connected_loops(upper_buffer, upper_buffer_consumer.get_expr());+ for (const auto& loop_id : connected_loops) {+ const auto& common_loop_info = loop_manager->get_loop_info<UnifiedLoopInfo>(loop_id);+ if (!common_loop_info->is_loop_port(lower_buffer_source) || !common_loop_info->is_loop_port(upper_buffer_consumer))+ continue;++ const auto upper_port_desc = common_loop_info->get_loop_port_info(upper_buffer_consumer);+ const auto lower_port_desc = common_loop_info->get_loop_port_info(lower_buffer_source);+ if (SetBufferRegGroup::can_be_in_one_reg_group(upper_port_desc, lower_port_desc)) {+ for (const auto& inner_buffer : *inner_cluster_it)+ inner_buffer->set_reg_group(outer_buffer->get_reg_group());++ add_buffers_to_cluster(outer_cluster, *inner_cluster_it);+ m_clusters.erase(inner_cluster_it);+ return true;+ }}}}return false;}-bool DefineBufferClusters::are_buffer_neighbours(const BufferExpressionPtr& up, const BufferExpressionPtr& down, ExpressionPtr& loop,- size_t& up_idx, size_t& down_idx) {- auto find_input = [&down](const PortConnectorPtr& in) {- return in->get_source().get_expr() == down;- };- auto find_output = [&down](const PortConnectorPtr& in) {- const auto consumers = in->get_consumers();- return std::any_of(consumers.cbegin(), consumers.cend(),- [&down](const ExpressionPort& port) { return port.get_expr() == down; });- };- auto find = [&](const std::vector<PortConnectorPtr>::const_iterator& begin,- const std::vector<PortConnectorPtr>::const_iterator& end,- const std::vector<PortConnectorPtr>::const_iterator& orig_begin,- const ExpressionPort& loop_port,- bool is_input) -> bool {- const auto in_buffer_it = is_input ? std::find_if(begin, end, find_input)- : std::find_if(begin, end, find_output);- if (in_buffer_it != end) {- up_idx = loop_port.get_index();- down_idx = std::distance(orig_begin, in_buffer_it);- loop = loop_port.get_expr();- return true;- }- return false;- };- for (const auto& out : up->get_output_port_connectors()) {- for (const auto& buffer_consumer : out->get_consumers()) {- const auto buffer_consumer_expr = buffer_consumer.get_expr();- const auto loop_end = ov::as_type_ptr<op::LoopEnd>(buffer_consumer_expr->get_node());- if (!loop_end)- continue;- const auto& loop_inputs = buffer_consumer_expr->get_input_port_connectors();- if (find(loop_inputs.cbegin(), loop_inputs.cbegin() + loop_end->get_input_num(), loop_inputs.cbegin(), buffer_consumer, true)) return true;- if (find(loop_inputs.cbegin() + loop_end->get_input_num(), loop_inputs.cend(), loop_inputs.cbegin(), buffer_consumer, false)) return true;- }- }- return false;-}-void DefineBufferClusters::parse_memory_access_op(const ExpressionPtr& expr) {const auto ma = std::dynamic_pointer_cast<modifier::MemoryAccess>(expr->get_node());// TODO: Some full MemoryAccess ops can have inplace inputs and outputs in general.@@ -340,7 +313,7 @@ bool DefineBufferClusters::run(lowered::LinearIR& linear_ir, lowered::LinearIR::const auto& expr = *expr_it;const auto op = expr->get_node();if (ov::is_type<op::LoopEnd>(op)) {- parse_loop(expr_it);+ parse_loop(linear_ir.get_loop_manager(), expr_it);continue;}diff --git a/src/common/snippets/src/lowered/pass/mark_invariant_shape_path.cpp b/src/common/snippets/src/lowered/pass/mark_invariant_shape_path.cppnew file mode 100644index 00000000000..b32056d4e32--- /dev/null+++ b/src/common/snippets/src/lowered/pass/mark_invariant_shape_path.cpp@@ -0,0 +1,128 @@+// Copyright (C) 2024 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+++#include "snippets/lowered/pass/mark_invariant_shape_path.hpp"++#include "snippets/lowered/expressions/buffer_expression.hpp"+#include "snippets/op/memory_access.hpp"+#include "snippets/snippets_isa.hpp"+#include "snippets/utils/utils.hpp"+#include "snippets/itt.hpp"++namespace ov {+namespace snippets {+namespace lowered {+namespace pass {++namespace {++// Specific value to mark ports which doesn't affect output shape of broadcastable ops.+// For example, ops with output scalar shape or Horizon ops.+static const size_t NOT_AFFECTING_PATH = SIZE_MAX;++static bool is_shape_broadcastable_op(const ExpressionPtr& expr) {+ return expr->get_node()->get_autob() != ov::op::AutoBroadcastType::NONE;+}++static bool is_not_affecting_op(const ExpressionPtr& expr) {+ const auto& node = expr->get_node();+ return ov::is_type<ov::snippets::op::HorizonMax>(node) ||+ ov::is_type<ov::snippets::op::HorizonSum>(node) ||+ ov::is_type<ov::snippets::op::ReduceMax>(node) ||+ ov::is_type<ov::snippets::op::ReduceSum>(node) ||+ ov::is_type<ov::snippets::op::VectorBuffer>(node) ||+ ov::is_type<ov::snippets::op::BroadcastMove>(node) ||+ ov::is_type<ov::snippets::op::Scalar>(node);+}++static bool is_affecting_op(const ExpressionPtr& expr) {+ const auto& node = expr->get_node();+ return ov::is_type<ov::snippets::op::Brgemm>(node) ||+ ov::is_type<ov::snippets::op::Reshape>(node) ||+ ov::is_type<ov::snippets::op::LoadReshape>(node);+}+} // namespace++size_t MarkInvariantShapePath::getInvariantPortShapePath(const ExpressionPort& port) {+ auto& rt = get_rt_info(port);+ const auto rinfo = rt.find("InvariantShapePath");+ OPENVINO_ASSERT(rinfo != rt.end(), "Invariant path for this expression port has not been marked!");+ return rinfo->second.as<size_t>();+}++void MarkInvariantShapePath::SetInvariantPortShapePath(const ExpressionPort& port, size_t value) {+ OPENVINO_ASSERT(port.get_type() == ExpressionPort::Output, "SetInvariantPortShapePath can be used only for output port");+ auto& rt = get_rt_info(port);+ rt["InvariantShapePath"] = value;+}++ov::RTMap& MarkInvariantShapePath::get_rt_info(const ExpressionPort& port) {+ const auto& source_port = port.get_type() == ExpressionPort::Input ? port.get_port_connector_ptr()->get_source() : port;+ const auto& node = source_port.get_expr()->get_node();+ const auto port_idx = source_port.get_index();+ OPENVINO_ASSERT(port_idx < node->get_output_size(), "Node has incompatible port count with the expression");+ return node->output(port_idx).get_rt_info();+}++bool MarkInvariantShapePath::run(lowered::LinearIR& linear_ir, lowered::LinearIR::constExprIt begin, lowered::LinearIR::constExprIt end) {+ OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::MarkInvariantShapePath");++ bool modified = false;++ // Shape -> color+ std::map<VectorDims, size_t> colored_shapes;++ size_t color_path = 0;++ auto merge_paths = [&color_path](size_t lhs, size_t rhs) {+ if (lhs == rhs || rhs == NOT_AFFECTING_PATH) return lhs;+ if (lhs == NOT_AFFECTING_PATH) return rhs;+ return ++color_path;+ };++ for (auto expr_it = begin; expr_it != end; ++expr_it) {+ const auto& expr = *expr_it;+ if (ov::is_type<ov::snippets::op::LoopBase>(expr->get_node()))+ continue;++ for (size_t out_idx = 0; out_idx < expr->get_output_count(); ++out_idx) {+ const auto& out_shape = expr->get_output_port_descriptor(out_idx)->get_shape();+ size_t current_color_path;+ if (colored_shapes.count(out_shape)) {+ current_color_path = colored_shapes.at(out_shape);+ } else if (!utils::is_dynamic_vdims(out_shape) && ov::shape_size(out_shape) == 1) {+ current_color_path = NOT_AFFECTING_PATH;+ } else {+ if (is_affecting_op(expr)) {+ current_color_path = ++color_path;+ } else if (is_not_affecting_op(expr)) {+ current_color_path = NOT_AFFECTING_PATH;+ } else if (is_shape_broadcastable_op(expr)) {+ current_color_path = NOT_AFFECTING_PATH;+ for (size_t in_idx = 0; in_idx < expr->get_input_count(); ++in_idx) {+ const auto input_path = getInvariantPortShapePath(expr->get_input_port(in_idx));+ current_color_path = merge_paths(current_color_path, input_path);+ }+ } else {+ current_color_path = expr->get_input_count() > 0 ? getInvariantPortShapePath(expr->get_input_port(0))+ : ++color_path;+ }++ if (!utils::is_dynamic_vdims(out_shape))+ colored_shapes[out_shape] = current_color_path;+ }++ SetInvariantPortShapePath(expr->get_output_port(out_idx), current_color_path);+ modified = true;+ }+ }++ return modified;+}++} // namespace pass+} // namespace lowered+} // namespace snippets+} // namespace ovdiff --git a/src/common/snippets/src/lowered/pass/set_buffer_reg_group.cpp b/src/common/snippets/src/lowered/pass/set_buffer_reg_group.cppindex 9bdb5e8ef3a..46248b9c277 100644--- a/src/common/snippets/src/lowered/pass/set_buffer_reg_group.cpp+++ b/src/common/snippets/src/lowered/pass/set_buffer_reg_group.cpp@@ -4,8 +4,10 @@#include "snippets/lowered/pass/set_buffer_reg_group.hpp"+#include "snippets/lowered/pass/mark_invariant_shape_path.hpp"#include "snippets/lowered/linear_ir.hpp"-#include "snippets/snippets_isa.hpp"+#include "snippets/lowered/loop_manager.hpp"+#include "snippets/lowered/expressions/buffer_expression.hpp"#include "snippets/itt.hpp"namespace ov {@@ -19,54 +21,44 @@ inline size_t index(size_t col_num, size_t row, size_t col) {}} // namespace-bool operator==(const SetBufferRegGroup::ShiftPtrParams& lhs, const SetBufferRegGroup::ShiftPtrParams& rhs) {- if (&lhs == &rhs)- return true;- return lhs.ptr_increment == rhs.ptr_increment && lhs.finalization_offset == rhs.finalization_offset && lhs.data_size == rhs.data_size;-}-bool operator!=(const SetBufferRegGroup::ShiftPtrParams& lhs, const SetBufferRegGroup::ShiftPtrParams& rhs) {- return !(rhs == lhs);-}-size_t SetBufferRegGroup::get_buffer_idx(const BufferExpressionPtr& target, const BufferPool& pool) {const auto iter = std::find(pool.cbegin(), pool.cend(), target);OPENVINO_ASSERT(iter != pool.cend(), "Buffer wasn't find in Buffer system of Subgraph");return std::distance(pool.cbegin(), iter);}-bool SetBufferRegGroup::can_be_in_one_group(const ShiftPtrParams& lhs, const ShiftPtrParams& rhs) {- // If data pointer shift parameters are unknown on model compilation stage (dynamic),- // we cannot be sure that these data pointers will be proportionally shifted.- // Then we force `false` value here to set unique registers for these buffers- const auto are_static = lhs.is_static() && rhs.is_static();- const auto equal_ptr_params_shifting = lhs.ptr_increment == rhs.ptr_increment && lhs.finalization_offset == rhs.finalization_offset;- const auto equal_element_type_sizes = lhs.data_size == rhs.data_size;- return are_static && equal_ptr_params_shifting && (equal_element_type_sizes || (lhs.ptr_increment == 0 && lhs.finalization_offset == 0));+bool SetBufferRegGroup::can_be_in_one_reg_group(const UnifiedLoopInfo::LoopPortInfo& lhs_info,+ const UnifiedLoopInfo::LoopPortInfo& rhs_info) {+ const auto equal_element_type_sizes = lhs_info.desc.data_size == rhs_info.desc.data_size;+ OPENVINO_ASSERT(lhs_info.port.expr_port && rhs_info.port.expr_port, "Expression ports are nullptr!");+ const auto equal_invariant_shape_paths =+ MarkInvariantShapePath::getInvariantPortShapePath(*lhs_info.port.expr_port) ==+ MarkInvariantShapePath::getInvariantPortShapePath(*rhs_info.port.expr_port);+ const auto equal_is_incremented = lhs_info.port.is_incremented == rhs_info.port.is_incremented;+ return equal_invariant_shape_paths && equal_is_incremented &&+ (equal_element_type_sizes || !lhs_info.port.is_incremented || (lhs_info.desc.ptr_increment == 0 && lhs_info.desc.finalization_offset == 0));}-bool SetBufferRegGroup::are_adjacent(const std::pair<BufferExpressionPtr, ShiftPtrParams>& lhs,- const std::pair<BufferExpressionPtr, ShiftPtrParams>& rhs) {+bool SetBufferRegGroup::are_adjacent(const BufferMap::value_type& lhs, const BufferMap::value_type& rhs) {const auto& lhs_ids = lhs.first->get_loop_ids();const auto& rhs_ids = rhs.first->get_loop_ids();const auto equal_loop_ids = lhs_ids == rhs_ids;if (equal_loop_ids) { // Buffers are connected to the same Loop and have the same outer Loops- return !can_be_in_one_group(lhs.second, rhs.second);+ return !can_be_in_one_reg_group(lhs.second, rhs.second);} else { // Buffers are connected to the same Loop, but one of Buffers - inside this Loop, another - outside- // Buffers are adjacent if outer Buffer has not zero data shift params+ // Buffers are adjacent if outer Buffer has non-zero data shift paramsif (lhs_ids.size() == rhs_ids.size()) // If the count of outer Loops are equal, it means that outer loops are already differentreturn true;const auto& outer_buffer = lhs_ids.size() < rhs_ids.size() ? lhs : rhs;const auto count_outer_loops = std::min(lhs_ids.size(), rhs_ids.size());const auto are_outer_loops_the_same = lhs_ids.size() != rhs_ids.size() &&std::equal(rhs_ids.cbegin(), rhs_ids.cbegin() + count_outer_loops, lhs_ids.cbegin());- const auto outer_buffer_has_zero_shifts = outer_buffer.second.ptr_increment == 0 && outer_buffer.second.finalization_offset == 0;+ const auto outer_buffer_has_zero_shifts = outer_buffer.second.desc.ptr_increment == 0 && outer_buffer.second.desc.finalization_offset == 0;return !(are_outer_loops_the_same && outer_buffer_has_zero_shifts);}}-void SetBufferRegGroup::update_adj_matrix(const std::pair<BufferExpressionPtr, ShiftPtrParams>& lhs,- const std::pair<BufferExpressionPtr, ShiftPtrParams>& rhs,- const BufferPool& buffers,+void SetBufferRegGroup::update_adj_matrix(const BufferMap::value_type& lhs, const BufferMap::value_type& rhs, const BufferPool& buffers,std::vector<bool>& adj) {const auto size = buffers.size();const auto lhs_idx = get_buffer_idx(lhs.first, buffers);@@ -80,7 +72,8 @@ void SetBufferRegGroup::update_adj_matrix(const std::pair<BufferExpressionPtr, S}}-std::vector<bool> SetBufferRegGroup::create_adjacency_matrix(LinearIR::constExprIt begin, LinearIR::constExprIt end, const BufferPool& pool) {+std::vector<bool> SetBufferRegGroup::create_adjacency_matrix(const LoopManagerPtr& loop_manager, LinearIR::constExprIt begin, LinearIR::constExprIt end,+ const BufferPool& pool) {// The sync point to check for adjacency is Loop because only in Loop we increment pointers.// So if some Buffers in the one Loop have conflict (cannot be inplace: the different ptr increment and data sizes)// they are called as adjacent@@ -91,10 +84,12 @@ std::vector<bool> SetBufferRegGroup::create_adjacency_matrix(LinearIR::constExprfor (auto expr_it = begin; expr_it != end; expr_it++) {const auto &expr = *expr_it;- if (!ov::is_type<op::LoopEnd>(expr->get_node()))+ const auto& loop_end = ov::as_type_ptr<op::LoopEnd>(expr->get_node());+ if (!loop_end)continue;- const auto buffer_loop_neighbours = get_buffer_loop_neighbours(expr);+ const auto& loop_info = loop_manager->get_loop_info<UnifiedLoopInfo>(loop_end->get_id());+ const auto buffer_loop_neighbours = get_buffer_loop_neighbours(loop_info);const auto buffers_loop_inside = get_buffer_loop_inside(expr_it);for (auto buffer_it = buffer_loop_neighbours.cbegin(); buffer_it != buffer_loop_neighbours.cend(); ++buffer_it) {// If Buffers, that are connected to the same Loop, have not proportionally ptr shift params for this Loop - these Buffers are adjacent@@ -113,47 +108,33 @@ std::vector<bool> SetBufferRegGroup::create_adjacency_matrix(LinearIR::constExprreturn adj;}-SetBufferRegGroup::BufferMap SetBufferRegGroup::get_buffer_loop_neighbours(const ExpressionPtr& loop_end_expr) {- const auto& loop_end = ov::as_type_ptr<op::LoopEnd>(loop_end_expr->get_node());- const auto input_count = loop_end->get_input_num();- const auto output_count = loop_end->get_output_num();-- const auto& ptr_increments = loop_end->get_ptr_increments();- const auto& finalization_offsets = loop_end->get_finalization_offsets();- const auto& data_sizes = loop_end->get_element_type_sizes();-+SetBufferRegGroup::BufferMap SetBufferRegGroup::get_buffer_loop_neighbours(const UnifiedLoopInfoPtr& loop_info) {BufferMap buffer_neighbours;- for (size_t i = 0; i < input_count; ++i) {- const auto& parent_output = loop_end_expr->get_input_port_connector(i)->get_source().get_expr();++ const auto& loop_inputs = loop_info->get_input_ports_info();+ for (const auto& port_info : loop_inputs) {+ const auto& parent_output = port_info.port.expr_port->get_port_connector_ptr()->get_source().get_expr();if (const auto buffer_expr = ov::as_type_ptr<BufferExpression>(parent_output)) {if (buffer_neighbours.count(buffer_expr) > 0) {- OPENVINO_ASSERT(buffer_neighbours[buffer_expr].ptr_increment == ptr_increments[i] &&- buffer_neighbours[buffer_expr].finalization_offset == finalization_offsets[i],+ const auto& port_desc = port_info.desc;+ OPENVINO_ASSERT(buffer_neighbours[buffer_expr].desc == port_desc,"Invalid data pointer shifts: If Buffer has several consumers, this consumers must have the same shifts or zero");continue;}- buffer_neighbours[buffer_expr] = { data_sizes[i], ptr_increments[i], finalization_offsets[i] };+ buffer_neighbours[buffer_expr] = port_info;}}- for (size_t i = input_count; i < input_count + output_count; ++i) {- // The consumers of the corresponding Store ops- const auto consumer_inputs = loop_end_expr->get_input_port_connector(i)->get_consumers();- size_t buffer_count = 0;- size_t loop_count = 0;++ const auto& loop_outputs = loop_info->get_output_ports_info();+ for (const auto& port_info : loop_outputs) {+ const auto& consumer_inputs = port_info.port.expr_port->get_port_connector_ptr()->get_consumers();for (const auto& consumer_input : consumer_inputs) {const auto& child_expr = consumer_input.get_expr();- if (const auto buffer_expr = ov::as_type_ptr<BufferExpression>(child_expr)) {- buffer_neighbours[buffer_expr] = { data_sizes[i], ptr_increments[i], finalization_offsets[i] };- buffer_count++;- } else if (ov::is_type<op::LoopEnd>(child_expr->get_node())) {- loop_count++;- }- }- if (buffer_count > 0) {- OPENVINO_ASSERT((buffer_count == 1) && (buffer_count + loop_count == consumer_inputs.size()),- "Loop output must have not more than 1 Buffer");+ if (const auto buffer_expr = ov::as_type_ptr<BufferExpression>(child_expr))+ buffer_neighbours[buffer_expr] = port_info;}}+return buffer_neighbours;}@@ -164,9 +145,9 @@ SetBufferRegGroup::BufferMap SetBufferRegGroup::get_buffer_loop_inside(const Linfor (auto it = std::reverse_iterator<LinearIR::constExprIt>(loop_end_it); (*it)->get_node() != loop_begin; ++it) {const auto& inner_expr = *it;if (const auto buffer_expr = ov::as_type_ptr<BufferExpression>(inner_expr)) {- // Set default zero values since it's not used for adjacency definition in case with Buffers in Loop+ // Set default value (zeroes) since it's not used for adjacency definition in case with Buffers in Loopif (inner_buffers.count(buffer_expr) == 0)- inner_buffers[buffer_expr] = { 0, 0, 0 };+ inner_buffers[buffer_expr] = UnifiedLoopInfo::LoopPortInfo();}}return inner_buffers;@@ -219,6 +200,7 @@ auto SetBufferRegGroup::coloring(BufferPool& buffers, std::vector<bool>& adj) ->bool SetBufferRegGroup::run(LinearIR& linear_ir, lowered::LinearIR::constExprIt begin, lowered::LinearIR::constExprIt end) {OV_ITT_SCOPED_TASK(ov::pass::itt::domains::SnippetsTransform, "Snippets::SetBufferRegGroup")+// Identify Buffers using Graph coloring algorithm.BufferPool buffer_pool = linear_ir.get_buffers();// For the better coloring Buffers should be stored in the order of execution numbers@@ -226,7 +208,7 @@ bool SetBufferRegGroup::run(LinearIR& linear_ir, lowered::LinearIR::constExprIt[](const BufferExpressionPtr& lhs, const BufferExpressionPtr& rhs) { return lhs->get_exec_num() < rhs->get_exec_num(); });// Creation of Adj matrix- auto adj = create_adjacency_matrix(begin, end, buffer_pool);+ auto adj = create_adjacency_matrix(linear_ir.get_loop_manager(), begin, end, buffer_pool);// Graph coloring algorithmconst auto color_groups = coloring(buffer_pool, adj);diff --git a/src/common/snippets/src/pass/mha_tokenization.cpp b/src/common/snippets/src/pass/mha_tokenization.cppindex c42eb08b82b..beb465ab3a3 100644--- a/src/common/snippets/src/pass/mha_tokenization.cpp+++ b/src/common/snippets/src/pass/mha_tokenization.cpp@@ -268,16 +268,11 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const SnippetsTokenconst auto pattern_rank = matmul0->get_output_partial_shape(0).size();- const auto ops_count_before_softmax = ordered_ops.size();auto interm_op = matmul0->get_output_target_inputs(0).begin()->get_node()->shared_from_this();// Add supported operations which are between MatMul0 and Softmax to ordered_opsif (!update_intermediate_supported_ops(interm_op, ordered_ops, hidden_virtual_ports_count, potential_body_params_count))return false;- // If before Softmax there is Eltwise ops, there will be one more Buffer- if (ops_count_before_softmax != ordered_ops.size() && interm_op->get_output_partial_shape(0).rbegin()->is_dynamic())- uniqie_buffer_reg_group_count++;-std::shared_ptr<ov::opset1::Reshape> reshape0 = nullptr;if (!tokenize_reshape_around_softmax(interm_op, reshape0, ordered_ops))return false;@@ -295,10 +290,6 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const SnippetsTokenif (axis != rank.get_length() - 1 || interm_op->get_output_target_inputs(0).size() != 1)return false;- // Softmax need one buffer at least- if (interm_op->get_output_partial_shape(0).rbegin()->is_dynamic())- uniqie_buffer_reg_group_count++;-ordered_ops.push_back(interm_op);interm_op = interm_op->get_output_target_inputs(0).begin()->get_node()->shared_from_this();@@ -333,7 +324,7 @@ ov::snippets::pass::TokenizeMHASnippets::TokenizeMHASnippets(const SnippetsToken// The Loop will have one Buffer with the same shape both on input and output.// Need to check for precision to get if we need one more register for Bufferconst auto matmul0_prc = op::Brgemm::get_output_type(matmul0->get_input_element_type(0), matmul0->get_input_element_type(1));- if (matmul1->get_input_element_type(0).size() != matmul0_prc.size() || matmul1->get_input_partial_shape(0).is_dynamic()) {+ if (matmul1->get_input_element_type(0).size() != matmul0_prc.size()) {uniqie_buffer_reg_group_count++;}diff --git a/src/plugins/intel_cpu/src/transformations/tpp/x64/pass/lowered/set_tpp_leading_dim.cpp b/src/plugins/intel_cpu/src/transformations/tpp/x64/pass/lowered/set_tpp_leading_dim.cppindex 4f38eddc2bd..2a85714a792 100644--- a/src/plugins/intel_cpu/src/transformations/tpp/x64/pass/lowered/set_tpp_leading_dim.cpp+++ b/src/plugins/intel_cpu/src/transformations/tpp/x64/pass/lowered/set_tpp_leading_dim.cpp@@ -16,13 +16,6 @@ namespace tpp {namespace pass {namespace {using ExpressionPort = snippets::lowered::ExpressionPort;-bool is_planar_layout(const std::vector<size_t>& layout) {- for (size_t i = 0; i < layout.size(); i++) {- if (layout[i] != i)- return false;- }- return true;-}// Note: Buffer is directly connected to the port if it remains in the same loops with the port's expression// Directly connected Buffers store data densely, so strides are defined by subternsor dims// Indirectly connected Buffers (with loops between the expr and Buffer) store data according@@ -81,12 +74,12 @@ size_t get_leading_dim(ExpressionPort port, const snippets::lowered::LoopManagersubtensor[idx] = shape[shape.size() - i];}}- OPENVINO_ASSERT(!full_dim_substituted || is_planar_layout(layout),+ OPENVINO_ASSERT(!full_dim_substituted || ov::snippets::utils::is_planar_layout(layout),"Only planar layouts are supported for FULL_DIM substitution");if (has_directly_connected_buffer(port, loop_mngr)) {shape = port_desc->get_subtensor();- OPENVINO_ASSERT(is_planar_layout(layout), "Only planar layouts are supported for Buffers");+ OPENVINO_ASSERT(ov::snippets::utils::is_planar_layout(layout), "Only planar layouts are supported for Buffers");const auto rank_diff = static_cast<int64_t>(layout.size()) - static_cast<int64_t>(shape.size());if (rank_diff > 0)layout.erase(layout.end() - rank_diff, layout.end());diff --git a/src/plugins/intel_cpu/tests/unit/snippets_transformations/x64/lowered/buffer_allocation.cpp b/src/plugins/intel_cpu/tests/unit/snippets_transformations/x64/lowered/buffer_allocation.cppindex 6dad1d4772f..e31a8bebb95 100644--- a/src/plugins/intel_cpu/tests/unit/snippets_transformations/x64/lowered/buffer_allocation.cpp+++ b/src/plugins/intel_cpu/tests/unit/snippets_transformations/x64/lowered/buffer_allocation.cpp@@ -36,21 +36,24 @@ using BRGEMM_TYPE = intel_cpu::brgemm_utils::BRGEMM_TYPE;*/typedef std::tuple<- bool, // Optimized pipeline- bool, // With SplitLoops opt- size_t, // Expected Buffer size in bytes- size_t, // Expected unique Buffer reg group count- size_t // Expected unique Buffer cluster count+ std::vector<ov::PartialShape>, // Input shapes+ bool, // Optimized pipeline+ bool, // With SplitLoops opt+ size_t, // Expected Buffer size in bytes+ size_t, // Expected unique Buffer reg group count+ size_t // Expected unique Buffer cluster count> BufferAllocationCPUParams;class BufferAllocationCPUTest : public testing::TestWithParam<BufferAllocationCPUParams> {public:using VectorDims = ov::snippets::VectorDims;static std::string getTestCaseName(testing::TestParamInfo<BufferAllocationCPUParams> obj) {+ std::vector<ov::PartialShape> shapes;bool is_optimized, with_split_loops;size_t expected_size, expected_reg_group_count, expected_cluster_count;- std::tie(is_optimized, with_split_loops, expected_size, expected_reg_group_count, expected_cluster_count) = obj.param;+ std::tie(shapes, is_optimized, with_split_loops, expected_size, expected_reg_group_count, expected_cluster_count) = obj.param;std::ostringstream result;+ result << "Shapes=" << ov::test::utils::partialShape2str(shapes) << "_";result << "Opt=" << ov::test::utils::bool2str(is_optimized) << "_";result << "Split=" << ov::test::utils::bool2str(with_split_loops) << "_";result << "ExpBufferSize=" << expected_size << "_";@@ -61,9 +64,11 @@ public:protected:void SetUp() override {- std::tie(m_is_buffer_optimized, m_with_split_loops, m_expected_size, m_expected_reg_group_count, m_expected_cluster_count) = this->GetParam();+ std::vector<ov::PartialShape> shapes;+ std::tie(shapes, m_is_buffer_optimized, m_with_split_loops, m_expected_size,+ m_expected_reg_group_count, m_expected_cluster_count) = this->GetParam();- const auto body = GetModel();+ const auto body = GetModel(shapes);m_linear_ir = ov::snippets::lowered::LinearIR(body, std::make_shared<ov::snippets::CPUShapeInferSnippetsFactory>());m_linear_ir.set_loop_depth(m_loop_depth);// When Subgraph::control_flow_transformations become public method,@@ -105,7 +110,7 @@ protected:EXPECT_EQ(m_linear_ir.get_static_buffer_scratchpad_size(), m_expected_size);}- virtual std::shared_ptr<ov::Model> GetModel() const = 0;+ virtual std::shared_ptr<ov::Model> GetModel(const std::vector<ov::PartialShape>& shapes) const = 0;void MarkOp(const std::shared_ptr<ov::Node>& node, const std::vector<size_t>& subtensor) const {for (const auto& input : node->inputs())@@ -131,20 +136,16 @@ protected:class MHAFP32BufferAllocationTest : public BufferAllocationCPUTest {protected:- std::shared_ptr<ov::Model> GetModel() const override {+ std::shared_ptr<ov::Model> GetModel(const std::vector<ov::PartialShape>& shapes) const override {const auto subtensor_scalar = std::vector<size_t>{1};const auto subtensor_power = std::vector<size_t>{1, ov::snippets::utils::get_full_dim_value()};const auto subtensor_full = std::vector<size_t>(2, ov::snippets::utils::get_full_dim_value());// Dims are selected in order to have blocking loops by each dim- const size_t m = 1024;- const size_t k = 1024;- const size_t n1 = 128;- const size_t n2 = 256;-- const auto parameter0 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape({1, 12, m, k}));- const auto parameter1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape({1, n1, 12, k}));- const auto parameter2 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape({1, 12, n1, n2}));+ OPENVINO_ASSERT(shapes.size() == 3, "Incorrect count of input shapes");+ const auto parameter0 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shapes[0]);+ const auto parameter1 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shapes[1]);+ const auto parameter2 = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, shapes[2]);const auto order = std::vector<size_t>{0, 2, 3, 1};const auto load_reshape = std::make_shared<ov::snippets::op::LoadReshape>(parameter1, 1, 0, order);@@ -186,20 +187,15 @@ protected:class MHABF16AMXBufferAllocationTest : public BufferAllocationCPUTest {protected:- std::shared_ptr<ov::Model> GetModel() const override {+ std::shared_ptr<ov::Model> GetModel(const std::vector<ov::PartialShape>& shapes) const override {const auto subtensor_scalar = std::vector<size_t>{1};const auto subtensor_power = std::vector<size_t>{1, ov::snippets::utils::get_full_dim_value()};const auto subtensor_full = std::vector<size_t>(2, ov::snippets::utils::get_full_dim_value());- // Dims are selected in order to have blocking loops by each dim- const size_t m = 1024;- const size_t k = 1024;- const size_t n1 = 128;- const size_t n2 = 256;-- const auto parameter0 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, ov::PartialShape({1, 12, m, k}));- const auto parameter1 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, ov::PartialShape({1, n1, 12, k}));- const auto parameter2 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, ov::PartialShape({1, 12, n1, n2}));+ OPENVINO_ASSERT(shapes.size() == 3, "Incorrect count of input shapes");+ const auto parameter0 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, shapes[0]);+ const auto parameter1 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, shapes[1]);+ const auto parameter2 = std::make_shared<ov::op::v0::Parameter>(ov::element::bf16, shapes[2]);const auto order = std::vector<size_t>{0, 2, 3, 1};const auto load_reshape = std::make_shared<ov::snippets::op::LoadReshape>(parameter1, 1, 0, order);@@ -264,8 +260,17 @@ TEST_P(MHABF16AMXBufferAllocationTest, BufferAllocationCPU) {namespace BufferAllocationCPUTest_Instances {+std::vector<ov::PartialShape> static_shapes = {+ { 1, 12, 1024, 1024 }, {1, 128, 12, 1024 }, {1, 12, 128, 256 },+};++std::vector<ov::PartialShape> dynamic_shapes = {+ { -1, -1, -1, -1 }, { -1, -1, -1, -1 }, { -1, -1, -1, -1 },+};+INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHANotOptimizedWSplit, MHAFP32BufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(false),::testing::Values(true),::testing::Values(591360), // Each Buffer has own allocated memory@@ -275,6 +280,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHANotOptimizedWSplit,INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHAOptimizedWSplit, MHAFP32BufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(true),::testing::Values(true),::testing::Values(573440), // (Buffer before brgemm) + (between brgemms) + (after brgemm)@@ -284,6 +290,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHAOptimizedWSplit, MHAINSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHANotOptimizedWOSplit, MHAFP32BufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(false),::testing::Values(false),::testing::Values(2622976), // Each Buffer has own allocated memory@@ -293,6 +300,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHANotOptimizedWOSplit,INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHAOptimizedWOSplit, MHAFP32BufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(true),::testing::Values(false),::testing::Values(1572864), // (between brgemms) + (Buffer before brgemm0 and after brgemm1)@@ -302,6 +310,7 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHAOptimizedWOSplit, MHINSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXNotOptimizedWSplit, MHABF16AMXBufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(false),::testing::Values(true),::testing::Values(713984),@@ -311,15 +320,17 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXNotOptimizedWINSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXOptimizedWSplit, MHABF16AMXBufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(true),::testing::Values(true),::testing::Values(524288),::testing::Values(3),- ::testing::Values(8)),+ ::testing::Values(7)),BufferAllocationCPUTest::getTestCaseName);INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXNotOptimizedWOSplit, MHABF16AMXBufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(false),::testing::Values(false),::testing::Values(2491648),@@ -329,11 +340,32 @@ INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXNotOptimizedWINSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXOptimizedWOSplit, MHABF16AMXBufferAllocationTest,::testing::Combine(+ ::testing::Values(static_shapes),::testing::Values(true),::testing::Values(false),- ::testing::Values(1409024),+ ::testing::Values(1671168),+ ::testing::Values(3),+ ::testing::Values(7)),+ BufferAllocationCPUTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHAOptimizedWSplit_Dynamic, MHAFP32BufferAllocationTest,+ ::testing::Combine(+ ::testing::Values(dynamic_shapes),+ ::testing::Values(true),+ ::testing::Values(true),+ ::testing::Values(0), // no static clusters+ ::testing::Values(2), // (Buffer before brgemm0 and after brgemm1) + (between brgemms)+ ::testing::Values(3)), // (Buffer before brgemm0) + (between brgemms) + (after brgemm1)+ BufferAllocationCPUTest::getTestCaseName);++INSTANTIATE_TEST_SUITE_P(smoke_Snippets_BufferAllocation_MHABF16AMXOptimizedWSplit_Dynamic, MHABF16AMXBufferAllocationTest,+ ::testing::Combine(+ ::testing::Values(dynamic_shapes),+ ::testing::Values(true),+ ::testing::Values(true),+ ::testing::Values(32768), // only WSP buffers::testing::Values(3),- ::testing::Values(8)),+ ::testing::Values(7)),BufferAllocationCPUTest::getTestCaseName);} // namespace BufferAllocationCPUTest_Instances