Skip to content

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

Extend Einsum Core and common transformation to support broadcasting, repeated labels and ellipsis (#28151)

Mateusz Mikolajczyk7697ca9e83c9
diff --git a/src/common/transformations/src/transformations/common_optimizations/transpose_reshape_elimination_for_matmul.cpp b/src/common/transformations/src/transformations/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
index 2a4e413f3cf..cbb159b01cc 100644
--- a/src/common/transformations/src/transformations/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
+++ b/src/common/transformations/src/transformations/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
@@ -9,10 +9,12 @@
#include "itt.hpp"
#include "openvino/core/rt_info.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/constant.hpp"
#include "openvino/op/matmul.hpp"
#include "openvino/op/reshape.hpp"
#include "openvino/op/transpose.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
namespace {
@@ -124,9 +126,16 @@ ov::pass::TransposeReshapeEliminationForMatmul::TransposeReshapeEliminationForMa
auto transpose_before_pattern =
ov::pass::pattern::wrap_type<ov::op::v1::Transpose>({input_2_pattern, const_transpose_before_pattern});
+ auto const_optional_broadcast_before_pattern = ov::pass::pattern::wrap_type<ov::op::v0::Constant>();
+ auto optional_broadcast_before_pattern = ov::pass::pattern::wrap_type<ov::op::v3::Broadcast>(
+ {transpose_before_pattern, const_optional_broadcast_before_pattern});
+
+ auto transpose_or_transpose_broadcast = std::make_shared<ov::pass::pattern::op::Or>(
+ OutputVector{transpose_before_pattern, optional_broadcast_before_pattern});
+
auto const_reshape_before_pattern = ov::pass::pattern::wrap_type<ov::op::v0::Constant>();
- auto reshape_before_pattern =
- ov::pass::pattern::wrap_type<ov::op::v1::Reshape>({transpose_before_pattern, const_reshape_before_pattern});
+ auto reshape_before_pattern = ov::pass::pattern::wrap_type<ov::op::v1::Reshape>(
+ {transpose_or_transpose_broadcast, const_reshape_before_pattern});
auto matmul_pattern = ov::pass::pattern::wrap_type<ov::op::v0::MatMul>({input_1_pattern, reshape_before_pattern});
@@ -181,8 +190,37 @@ ov::pass::TransposeReshapeEliminationForMatmul::TransposeReshapeEliminationForMa
// transposes
if (!check_transposes(transpose_before_order, transpose_after_order, transposed_b))
return false;
-
- const auto new_matmul = std::make_shared<ov::op::v0::MatMul>(input_1, input_2, transposed_a, false);
+ auto matmul_2_input = input_2;
+ // for einsum decomposition, check if broadcast exist and if so, reorder target shape based on transpose
+ if (pattern_value_map.count(optional_broadcast_before_pattern)) {
+ auto broadcast_before = ov::as_type_ptr<ov::op::v3::Broadcast>(
+ pattern_value_map.at(optional_broadcast_before_pattern).get_node_shared_ptr());
+ if (!broadcast_before) {
+ return false;
+ }
+ auto broadcast_before_constant =
+ ov::as_type_ptr<ov::op::v0::Constant>(broadcast_before->get_input_node_shared_ptr(1));
+ if (!broadcast_before_constant) {
+ return false;
+ }
+ auto broadcast_shape_after_transpose = broadcast_before_constant->cast_vector<int64_t>();
+ if (broadcast_shape_after_transpose.size() != transpose_before_order.size()) {
+ return false;
+ }
+ std::vector<int64_t> broadcast_shape_no_transpose;
+ broadcast_shape_no_transpose.reserve(broadcast_shape_after_transpose.size());
+ for (auto idx : transpose_before_order) {
+ broadcast_shape_no_transpose.push_back(broadcast_shape_after_transpose[idx]);
+ }
+ auto broadcast_shape_no_transpose_constant =
+ ov::op::v0::Constant::create(element::i64,
+ broadcast_before_constant->get_shape(),
+ broadcast_shape_no_transpose);
+ matmul_2_input = broadcast_before->clone_with_new_inputs({input_2, broadcast_shape_no_transpose_constant});
+ copy_runtime_info(broadcast_before, matmul_2_input.get_node_shared_ptr());
+ }
+
+ const auto new_matmul = std::make_shared<ov::op::v0::MatMul>(input_1, matmul_2_input, transposed_a, false);
new_matmul->set_friendly_name(transpose_after->get_friendly_name());
copy_runtime_info({transpose_before, reshape_before, matmul, reshape_after, transpose_after}, new_matmul);
replace_node(transpose_after, new_matmul);
diff --git a/src/common/transformations/src/transformations/op_conversions/einsum_decomposition.cpp b/src/common/transformations/src/transformations/op_conversions/einsum_decomposition.cpp
index 4a88b4d6f90..3c860479547 100644
--- a/src/common/transformations/src/transformations/op_conversions/einsum_decomposition.cpp
+++ b/src/common/transformations/src/transformations/op_conversions/einsum_decomposition.cpp
@@ -9,35 +9,33 @@
#include "itt.hpp"
#include "openvino/core/rt_info.hpp"
#include "openvino/core/validation_util.hpp"
+#include "openvino/op/broadcast.hpp"
#include "openvino/op/concat.hpp"
#include "openvino/op/constant.hpp"
+#include "openvino/op/convert_like.hpp"
+#include "openvino/op/divide.hpp"
#include "openvino/op/einsum.hpp"
+#include "openvino/op/gather.hpp"
#include "openvino/op/matmul.hpp"
+#include "openvino/op/maximum.hpp"
#include "openvino/op/multiply.hpp"
+#include "openvino/op/pad.hpp"
+#include "openvino/op/power.hpp"
+#include "openvino/op/range.hpp"
#include "openvino/op/reduce_prod.hpp"
#include "openvino/op/reduce_sum.hpp"
#include "openvino/op/reshape.hpp"
+#include "openvino/op/scatter_elements_update.hpp"
#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
#include "openvino/op/strided_slice.hpp"
+#include "openvino/op/subtract.hpp"
#include "openvino/op/transpose.hpp"
#include "openvino/op/unsqueeze.hpp"
#include "openvino/pass/pattern/op/wrap_type.hpp"
#include "transformations/utils/utils.hpp"
namespace {
-/// \brief Check if the EinsumDecomposition transformation is applicable to a given Einsum.
-/// The transformation is applicable if input subscript does not have repeated labels and ellipsis.
-///
-/// \param subscript A subscript to check its format
-///
-/// \return true - applicable, false - not applicable
-///
-bool is_subscript_applicable(const std::string& subscript) {
- auto labels = ov::op::v7::Einsum::extract_labels(subscript);
- auto unique_labels = std::unordered_set<std::string>(labels.begin(), labels.end());
- return std::find(labels.begin(), labels.end(), "...") == labels.end() && unique_labels.size() == labels.size();
-}
-
/// \brief Compute einsum_path for a given Einsum node meaning that the (pseudo-)optimal
/// order of operands contraction in terms of performance and memory consumption
///
@@ -174,7 +172,119 @@ void update_operands(ov::OutputVector& input_nodes,
input_subscripts.erase(input_subscripts.begin() + input_ind1);
input_subscripts.push_back(new_subscript);
}
+using LabelDimMap = std::unordered_map<std::string, std::vector<size_t>>;
+
+/// \brief Computes a mapping from labels to dimensions based on the input rank and subscript.
+///
+/// This function processes the input subscript to extract labels and maps them to the corresponding
+/// dimensions of the input tensor. The function also considers the presence of ellipsis ("...") in
+/// the labels and adjusts the dimension map accordingly.
+///
+/// \param input_rank The rank of the input tensor. It can be static or dynamic.
+/// \param input_subscript The subscript string representing the labels of the input tensor dimensions.
+/// \return A map where the keys are labels (strings) and the values are vectors of dimension indices.
+///
+LabelDimMap compute_label_dim_map(const ov::Rank& input_rank, const std::string& input_subscript) {
+ static const std::string ellipsis = "...";
+ const auto labels = ov::op::v7::Einsum::extract_labels(input_subscript);
+ const auto static_input_rank = input_rank.is_static();
+ OPENVINO_ASSERT(static_input_rank || (std::find(labels.begin(), labels.end(), ellipsis) == labels.end()),
+ "Input rank cannot be dynamic in case of ellipsis in input subscript");
+ const size_t input_rank_length = static_input_rank ? input_rank.get_length() : labels.size();
+ OPENVINO_ASSERT(input_rank_length >= labels.size());
+ const size_t num_broadcasted_dims = input_rank_length - labels.size() + 1;
+ OPENVINO_ASSERT(num_broadcasted_dims > 0);
+
+ LabelDimMap resulted_map;
+ size_t current_dim = 0;
+ for (const auto& label : labels) {
+ if (label == ellipsis) {
+ std::vector<size_t> label_dims(num_broadcasted_dims);
+ std::iota(label_dims.begin(), label_dims.end(), current_dim);
+ resulted_map[label] = label_dims;
+ current_dim += num_broadcasted_dims;
+ } else if (resulted_map.find(label) != resulted_map.end()) {
+ resulted_map[label].push_back(current_dim);
+ ++current_dim;
+ } else {
+ std::vector<size_t> label_dims{current_dim};
+ resulted_map[label] = label_dims;
+ ++current_dim;
+ }
+ }
+
+ return resulted_map;
+}
+
+/// \brief Computes the ranges for common, separated, and reduced labels in the input subscript.
+///
+/// This function calculates the start and end indices for common, separated, and reduced labels
+/// based on the input rank and subscript. It also considers the presence of ellipsis ("...") in
+/// the labels and adjusts the ranks accordingly.
+///
+/// \param input_rank The rank of the input tensor.
+/// \param input_subscript The subscript string representing the input tensor dimensions.
+/// \param common_labels A vector of strings representing the common labels.
+/// \param sep_labels A vector of strings representing the separated labels.
+/// \param reduced_labels A vector of strings representing the reduced labels.
+/// \param common_begin Reference to a size_t variable to store the beginning index of common labels.
+/// \param common_end Reference to a size_t variable to store the ending index of common labels.
+/// \param sep_begin Reference to a size_t variable to store the beginning index of separated labels.
+/// \param sep_end Reference to a size_t variable to store the ending index of separated labels.
+/// \param reduced_begin Reference to a size_t variable to store the beginning index of reduced labels.
+/// \param reduced_end Reference to a size_t variable to store the ending index of reduced labels.
+/// \param is_separated_first Boolean flag indicating whether the separated labels should come before the reduced
+/// labels.
+///
+void compute_ranges(const ov::Rank& input_rank,
+ const std::string& input_subscript,
+ const std::vector<std::string>& common_labels,
+ const std::vector<std::string>& sep_labels,
+ const std::vector<std::string>& reduced_labels,
+ size_t& common_begin,
+ size_t& common_end,
+ size_t& sep_begin,
+ size_t& sep_end,
+ size_t& reduced_begin,
+ size_t& reduced_end,
+ bool is_separated_first) {
+ auto label_to_dim_map = compute_label_dim_map(input_rank, input_subscript);
+
+ size_t common_rank = common_labels.size();
+ size_t sep_rank = sep_labels.size();
+ size_t reduced_rank = reduced_labels.size();
+
+ static const std::string ellipsis = "...";
+ // Adjust rank to include ellipsis dimensions.
+ // Initial rank is the number of labels in the input subscript, so if the ellipsis is present, initial ellipsis rank
+ // would be counted as 1. Adjust the rank to include actual ellipsis rank with accounting for existing "placeholder"
+ // by subtracting by 1.
+ if (label_to_dim_map.find(ellipsis) != label_to_dim_map.end()) {
+ if (std::find(common_labels.begin(), common_labels.end(), ellipsis) != common_labels.end()) {
+ common_rank += label_to_dim_map[ellipsis].size() - 1;
+ }
+ if (std::find(sep_labels.begin(), sep_labels.end(), ellipsis) != sep_labels.end()) {
+ sep_rank += label_to_dim_map[ellipsis].size() - 1;
+ }
+ if (std::find(reduced_labels.begin(), reduced_labels.end(), ellipsis) != reduced_labels.end()) {
+ reduced_rank += label_to_dim_map[ellipsis].size() - 1;
+ }
+ }
+ common_begin = 0;
+ common_end = common_begin + common_rank;
+ if (is_separated_first) {
+ sep_begin = common_end;
+ sep_end = sep_begin + sep_rank;
+ reduced_begin = sep_end;
+ reduced_end = reduced_begin + reduced_rank;
+ } else {
+ reduced_begin = common_end;
+ reduced_end = reduced_begin + reduced_rank;
+ sep_begin = reduced_end;
+ sep_end = sep_begin + sep_rank;
+ }
+}
/// \brief Return input node with computed sub-shape defined by a range [s_begin;s_end)
///
/// \param data_shape Input node that contains some tensor shape
@@ -243,6 +353,92 @@ ov::Output<ov::Node> unsqueeze_input(const ov::Output<ov::Node>& input_node,
return unsqueeze->output(0);
}
+/// \brief Broadcasts and merges two shapes of the same rank.
+///
+/// This function takes two shapes (shapes_lhs and shapes_rhs) of same rank and attempts to broadcast
+/// and merge them into a single shape. The resulting broadcasted shape is returned as an OutputVector.
+/// If one of the input vectors is empty, the other vector is returned as is.
+///
+/// \param shapes_lhs A single element vector containing the left-hand side shape to be broadcasted or empty.
+/// \param shapes_rhs A single element vector containing the right-hand side shape to be broadcasted or empty.
+/// \param subgraph_nodes A vector to which the nodes created during the broadcasting process are added.
+/// \return An OutputVector containing the broadcasted and merged shape. If one of the input vectors is empty,
+/// the other vector is returned.
+///
+ov::OutputVector broadcast_merge_shapes(const ov::OutputVector& shapes_lhs,
+ const ov::OutputVector& shapes_rhs,
+ ov::NodeVector& subgraph_nodes) {
+ ov::OutputVector broadcasted_shape_nodes{};
+ // OutputVector is either empty or contains a single shape
+ if (shapes_lhs.size() == 1 && shapes_rhs.size() == 1) {
+ // For common and reference subshapes, same rank should already be ensured by function
+ // `unsqueeze_ellipses_to_same_rank`.
+ const auto& maximum = std::make_shared<ov::op::v1::Maximum>(shapes_lhs[0], shapes_rhs[0]);
+ subgraph_nodes.push_back(maximum);
+ broadcasted_shape_nodes.push_back(maximum);
+ } else if (shapes_lhs.size() == 0 && shapes_rhs.size() == 1) {
+ return shapes_rhs;
+ } else if (shapes_lhs.size() == 1 && shapes_rhs.size() == 0) {
+ return shapes_lhs;
+ }
+ return broadcasted_shape_nodes;
+}
+
+/// \brief Broadcast input node to the new shape specified by broadcasted sub-shapes of the common,
+/// separate and reduced dimensions so that the broadcasted input has a format acceptable by Reshape MatMul
+///
+/// \param input_node Input node to reshape
+/// \param common_sub_shape A sub-shape corresponding to the broadcasted common dimensions
+/// \param separate_sub_shape A sub-shape corresponding to the broadcasted separate dimensions
+/// \param reduced_sub_shape_prod A product of the broadcasted separate dimensions sizes
+/// \param is_separate_first true - the separate dimensions placed before reduced
+/// dimensions, otherwise, it is after them
+/// \param subgraph_nodes A vector of operation nodes that is included into
+/// a sub-graph decomposing Einsum that is needed for copy_runtime_info
+///
+/// \return Broadcasted input node
+///
+ov::Output<ov::Node> broadcast_input(const ov::Output<ov::Node>& input_node,
+ const ov::OutputVector& common_sub_shape,
+ const ov::OutputVector& separate_sub_shape,
+ const ov::OutputVector& reduced_sub_shape,
+ bool is_separate_first,
+ ov::NodeVector& subgraph_nodes) {
+ ov::OutputVector new_shape_parts;
+ new_shape_parts.insert(new_shape_parts.end(), common_sub_shape.begin(), common_sub_shape.end());
+ // form a new shape for input so that collapsed dimensions corresponding
+ // to the common, separate and reduced dimensions are placed in the correct order
+ if (is_separate_first) {
+ new_shape_parts.insert(new_shape_parts.end(), separate_sub_shape.begin(), separate_sub_shape.end());
+ new_shape_parts.insert(new_shape_parts.end(), reduced_sub_shape.begin(), reduced_sub_shape.end());
+ } else {
+ new_shape_parts.insert(new_shape_parts.end(), reduced_sub_shape.begin(), reduced_sub_shape.end());
+ new_shape_parts.insert(new_shape_parts.end(), separate_sub_shape.begin(), separate_sub_shape.end());
+ }
+
+ // in case of scalar reshape is not needed
+ if (new_shape_parts.size() == 0) {
+ return input_node;
+ }
+ auto new_shape_op = std::make_shared<ov::op::v0::Concat>(new_shape_parts, 0);
+ // if new shape is possible to compute on the shape infer stage, insert Constant node immediately
+ // in order to prevent repeated computing during constant-folding pass
+ std::shared_ptr<ov::op::v3::Broadcast> reshaped_input_op;
+ if (auto new_shape_const = ov::util::get_constant_from_source(new_shape_op)) {
+ reshaped_input_op =
+ std::make_shared<ov::op::v3::Broadcast>(input_node, new_shape_const, ov::op::BroadcastType::BIDIRECTIONAL);
+ subgraph_nodes.insert(subgraph_nodes.end(), {new_shape_const});
+ } else {
+ reshaped_input_op = std::make_shared<ov::op::v3::Broadcast>(input_node,
+ new_shape_op->output(0),
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ subgraph_nodes.insert(subgraph_nodes.end(), {new_shape_op});
+ }
+
+ subgraph_nodes.insert(subgraph_nodes.end(), {reshaped_input_op});
+ return reshaped_input_op->output(0);
+}
+
/// \brief Reshape input node to the new shape specified by sub-shapes of the common,
/// separate and reduced dimensions so that the reshaped input has a format acceptable by MatMul
///
@@ -260,7 +456,7 @@ ov::Output<ov::Node> unsqueeze_input(const ov::Output<ov::Node>& input_node,
ov::Output<ov::Node> reshape_input_for_matmul(const ov::Output<ov::Node>& input_node,
const ov::OutputVector& common_sub_shape,
const ov::OutputVector& separate_sub_shape,
- const ov::OutputVector& reduced_sub_shape_prod,
+ const ov::OutputVector& reduced_sub_shape,
bool is_separate_first,
ov::NodeVector& subgraph_nodes) {
ov::OutputVector new_shape_parts;
@@ -268,6 +464,7 @@ ov::Output<ov::Node> reshape_input_for_matmul(const ov::Output<ov::Node>& input_
// compute a product of a sub-shape for separate labels
ov::OutputVector separate_parts;
+ auto reduce_axis_const = ov::op::v0::Constant::create(ov::element::Type_t::i64, ov::Shape{1}, {0});
if (common_sub_shape.size() > 0 && separate_sub_shape.size() == 0) {
// in this case new dimension corresponding to separate labels must be added
// since MatMul operation is not possible to do without separate dimensions if the
@@ -278,15 +475,22 @@ ov::Output<ov::Node> reshape_input_for_matmul(const ov::Output<ov::Node>& input_
} else if (separate_sub_shape.size() > 0) {
// in this case compute a product of separate dimension sizes since they must be
// presented with just one dimension for MatMul
- auto reduce_axis_const = ov::op::v0::Constant::create(ov::element::Type_t::i64, ov::Shape{1}, {0});
auto separate_shape_prod =
std::make_shared<ov::op::v1::ReduceProd>(separate_sub_shape[0], reduce_axis_const, true);
separate_parts.push_back(separate_shape_prod->output(0));
subgraph_nodes.insert(subgraph_nodes.end(), {reduce_axis_const, separate_shape_prod});
}
+ ov::OutputVector reduced_sub_shape_prod;
+ if (reduced_sub_shape.size() > 0) {
+ auto const_0 = ov::op::v0::Constant::create(ov::element::i32, {1}, {0});
+ auto product = std::make_shared<ov::op::v1::ReduceProd>(reduced_sub_shape[0], const_0, true);
+ subgraph_nodes.insert(subgraph_nodes.end(), {reduce_axis_const, const_0, product});
+ reduced_sub_shape_prod.push_back(product->output(0));
+ }
// form a new shape for input so that collapsed dimensions corresponding
// to the common, separate and reduced dimensions are placed in the correct order
+
if (is_separate_first) {
new_shape_parts.insert(new_shape_parts.end(), separate_parts.begin(), separate_parts.end());
new_shape_parts.insert(new_shape_parts.end(), reduced_sub_shape_prod.begin(), reduced_sub_shape_prod.end());
@@ -302,7 +506,7 @@ ov::Output<ov::Node> reshape_input_for_matmul(const ov::Output<ov::Node>& input_
auto new_shape_op = std::make_shared<ov::op::v0::Concat>(new_shape_parts, 0);
- // if new shape is possible to compute on the shape infer stage, insert Constant node immediatelly
+ // if new shape is possible to compute on the shape infer stage, insert Constant node immediately
// in order to prevent repeated computing during constant-folding pass
std::shared_ptr<ov::op::v1::Reshape> reshaped_input_op;
if (auto new_shape_const = ov::util::get_constant_from_source(new_shape_op)) {
@@ -334,7 +538,7 @@ void transpose_input(ov::OutputVector& input_nodes,
size_t input_ind,
ov::NodeVector& subgraph_nodes) {
// perform sanity check for arguments
- auto num_inputs = input_nodes.size();
+ const auto num_inputs = input_nodes.size();
OPENVINO_ASSERT(num_inputs == input_subscripts.size(), "Each input must have own subscript.");
OPENVINO_ASSERT(input_ind < num_inputs, "Input index is out of range.");
@@ -350,21 +554,21 @@ void transpose_input(ov::OutputVector& input_nodes,
// find permutation that establishes bijection between the input subscript
// and the required one
- auto labels = ov::op::v7::Einsum::extract_labels(input_subscript);
- auto required_labels = ov::op::v7::Einsum::extract_labels(required_subscript);
- OPENVINO_ASSERT(labels.size() == required_labels.size());
+ const auto& input_node = input_nodes[input_ind];
+ const auto labels = ov::op::v7::Einsum::extract_labels(input_subscript);
+ const auto required_labels = ov::op::v7::Einsum::extract_labels(required_subscript);
+ const auto label_dim_map = compute_label_dim_map(input_node.get_partial_shape().rank(), input_subscript);
for (const auto& required_label : required_labels) {
- auto it = std::find(labels.begin(), labels.end(), required_label);
- OPENVINO_ASSERT(it != labels.end());
- int64_t found_index = static_cast<int64_t>(it - labels.begin());
- permutation.push_back(found_index);
+ const auto label_dims_it = label_dim_map.find(required_label);
+ OPENVINO_ASSERT(label_dims_it != label_dim_map.end());
+ const auto& label_dims = label_dims_it->second;
+ permutation.insert(permutation.end(), label_dims.begin(), label_dims.end());
}
// create a sub-graph for transposing into the required layout
- const auto& input_node = input_nodes[input_ind];
- auto permutation_const =
+ const auto permutation_const =
ov::op::v0::Constant::create(ov::element::Type_t::i64, ov::Shape{permutation.size()}, permutation);
- auto transpose = std::make_shared<ov::op::v1::Transpose>(input_node, permutation_const);
+ const auto transpose = std::make_shared<ov::op::v1::Transpose>(input_node, permutation_const);
// update a vector of inputs and input subscripts
input_nodes[input_ind] = transpose->output(0);
@@ -377,7 +581,6 @@ void transpose_input(ov::OutputVector& input_nodes,
/// \brief Find labels (in a given input subscript) that are met once in the equation
/// and reduce dimensions corresponding to such labels
///
-/// \param einsum_decompose_ptr A pointer to Einsum decomposing pass
/// \param input_nodes A vector of input nodes to Einsum operation
/// \param input_subscripts A vector of corresponding subscripts for the input nodes
/// \param output_subscript The output subscript
@@ -386,46 +589,51 @@ void transpose_input(ov::OutputVector& input_nodes,
/// \param subgraph_nodes A vector of operation nodes that is included into
/// a sub-graph decomposing Einsum that is needed for copy_runtime_info
///
-void reduce_input(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
- ov::OutputVector& input_nodes,
+void reduce_input(ov::OutputVector& input_nodes,
std::vector<std::string>& input_subscripts,
const std::string& output_subscript,
size_t input_ind,
ov::NodeVector& subgraph_nodes) {
// perform sanity check for arguments
- auto num_inputs = input_nodes.size();
+ const auto num_inputs = input_nodes.size();
OPENVINO_ASSERT(num_inputs == input_subscripts.size(), "Each input must have own subscript.");
OPENVINO_ASSERT(input_ind < num_inputs, "Input index is out of range.");
- std::vector<int64_t> reduced_axes;
- auto labels = ov::op::v7::Einsum::extract_labels(input_subscripts[input_ind]);
+ const auto& input_node = input_nodes[input_ind];
+ const auto& input_subscript = input_subscripts[input_ind];
+
+ // compute output shape and axes to reduce
+ std::set<int64_t> reduced_axes;
+ const auto labels = ov::op::v7::Einsum::extract_labels(input_subscripts[input_ind]);
+ auto label_dim_map = compute_label_dim_map(input_node.get_partial_shape().rank(), input_subscript);
std::string new_input_subscript = "";
- for (size_t dim_ind = 0; dim_ind < labels.size(); ++dim_ind) {
- const auto& label = labels[dim_ind];
+ for (const auto& label : labels) {
// check if the current label is met in the other input subscripts
// or the output subscript
- bool is_dim_reduced = is_dimension_reduced(input_subscripts, output_subscript, label, {input_ind});
+ const bool is_dim_reduced = is_dimension_reduced(input_subscripts, output_subscript, label, {input_ind});
+
+ OPENVINO_ASSERT(label_dim_map.find(label) != label_dim_map.end());
+ const auto& label_dims = label_dim_map[label];
// if label is not met, dimension corresponding to the label is to reduce
if (is_dim_reduced) {
- reduced_axes.push_back(dim_ind);
+ reduced_axes.insert(label_dims.begin(), label_dims.end());
} else {
new_input_subscript += label;
}
}
- if (reduced_axes.size() == 0) {
+ if (reduced_axes.empty()) {
// there is no axis to reduce
return;
}
// reduce by summed up elements along dimension for which label is met just once
- const auto& input_node = input_nodes[input_ind];
- auto axes_const =
- ov::op::v0::Constant::create(ov::element::Type_t::i64, ov::Shape{reduced_axes.size()}, reduced_axes);
- auto reduce_sum = einsum_decompose_ptr->register_new_node<ov::op::v1::ReduceSum>(input_node, axes_const, false);
-
+ const std::vector<int64_t> reduced_axes_vec{reduced_axes.cbegin(), reduced_axes.cend()};
+ const auto axes_const =
+ ov::op::v0::Constant::create(ov::element::Type_t::i64, ov::Shape{reduced_axes.size()}, reduced_axes_vec);
+ const auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(input_node, axes_const, false);
// update a vector of inputs and input subscripts
input_nodes[input_ind] = reduce_sum->output(0);
input_subscripts[input_ind] = new_input_subscript;
@@ -434,12 +642,273 @@ void reduce_input(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
subgraph_nodes.insert(subgraph_nodes.end(), {axes_const, reduce_sum});
}
+/// \brief Prepares data for diagonal extraction in Einsum operation.
+///
+/// This function processes the input subscript and label-dimension map to identify repeated labels,
+/// update the resultant subscript, and determine the axes to be reduced.
+///
+/// \param input_subscript The input subscript string representing the Einsum equation.
+/// \param label_dim_map A map from labels to their corresponding dimensions.
+/// \param resultant_subscript A reference to the resultant subscript string to be updated.
+/// \param resultant_subscript_with_duplicates A reference to a resultant subscript string with duplicates.
+/// \param repeated_labels A reference to a vector of strings to store repeated labels found in input subscript.
+/// \param unrepeated_labels A reference to a vector where unrepeated labels will be stored.
+/// \param reduced_axes A reference to an AxisVector to store the axes that need to be reduced.
+///
+void prepare_diagonal_extraction_data(const std::string& input_subscript,
+ const LabelDimMap& label_dim_map,
+ std::string& resultant_subscript,
+ std::string& resultant_subscript_with_duplicates,
+ std::vector<std::string>& repeated_labels,
+ std::vector<std::string>& unrepeated_labels,
+ ov::AxisVector& reduced_axes) {
+ static const std::string ellipsis = "...";
+ const auto labels = ov::op::v7::Einsum::extract_labels(input_subscript);
+ std::vector<std::string> repeated_labels_with_duplicates;
+ size_t reduced_dim = 1;
+ for (const auto& label : labels) {
+ if (resultant_subscript.find(label) != std::string::npos) {
+ continue;
+ }
+
+ const auto dims_it = label_dim_map.find(label);
+ OPENVINO_ASSERT(dims_it != label_dim_map.end());
+
+ auto dims = dims_it->second;
+ const auto dims_size = dims.size();
+ OPENVINO_ASSERT(dims_size > 0);
+
+ if (label != ellipsis && dims_size > 1) {
+ // repeated label is found
+ // save only the first dimension corresponding to the repeated label
+ dims = {dims[0]};
+ reduced_axes.push_back(reduced_dim);
+ repeated_labels.push_back(label);
+ repeated_labels_with_duplicates.insert(repeated_labels_with_duplicates.end(), dims_size, label);
+ reduced_dim += 2;
+ resultant_subscript += label;
+ } else {
+ unrepeated_labels.push_back(label);
+ }
+ }
+ resultant_subscript = std::accumulate(unrepeated_labels.begin(), unrepeated_labels.end(), resultant_subscript);
+ resultant_subscript_with_duplicates = std::accumulate(repeated_labels_with_duplicates.begin(),
+ repeated_labels_with_duplicates.end(),
+ std::string(""));
+ resultant_subscript_with_duplicates =
+ std::accumulate(unrepeated_labels.begin(), unrepeated_labels.end(), resultant_subscript_with_duplicates);
+}
+
+///
+/// \brief Extracts the diagonal elements from the input tensor based on the provided subscripts.
+///
+/// This function modifies the input tensor by extracting its diagonal elements for repeated labels and updating the
+/// corresponding subscript.
+///
+/// \param inputs A vector of input tensors.
+/// \param input_subscripts A vector of subscripts corresponding to each input tensor.
+/// \param input_ind The index of the input tensor to be processed.
+/// \param subgraph_nodes A vector of operation nodes that is included into
+/// a sub-graph decomposing Einsum that is needed for copy_runtime_info
+///
+void extract_diagonal(ov::OutputVector& inputs,
+ std::vector<std::string>& input_subscripts,
+ size_t input_ind,
+ ov::NodeVector& subgraph_nodes) {
+ // perform sanity check for arguments
+ const auto& num_inputs = inputs.size();
+ OPENVINO_ASSERT(num_inputs == input_subscripts.size(), "Each input must have own subscript.");
+ OPENVINO_ASSERT(input_ind < num_inputs, "Input index is out of range.");
+
+ const auto& input_node = inputs[input_ind];
+ const auto& input_subscript = input_subscripts[input_ind];
+
+ // Compute the label to dimension map for the input subscript
+ const auto label_dim_map = compute_label_dim_map(input_node.get_partial_shape().rank(), input_subscript);
+ std::string resultant_subscript;
+ std::string resultant_subscript_with_duplicates;
+ std::vector<std::string> repeated_labels;
+ std::vector<std::string> unrepeated_labels;
+ ov::AxisVector reduced_axes;
+
+ // Prepare data for diagonal extraction
+ prepare_diagonal_extraction_data(input_subscript,
+ label_dim_map,
+ resultant_subscript,
+ resultant_subscript_with_duplicates,
+ repeated_labels,
+ unrepeated_labels,
+ reduced_axes);
+
+ // If there are no repeated labels, return early
+ if (repeated_labels.size() == 0) {
+ return;
+ }
+
+ // Transpose input so that repeated labels are grouped by same label and un-repeated labels are moved to the end
+ transpose_input(inputs, input_subscripts, resultant_subscript, input_ind, subgraph_nodes);
+
+ // Create a ShapeOf operation to get the shape of the input tensor
+ const auto& input_shape = std::make_shared<ov::op::v3::ShapeOf>(input_node);
+ ov::NodeVector begins;
+ ov::NodeVector ends;
+
+ // Compute the label to dimension map for the transposed input subscript
+ const auto transposed_label_dim_map =
+ compute_label_dim_map(input_node.get_partial_shape().rank(), resultant_subscript_with_duplicates);
+ const auto& const_0 = ov::op::v0::Constant::create(ov::element::i64, {1}, {0});
+ const auto& const_1 = ov::op::v0::Constant::create(ov::element::i64, {1}, {1});
+ subgraph_nodes.insert(subgraph_nodes.end(), {input_shape, const_0, const_1});
+ ov::NodeVector convenient_shape_vector;
+ ov::NodeVector shape_after_pad_vector;
+
+ // Process each repeated label
+ for (const std::string& repeated_label : repeated_labels) {
+ const auto dim_map_repeated_label = transposed_label_dim_map.find(repeated_label);
+ OPENVINO_ASSERT(dim_map_repeated_label != transposed_label_dim_map.end());
+ const auto& repeated_label_dims = dim_map_repeated_label->second;
+ const auto& repeated_label_indices =
+ ov::op::v0::Constant::create(ov::element::i64, {repeated_label_dims.size()}, repeated_label_dims);
+ const auto& repeated_label_indices_len =
+ ov::op::v0::Constant::create(ov::element::i64, {}, {repeated_label_dims.size()});
+ const auto& repeated_dimensions =
+ std::make_shared<ov::op::v7::Gather>(input_shape, repeated_label_indices, const_0);
+ const auto& repeated_dimension = std::make_shared<ov::op::v7::Gather>(repeated_dimensions, const_0, const_0);
+ const auto& range_max_val = std::make_shared<ov::op::v1::Power>(repeated_dimension, repeated_label_indices_len);
+ const auto& step_numerator = std::make_shared<ov::op::v1::Subtract>(range_max_val, const_1);
+ const auto& step_denominator = std::make_shared<ov::op::v1::Subtract>(repeated_dimension, const_1);
+ const auto& step_denominator_but_not_0 = std::make_shared<ov::op::v1::Maximum>(step_denominator, const_1);
+ const auto& step_numerator_but_not_0 = std::make_shared<ov::op::v1::Maximum>(step_numerator, const_1);
+ const auto& step = std::make_shared<ov::op::v1::Divide>(step_numerator_but_not_0, step_denominator_but_not_0);
+ const auto& end = std::make_shared<ov::op::v1::Subtract>(step, const_1);
+ const auto& reduced_size = std::make_shared<ov::op::v1::ReduceProd>(repeated_dimensions, const_0, true);
+ // Flatten dimensions of repeated label
+ convenient_shape_vector.push_back(reduced_size);
+ // Compute the new shape after padding, separate diagonal elements
+ shape_after_pad_vector.push_back(repeated_dimension);
+ shape_after_pad_vector.push_back(step);
+ begins.push_back(const_0);
+ ends.push_back(end);
+ subgraph_nodes.insert(subgraph_nodes.end(),
+ {repeated_label_indices,
+ repeated_label_indices_len,
+ repeated_dimensions,
+ repeated_dimension,
+ range_max_val,
+ step_numerator,
+ step_denominator,
+ step_denominator_but_not_0,
+ step_numerator_but_not_0,
+ step,
+ end,
+ reduced_size});
+ }
+
+ // Process unrepeated labels - do not modify or pad dimensions
+ std::vector<size_t> unrepeated_dimension_indices_vec;
+ for (std::string unrepeated_label : unrepeated_labels) {
+ const auto& dim_map_unrepeated_label = transposed_label_dim_map.find(unrepeated_label);
+ OPENVINO_ASSERT(dim_map_unrepeated_label != transposed_label_dim_map.end());
+ const auto& unrepeated_label_dims = dim_map_unrepeated_label->second;
+ unrepeated_dimension_indices_vec.insert(unrepeated_dimension_indices_vec.end(),
+ unrepeated_label_dims.begin(),
+ unrepeated_label_dims.end());
+ begins.insert(begins.end(), unrepeated_label_dims.size(), const_0);
+ ends.insert(ends.end(), unrepeated_label_dims.size(), const_0);
+ }
+
+ // Gather the dimensions for unrepeated labels in single call
+ const auto& unrepeated_dimensions_indices = ov::op::v0::Constant::create(ov::element::i64,
+ {unrepeated_dimension_indices_vec.size()},
+ unrepeated_dimension_indices_vec);
+ const auto& unrepeated_dimensions =
+ std::make_shared<ov::op::v7::Gather>(input_shape, unrepeated_dimensions_indices, const_0);
+ subgraph_nodes.insert(subgraph_nodes.end(), {unrepeated_dimensions_indices, unrepeated_dimensions});
+ convenient_shape_vector.push_back(unrepeated_dimensions);
+ shape_after_pad_vector.push_back(unrepeated_dimensions);
+
+ // Create the new shape for the input tensor that would flatten repeated label dimensions
+ const auto& convenient_shape = std::make_shared<ov::op::v0::Concat>(convenient_shape_vector, 0);
+ const auto& reshaped_input = std::make_shared<ov::op::v1::Reshape>(input_node, convenient_shape, false);
+ // Create the pads for the label-flattened input tensor to extract the diagonal elements
+ const auto& pads_end = std::make_shared<ov::op::v0::Concat>(ends, 0);
+ const auto& pads_begin = std::make_shared<ov::op::v0::Concat>(begins, 0);
+ const auto& pad =
+ std::make_shared<ov::op::v1::Pad>(reshaped_input, pads_begin, pads_end, ov::op::PadMode::CONSTANT);
+ // Reshape the tensor after padding to extract the diagonal elements to separate dimensions
+ const auto& reshape_after_pad_target = std::make_shared<ov::op::v0::Concat>(shape_after_pad_vector, 0);
+ const auto& reshape_after_pad = std::make_shared<ov::op::v1::Reshape>(pad, reshape_after_pad_target, false);
+ subgraph_nodes.insert(
+ subgraph_nodes.end(),
+ {convenient_shape, pads_begin, pads_end, reshaped_input, pad, reshape_after_pad_target, reshape_after_pad});
+
+ // Gather the diagonal elements
+ std::shared_ptr<ov::Node> gather = reshape_after_pad;
+ for (auto axis : reduced_axes) {
+ auto axis_const = ov::op::v0::Constant::create(ov::element::i64, {1}, {axis});
+ gather = std::make_shared<ov::op::v7::Gather>(gather, const_0, axis_const);
+ subgraph_nodes.insert(subgraph_nodes.end(), {axis_const, gather});
+ }
+
+ // Squeeze the gathered tensor to remove the reduced axes
+ const auto& reduced_indices = ov::op::v0::Constant::create(ov::element::i64, {reduced_axes.size()}, reduced_axes);
+ const auto& out_node = std::make_shared<ov::op::v0::Squeeze>(gather, reduced_indices);
+ subgraph_nodes.insert(subgraph_nodes.end(), {reduced_indices, out_node});
+
+ // Update the input tensor and its subscript
+ inputs[input_ind] = out_node->output(0);
+ input_subscripts[input_ind] = resultant_subscript;
+}
+
+/// \brief Adjusts the ranks of two input tensors by unsqueezing ellipses to the same rank.
+///
+/// This function ensures that the ellipses in the input subscripts of the two tensors have the same rank by unsqueezing
+/// the necessary dimensions. It modifies the inputs in place.
+///
+/// \param inputs A vector of input tensors.
+/// \param input_subscripts A vector of input subscripts corresponding to the input tensors.
+/// \param input_ind1 The index of the first input tensor in the inputs vector.
+/// \param input_ind2 The index of the second input tensor in the inputs vector.
+/// \param subgraph_nodes A vector of operation nodes that is included into
+/// a sub-graph decomposing Einsum that is needed for copy_runtime_info
+void unsqueeze_ellipses_to_same_rank(ov::OutputVector& inputs,
+ std::vector<std::string>& input_subscripts,
+ size_t input_ind1,
+ size_t input_ind2,
+ ov::NodeVector& subgraph_nodes) {
+ constexpr char ellipsis[] = "...";
+ const auto& input1 = inputs[input_ind1];
+ const auto& input2 = inputs[input_ind2];
+ OPENVINO_ASSERT(input1.get_partial_shape().rank().is_static() && input2.get_partial_shape().rank().is_static());
+ auto label_to_dim_map1 = compute_label_dim_map(input1.get_partial_shape().size(), input_subscripts[input_ind1]);
+ auto label_to_dim_map2 = compute_label_dim_map(input2.get_partial_shape().size(), input_subscripts[input_ind2]);
+ if (label_to_dim_map1.find(ellipsis) != label_to_dim_map1.end() &&
+ label_to_dim_map2.find(ellipsis) != label_to_dim_map2.end()) {
+ std::vector<int64_t> unsqueeze_axis1, unsqueeze_axis2;
+ const auto& ellipsis_dims1 = label_to_dim_map1[ellipsis];
+ const auto& ellipsis_dims2 = label_to_dim_map2[ellipsis];
+ if (ellipsis_dims2.size() > ellipsis_dims1.size()) {
+ for (size_t i = 0; i < ellipsis_dims2.size() - ellipsis_dims1.size(); ++i) {
+ unsqueeze_axis1.push_back(ellipsis_dims1[0] + i);
+ }
+ } else if (ellipsis_dims1.size() > ellipsis_dims2.size()) {
+ for (size_t i = 0; i < ellipsis_dims1.size() - ellipsis_dims2.size(); ++i) {
+ unsqueeze_axis2.push_back(ellipsis_dims2[0] + i);
+ }
+ }
+ ov::Output<ov::Node> unsqueeze_output1 = unsqueeze_input(input1, unsqueeze_axis1, subgraph_nodes);
+ ov::Output<ov::Node> unsqueeze_output2 = unsqueeze_input(input2, unsqueeze_axis2, subgraph_nodes);
+ inputs[input_ind1] = unsqueeze_output1;
+ inputs[input_ind2] = unsqueeze_output2;
+ return;
+ }
+}
+
/// \brief Contract two inputs of Einsum operation according to equation.
/// The result of the contraction is appended into input_nodes along with its subscript.
/// The input nodes for these two operands are removed from input_nodes along with their input
/// subscripts
///
-/// \param einsum_decompose_ptr A pointer to Einsum decomposing pass
/// \param input_nodes A vector of input nodes to Einsum operation
/// \param input_subscripts A vector of corresponding subscripts for the input nodes
/// \param output_subscript The output subscript
@@ -448,8 +917,7 @@ void reduce_input(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
/// \param subgraph_nodes A vector of operation nodes that is included into a
/// sub-graph decomposing Einsum that is needed for copy_runtime_info
///
-void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
- ov::OutputVector& input_nodes,
+void contract_two_inputs(ov::OutputVector& input_nodes,
std::vector<std::string>& input_subscripts,
const std::string& output_subscript,
size_t input_ind1,
@@ -468,9 +936,16 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
const auto& input_node1 = input_nodes[input_ind1];
const auto& input_node2 = input_nodes[input_ind2];
+ // unsqueeze inputs to have same rank of ellipsis for correct broadcasting
+ unsqueeze_ellipses_to_same_rank(input_nodes, input_subscripts, input_ind1, input_ind2, subgraph_nodes);
+
+ // extract diagonals in case repeated labels in the corresponding input subscripts
+ extract_diagonal(input_nodes, input_subscripts, input_ind1, subgraph_nodes);
+ extract_diagonal(input_nodes, input_subscripts, input_ind2, subgraph_nodes);
+
// reduce dimensions for input operands if possible
- reduce_input(einsum_decompose_ptr, input_nodes, input_subscripts, output_subscript, input_ind1, subgraph_nodes);
- reduce_input(einsum_decompose_ptr, input_nodes, input_subscripts, output_subscript, input_ind2, subgraph_nodes);
+ reduce_input(input_nodes, input_subscripts, output_subscript, input_ind1, subgraph_nodes);
+ reduce_input(input_nodes, input_subscripts, output_subscript, input_ind2, subgraph_nodes);
// step 0. split dimensions of both operands into three groups:
// 1. dimension indices with the same labels (in both subscripts) that are NOT reduced -
@@ -491,6 +966,7 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
std::vector<int64_t> common_labels_inds1, common_labels_inds2;
std::vector<int64_t> separate_labels_inds1, separate_labels_inds2;
std::vector<int64_t> reduced_labels_inds1, reduced_labels_inds2;
+ std::vector<std::string> common_labels, sep_labels1, sep_labels2, reduced_labels;
for (size_t label_ind = 0; label_ind < labels1.size(); ++label_ind) {
const auto& label = labels1[label_ind];
auto iter = std::find(labels2.begin(), labels2.end(), label);
@@ -501,13 +977,16 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
if (is_dim_reduced) {
reduced_labels_inds1.push_back(static_cast<int64_t>(label_ind));
reduced_labels_inds2.push_back(static_cast<int64_t>(iter - labels2.begin()));
+ reduced_labels.push_back(label);
} else {
common_labels_inds1.push_back(static_cast<int64_t>(label_ind));
common_labels_inds2.push_back(static_cast<int64_t>(iter - labels2.begin()));
+ common_labels.push_back(label);
}
} else {
separate_part1 += label;
separate_labels_inds1.push_back(static_cast<int64_t>(label_ind));
+ sep_labels1.push_back(label);
}
}
for (size_t label_ind = 0; label_ind < labels2.size(); ++label_ind) {
@@ -516,6 +995,7 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
if (iter == labels1.end()) {
separate_part2 += label;
separate_labels_inds2.push_back(static_cast<int64_t>(label_ind));
+ sep_labels2.push_back(label);
}
}
@@ -531,9 +1011,15 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
// unsqueeze the first operand with new dimensions in the tail
// and the number of them is equal to the number of separate labels in the second
// subscript
- int64_t unsqueeze_dim = labels1.size();
+
+ int64_t unsqueeze_dim = input_node1.get_partial_shape().size();
+ size_t axis_1_unsqueeze_amount = separate_labels_inds2.size();
+ if (separate_part2.find("...") != std::string::npos) {
+ size_t input2_ellipsis_rank = input_node2.get_partial_shape().size() - labels2.size();
+ axis_1_unsqueeze_amount += input2_ellipsis_rank;
+ }
std::vector<int64_t> unsqueeze_axis1;
- for (size_t label_ind = 0; label_ind < separate_labels_inds2.size(); ++label_ind) {
+ for (size_t label_ind = 0; label_ind < axis_1_unsqueeze_amount; ++label_ind) {
unsqueeze_axis1.push_back(unsqueeze_dim++);
}
const auto& unsqueeze_axis2 = separate_labels_inds1;
@@ -573,6 +1059,71 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
is_separate_first2);
transpose_input(input_nodes, input_subscripts, int_subscript2, input_ind2, subgraph_nodes);
+ auto matmul_operand1 = input_node1;
+ auto matmul_operand2 = input_node2;
+
+ size_t common_dims_begin, common_dims_end, reduced_dims_begin, reduced_dims_end, separate1_dims_begin,
+ separate1_dims_end;
+ compute_ranges(input_node1.get_partial_shape().rank(),
+ input_subscript1,
+ common_labels,
+ sep_labels1,
+ reduced_labels,
+ common_dims_begin,
+ common_dims_end,
+ separate1_dims_begin,
+ separate1_dims_end,
+ reduced_dims_begin,
+ reduced_dims_end,
+ is_separate_first1);
+
+ size_t common_dims_begin2, common_dims_end2, reduced_dims_begin2, reduced_dims_end2, separate2_dims_begin,
+ separate2_dims_end;
+ compute_ranges(input_node2.get_partial_shape().rank(),
+ input_subscript2,
+ common_labels,
+ sep_labels2,
+ reduced_labels,
+ common_dims_begin2,
+ common_dims_end2,
+ separate2_dims_begin,
+ separate2_dims_end,
+ reduced_dims_begin2,
+ reduced_dims_end2,
+ is_separate_first2);
+
+ ov::OutputVector common_sub_shape, separate1_sub_shape, separate2_sub_shape;
+
+ auto data_shape1 = std::make_shared<ov::op::v3::ShapeOf>(input_node1);
+ auto data_shape2 = std::make_shared<ov::op::v3::ShapeOf>(input_node2);
+ subgraph_nodes.insert(subgraph_nodes.end(), {data_shape1});
+ subgraph_nodes.insert(subgraph_nodes.end(), {data_shape2});
+ common_sub_shape = compute_sub_shape(data_shape1, common_dims_begin, common_dims_end, subgraph_nodes);
+ auto common_sub_shape2 = compute_sub_shape(data_shape2, common_dims_begin2, common_dims_end2, subgraph_nodes);
+ OPENVINO_ASSERT(common_sub_shape.size() == common_sub_shape2.size());
+ common_sub_shape = broadcast_merge_shapes(common_sub_shape, common_sub_shape2, subgraph_nodes);
+ auto reduced_sub_shape =
+ compute_sub_shape(data_shape1, reduced_dims_begin, reduced_dims_end, subgraph_nodes, false);
+ auto reduced_sub_shape2 =
+ compute_sub_shape(data_shape2, reduced_dims_begin2, reduced_dims_end2, subgraph_nodes, false);
+
+ reduced_sub_shape = broadcast_merge_shapes(reduced_sub_shape, reduced_sub_shape2, subgraph_nodes);
+
+ separate1_sub_shape = compute_sub_shape(data_shape1, separate1_dims_begin, separate1_dims_end, subgraph_nodes);
+ matmul_operand1 = broadcast_input(input_node1,
+ common_sub_shape,
+ separate1_sub_shape,
+ reduced_sub_shape,
+ is_separate_first1,
+ subgraph_nodes);
+ separate2_sub_shape = compute_sub_shape(data_shape2, separate2_dims_begin, separate2_dims_end, subgraph_nodes);
+ matmul_operand2 = broadcast_input(input_node2,
+ common_sub_shape,
+ separate2_sub_shape,
+ reduced_sub_shape,
+ is_separate_first2,
+ subgraph_nodes);
+
// step 2. reshape both operands so that separate labels and reduced labels are represented
// with just one dimension this is needed by MatMul operation requirement to operands
// format. For example, the shape must be in a format [B1, ..., Bm, X1, Y] or [B1, ..., Bm,
@@ -581,70 +1132,41 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
// this step is not needed for the operand if it satisfies to one of the requirements:
// 1. there is just one separate dimension and just one reduced dimension
// 2. there is no separate dimension, no common dimensions, and just one reduced dimension
- bool no_reshape_for_matmul1 =
- (reduced_labels_inds1.size() == 1 && separate_labels_inds1.size() == 1) ||
- (reduced_labels_inds1.size() == 1 && common_labels_inds1.size() == 0 && separate_labels_inds1.size() == 0);
- bool no_reshape_for_matmul2 =
- (reduced_labels_inds2.size() == 1 && separate_labels_inds2.size() == 1) ||
- (reduced_labels_inds2.size() == 1 && common_labels_inds2.size() == 0 && separate_labels_inds2.size() == 0);
- // reshape back after MatMul is not needed if one of two requrements satisfies for both operands:
+ const auto common_labels1_size = common_dims_end - common_dims_begin;
+ const auto common_labels2_size = common_dims_end2 - common_dims_begin2;
+ const auto reduced_labels1_size = reduced_dims_end - reduced_dims_begin;
+ const auto reduced_labels2_size = reduced_dims_end2 - reduced_dims_begin2;
+ const auto separate_labels1_size = separate1_dims_end - separate1_dims_begin;
+ const auto separate_labels2_size = separate2_dims_end - separate2_dims_begin;
+ bool no_reshape_for_matmul1 = (reduced_labels1_size == 1 && separate_labels1_size == 1) ||
+ (reduced_labels1_size == 1 && common_labels1_size == 0 && separate_labels1_size == 0);
+ bool no_reshape_for_matmul2 = (reduced_labels2_size == 1 && separate_labels2_size == 1) ||
+ (reduced_labels2_size == 1 && common_labels2_size == 0 && separate_labels2_size == 0);
+ // reshape back after MatMul is not needed if one of two requirements satisfies for both operands:
// 1. there is just one separate dimension
// 2. there is no separate dimension and no common dimensions present.
// If there is no separate dimension and common dimensions present, reshape is needed
// because auxiliary separate dimension has been added by Unsqueeze operation
// in the purpose for MatMul
- bool no_reshape_back1 =
- (separate_labels_inds1.size() == 1) || (common_labels_inds1.size() == 0 && separate_labels_inds1.size() == 0);
- bool no_reshape_back2 =
- (separate_labels_inds2.size() == 1) || (common_labels_inds2.size() == 0 && separate_labels_inds2.size() == 0);
+ bool no_reshape_back1 = (separate_labels1_size == 1) || (common_labels1_size == 0 && separate_labels1_size == 0);
+ bool no_reshape_back2 = (separate_labels2_size == 1) || (common_labels2_size == 0 && separate_labels2_size == 0);
bool no_reshape_after_matmul = no_reshape_back1 && no_reshape_back2;
+ if (no_reshape_for_matmul1 == false || no_reshape_after_matmul == false) {
+ matmul_operand1 = reshape_input_for_matmul(matmul_operand1,
+ common_sub_shape,
+ separate1_sub_shape,
+ reduced_sub_shape,
+ is_separate_first1,
+ subgraph_nodes);
+ }
- auto matmul_operand1 = input_node1;
- auto matmul_operand2 = input_node2;
- int64_t common_dims_begin = 0;
- int64_t common_dims_end = common_labels_inds1.size();
- ov::OutputVector common_sub_shape, separate1_sub_shape, separate2_sub_shape;
- if (no_reshape_for_matmul1 == false || no_reshape_for_matmul2 == false) {
- auto data_shape1 = std::make_shared<ov::op::v3::ShapeOf>(input_node1);
- common_sub_shape = compute_sub_shape(data_shape1, common_dims_begin, common_dims_end, subgraph_nodes);
- int64_t reduced_dims_begin = (is_separate_first1 ? common_labels_inds1.size() + separate_labels_inds1.size()
- : common_labels_inds1.size());
- int64_t reduced_dims_end = reduced_dims_begin + reduced_labels_inds1.size();
- auto reduced_sub_shape_prod =
- compute_sub_shape(data_shape1, reduced_dims_begin, reduced_dims_end, subgraph_nodes, true);
-
- if (no_reshape_for_matmul1 == false || no_reshape_after_matmul == false) {
- int64_t separate1_dims_begin =
- (is_separate_first1 ? common_labels_inds1.size()
- : common_labels_inds1.size() + reduced_labels_inds1.size());
- int64_t separate1_dims_end = separate1_dims_begin + separate_labels_inds1.size();
- separate1_sub_shape =
- compute_sub_shape(data_shape1, separate1_dims_begin, separate1_dims_end, subgraph_nodes);
- matmul_operand1 = reshape_input_for_matmul(input_node1,
- common_sub_shape,
- separate1_sub_shape,
- reduced_sub_shape_prod,
- is_separate_first1,
- subgraph_nodes);
- }
-
- if (no_reshape_for_matmul2 == false || no_reshape_after_matmul == false) {
- auto data_shape2 = std::make_shared<ov::op::v3::ShapeOf>(input_node2);
- int64_t separate2_dims_begin =
- (is_separate_first2 ? common_labels_inds2.size()
- : common_labels_inds2.size() + reduced_labels_inds2.size());
- int64_t separate2_dims_end = separate2_dims_begin + separate_labels_inds2.size();
- separate2_sub_shape =
- compute_sub_shape(data_shape2, separate2_dims_begin, separate2_dims_end, subgraph_nodes);
- matmul_operand2 = reshape_input_for_matmul(input_node2,
- common_sub_shape,
- separate2_sub_shape,
- reduced_sub_shape_prod,
- is_separate_first2,
- subgraph_nodes);
- subgraph_nodes.insert(subgraph_nodes.end(), {data_shape2});
- }
- subgraph_nodes.insert(subgraph_nodes.end(), {data_shape1});
+ if (no_reshape_for_matmul2 == false || no_reshape_after_matmul == false) {
+ matmul_operand2 = reshape_input_for_matmul(matmul_operand2,
+ common_sub_shape,
+ separate2_sub_shape,
+ reduced_sub_shape,
+ is_separate_first2,
+ subgraph_nodes);
}
// step 3. apply MatMul operation for formatted inputs
@@ -654,8 +1176,11 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
// step 4. reshape back by unrolling dimensions corresponding to separate labels if needed
// now dimensions corresponding to reduced labels are reduced by the MatMul operation
- std::string resultant_subscript =
- input_subscript1.substr(common_dims_begin, common_dims_end) + separate_part1 + separate_part2;
+ common_part = "";
+ for (const auto& common_label : common_labels) {
+ common_part += common_label;
+ }
+ const std::string resultant_subscript = common_part + separate_part1 + separate_part2;
if (no_reshape_after_matmul) {
// this is a case when Reshape is not needed after MatMul operation
// since there are no collapsed (or auxiliary added) separated dimensions
@@ -667,12 +1192,12 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
new_shape.insert(new_shape.end(), separate2_sub_shape.begin(), separate2_sub_shape.end());
auto result_shape_op = std::make_shared<ov::op::v0::Concat>(new_shape, 0);
- // if new shape is possible to compute on the shape infer stage, insert Constant node immediatelly
+ // if new shape is possible to compute on the shape infer stage, insert Constant node immediately
// in order to prevent repeated computing during constant-folding pass
std::shared_ptr<ov::op::v1::Reshape> result_op;
if (auto new_shape_const = ov::util::get_constant_from_source(result_shape_op)) {
result_op = std::make_shared<ov::op::v1::Reshape>(matmul->output(0), new_shape_const, false);
- subgraph_nodes.insert(subgraph_nodes.end(), {new_shape_const});
+ subgraph_nodes.insert(subgraph_nodes.end(), {result_shape_op, new_shape_const});
} else {
result_op = std::make_shared<ov::op::v1::Reshape>(matmul->output(0), result_shape_op->output(0), false);
subgraph_nodes.insert(subgraph_nodes.end(), {result_shape_op});
@@ -691,47 +1216,117 @@ void contract_two_inputs(ov::pass::EinsumDecomposition* einsum_decompose_ptr,
// update a vector of nodes for copy_runtime_info
subgraph_nodes.insert(subgraph_nodes.end(), {matmul});
}
+
+/// \brief Adjusts input subscripts and nodes to handle 0-dimensional ellipsis in Einsum operations.
+///
+/// Handle ellipses labels that do not represent any dimensions:
+/// 1. If there is no ellipsis in the input subscripts, remove ellipsis from the output subscript.
+/// 2. If all ellipses in the input subscripts do not represent any dimensions, remove ellipses from all subscripts.
+/// 3. If there is at least one ellipsis that represents dimension, unsqueeze ellipses that do not represent any,
+///
+/// \param input_nodes A vector of input nodes for the Einsum operation.
+/// \param input_subscripts A vector of input subscripts corresponding to the input nodes.
+/// \param output_subscript The output subscript for the Einsum operation.
+/// \param subgraph_nodes A vector to store nodes created during the subgraph transformation.
+void fix_inputs_with_0d_ellipsis(ov::OutputVector& input_nodes,
+ std::vector<std::string>& input_subscripts,
+ std::string& output_subscript,
+ ov::NodeVector& subgraph_nodes) {
+ static const std::string ellipsis = "...";
+ bool has_ellipsis = false;
+ bool all_no_ellipsis_or_empty = true;
+
+ for (size_t i = 0; i < input_nodes.size(); ++i) {
+ const auto& labels = ov::op::v7::Einsum::extract_labels(input_subscripts[i]);
+ bool has_ellipsis_in_input = std::find(labels.begin(), labels.end(), ellipsis) != labels.end();
+ has_ellipsis |= has_ellipsis_in_input;
+ all_no_ellipsis_or_empty &=
+ !has_ellipsis_in_input || (input_nodes[i].get_partial_shape().size() + 1 == labels.size());
+ }
+
+ if (!has_ellipsis) {
+ if (output_subscript.find(ellipsis) != std::string::npos) {
+ output_subscript.erase(output_subscript.find(ellipsis), ellipsis.size());
+ }
+ } else if (all_no_ellipsis_or_empty) {
+ for (auto& subscript : input_subscripts) {
+ if (subscript.find(ellipsis) != std::string::npos) {
+ subscript.erase(subscript.find(ellipsis), ellipsis.size());
+ }
+ }
+ if (output_subscript.find(ellipsis) != std::string::npos) {
+ output_subscript.erase(output_subscript.find(ellipsis), ellipsis.size());
+ }
+ } else {
+ for (size_t i = 0; i < input_nodes.size(); ++i) {
+ const auto& labels = ov::op::v7::Einsum::extract_labels(input_subscripts[i]);
+ if (std::find(labels.begin(), labels.end(), ellipsis) != labels.end() &&
+ input_nodes[i].get_partial_shape().size() + 1 == labels.size()) {
+ input_nodes[i] = unsqueeze_input(
+ input_nodes[i],
+ {static_cast<int64_t>(
+ std::distance(labels.begin(), std::find(labels.begin(), labels.end(), ellipsis)))},
+ subgraph_nodes);
+ }
+ }
+ }
+}
} // namespace
+/// \brief Constructor for the EinsumDecomposition transformation pass.
+///
+/// This transformation decomposes the Einsum operation into a sequence of more basic operations.
+/// It matches the Einsum operation and replaces it with a sub-graph of operations that perform
+/// the same computation.
+///
+/// The transformation follows these steps:
+/// 1. Parse the Einsum equation to extract input and output subscripts.
+/// 2. Check if the transformation is applicable by ensuring all input nodes have static ranks.
+/// 3. Compute the optimal path for contracting pairs of operands.
+/// 4. Fix inputs where ellipsis does not contain any dimensions.
+/// 5. Contract inputs by Einsum until only one input remains.
+/// 6. Extract the diagonal for the single remaining operand.
+/// 7. Reduce dimensions for the remaining input node.
+/// 8. Transpose dimensions to match the layout required by the output subscript.
+/// 9. Replace the original Einsum node with the last node from the decomposed sub-graph,
+/// preserving the original node's name and runtime information.
ov::pass::EinsumDecomposition::EinsumDecomposition() {
- // NOTE: The transformation is applicable if Einsum equation does not contain ellipsis label
- // and does not contain subscripts with repeated labels.
- // For example, the transformation is applicable to Einsum with equation="abc,bd->ad"
- // but not applicable to a case with equation="aabc,bd->ad" due to repeated labels
- // in the first input subscript.
MATCHER_SCOPE(EinsumDecomposition);
auto einsum = ov::pass::pattern::wrap_type<ov::op::v7::Einsum>();
- matcher_pass_callback callback = [this](ov::pass::pattern::Matcher& m) {
+ matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {
auto einsum_node = ov::as_type_ptr<ov::op::v7::Einsum>(m.get_match_root());
if (!einsum_node) {
return false;
}
+ // Parse the Einsum equation to get input and output subscripts
auto equation = einsum_node->get_equation();
std::vector<std::string> input_subscripts;
std::string output_subscript;
ov::op::v7::Einsum::parse_equation(equation, input_subscripts, output_subscript);
- // check that the transformation is applicable
- if (std::any_of(input_subscripts.cbegin(), input_subscripts.cend(), [](const std::string& subscript) {
- return is_subscript_applicable(subscript) == false;
- })) {
- return false;
- }
-
// create a list of input nodes with preserving their order
// and a vector of sub-graph nodes for copy_runtime_info
ov::OutputVector input_nodes = einsum_node->input_values();
ov::NodeVector subgraph_nodes;
+ // Check if the transformation is applicable by ensuring all input nodes have static ranks
+ if (std::any_of(input_nodes.cbegin(), input_nodes.cend(), [](ov::Output<Node> node) {
+ return node.get_partial_shape().rank().is_dynamic();
+ })) {
+ return false;
+ }
+
// compute einsum path that is used to contract a pair of operands
// in more optimal order
auto einsum_path = compute_einsum_path(einsum_node);
+ // fix inputs where ellipsis does not contain any dimensions
+ fix_inputs_with_0d_ellipsis(input_nodes, input_subscripts, output_subscript, subgraph_nodes);
+
// contract inputs by Einsum until just one is remained
for (auto const& inds_pair : einsum_path) {
- contract_two_inputs(this,
- input_nodes,
+ contract_two_inputs(input_nodes,
input_subscripts,
output_subscript,
inds_pair.first,
@@ -739,13 +1334,15 @@ ov::pass::EinsumDecomposition::EinsumDecomposition() {
subgraph_nodes);
}
- // reduce dimensions for the remained input node
+ // Ensure only one input node remains after contraction
OPENVINO_ASSERT(input_nodes.size() == 1);
- reduce_input(this, input_nodes, input_subscripts, output_subscript, 0, subgraph_nodes);
+ // extract diagonal for the single operand
+ extract_diagonal(input_nodes, input_subscripts, 0, subgraph_nodes);
+ // reduce dimensions for the remained input node
+ reduce_input(input_nodes, input_subscripts, output_subscript, 0, subgraph_nodes);
// transpose dimensions to layout required by the output subscript
transpose_input(input_nodes, input_subscripts, output_subscript, 0, subgraph_nodes);
-
// replace the original Einsum node with the last node from decomposing sub-graph
// preserve the original node name
auto last_node = input_nodes[0].get_node_shared_ptr();
diff --git a/src/common/transformations/tests/common_optimizations/transpose_reshape_elimination_for_matmul.cpp b/src/common/transformations/tests/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
index 3238c7a05a9..ca5cb31c8e7 100644
--- a/src/common/transformations/tests/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
+++ b/src/common/transformations/tests/common_optimizations/transpose_reshape_elimination_for_matmul.cpp
@@ -138,11 +138,21 @@ TEST_F(TransformationTestsF, TransposeReshapeEliminationForMatMul_Einsum) {
{
auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto broadcast_shape_constant_1 =
+ std::make_shared<ov::op::v0::Constant>(element::i64, Shape{data_shape_1.size()}, data_shape_1);
+ auto broadcast_shape_constant_2 =
+ std::make_shared<ov::op::v0::Constant>(element::i64, Shape{data_shape_2.size()}, data_shape_2);
+ auto broadcast_1 = std::make_shared<ov::op::v3::Broadcast>(data_1,
+ broadcast_shape_constant_1,
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ auto broadcast_2 = std::make_shared<ov::op::v3::Broadcast>(data_2,
+ broadcast_shape_constant_2,
+ ov::op::BroadcastType::BIDIRECTIONAL);
// for some cases Reshape may be first input for Matmul
auto shape_constant =
std::make_shared<ov::op::v0::Constant>(element::i64, Shape{data_shape_1.size()}, data_shape_1);
- auto reshape = std::make_shared<ov::op::v1::Reshape>(data_1, shape_constant, false);
- auto matmul = std::make_shared<ov::op::v0::MatMul>(reshape, data_2, false, false);
+ auto reshape = std::make_shared<ov::op::v1::Reshape>(broadcast_1, shape_constant, false);
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(reshape, broadcast_2, false, false);
model_ref = std::make_shared<Model>(NodeVector{matmul}, ParameterVector{data_1, data_2});
}
}
diff --git a/src/common/transformations/tests/op_conversions/einsum_decomposition_test.cpp b/src/common/transformations/tests/op_conversions/einsum_decomposition_test.cpp
new file mode 100644
index 00000000000..bcd5cabd376
--- /dev/null
+++ b/src/common/transformations/tests/op_conversions/einsum_decomposition_test.cpp
@@ -0,0 +1,670 @@
+// // Copyright (C) 2018-2025 Intel Corporation
+// // SPDX-License-Identifier: Apache-2.0
+// //
+
+#include "transformations/op_conversions/einsum_decomposition.hpp"
+
+#include <gtest/gtest.h>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/opsets/opset7.hpp"
+#include "openvino/pass/constant_folding.hpp"
+#include "transformations/utils/gen_pattern.hpp"
+
+using namespace ov;
+namespace {
+using namespace ov::gen_pattern;
+std::shared_ptr<ov::Node> extract_subshape_from_shape(const std::shared_ptr<ov::Node>& shape_node,
+ size_t begin,
+ size_t end) {
+ auto const_begin = makeConst(element::i64, ov::Shape({1}), {begin});
+ auto const_end = makeConst(element::i64, ov::Shape({1}), {end});
+ auto const_1 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto subshape = makeOP<opset1::StridedSlice>({shape_node, const_begin, const_end, const_1},
+ {{"begin_mask", {0}},
+ {"end_mask", {0}},
+ {"new_axis_mask", {}},
+ {"shrink_axis_mask", {}},
+ {"ellipsis_mask", {}}});
+ return subshape;
+}
+
+std::shared_ptr<ov::Node> broadcast_merge_shapes(const std::shared_ptr<ov::Node>& shape_node_lhs,
+ const std::shared_ptr<ov::Node>& shape_node_rhs) {
+ auto broadcasted_shapes = makeOP<opset1::Maximum>({shape_node_lhs, shape_node_rhs}, {{"auto_broadcast", "numpy"}});
+ return broadcasted_shapes;
+}
+///
+/// \brief Extracts the diagonal elements from the input tensor based on the specified repeated and unrepeated indices.
+///
+/// This function performs a series of operations to extract the diagonal elements from the input tensor `data`.
+/// It first transposes the input tensor based on the repeated and unrepeated indices, then reshapes and pads the tensor
+/// to isolate the diagonal elements. Finally, it gathers and squeezes the tensor to obtain the diagonal elements.
+///
+/// \param data A shared pointer to the input tensor node.
+/// \param indices_of_repeated_labels A vector of vectors containing the indices of repeated labels.
+/// \param unrepeated_indices A vector containing the indices of unrepeated labels. Default is an empty vector.
+/// \return A shared pointer to the node representing the diagonal elements of the input tensor.
+std::shared_ptr<ov::Node> extract_diagonal(const std::shared_ptr<ov::Node>& data,
+ const std::vector<std::vector<size_t>>& indices_of_repeated_labels,
+ const std::vector<size_t>& unrepeated_indices = {}) {
+ std::vector<size_t> transpose_group_labels_target;
+ std::vector<size_t> reduced_axes;
+
+ // Prepare the target order for transposing the input tensor
+ for (size_t i = 0; i < indices_of_repeated_labels.size(); i++) {
+ auto repeated_label = indices_of_repeated_labels[i];
+ size_t step = i * 2;
+ reduced_axes.push_back(step + 1);
+ transpose_group_labels_target.insert(transpose_group_labels_target.end(),
+ repeated_label.begin(),
+ repeated_label.end());
+ }
+ transpose_group_labels_target.insert(transpose_group_labels_target.end(),
+ unrepeated_indices.begin(),
+ unrepeated_indices.end());
+
+ // Transpose the input tensor to group repeated and unrepeated labels
+ auto const_transpose_group_labels_target =
+ makeConst(element::i64, ov::Shape({transpose_group_labels_target.size()}), transpose_group_labels_target);
+ auto transpose_group_labels = std::make_shared<ov::op::v1::Transpose>(data, const_transpose_group_labels_target);
+
+ // Get the shape of the transposed tensor
+ auto shapeof_transposed_data = std::make_shared<ov::op::v3::ShapeOf>(transpose_group_labels);
+
+ auto const_0 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape({1}), {0});
+ auto const_1 = ov::op::v0::Constant::create(ov::element::i64, ov::Shape({1}), {1});
+
+ ov::NodeVector flattened_shapes;
+ ov::NodeVector unflattened_shapes;
+ ov::NodeVector begins;
+ ov::NodeVector ends;
+
+ std::vector<size_t> dim_iota(transpose_group_labels_target.size());
+ std::iota(dim_iota.begin(), dim_iota.end(), 0);
+
+ size_t dimension_iter = 0;
+
+ // Process each repeated label group
+ for (auto repeated_label : indices_of_repeated_labels) {
+ auto num_repeats = repeated_label.size();
+ std::vector<size_t> label_indices = {dim_iota.begin() + dimension_iter,
+ dim_iota.begin() + dimension_iter + num_repeats};
+ auto repeated_label_indices_len = ov::op::v0::Constant::create(ov::element::i64, {}, {num_repeats});
+ auto repeated_label_indices =
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape({num_repeats}), label_indices);
+ auto repeated_dimensions =
+ std::make_shared<ov::op::v7::Gather>(shapeof_transposed_data, repeated_label_indices, const_0);
+ auto repeated_dimension = std::make_shared<ov::op::v7::Gather>(repeated_dimensions, const_0, const_0);
+ auto range_max_val = std::make_shared<ov::op::v1::Power>(repeated_dimension, repeated_label_indices_len);
+ auto step_numerator = std::make_shared<ov::op::v1::Subtract>(range_max_val, const_1);
+ auto step_denominator = std::make_shared<ov::op::v1::Subtract>(repeated_dimension, const_1);
+ auto step_denominator_but_not_0 = std::make_shared<ov::op::v1::Maximum>(step_denominator, const_1);
+ auto step_numerator_but_not_0 = std::make_shared<ov::op::v1::Maximum>(step_numerator, const_1);
+ auto step = std::make_shared<ov::op::v1::Divide>(step_numerator_but_not_0, step_denominator_but_not_0);
+ auto end = std::make_shared<ov::op::v1::Subtract>(step, const_1);
+ // Flatten all dimensions of single repeated label.
+ auto reduced_size = std::make_shared<ov::op::v1::ReduceProd>(repeated_dimensions, const_0, true);
+ flattened_shapes.push_back(reduced_size);
+ // Reshape the tensor to restore the original shape with diagonal elements isolated and remainder.
+ unflattened_shapes.push_back(repeated_dimension);
+ unflattened_shapes.push_back(step);
+ begins.push_back(const_0);
+ ends.push_back(end);
+ dimension_iter += num_repeats;
+ }
+
+ // Process unrepeated labels, do not perform flatten or pads on dimensions.
+ std::vector<size_t> unrepeated_indices_after_transpose = {dim_iota.begin() + dimension_iter, dim_iota.end()};
+ const auto& unrepeated_dimensions_indices =
+ ov::op::v0::Constant::create(ov::element::i64,
+ {unrepeated_indices_after_transpose.size()},
+ unrepeated_indices_after_transpose);
+ const auto unrepeated_dimensions =
+ std::make_shared<ov::op::v7::Gather>(shapeof_transposed_data, unrepeated_dimensions_indices, const_0);
+ begins.insert(begins.end(), unrepeated_indices_after_transpose.size(), const_0);
+ ends.insert(ends.end(), unrepeated_indices_after_transpose.size(), const_0);
+ flattened_shapes.push_back(unrepeated_dimensions);
+ unflattened_shapes.push_back(unrepeated_dimensions);
+
+ // Flatten the tensor to isolate diagonal elements
+ auto flatten_labels_shape_target = std::make_shared<ov::op::v0::Concat>(flattened_shapes, 0);
+ auto flatten_labels =
+ std::make_shared<ov::op::v1::Reshape>(transpose_group_labels, flatten_labels_shape_target, false);
+
+ // Pad the tensor to prepare for gathering diagonal elements
+ auto pad_begin = std::make_shared<ov::op::v0::Concat>(begins, 0);
+ auto pad_end = std::make_shared<ov::op::v0::Concat>(ends, 0);
+ auto pad = std::make_shared<ov::op::v1::Pad>(flatten_labels, pad_begin, pad_end, ov::op::PadMode::CONSTANT);
+
+ // Unflatten the tensor to restore the original shape with diagonal elements isolated
+ auto unflatten_labels_shape_target = std::make_shared<ov::op::v0::Concat>(unflattened_shapes, 0);
+ auto unflatten_labels = std::make_shared<ov::op::v1::Reshape>(pad, unflatten_labels_shape_target, false);
+
+ // Gather the diagonal elements
+ std::shared_ptr<ov::Node> gather = unflatten_labels;
+ for (auto axis : reduced_axes) {
+ auto axis_const = ov::op::v0::Constant::create(ov::element::i64, ov::Shape({1}), {axis});
+ gather = std::make_shared<ov::op::v7::Gather>(gather, const_0, axis_const);
+ }
+
+ // Squeeze the tensor to remove the reduced dimensions
+ auto squeeze_reduced_axes =
+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape({reduced_axes.size()}), reduced_axes);
+ auto diagonal = std::make_shared<ov::op::v0::Squeeze>(gather, squeeze_reduced_axes);
+
+ return diagonal;
+}
+
+} // namespace
+
+TEST_F(TransformationTestsF, Einsum_2in_matmul) {
+ PartialShape data_shape_1{5, 2};
+ PartialShape data_shape_2{10, 1, 25};
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto einsum = std::make_shared<opset7::Einsum>(OutputVector{data_1, data_2}, "kl,mlj->mkj");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1, data_2});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ }
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+
+ // Transpose data_2 so that common labels, separated and reduced labels are grouped for both operands.
+ auto order_2 = ov::op::v0::Constant::create(element::i64, {3}, {0, 2, 1});
+ auto transpose_2 = std::make_shared<ov::op::v1::Transpose>(data_2, order_2);
+
+ // Broadcast data_1 and data_2 to common broadcasted shapes for common and reduced subshapes.
+ // Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ auto broadcast_shape_constant_1 =
+ ov::op::v0::Constant::create(element::i64, Shape{data_shape_1.size()}, {5, 2});
+ auto broadcast_shape_constant_2 =
+ ov::op::v0::Constant::create(element::i64, Shape{data_shape_2.size()}, {10, 25, 2});
+ auto broadcast_1 = std::make_shared<ov::op::v3::Broadcast>(data_1,
+ broadcast_shape_constant_1,
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ auto broadcast_2 = std::make_shared<ov::op::v3::Broadcast>(transpose_2,
+ broadcast_shape_constant_2,
+ ov::op::BroadcastType::BIDIRECTIONAL);
+ // Optionally reshape broadcasted data_1 and data_2 so separate and reduced labels are represented by one
+ // dimension. Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ auto shape_constant_1 = ov::op::v0::Constant::create(element::i64, Shape{2}, {5, 2});
+ auto shape_constant_2 = ov::op::v0::Constant::create(element::i64, Shape{2}, {250, 2});
+ auto reshape_1 = std::make_shared<ov::op::v1::Reshape>(broadcast_1, shape_constant_1, false);
+ auto reshape_2 = std::make_shared<ov::op::v1::Reshape>(broadcast_2, shape_constant_2, false);
+ // Apply MatMul operation for formatted inputs.
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(reshape_1, reshape_2, false, true);
+ // Optionally reshape back by unrolling dimensions corresponding to separate labels if needed.
+ // Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ auto shape_out = ov::op::v0::Constant::create(element::i64, {3}, {5, 10, 25});
+ auto reshape_out = std::make_shared<ov::op::v1::Reshape>(matmul, shape_out, false);
+ // Transpose to the original order of output labels.
+ auto order_out = ov::op::v0::Constant::create(element::i64, {3}, {1, 0, 2});
+ auto transpose_out = std::make_shared<ov::op::v1::Transpose>(reshape_out, order_out);
+
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1, data_2});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_2in_matmul_dynamic) {
+ PartialShape data_shape_1 = PartialShape::dynamic(2);
+ PartialShape data_shape_2 = PartialShape::dynamic(3);
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto einsum = std::make_shared<opset7::Einsum>(OutputVector{data_1, data_2}, "kl,mlj->mkj");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1, data_2});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ // Transpose data_2 so that common labels, separated and reduced labels are grouped for both operands.
+ auto Constant_485 = makeConst(element::i64, ov::Shape({3}), {0, 2, 1});
+ auto Transpose_486 = makeOP<opset1::Transpose>({data_2, Constant_485});
+ // Get shapes of data_1 and data_2.
+ auto ShapeOf_data_1 = makeOP<opset3::ShapeOf>({data_1}, {{"output_type", "i64"}});
+ auto ShapeOf_data_2 = makeOP<opset3::ShapeOf>({Transpose_486}, {{"output_type", "i64"}});
+
+ // Get reduced subshape for data_1.
+ auto reduced1 = extract_subshape_from_shape(ShapeOf_data_1, 1, 2);
+
+ // Get reduced subshape for data_2.
+ auto reduced2 = extract_subshape_from_shape(ShapeOf_data_2, 2, 3);
+
+ // broadcast_merge_shapes(reduced1, reduced2)
+ auto reduced_subshape_broadcast_merge_shapes = broadcast_merge_shapes(reduced1, reduced2);
+
+ // Extract separate subshape for data_1.
+ auto separate1_subshape = extract_subshape_from_shape(ShapeOf_data_1, 0, 1);
+
+ // Extract separate subshape for data_2.
+ auto separate2_subshape = extract_subshape_from_shape(ShapeOf_data_2, 0, 2);
+
+ // Broadcast data_1 and data_2 based on caluculated subshapes.
+ auto Concat_512 =
+ makeOP<opset1::Concat>({separate1_subshape, reduced_subshape_broadcast_merge_shapes}, {{"axis", 0}});
+ auto Broadcast_data_1 = makeOP<opset3::Broadcast>({data_1, Concat_512}, {{"mode", "bidirectional"}});
+ auto Concat_521 =
+ makeOP<opset1::Concat>({separate2_subshape, reduced_subshape_broadcast_merge_shapes}, {{"axis", 0}});
+ auto Broadcast_data_2 = makeOP<opset3::Broadcast>({Transpose_486, Concat_521}, {{"mode", "bidirectional"}});
+
+ // Optionally reshape broadcasted data_1 and data_2 so separate and reduced labels are represented by one
+ // dimension. Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ // Reshape 1
+ auto Constant_525 = makeConst(element::i64, ov::Shape({1}), {0});
+ // Reduce separate and reduced
+ auto Separate1_subshape_red =
+ makeOP<opset1::ReduceProd>({separate1_subshape, Constant_525}, {{"keep_dims", true}});
+ auto reduced1_subshape_red =
+ makeOP<opset1::ReduceProd>({reduced_subshape_broadcast_merge_shapes, {0}}, {{"keep_dims", true}});
+ // Merge subshapes
+ auto reshape_subshape1 = makeOP<opset1::Concat>({Separate1_subshape_red, reduced1_subshape_red}, {{"axis", 0}});
+ auto Reshape_1 = makeOP<opset1::Reshape>({Broadcast_data_1, reshape_subshape1}, {{"special_zero", false}});
+ // Reshape 2
+ auto Constant_569 = makeConst(element::i64, ov::Shape({1}), {0});
+ // Reduce separate and reduced
+ auto Separate2_subshape_red =
+ makeOP<opset1::ReduceProd>({separate2_subshape, Constant_569}, {{"keep_dims", true}});
+ auto Reduced2_subshape_red =
+ makeOP<opset1::ReduceProd>({reduced_subshape_broadcast_merge_shapes, {0}}, {{"keep_dims", true}});
+ // Merge subshapes
+ auto reshape_subshape2 = makeOP<opset1::Concat>({Separate2_subshape_red, Reduced2_subshape_red}, {{"axis", 0}});
+ auto Reshape_2 = makeOP<opset1::Reshape>({Broadcast_data_2, reshape_subshape2}, {{"special_zero", false}});
+
+ // Apply MatMul operation for formatted inputs.
+ auto matmul = std::make_shared<ov::op::v0::MatMul>(Reshape_1, Reshape_2, false, true);
+
+ // Optionally reshape back by unrolling dimensions corresponding to separate labels if needed.
+ // Target subshapes are calculated broadcast_merge_shapes function and concatenated.
+ auto shape_out = makeOP<opset1::Concat>({separate1_subshape, separate2_subshape}, {{"axis", 0}});
+ auto reshape_out = std::make_shared<ov::op::v1::Reshape>(matmul, shape_out, false);
+ // Transpose to the original order of output labels.
+ auto order_out = ov::op::v0::Constant::create(element::i64, {3}, {1, 0, 2});
+ auto transpose_out = std::make_shared<ov::op::v1::Transpose>(reshape_out, order_out);
+
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1, data_2});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_2in_matmul_ellipsis_dynamic) {
+ PartialShape data_shape_1 = PartialShape::dynamic(2);
+ PartialShape data_shape_2 = PartialShape::dynamic(5);
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto einsum = std::make_shared<opset7::Einsum>(OutputVector{data_1, data_2}, "kl...,m...lj->mkj");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1, data_2});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ // Process data_1
+ // data_1 contains no dimensions at ellipsis label, unsqueeze to allow for broadcasting
+ auto Constant_1200 = makeConst(element::i64, ov::Shape({1}), {2});
+ auto Unsqueeze_1201 = makeOP<opset1::Unsqueeze>({data_1, Constant_1200});
+ // Match ranks of dimensions covered by ellipsis labels
+ auto Constant_1202 = makeConst(element::i64, ov::Shape({1}), {2});
+ auto data_1_processed = makeOP<opset1::Unsqueeze>({Unsqueeze_1201, Constant_1202});
+ // Process data_2
+ // Transpose data_2 so that common labels, separated and reduced labels are grouped for both operands.
+ auto Constant_1204 = makeConst(element::i64, ov::Shape({5}), {0, 4, 3, 1, 2});
+ auto data_2_processed = makeOP<opset1::Transpose>({data_2, Constant_1204});
+
+ // Get shapes for data_1 and data_2
+ auto ShapeOf_data_1 = makeOP<opset3::ShapeOf>({data_1_processed}, {{"output_type", "i64"}});
+ auto ShapeOf_data_2 = makeOP<opset3::ShapeOf>({data_2_processed}, {{"output_type", "i64"}});
+
+ // Get reduced subshape for data_1.
+ auto reduced1 = extract_subshape_from_shape(ShapeOf_data_1, 1, 4);
+
+ // Get reduced subshape for data_2.
+ auto reduced2 = extract_subshape_from_shape(ShapeOf_data_2, 2, 5);
+
+ // broadcast_merge_shapes(reduced1, reduced_2)
+ auto reduced_subshape_broadcast_merge_shapes = broadcast_merge_shapes(reduced1, reduced2);
+
+ // Extract separate subshape for data_1.
+ auto separate1_subshape = extract_subshape_from_shape(ShapeOf_data_1, 0, 1);
+
+ // Extract separate subshape for data_2.
+ auto separate2_subshape = extract_subshape_from_shape(ShapeOf_data_2, 0, 2);
+
+ // Broadcast data_1 and data_2 based on caluculated subshapes.
+ auto Concat_1231 =
+ makeOP<opset1::Concat>({separate1_subshape, reduced_subshape_broadcast_merge_shapes}, {{"axis", 0}});
+ auto Broadcast_data_1 = makeOP<opset3::Broadcast>({data_1_processed, Concat_1231}, {{"mode", "bidirectional"}});
+ auto Concat_1240 =
+ makeOP<opset1::Concat>({separate2_subshape, reduced_subshape_broadcast_merge_shapes}, {{"axis", 0}});
+ auto Broadcast_data_2 = makeOP<opset3::Broadcast>({data_2_processed, Concat_1240}, {{"mode", "bidirectional"}});
+
+ // Optionally reshape broadcasted data_1 and data_2 so separate and reduced labels are represented by one
+ // dimension. Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ // Reshape 1
+ auto Constant_1244 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Separate1_subshape_red =
+ makeOP<opset1::ReduceProd>({separate1_subshape, Constant_1244}, {{"keep_dims", true}});
+ auto reduced1_subshape_red =
+ makeOP<opset1::ReduceProd>({reduced_subshape_broadcast_merge_shapes, {0}}, {{"keep_dims", true}});
+ auto reshape1_shape = makeOP<opset1::Concat>({Separate1_subshape_red, reduced1_subshape_red}, {{"axis", 0}});
+ auto Reshape_1 = makeOP<opset1::Reshape>({Broadcast_data_1, reshape1_shape}, {{"special_zero", false}});
+
+ // Reshape 2
+ auto Constant_1302 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Separate2_subshape_red =
+ makeOP<opset1::ReduceProd>({separate2_subshape, Constant_1302}, {{"keep_dims", true}});
+ auto Reduced2_subshape_red =
+ makeOP<opset1::ReduceProd>({reduced_subshape_broadcast_merge_shapes, {0}}, {{"keep_dims", true}});
+ auto reshape2_shape = makeOP<opset1::Concat>({Separate2_subshape_red, Reduced2_subshape_red}, {{"axis", 0}});
+ auto Reshape_2 = makeOP<opset1::Reshape>({Broadcast_data_2, reshape2_shape}, {{"special_zero", false}});
+ // Apply MatMul operation for formatted inputs.
+ auto matmul = makeOP<opset1::MatMul>({Reshape_1, Reshape_2}, {{"transpose_a", false}, {"transpose_b", true}});
+ // Optionally reshape back by unrolling dimensions corresponding to separate labels if needed.
+ // Target subshapes are calculated broadcast_merge_shapes function and concatenated.
+ auto reshape_outshape = makeOP<opset1::Concat>({separate1_subshape, separate2_subshape}, {{"axis", 0}});
+ auto reshape_out = makeOP<opset1::Reshape>({matmul, reshape_outshape}, {{"special_zero", false}});
+ // Transpose to the original order of output labels.
+ auto Constant_1363 = makeConst(element::i64, ov::Shape({3}), {1, 0, 2});
+ auto transpose_out = makeOP<opset1::Transpose>({reshape_out, Constant_1363});
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1, data_2});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_1in_repeated_labels_ellipsis_static_cf) {
+ Shape data_shape_1 = {1, 3, 2, 1, 3, 1};
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto einsum = std::make_shared<opset7::Einsum>(OutputVector{data_1}, "ij...iji->j...i");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ manager.register_pass<ov::pass::ConstantFolding>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto const_0 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto const_1 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto const_3 = makeConst(element::i64, ov::Shape({1}), {3});
+ // Transpose data so repeated labels are grouped and unrepeated labels are moved to back.
+ // ij...iji -> iiijj...
+ auto transpose_diagonal =
+ makeOP<opset1::Transpose>({data_1, makeConst(element::i64, ov::Shape({6}), {0, 3, 5, 1, 4, 2})});
+ // Flatten groups of repeated labels (ij...)
+ auto flatten_repeated_labels =
+ makeOP<opset1::Reshape>({transpose_diagonal, makeConst(element::i64, ov::Shape({3}), {1, 9, 2})},
+ {{"special_zero", false}});
+ // Pad begin and end are constant-folded.
+ auto pad_begin = makeConst(element::i64, ov::Shape({3}), {0, 0, 0});
+ auto pad_end = makeConst(element::i64, ov::Shape({3}), {0, 3, 0});
+ auto pad = makeOP<opset1::Pad>(
+ {flatten_repeated_labels, pad_begin, pad_end, makeConst(element::f32, ov::Shape({}), {0})},
+ {{"pad_mode", "constant"}});
+ // unflatten padded groups of repeated labels so i(padded reminder of i)j(padded reminder of j)...
+ auto unflatten_repeated_labels =
+ makeOP<opset1::Reshape>({pad, makeConst(element::i64, ov::Shape({5}), {1, 1, 3, 4, 2})},
+ {{"special_zero", false}});
+ // Reduce padded dimensions to get diagonal.
+ auto reduce_first_repeat =
+ makeOP<opset7::Gather>({unflatten_repeated_labels, const_0, const_1}, {{"batch_dims", 0}});
+ auto reduce_second_repeat =
+ makeOP<opset7::Gather>({reduce_first_repeat, const_0, const_3}, {{"batch_dims", 0}});
+ auto remove_reduced_dims =
+ makeOP<opset1::Squeeze>({reduce_second_repeat, makeConst(element::i64, ov::Shape({2}), {1, 3})});
+ // Transpose to the original order of output labels.
+ auto Constant_1386 = makeConst(element::i64, ov::Shape({3}), {1, 2, 0});
+ auto transpose_out = makeOP<opset1::Transpose>({remove_reduced_dims, Constant_1386});
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_1in_repeated_labels_empty_ellipsis_dynamic) {
+ PartialShape data_shape_1 = PartialShape::dynamic(5);
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto einsum = std::make_shared<opset7::Einsum>(OutputVector{data_1}, "ij...iji->j...i");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+
+ // Extract diagonal
+ auto data_1_diagonal = extract_diagonal(data_1,
+ {
+ {0, 2, 4}, // indices of repeated label i
+ {1, 3}, // indices of repeated label j
+ });
+
+ // Transpose to the original order of output labels.
+ auto Constant_3027 = makeConst(element::i64, ov::Shape({2}), {1, 0});
+ auto transpose_out = makeOP<opset1::Transpose>({data_1_diagonal, Constant_3027});
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_3in_broadcast_duplicated_ellipsis_repeated_static_cf) {
+ PartialShape data_shape_1 = {1, 2, 2, 1, 1, 1};
+ PartialShape data_shape_2 = {4, 1, 1, 1, 1, 1};
+ PartialShape data_shape_3 = {3, 1, 3, 3};
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto data_3 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_3);
+ auto einsum =
+ std::make_shared<opset7::Einsum>(OutputVector{data_1, data_2, data_3}, "ba...b,bcccdd,...dbcc->c...b");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1, data_2, data_3});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ manager.register_pass<ov::pass::ConstantFolding>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto node_0 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_3);
+ auto node_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto node_4 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto Constant_8230 = makeConst(element::i64, ov::Shape({6}), {1, 2, 3, 4, 5, 0});
+ auto Transpose_8231 = makeOP<opset1::Transpose>({node_2, Constant_8230});
+ auto Concat_8261 = makeConst(element::i64, ov::Shape({3}), {1, 1, 4});
+ auto Reshape_8264 = makeOP<opset1::Reshape>({Transpose_8231, Concat_8261}, {{"special_zero", false}});
+ auto Concat_8263 = makeConst(element::i64, ov::Shape({3}), {0, 0, 0});
+ auto Concat_8262 = makeConst(element::i64, ov::Shape({3}), {0, 0, 0});
+ auto Pad_8304 =
+ makeOP<opset1::Pad>({Reshape_8264, Concat_8263, Concat_8262, 0.000000f}, {{"pad_mode", "constant"}});
+ auto Concat_8381 = makeConst(element::i64, ov::Shape({5}), {1, 1, 1, 1, 4});
+ auto Reshape_8382 = makeOP<opset1::Reshape>({Pad_8304, Concat_8381}, {{"special_zero", false}});
+ auto Constant_8233 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Constant_8459 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto Gather_8460 = makeOP<opset7::Gather>({Reshape_8382, Constant_8233, Constant_8459}, {{"batch_dims", 0}});
+ auto Constant_8461 = makeConst(element::i64, ov::Shape({1}), {3});
+ auto Gather_8462 = makeOP<opset7::Gather>({Gather_8460, Constant_8233, Constant_8461}, {{"batch_dims", 0}});
+ auto Constant_8463 = makeConst(element::i64, ov::Shape({2}), {1, 3});
+ auto Squeeze_8464 = makeOP<opset1::Squeeze>({Gather_8462, Constant_8463});
+ auto Constant_8465 = makeConst(element::i64, ov::Shape({3}), {0, 2, 1});
+ auto Transpose_8466 = makeOP<opset1::Transpose>({Squeeze_8464, Constant_8465});
+ auto Constant_8494 = makeConst(element::i64, ov::Shape({3}), {3, 4, 3});
+ auto Broadcast_8495 = makeOP<opset3::Broadcast>({Transpose_8466, Constant_8494}, {{"mode", "bidirectional"}});
+ auto Constant_8528 = makeConst(element::i64, ov::Shape({4}), {3, 4, 1, 3});
+ auto Reshape_8529 = makeOP<opset1::Reshape>({Broadcast_8495, Constant_8528}, {{"special_zero", false}});
+ auto Constant_7971 = makeConst(element::i64, ov::Shape({6}), {0, 5, 1, 2, 3, 4});
+ auto Transpose_7972 = makeOP<opset1::Transpose>({node_4, Constant_7971});
+ auto Concat_7990 = makeConst(element::i64, ov::Shape({5}), {1, 2, 2, 1, 1});
+ auto Reshape_7993 = makeOP<opset1::Reshape>({Transpose_7972, Concat_7990}, {{"special_zero", false}});
+ auto Concat_7992 = makeConst(element::i64, ov::Shape({5}), {0, 0, 0, 0, 0});
+ auto Concat_7991 = makeConst(element::i64, ov::Shape({5}), {0, 0, 0, 0, 0});
+ auto Pad_8014 =
+ makeOP<opset1::Pad>({Reshape_7993, Concat_7992, Concat_7991, 0.000000f}, {{"pad_mode", "constant"}});
+ auto Concat_8053 = makeConst(element::i64, ov::Shape({6}), {1, 1, 2, 2, 1, 1});
+ auto Reshape_8054 = makeOP<opset1::Reshape>({Pad_8014, Concat_8053}, {{"special_zero", false}});
+ auto Constant_7974 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Constant_8093 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto Gather_8094 = makeOP<opset7::Gather>({Reshape_8054, Constant_7974, Constant_8093}, {{"batch_dims", 0}});
+ auto Constant_8095 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto Squeeze_8096 = makeOP<opset1::Squeeze>({Gather_8094, Constant_8095});
+ auto Constant_8223 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto ReduceSum_8224 = makeOP<opset1::ReduceSum>({Squeeze_8096, Constant_8223}, {{"keep_dims", false}});
+ auto Constant_8227 = makeConst(element::i64, ov::Shape({2}), {4, 5});
+ auto Unsqueeze_8228 = makeOP<opset1::Unsqueeze>({ReduceSum_8224, Constant_8227});
+ auto Constant_7967 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Unsqueeze_7968 = makeOP<opset1::Unsqueeze>({node_0, Constant_7967});
+ auto Constant_7969 = makeConst(element::i64, ov::Shape({2}), {0, 1});
+ auto Unsqueeze_7970 = makeOP<opset1::Unsqueeze>({Unsqueeze_7968, Constant_7969});
+ auto Constant_8097 = makeConst(element::i64, ov::Shape({7}), {5, 6, 0, 1, 2, 3, 4});
+ auto Transpose_8098 = makeOP<opset1::Transpose>({Unsqueeze_7970, Constant_8097});
+ auto Concat_8116 = makeConst(element::i64, ov::Shape({6}), {9, 1, 1, 1, 3, 1});
+ auto Reshape_8119 = makeOP<opset1::Reshape>({Transpose_8098, Concat_8116}, {{"special_zero", false}});
+ auto Concat_8118 = makeConst(element::i64, ov::Shape({6}), {0, 0, 0, 0, 0, 0});
+ auto Concat_8117 = makeConst(element::i64, ov::Shape({6}), {3, 0, 0, 0, 0, 0});
+ auto Pad_8140 =
+ makeOP<opset1::Pad>({Reshape_8119, Concat_8118, Concat_8117, 0.000000f}, {{"pad_mode", "constant"}});
+ auto Concat_8179 = makeConst(element::i64, ov::Shape({7}), {3, 4, 1, 1, 1, 3, 1});
+ auto Reshape_8180 = makeOP<opset1::Reshape>({Pad_8140, Concat_8179}, {{"special_zero", false}});
+ auto Constant_8100 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto Constant_8219 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto Gather_8220 = makeOP<opset7::Gather>({Reshape_8180, Constant_8100, Constant_8219}, {{"batch_dims", 0}});
+ auto Constant_8221 = makeConst(element::i64, ov::Shape({1}), {1});
+ auto Squeeze_8222 = makeOP<opset1::Squeeze>({Gather_8220, Constant_8221});
+ auto Constant_8225 = makeConst(element::i64, ov::Shape({6}), {5, 1, 2, 3, 0, 4});
+ auto Transpose_8226 = makeOP<opset1::Transpose>({Squeeze_8222, Constant_8225});
+ auto Multiply_8229 = makeOP<opset1::Multiply>({Unsqueeze_8228, Transpose_8226}, {{"auto_broadcast", "numpy"}});
+ auto Constant_8467 = makeConst(element::i64, ov::Shape({6}), {4, 0, 1, 2, 3, 5});
+ auto Transpose_8468 = makeOP<opset1::Transpose>({Multiply_8229, Constant_8467});
+ auto Constant_8502 = makeConst(element::i64, ov::Shape({6}), {3, 4, 2, 1, 1, 3});
+ auto Broadcast_8503 = makeOP<opset3::Broadcast>({Transpose_8468, Constant_8502}, {{"mode", "bidirectional"}});
+ auto Constant_8573 = makeConst(element::i64, ov::Shape({4}), {3, 4, 2, 3});
+ auto Reshape_8574 = makeOP<opset1::Reshape>({Broadcast_8503, Constant_8573}, {{"special_zero", false}});
+ auto MatMul_8575 =
+ makeOP<opset1::MatMul>({Reshape_8529, Reshape_8574}, {{"transpose_a", false}, {"transpose_b", true}});
+ auto Constant_8577 = makeConst(element::i64, ov::Shape({5}), {3, 4, 2, 1, 1});
+ auto Reshape_8578 = makeOP<opset1::Reshape>({MatMul_8575, Constant_8577}, {{"special_zero", false}});
+ auto Constant_8579 = makeConst(element::i64, ov::Shape({5}), {0, 2, 3, 4, 1});
+ auto node_6 = makeOP<opset1::Transpose>({Reshape_8578, Constant_8579});
+ model_ref = std::make_shared<Model>(NodeVector{node_6}, ParameterVector{node_4, node_2, node_0});
+ }
+}
+
+TEST_F(TransformationTestsF, Einsum_3in_broadcast_duplicated_ellipsis_repeated_dynamic) {
+ PartialShape data_shape_1 = PartialShape::dynamic(5);
+ PartialShape data_shape_2 = PartialShape::dynamic(6);
+ PartialShape data_shape_3 = PartialShape::dynamic(4);
+ comparator.enable(FunctionsComparator::CmpValues::ACCURACY);
+ {
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto data_3 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_3);
+ auto einsum =
+ std::make_shared<opset7::Einsum>(OutputVector{data_1, data_2, data_3}, "a...b,bcccdd,...dbcc->c...b");
+ model = std::make_shared<Model>(NodeVector{einsum}, ParameterVector{data_1, data_2, data_3});
+ manager.register_pass<ov::pass::EinsumDecomposition>();
+ }
+ {
+ using namespace ov::gen_pattern;
+ auto data_1 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_1);
+ auto data_2 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_2);
+ auto data_3 = std::make_shared<ov::op::v0::Parameter>(element::f32, data_shape_3);
+
+ // First pair of einsum inputs - data_1 and data_3
+ // data_1 - label `a` can be reduced by reduce_input()
+ auto indice_of_a_in_data_1 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto data_1_processed = makeOP<opset1::ReduceSum>({data_1, indice_of_a_in_data_1}, {{"keep_dims", false}});
+ // data_3 - unsqueeze ellipse labels to allow for broadcasting and handle repeated labels
+ auto ellipsis_idx = makeConst(element::i64, ov::Shape({1}), {0});
+ auto data3_insert_missing_ellipsis = makeOP<opset1::Unsqueeze>({data_3, ellipsis_idx});
+ auto align_ellipsis_idx = makeConst(element::i64, ov::Shape({2}), {0, 1});
+ auto data_3_processed = makeOP<opset1::Unsqueeze>({data3_insert_missing_ellipsis, align_ellipsis_idx});
+ auto data_3_diagonal = extract_diagonal(data_3_processed, {{5, 6}}, {0, 1, 2, 3, 4});
+
+ // No reduced labels - use simplified subgraph that uses Multiply instead Matmul
+ // c...db -> ...bcd
+ auto convenient_layout = makeConst(element::i64, ov::Shape({6}), {1, 2, 3, 5, 0, 4});
+ auto rhs_convenient_layout = makeOP<opset1::Transpose>({data_3_diagonal, convenient_layout});
+ // Optionally unsqueeze both operands for elementwise-multiplication with broadcasting
+ // For LHS operand, unsqueeze at RHS separate dimensions indices (placed at end of RHS by transpose)
+ auto lhs_unsqueeze_dims = makeConst(element::i64, ov::Shape({2}), {4, 5});
+ auto lhs_unsqueeze = makeOP<opset1::Unsqueeze>({data_1_processed, lhs_unsqueeze_dims});
+ // Out subscript = LHS_subscript + RHS_separate_part_subscript
+ // ...bcd = ...b + cd
+ auto data_1_3 = makeOP<opset1::Multiply>({lhs_unsqueeze, rhs_convenient_layout}, {{"auto_broadcast", "numpy"}});
+
+ // Second pair of einsum inputs - data_2 and result of the first pair
+ // bcccdd,...bcd->c...b
+ // data_2 - handle repeated labels
+ auto data_2_diagonal = extract_diagonal(data_2,
+ {
+ {1, 2, 3}, // indices of repeated label c
+ {4, 5}, // indices_of_repeated_label_d
+ },
+ {
+ 0, // indices of unrepeated label b
+ });
+ // Transpose data_2 so that common labels, separated and reduced labels are grouped for both operands.
+ auto data_2_processed =
+ makeOP<opset1::Transpose>({data_2_diagonal, makeConst(element::i64, ov::Shape({3}), {0, 2, 1})});
+ // data_1_3 - transpose to correctly group common, separate and reduced labels
+ auto transpose_data_1_3_target = makeConst(element::i64, ov::Shape({6}), {4, 3, 0, 1, 2, 5});
+ auto data_1_3_processed = makeOP<opset1::Transpose>({data_1_3, transpose_data_1_3_target});
+ // Extract and broadcast common subshapes (bc)
+ auto shapeof_data_1_3 = makeOP<opset3::ShapeOf>({data_1_3_processed}, {{"output_type", "i64"}});
+ auto common_data_1_3 = extract_subshape_from_shape(shapeof_data_1_3, 0, 2);
+ auto shapeof_data_2 = makeOP<opset3::ShapeOf>({data_2_processed}, {{"output_type", "i64"}});
+ auto common_data_2 = extract_subshape_from_shape(shapeof_data_2, 0, 2);
+ auto common_broadcast_merge_shapes = broadcast_merge_shapes(common_data_2, common_data_1_3);
+
+ // Extract and broadcast reduced subshapes (d)
+ auto reduced_data_2 = extract_subshape_from_shape(shapeof_data_2, 2, 3);
+ auto reduced_data_1_3 = extract_subshape_from_shape(shapeof_data_1_3, 5, 6);
+ auto reduced_broadcast_merge_shapes = broadcast_merge_shapes(reduced_data_2, reduced_data_1_3);
+
+ // Extract and broadcast separate subshapes if needed
+ auto separate_data_1_3 = extract_subshape_from_shape(shapeof_data_1_3, 2, 5); // (...)
+
+ // Broadcast data_2 and data_1_3 based on calculated subshapes
+ auto broadcast_data_2_target =
+ makeOP<opset1::Concat>({common_broadcast_merge_shapes, reduced_broadcast_merge_shapes}, {{"axis", 0}});
+ auto broadcast_data_2 =
+ makeOP<opset3::Broadcast>({data_2_processed, broadcast_data_2_target}, {{"mode", "bidirectional"}});
+ auto broadcast_data_1_3_target =
+ makeOP<opset1::Concat>({common_broadcast_merge_shapes, separate_data_1_3, reduced_broadcast_merge_shapes},
+ {{"axis", 0}});
+ auto broadcast_data_1_3 =
+ makeOP<opset3::Broadcast>({data_1_3_processed, broadcast_data_1_3_target}, {{"mode", "bidirectional"}});
+
+ // Optionally reshape broadcasted data_2 and data_1_3 so separate and reduced labels are represented by one
+ // dimension. Subgraphes are constant-folded, target subshapes are calculated broadcast_merge_shapes function.
+ auto reduced_prod = makeOP<opset1::ReduceProd>({reduced_broadcast_merge_shapes, {0}}, {{"keep_dims", true}});
+ // Reshape data_2
+ auto separate_data_2_placeholder = makeConst(element::i64, ov::Shape({1}), {1});
+ auto reshape_data_2_target =
+ makeOP<opset1::Concat>({common_broadcast_merge_shapes, separate_data_2_placeholder, reduced_prod},
+ {{"axis", 0}});
+ auto reshape_data_2 =
+ makeOP<opset1::Reshape>({broadcast_data_2, reshape_data_2_target}, {{"special_zero", false}});
+ // Reshape data_1_3
+ auto Constant_1904 = makeConst(element::i64, ov::Shape({1}), {0});
+ auto separate_data_1_3_prod =
+ makeOP<opset1::ReduceProd>({separate_data_1_3, Constant_1904}, {{"keep_dims", true}});
+ auto reshape_data_1_3_target =
+ makeOP<opset1::Concat>({common_broadcast_merge_shapes, separate_data_1_3_prod, reduced_prod},
+ {{"axis", 0}});
+ auto reshape_data_1_3 =
+ makeOP<opset1::Reshape>({broadcast_data_1_3, reshape_data_1_3_target}, {{"special_zero", false}});
+ auto matmul =
+ makeOP<opset1::MatMul>({reshape_data_2, reshape_data_1_3}, {{"transpose_a", false}, {"transpose_b", true}});
+ auto reshape_out_subshape =
+ makeOP<opset1::Concat>({common_broadcast_merge_shapes, separate_data_1_3}, {{"axis", 0}});
+ auto reshape_out = makeOP<opset1::Reshape>({matmul, reshape_out_subshape}, {{"special_zero", false}});
+ auto Constant_1965 = makeConst(element::i64, ov::Shape({5}), {0, 2, 3, 4, 1});
+ auto transpose_out = makeOP<opset1::Transpose>({reshape_out, Constant_1965});
+ model_ref = std::make_shared<Model>(NodeVector{transpose_out}, ParameterVector{data_1, data_2, data_3});
+ }
+}
diff --git a/src/core/reference/src/op/einsum.cpp b/src/core/reference/src/op/einsum.cpp
index 968842c5ade..b0ea9ab663b 100644
--- a/src/core/reference/src/op/einsum.cpp
+++ b/src/core/reference/src/op/einsum.cpp
@@ -413,7 +413,7 @@ void transpose_input(ov::TensorVector& inputs,
}
/// \brief Broadcast input to a new shape. The MatMul operation requires the
-/// same shape of both operands in the common (or batch) dimensionsy.
+/// same shape of both operands in the common (or batch) dimensions.
///
template <typename T>
void broadcast_input(ov::TensorVector& inputs,
@@ -425,7 +425,7 @@ void broadcast_input(ov::TensorVector& inputs,
OPENVINO_ASSERT(input_ind < inputs.size());
ov::Tensor& input = inputs[input_ind];
const Shape old_shape = input.get_shape();
- Shape new_shape;
+ PartialShape new_shape;
new_shape.insert(new_shape.end(), new_common_shape.begin(), new_common_shape.end());
if (is_separate_first) {
new_shape.insert(new_shape.end(), separate_shape.begin(), separate_shape.end());
@@ -435,15 +435,15 @@ void broadcast_input(ov::TensorVector& inputs,
new_shape.insert(new_shape.end(), separate_shape.begin(), separate_shape.end());
}
- if (input.get_shape() == new_shape) {
+ if (input.get_shape() == new_shape.to_shape()) {
return;
}
OPENVINO_ASSERT(old_shape.size() <= new_shape.size());
- auto output = ov::Tensor(input.get_element_type(), new_shape);
-
std::vector<size_t> broadcast_axes(old_shape.size());
std::iota(broadcast_axes.begin(), broadcast_axes.end(), new_shape.size() - old_shape.size());
+ OPENVINO_ASSERT(PartialShape::broadcast_merge_into(new_shape, old_shape, ov::op::AutoBroadcastType::NUMPY));
+ auto output = ov::Tensor(input.get_element_type(), new_shape.to_shape());
reference::broadcast(reinterpret_cast<const char*>(input.data<T>()),
reinterpret_cast<char*>(output.data<T>()),
@@ -650,6 +650,48 @@ ov::Tensor reshape_input_for_matmul(const ov::Tensor& input,
return output;
}
+/// \brief Adjusts the rank of two input tensors by unsqueezing ellipses to the same rank.
+///
+/// This function takes two input tensors and their corresponding subscripts, and ensures that
+/// the ellipses ("...") in the subscripts have the same rank by unsqueezing dimensions as needed.
+/// It modifies the input tensors in place.
+///
+/// \param inputs A vector of input tensors.
+/// \param input_subscripts A vector of strings representing the subscripts for each input tensor.
+/// \param input_ind1 The index of the first input tensor in the inputs vector.
+/// \param input_ind2 The index of the second input tensor in the inputs vector.
+template <typename T>
+void unsqueeze_ellipses_to_same_rank(ov::TensorVector& inputs,
+ std::vector<std::string>& input_subscripts,
+ size_t input_ind1,
+ size_t input_ind2) {
+ constexpr char ellipsis[] = "...";
+ const auto& input1 = inputs[input_ind1];
+ const auto& input2 = inputs[input_ind2];
+ auto label_to_dim_map1 = compute_label_dim_map(input1.get_shape().size(), input_subscripts[input_ind1]);
+ auto label_to_dim_map2 = compute_label_dim_map(input2.get_shape().size(), input_subscripts[input_ind2]);
+ if (label_to_dim_map1.find(ellipsis) != label_to_dim_map1.end() &&
+ label_to_dim_map2.find(ellipsis) != label_to_dim_map2.end()) {
+ std::vector<int64_t> unsqueeze_axis1, unsqueeze_axis2;
+ const auto& ellipsis_dims1 = label_to_dim_map1[ellipsis];
+ const auto& ellipsis_dims2 = label_to_dim_map2[ellipsis];
+ if (ellipsis_dims2.size() > ellipsis_dims1.size()) {
+ for (size_t i = 0; i < ellipsis_dims2.size() - ellipsis_dims1.size(); ++i) {
+ unsqueeze_axis1.push_back(ellipsis_dims1[0] + i);
+ }
+ } else if (ellipsis_dims1.size() > ellipsis_dims2.size()) {
+ for (size_t i = 0; i < ellipsis_dims1.size() - ellipsis_dims2.size(); ++i) {
+ unsqueeze_axis2.push_back(ellipsis_dims2[0] + i);
+ }
+ }
+ ov::Tensor unsqueeze_output1 = unsqueeze_input<T>(input1, unsqueeze_axis1);
+ ov::Tensor unsqueeze_output2 = unsqueeze_input<T>(input2, unsqueeze_axis2);
+ inputs[input_ind1] = std::move(unsqueeze_output1);
+ inputs[input_ind2] = std::move(unsqueeze_output2);
+ return;
+ }
+}
+
/// \brief Contract two inputs of Einsum operation according to equation.
/// The result of the contraction is appended into inputs along with its
/// subscript. The inputs with indices input_ind1 and input_ind2 are removed from
@@ -675,6 +717,9 @@ void contract_two_inputs(ov::TensorVector& inputs,
const auto& input1 = inputs[input_ind1];
const auto& input2 = inputs[input_ind2];
+ // unsqueeze inputs to have same rank of ellipsis for correct broadcasting
+ unsqueeze_ellipses_to_same_rank<T>(inputs, input_subscripts, input_ind1, input_ind2);
+
// extract diagonals in case repeated labels in the corresponding input
// subscripts
extract_diagonal<T>(inputs, input_subscripts, input_ind1);
@@ -853,8 +898,8 @@ void contract_two_inputs(ov::TensorVector& inputs,
PartialShape common_sub_shape1 = compute_sub_shape(input_shape1, common_dims_begin, common_dims_end);
PartialShape common_sub_shape2 = compute_sub_shape(input_shape2, common_dims_begin2, common_dims_end2);
- Shape reduced_sub_shape_prod = compute_sub_shape(input_shape1, reduced_dims_begin, reduced_dims_end, true);
- Shape reduced_sub_shape = compute_sub_shape(input_shape1, reduced_dims_begin, reduced_dims_end);
+ PartialShape reduced_sub_shape = compute_sub_shape(input_shape1, reduced_dims_begin, reduced_dims_end);
+ Shape reduced_sub_shape2 = compute_sub_shape(input_shape2, reduced_dims_begin2, reduced_dims_end2);
Shape separate1_sub_shape = compute_sub_shape(input_shape1, separate1_dims_begin, separate1_dims_end);
Shape separate2_sub_shape = compute_sub_shape(input_shape2, separate2_dims_begin, separate2_dims_end);
@@ -862,18 +907,20 @@ void contract_two_inputs(ov::TensorVector& inputs,
// in case of ellipsis among the common labels
// reference::broadcast()
PartialShape::broadcast_merge_into(common_sub_shape1, common_sub_shape2, op::AutoBroadcastType::NUMPY);
+ PartialShape::broadcast_merge_into(reduced_sub_shape, reduced_sub_shape2, op::AutoBroadcastType::NUMPY);
+ Shape reduced_sub_shape_prod = {shape_size(reduced_sub_shape.get_shape())};
Shape common_sub_shape = common_sub_shape1.get_shape();
broadcast_input<T>(inputs,
input_ind1,
common_sub_shape,
separate1_sub_shape,
- reduced_sub_shape,
+ reduced_sub_shape.get_shape(),
is_separate_first1);
broadcast_input<T>(inputs,
input_ind2,
common_sub_shape,
separate2_sub_shape,
- reduced_sub_shape,
+ reduced_sub_shape.get_shape(),
is_separate_first2);
ov::Tensor matmul_operand1 = reshape_input_for_matmul<T>(input1,
@@ -881,6 +928,7 @@ void contract_two_inputs(ov::TensorVector& inputs,
separate1_sub_shape,
reduced_sub_shape_prod,
is_separate_first1);
+
ov::Tensor matmul_operand2 = reshape_input_for_matmul<T>(input2,
common_sub_shape,
separate2_sub_shape,
@@ -924,6 +972,58 @@ void contract_two_inputs(ov::TensorVector& inputs,
update_operands(inputs, input_subscripts, input_ind1, input_ind2, contract_output, resultant_subscript);
}
+/// \brief Adjusts input subscripts and nodes to handle 0-dimensional ellipsis in Einsum operations.
+///
+/// Handle ellipses labels that do not represent any dimensions:
+/// 1. If there is no ellipsis in the input subscripts, remove ellipsis from the output subscript.
+/// 2. If all ellipses in the input subscripts do not represent any dimensions, remove ellipses from all subscripts.
+/// 3. If there is at least one ellipsis that represents dimension, unsqueeze ellipses that do not represent any,
+///
+/// \param input_nodes A vector of input tensors for the Einsum operation.
+/// \param input_subscripts A vector of input subscripts corresponding to the input nodes.
+/// \param output_subscript The output subscript for the Einsum operation.
+template <typename T>
+void fix_inputs_with_0d_ellipsis(ov::TensorVector& input_nodes,
+ std::vector<std::string>& input_subscripts,
+ std::string& output_subscript) {
+ static const std::string ellipsis = "...";
+ bool has_ellipsis = false;
+ bool all_no_ellipsis_or_empty = true;
+
+ for (size_t i = 0; i < input_nodes.size(); ++i) {
+ const auto& labels = ov::op::v7::Einsum::extract_labels(input_subscripts[i]);
+ bool has_ellipsis_in_input = std::find(labels.begin(), labels.end(), ellipsis) != labels.end();
+ has_ellipsis |= has_ellipsis_in_input;
+ all_no_ellipsis_or_empty &=
+ !has_ellipsis_in_input || (input_nodes[i].get_shape().size() == (labels.size() - 1));
+ }
+
+ if (!has_ellipsis) {
+ if (output_subscript.find(ellipsis) != std::string::npos) {
+ output_subscript.erase(output_subscript.find(ellipsis), ellipsis.size());
+ }
+ } else if (all_no_ellipsis_or_empty) {
+ for (auto& subscript : input_subscripts) {
+ if (subscript.find(ellipsis) != std::string::npos) {
+ subscript.erase(subscript.find(ellipsis), ellipsis.size());
+ }
+ }
+ if (output_subscript.find(ellipsis) != std::string::npos) {
+ output_subscript.erase(output_subscript.find(ellipsis), ellipsis.size());
+ }
+ } else {
+ for (size_t i = 0; i < input_nodes.size(); ++i) {
+ const auto& labels = ov::op::v7::Einsum::extract_labels(input_subscripts[i]);
+ if (std::find(labels.begin(), labels.end(), ellipsis) != labels.end() &&
+ input_nodes[i].get_shape().size() == (labels.size() - 1)) {
+ std::vector<int64_t> ellipsis_idx{
+ std::distance(labels.begin(), std::find(labels.begin(), labels.end(), ellipsis))};
+ input_nodes[i] = unsqueeze_input<T>(input_nodes[i], ellipsis_idx);
+ }
+ }
+ }
+}
+
template <typename T>
void einsum_impl(const ov::TensorVector& inputs, ov::TensorVector& outputs, const std::string& equation) {
std::vector<std::string> input_subscripts;
@@ -934,9 +1034,11 @@ void einsum_impl(const ov::TensorVector& inputs, ov::TensorVector& outputs, cons
// in more optimal order
size_t num_inputs = inputs.size();
auto einsum_path = compute_einsum_path(num_inputs);
-
ov::TensorVector int_inputs = inputs;
+ // fix inputs where ellipsis does not contain any dimensions
+ fix_inputs_with_0d_ellipsis<T>(int_inputs, input_subscripts, output_subscript);
+
// contract inputs by Einsum until just one is remained
for (auto const& inds_pair : einsum_path) {
contract_two_inputs<T>(int_inputs, input_subscripts, output_subscript, inds_pair.first, inds_pair.second);
diff --git a/src/core/shape_inference/include/einsum_shape_inference.hpp b/src/core/shape_inference/include/einsum_shape_inference.hpp
index 709cb54c345..26e7fd583bb 100644
--- a/src/core/shape_inference/include/einsum_shape_inference.hpp
+++ b/src/core/shape_inference/include/einsum_shape_inference.hpp
@@ -24,23 +24,30 @@ std::vector<TRShape> shape_infer(const Einsum* op, const std::vector<T>& input_s
input_subscripts.size() == input_shapes.size(),
"Equation must contain a number of subscripts equal to a number of Einsum inputs.");
+ const auto output_labels = Einsum::extract_labels(output_subscript);
+ const auto has_out_ellipsis = std::any_of(output_labels.begin(), output_labels.end(), [](std::string label) {
+ return label == "...";
+ });
// create a dictionary with dimension sizes (or ranges in case of dynamic shapes) for each label
// and check their compatibility in case of repeating labels
std::unordered_map<std::string, TRShape> label_to_shape;
-
for (size_t input_idx = 0; input_idx < input_shapes.size(); ++input_idx) {
const auto& pshape = input_shapes[input_idx];
const auto labels = Einsum::extract_labels(input_subscripts[input_idx]);
+ const auto has_ellipsis = std::any_of(labels.begin(), labels.end(), [](std::string label) {
+ return label == "...";
+ });
if (pshape.rank().is_static()) {
size_t input_rank = pshape.size();
// check that a rank is greater or equal to a number of labels
// these numbers are always equal if there is no ellipsis in the subscript
- NODE_VALIDATION_CHECK(op,
- input_rank >= labels.size(),
- "Input rank must be greater or equal to a number of labels in the "
- "corresponding input subscript.");
-
+ NODE_VALIDATION_CHECK(
+ op,
+ (input_rank >= (labels.size() - 1) && has_ellipsis) || (input_rank == labels.size() && !has_ellipsis),
+ "Input rank must be greater or equal to a number of labels in the "
+ "corresponding input subscript.");
+ std::unordered_map<std::string, TRShape> single_input_label_to_shape;
for (size_t label_ind = 0, dim_ind = 0; label_ind < labels.size() && dim_ind < input_rank; ++label_ind) {
auto const& label = labels[label_ind];
if (label.compare("...") == 0) {
@@ -60,25 +67,40 @@ std::vector<TRShape> shape_infer(const Einsum* op, const std::vector<T>& input_s
}
dim_ind += num_broadcasted_dims;
} else {
- if (label_to_shape.find(label) == label_to_shape.end()) {
- label_to_shape[label] = TRShape{pshape[dim_ind]};
+ // Check if repeated label dimension in single input are compatible
+ if (single_input_label_to_shape.find(label) == single_input_label_to_shape.end()) {
+ single_input_label_to_shape[label] = TRShape{pshape[dim_ind]};
} else {
- NODE_VALIDATION_CHECK(op,
- label_to_shape[label].compatible(TRShape{pshape[label_ind]}),
- "Different input dimensions indicated by the same labels for Einsum "
- "must be compatible.");
- OPENVINO_ASSERT(TRShape::merge_into(label_to_shape[label], TRShape{pshape[dim_ind]}));
+ NODE_VALIDATION_CHECK(
+ op,
+ TRShape::merge_into(single_input_label_to_shape[label], TRShape{pshape[dim_ind]}),
+ "Different input dimensions indicated by the repeated labels within single input node for "
+ "Einsum "
+ "must be compatible.");
}
++dim_ind;
}
}
+ for (auto label_it : single_input_label_to_shape) {
+ // Repeated labels in single input node are eliminated, so we can merge them into the global
+ // label_to_shape.
+ if (label_to_shape.find(label_it.first) == label_to_shape.end()) {
+ label_to_shape[label_it.first] = label_it.second;
+ } else {
+ NODE_VALIDATION_CHECK(op,
+ TRShape::broadcast_merge_into(label_to_shape[label_it.first],
+ label_it.second,
+ op::AutoBroadcastType::NUMPY),
+ "Different input dimensions indicated by the same labels for Einsum "
+ "must be broadcastable.");
+ }
+ }
} else {
+ if (has_ellipsis && has_out_ellipsis) {
+ // Shape has dynamic rank and ellipsis
+ return {pshape};
+ }
for (auto const& label : labels) {
- NODE_VALIDATION_CHECK(op,
- label != "...",
- "The subscript corresponding to a dynamic rank input must "
- "not contain ellipsis.");
-
if (label_to_shape.find(label) == label_to_shape.end()) {
label_to_shape[label] = ov::PartialShape{Dimension::dynamic()};
}
@@ -87,11 +109,14 @@ std::vector<TRShape> shape_infer(const Einsum* op, const std::vector<T>& input_s
}
// compute the output shape
- const auto output_labels = Einsum::extract_labels(output_subscript);
auto output_shapes = std::vector<TRShape>(1);
auto& output_shape = output_shapes[0];
for (auto const& output_label : output_labels) {
+ if (output_label == "..." && label_to_shape.find(output_label) == label_to_shape.end()) {
+ // Output labels may contain ellipsis that does not cover any dimensions.
+ continue;
+ }
NODE_VALIDATION_CHECK(op,
label_to_shape.find(output_label) != label_to_shape.end(),
"Label in output subscript of Einsum equation must enter at least "
diff --git a/src/core/src/op/einsum.cpp b/src/core/src/op/einsum.cpp
index 2d82275bbf0..a05ad1482c8 100644
--- a/src/core/src/op/einsum.cpp
+++ b/src/core/src/op/einsum.cpp
@@ -139,11 +139,6 @@ void op::v7::Einsum::parse_equation(const std::string& equation,
OPENVINO_ASSERT(is_subscript_correct(output_subscript, output_is_ellipsis_met),
"Output subscript of Einsum equation must consist of either only "
"alphabetic letters or alphabetic letters with one ellipsis.");
-
- // if the ellipsis is met in input subscripts, one ellipsis must be in the output subscript
- OPENVINO_ASSERT(is_ellipsis_met == output_is_ellipsis_met,
- "Output subscript of Einsum equation must contain one ellipsis if "
- "ellipsis is met in any input subscript.");
}
}
diff --git a/src/core/tests/type_prop/einsum.cpp b/src/core/tests/type_prop/einsum.cpp
index 0436bb98336..5ff6904d012 100644
--- a/src/core/tests/type_prop/einsum.cpp
+++ b/src/core/tests/type_prop/einsum.cpp
@@ -143,6 +143,25 @@ TEST_F(TypePropEinsumTest, static_shape_ellipsis) {
EXPECT_EQ(o->get_shape(), Shape({11, 11, 7, 4}));
}
+TEST_F(TypePropEinsumTest, static_shape_multi_input_broadcasting) {
+ const std::string equation = "a...b,b...,aacd,,...dd->da...c";
+ constexpr auto et = element::i32;
+ const auto input_shapes = Shapes{
+ {1, 5},
+ {1, 1, 2, 1},
+ {2, 2, 1, 4},
+ {},
+ {2, 1, 1},
+ };
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_shape(), Shape({4, 2, 1, 2, 2, 1}));
+}
+
// Dynamic shapes test also symbol propagation as each Einsum tests different equation
TEST_F(TypePropEinsumTest, dynamic_shape_dot_product) {
@@ -349,7 +368,19 @@ TEST_F(TypePropEinsumTest, incorrect_equation_invalid_symbols) {
"letters or alphabetic letters with one ellipsis."));
}
-TEST_F(TypePropEinsumTest, incorrect_equation_incompatible_shapes) {
+TEST_F(TypePropEinsumTest, incorrect_equation_incompatible_repeated_label_shape) {
+ const std::string equation = "aa->a";
+
+ const auto input_shapes = Shapes{{1, 10}};
+ const auto inputs = make_inputs(element::f32, input_shapes);
+
+ OV_EXPECT_THROW(auto o = make_op(inputs, equation),
+ AssertFailure,
+ HasSubstr("Different input dimensions indicated by the repeated labels within single "
+ "input node for Einsum must be compatible."));
+}
+
+TEST_F(TypePropEinsumTest, incorrect_equation_not_broadcastable_label_shape) {
const std::string equation = "ab,bc->ac";
const auto input_shapes = Shapes{{2, 10}, {3, 4}};
@@ -358,10 +389,10 @@ TEST_F(TypePropEinsumTest, incorrect_equation_incompatible_shapes) {
OV_EXPECT_THROW(auto o = make_op(inputs, equation),
AssertFailure,
HasSubstr("Different input dimensions indicated by the same labels "
- "for Einsum must be compatible."));
+ "for Einsum must be broadcastable."));
}
-TEST_F(TypePropEinsumTest, incorrect_equation_not_broadcastable_shapes) {
+TEST_F(TypePropEinsumTest, incorrect_equation_not_broadcastable_ellipsis_shapes) {
const std::string equation = "a...b,b...->a...";
const auto input_shapes = Shapes{{11, 1, 4, 3}, {3, 11, 7, 5}};
@@ -372,14 +403,351 @@ TEST_F(TypePropEinsumTest, incorrect_equation_not_broadcastable_shapes) {
HasSubstr("Input dimensions labeled with ellipsis for Einsum must be broadcastable."));
}
-TEST_F(TypePropEinsumTest, incorrect_equation_missed_ellipsis) {
+TEST_F(TypePropEinsumTest, missed_out_ellipsis) {
const std::string equation = "a...b,b...->a";
- const auto input_shapes = Shapes{{11, 1, 4, 3}, {3, 11, 7, 5}};
+ auto input_shapes = PartialShapes{{11, 1, 4, 3}, {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, missed_rhs_out_ellipsis) {
+ const std::string equation = "a...b,b->a";
+
+ auto input_shapes = PartialShapes{{11, 1, 4, 3}, {3}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, missed_lhs_out_ellipsis) {
+ const std::string equation = "ab,b...->a";
+
+ auto input_shapes = PartialShapes{{11, 3}, {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, missed_rhs_ellipsis) {
+ const std::string equation = "a...b,b->a...";
+
+ auto input_shapes = PartialShapes{{11, 1, 4, 3}, {3}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11, 1, 4}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_a[0], symbols_a[1], symbols_a[2]));
+}
+
+TEST_F(TypePropEinsumTest, missed_lhs_ellipsis) {
+ const std::string equation = "ab,b...->a...";
+
+ auto input_shapes = PartialShapes{{11, 3}, {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11, 11, 7, 4}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_a[0], symbols_b[1], symbols_b[2], symbols_b[3]));
+}
+
+TEST_F(TypePropEinsumTest, missed_rhs_ellipsis_implicit) {
+ const std::string equation = "a...b,b";
+
+ auto input_shapes = PartialShapes{{11, 1, 4, 3}, {3}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({1, 4, 11}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_a[1], symbols_a[2], symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, missed_lhs_ellipsis_implicit) {
+ const std::string equation = "ab,b...";
+
+ auto input_shapes = PartialShapes{{11, 3}, {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(element::f32, input_shapes);
+ const auto o = make_op(inputs, equation);
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), element::f32);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({11, 7, 4, 11}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_b[1], symbols_b[2], symbols_b[3], symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, all_dynamic_rank_ellipsis) {
+ const std::string equation = "a...b,b...->...a";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes(2, PartialShape::dynamic());
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape::dynamic());
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), Each(nullptr));
+}
+
+TEST_F(TypePropEinsumTest, lhs_dynamic_rank_ellipsis) {
+ const std::string equation = "a...b,b...->...a";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{PartialShape::dynamic(), {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape::dynamic());
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), Each(nullptr));
+}
+
+TEST_F(TypePropEinsumTest, rhs_dynamic_rank_ellipsis) {
+ const std::string equation = "a...b,b...->...a";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{3, 11, 7, 4}, PartialShape::dynamic()};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape::dynamic());
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), Each(nullptr));
+}
+
+TEST_F(TypePropEinsumTest, lhs_dynamic_rank_ellipsis_reduced_out_ellipsis) {
+ const std::string equation = "a...b,b...->a";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{PartialShape::dynamic(), {3, 11, 7, 4}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({ov::Dimension::dynamic()}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), Each(nullptr));
+}
+
+TEST_F(TypePropEinsumTest, rhs_dynamic_rank_ellipsis_reduced_out_ellipsis) {
+ const std::string equation = "a...b,b...->a";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{3, 11, 7, 4}, PartialShape::dynamic()};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({3}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[0]));
+}
+
+TEST_F(TypePropEinsumTest, broadcasting_same_symbol_common) {
+ const std::string equation = "ab,ba->b";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{7, 5}, {1, 7}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({5}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[1]));
+}
+
+TEST_F(TypePropEinsumTest, broadcasting_same_symbol_reduced) {
+ const std::string equation = "ab,ba->b";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{1, 5}, {5, 7}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({5}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_a[1]));
+}
+
+TEST_F(TypePropEinsumTest, broadcasting_same_symbol) {
+ const std::string equation = "ab,ba->b";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{7, 1}, {5, 1}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({5}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_b[0]));
+}
+
+TEST_F(TypePropEinsumTest, ellipsis_no_dimension) {
+ const std::string equation = "...ab,ba...->b...";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{5, 1}, {5, 5}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({5}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_b[0]));
+}
+
+TEST_F(TypePropEinsumTest, ellipsis_dynamic_shape) {
+ const std::string equation = "...ab,ba...->b...";
+ constexpr auto et = element::i32;
+
+ auto input_shapes = PartialShapes{{-1, 57, 5, 5}, {5, 5}};
+ auto symbols_a = set_shape_symbols(input_shapes[0]);
+ auto symbols_b = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({5, -1, 57}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_a[3], symbols_a[0], symbols_a[1]));
+}
+
+TEST_F(TypePropEinsumTest, dynamic_shape_repeated_label_2_input_broadcasting) {
+ const std::string equation = "aabb,aabb->ab";
+ constexpr auto et = element::i32;
+ auto input_shapes = PartialShapes{
+ {{1, 2}, {1, 4}, {1, 5}, {2, 4}},
+ {{1, 3}, {2, 4}, {1, 3}, {3, 4}},
+ };
+ auto symbols_0 = set_shape_symbols(input_shapes[0]);
+ auto symbols_1 = set_shape_symbols(input_shapes[1]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({{2, 3}, {3}}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)), ElementsAre(symbols_1[0], symbols_0[2]));
+}
+
+TEST_F(TypePropEinsumTest, dynamic_shape_multi_input_broadcasting) {
+ const std::string equation = "a...b,b...,aacd,,...dd->da...c";
+ constexpr auto et = element::i32;
+ auto input_shapes = PartialShapes{
+ {{1, 2}, {5, 6}},
+ {{1, 3}, 1, {3, 4}, 1},
+ {{1, 2}, {2, 4}, 1, 4},
+ {},
+ {2, 1, 1},
+ };
+ auto symbols_0 = set_shape_symbols(input_shapes[0]);
+ auto symbols_1 = set_shape_symbols(input_shapes[1]);
+ auto symbols_2 = set_shape_symbols(input_shapes[2]);
+ auto symbols_3 = set_shape_symbols(input_shapes[3]);
+ auto symbols_4 = set_shape_symbols(input_shapes[4]);
+ const auto inputs = make_inputs(et, input_shapes);
+ const auto o = make_op(inputs, equation);
+
+ EXPECT_EQ(o->get_equation(), equation);
+ EXPECT_EQ(o->get_element_type(), et);
+ EXPECT_EQ(o->get_output_size(), exp_einsum_outputs_count);
+ EXPECT_EQ(o->get_output_partial_shape(0), PartialShape({4, 2, 1, {3, 4}, 2, 1}));
+ EXPECT_THAT(get_shape_symbols(o->get_output_partial_shape(0)),
+ ElementsAre(symbols_2[3], symbols_2[0], symbols_1[1], symbols_1[2], symbols_4[0], symbols_2[2]));
+}
+
+TEST_F(TypePropEinsumTest, input_rank_incompatible_with_equation) {
+ const std::string equation = "ab,bc->ac";
+
+ const auto input_shapes = Shapes{{2, 2, 10}, {3, 4}};
+ const auto inputs = make_inputs(element::f32, input_shapes);
+
+ OV_EXPECT_THROW(auto o = make_op(inputs, equation),
+ AssertFailure,
+ HasSubstr("Input rank must be greater or equal to a number of labels in the "
+ "corresponding input subscript."));
+}
+
+TEST_F(TypePropEinsumTest, input_rank_incompatible_with_equation_single_input) {
+ const std::string equation = "ab->ba";
+
+ const auto input_shapes = Shapes{{3, 5, 7}};
const auto inputs = make_inputs(element::f32, input_shapes);
OV_EXPECT_THROW(auto o = make_op(inputs, equation),
AssertFailure,
- HasSubstr("Output subscript of Einsum equation must contain one "
- "ellipsis if ellipsis is met in any input subscript."));
+ HasSubstr("Input rank must be greater or equal to a number of labels in the "
+ "corresponding input subscript."));
}
diff --git a/src/frontends/onnx/tests/__init__.py b/src/frontends/onnx/tests/__init__.py
index f042120a719..a46e891073d 100644
--- a/src/frontends/onnx/tests/__init__.py
+++ b/src/frontends/onnx/tests/__init__.py
@@ -120,7 +120,6 @@ xfail_issue_49753 = xfail_test(reason="RuntimeError: Unsupported dynamic ops: v1
xfail_issue_49754 = xfail_test(reason="RuntimeError: Unsupported dynamic ops: v1::TopKIE")
xfail_issue_52463 = xfail_test(reason="test_operator_add_size1_singleton_broadcast_cpu - "
"Not equal to tolerance")
-xfail_issue_58033 = xfail_test(reason="Einsum operation misses support for complex ellipsis equations")
xfail_issue_58676 = xfail_test(reason="AssertionError: Not equal to tolerance rtol=0.001, atol=1e-07")
skip_issue_58676 = pytest.mark.skip(reason="AssertionError: Not equal to tolerance rtol=0.001, atol=1e-07")
xfail_issue_onnx_models_140 = xfail_test(reason="https://github.com/onnx/models/issues/140")
diff --git a/src/frontends/onnx/tests/tests_python/test_backend.py b/src/frontends/onnx/tests/tests_python/test_backend.py
index 433a8cf0f83..41ca8b4f9a7 100644
--- a/src/frontends/onnx/tests/tests_python/test_backend.py
+++ b/src/frontends/onnx/tests/tests_python/test_backend.py
@@ -32,7 +32,6 @@ from tests import (
xfail_issue_73538,
xfail_issue_48052,
xfail_issue_52463,
- xfail_issue_58033,
xfail_issue_63033,
xfail_issue_63036,
xfail_issue_63043,
@@ -292,7 +291,6 @@ tests_expected_to_fail = [
"OnnxBackendNodeModelTest.test_sequence_insert_at_back_cpu",
"OnnxBackendNodeModelTest.test_sequence_insert_at_front_cpu",
),
- (xfail_issue_58033, "OnnxBackendNodeModelTest.test_einsum_batch_diagonal_cpu"),
(
xfail_issue_63033,
"OnnxBackendNodeModelTest.test_batchnorm_epsilon_training_mode_cpu",
diff --git a/src/plugins/template/tests/functional/op_reference/einsum.cpp b/src/plugins/template/tests/functional/op_reference/einsum.cpp
index 2d3e7fb6273..431c413945b 100644
--- a/src/plugins/template/tests/functional/op_reference/einsum.cpp
+++ b/src/plugins/template/tests/functional/op_reference/einsum.cpp
@@ -154,6 +154,276 @@ std::vector<EinsumParams> generateParams() {
.equation("abbac,bad->ad")
.expectedResult({ET, {2, 1}, std::vector<T>{123, 129}})
.testcaseName("einsum_diagonal_with_matmul"),
+
+ Builder{}
+ .inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
+ .equation("...->...")
+ .expectedResult({ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}})
+ .testcaseName("einsum_identity"),
+ Builder{}
+ .inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
+ .equation("i...->i")
+ .expectedResult({ET, {2}, std::vector<T>{6, 15}})
+ .testcaseName("einsum_reduce_ellipsis"),
+ Builder{}
+ .inputs({{ET, {3, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}}})
+ .equation("iii->")
+ .expectedResult({ET, {}, std::vector<T>{42}})
+ .testcaseName("einsum_trace"),
+ Builder{}
+ .inputs({{ET, {3, 3, 4}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}}})
+ .equation("ii...->")
+ .expectedResult({ET, {}, std::vector<T>{222}})
+ .testcaseName("einsum_trace_ellipsis"),
+ Builder{}
+ .inputs({{ET, {3, 2, 1, 2, 1, 3, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}}})
+ .equation("ijkjkik->ijk")
+ .expectedResult({ET, {3, 2, 1}, std::vector<T>{1, 10, 14, 23, 27, 36}})
+ .testcaseName("einsum_diagonal_mixed_order"),
+ Builder{}
+ .inputs({{ET,
+ {3, 3, 3, 3, 3},
+ std::vector<T>{
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
+ 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
+ 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
+ 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
+ 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171,
+ 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190,
+ 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
+ 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228,
+ 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243}}})
+ .equation("iiiii->i")
+ .expectedResult({ET, {3}, std::vector<T>{1, 122, 243}})
+ .testcaseName("einsum_5d_diagonal"),
+ Builder{}
+ .inputs({{ET, {2, 1}, std::vector<T>{1, 2}},
+ {ET, {4, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {3, 1, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9}}})
+ .equation("ab,bcd,dbc->ca")
+ .expectedResult({ET, {3, 2}, std::vector<T>{120, 240, 150, 300, 180, 360}})
+ .testcaseName("einsum_3in_broadcast"),
+ Builder{}
+ .inputs({{ET, {2, 1}, std::vector<T>{1, 2}}, {ET, {3, 2}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
+ .equation("ab,bc->ac")
+ .expectedResult({ET, {2, 2}, std::vector<T>{9, 12, 18, 24}})
+ .testcaseName("einsum_2in_broadcast_lhs_reduced"),
+ Builder{}
+ .inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}, {ET, {1, 2}, std::vector<T>{1, 2}}})
+ .equation("ab,bc->ac")
+ .expectedResult({ET, {2, 2}, std::vector<T>{6, 12, 15, 30}})
+ .testcaseName("einsum_2in_broadcast_rhs_reduced"),
+ Builder{}
+ .inputs({{ET, {2, 1}, std::vector<T>{1, 2}}, {ET, {3, 2}, std::vector<T>{1, 2, 3, 4, 5, 6}}})
+ .equation("ab,bc->bc")
+ .expectedResult({ET, {3, 2}, std::vector<T>{3, 6, 9, 12, 15, 18}})
+ .testcaseName("einsum_2in_broadcast_lhs_common"),
+ Builder{}
+ .inputs({{ET, {2, 3}, std::vector<T>{1, 2, 3, 4, 5, 6}}, {ET, {1, 2}, std::vector<T>{1, 2}}})
+ .equation("ab,bc->cb")
+ .expectedResult({ET, {2, 3}, std::vector<T>{5, 7, 9, 10, 14, 18}})
+ .testcaseName("einsum_2in_broadcast_rhs_common"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}},
+ {ET, {3, 4, 2, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}})
+ .equation("aj,j...->a...")
+ .expectedResult({ET, {1, 4, 2, 1}, std::vector<T>{70, 76, 82, 88, 94, 100, 106, 112}})
+ .testcaseName("einsum_2in_only_rhs_out_ellipsis"),
+ Builder{}
+ .inputs({{ET,
+ {2, 7, 4, 3},
+ std::vector<T>{
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
+ 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
+ 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
+ 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
+ 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168}},
+ {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j->a...")
+ .expectedResult(
+ {ET, {2, 7, 4}, std::vector<T>{14, 32, 50, 68, 86, 104, 122, 140, 158, 176, 194, 212, 230, 248,
+ 266, 284, 302, 320, 338, 356, 374, 392, 410, 428, 446, 464, 482, 500,
+ 518, 536, 554, 572, 590, 608, 626, 644, 662, 680, 698, 716, 734, 752,
+ 770, 788, 806, 824, 842, 860, 878, 896, 914, 932, 950, 968, 986, 1004}})
+ .testcaseName("einsum_2in_only_lhs_out_ellipsis"),
+ Builder{}
+ .inputs({{ET,
+ {2, 7, 4, 3},
+ std::vector<T>{
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
+ 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
+ 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
+ 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
+ 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
+ 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
+ 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133,
+ 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152,
+ 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168}},
+ {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j->a")
+ .expectedResult({ET, {2}, std::vector<T>{7196, 21308}})
+ .testcaseName("einsum_2in_lhs_ellipsis_out_reduced"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}},
+ {ET, {3, 4, 2, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}})
+ .equation("aj,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{728}})
+ .testcaseName("einsum_2in_rhs_ellipsis_out_reduced"),
+ Builder{}
+ .inputs({{ET, {1, 1, 4, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}},
+ {ET, {3, 4, 2, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}})
+ .equation("a...j,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{8312}})
+ .testcaseName("einsum_2in_broadcast_ellipsis_out_reduced"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}},
+ {ET, {3, 4, 2, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}})
+ .equation("a...j,j...->a...")
+ .expectedResult({ET, {1, 4, 2, 1}, std::vector<T>{70, 76, 82, 88, 94, 100, 106, 112}})
+ .testcaseName("einsum_2in_unsqueeze_lhs_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 1, 4, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}},
+ {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j...->a...")
+ .expectedResult({ET, {1, 1, 4}, std::vector<T>{14, 32, 50, 68}})
+ .testcaseName("einsum_2in_unsqueeze_rhs_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}},
+ {ET, {3, 4, 2, 1}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}}})
+ .equation("a...j,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{728}})
+ .testcaseName("einsum_2in_unsqueeze_lhs_ellipsis_no_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 1, 4, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}},
+ {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{164}})
+ .testcaseName("einsum_2in_unsqueeze_rhs_ellipsis_no_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j->a...")
+ .expectedResult({ET, {1}, std::vector<T>{14}})
+ .testcaseName("einsum_2in_prune_lhs_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("aj,j...->a...")
+ .expectedResult({ET, {1}, std::vector<T>{14}})
+ .testcaseName("einsum_2in_prune_rhs_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("aj,j->a...")
+ .expectedResult({ET, {1}, std::vector<T>{14}})
+ .testcaseName("einsum_2in_prune_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j...->a...")
+ .expectedResult({ET, {1}, std::vector<T>{14}})
+ .testcaseName("einsum_2in_prune_all_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {1}, std::vector<T>{1}}})
+ .equation("a...j,j->a")
+ .expectedResult({ET, {1}, std::vector<T>{6}})
+ .testcaseName("einsum_2in_prune_lhs_ellipsis_no_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 1}, std::vector<T>{1}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("aj,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{6}})
+ .testcaseName("einsum_2in_prune_rhs_ellipsis_no_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 3}, std::vector<T>{1, 2, 3}}, {ET, {3}, std::vector<T>{1, 2, 3}}})
+ .equation("a...j,j...->a")
+ .expectedResult({ET, {1}, std::vector<T>{14}})
+ .testcaseName("einsum_2in_prune_inp_ellipsis_no_out_ellipsis"),
+ Builder{}
+ .inputs({{ET, {2, 2, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {4, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET,
+ {1, 1, 2, 3, 1, 3},
+ std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18}}})
+ .equation("a...b,bcd,...dbc->c...a")
+ .expectedResult(
+ {ET, {3, 1, 1, 2, 2}, std::vector<T>{120, 360, 780, 1560, 150, 450, 840, 1680, 180, 540, 900, 1800}})
+ .testcaseName("einsum_3in_broadcast_duplicated_ellipsis"),
+
+ Builder{}
+ .inputs({{ET, {2, 2, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {4, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {1, 2, 3, 1, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54}}})
+ .equation("a...b,bcd,...dbcc->c...a")
+ .expectedResult(
+ {ET, {3, 1, 2, 2}, std::vector<T>{300, 900, 2220, 4440, 420, 1260, 2460, 4920, 540, 1620, 2700, 5400}})
+ .testcaseName("einsum_3in_broadcast_duplicated_ellipsis_repeated_1"),
+ Builder{}
+ .inputs({{ET, {2, 2, 1, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {4, 1, 1, 1, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {3, 1, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}}})
+ .equation("a...b,bcccdd,...dbcc->cb...")
+ .expectedResult(
+ {ET, {3, 4, 2, 1, 1}, std::vector<T>{120, 180, 240, 360, 360, 540, 480, 720, 168, 252, 336, 504,
+ 504, 756, 672, 1008, 216, 324, 432, 648, 648, 972, 864, 1296}})
+ .testcaseName("einsum_3in_broadcast_duplicated_ellipsis_repeated_1"),
+ Builder{}
+ .inputs({{ET, {2, 2, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {4, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {1, 2, 3, 1, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28,
+ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
+ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54}}})
+ .equation("a...b,bcd,...dbcc->ca")
+ .expectedResult({ET, {3, 2}, std::vector<T>{2520, 5340, 2880, 6180, 3240, 7020}})
+ .testcaseName("einsum_3in_broadcast_duplicated_ellipsis_repeated_3"),
+ Builder{}
+ .inputs({{ET, {2, 2, 1, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {4, 1, 1, 1, 1, 1}, std::vector<T>{1, 2, 3, 4}},
+ {ET, {3, 1, 3, 3}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27}}})
+ .equation("a...b,bcccdd,...dbcc->cb")
+ .expectedResult(
+ {ET, {3, 4}, std::vector<T>{300, 600, 900, 1200, 420, 840, 1260, 1680, 540, 1080, 1620, 2160}})
+ .testcaseName("einsum_3in_broadcast_duplicated_ellipsis_repeated_4"),
+ Builder{}
+ .inputs({{ET, {2, 1, 4}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8}},
+ {ET, {1, 1, 1, 2, 2}, std::vector<T>{1, 2, 3, 4}}})
+ .equation("acd,ad...->acd...")
+ .expectedResult(
+ {ET, {2, 1, 4, 1, 2, 2}, std::vector<T>{1, 2, 3, 4, 2, 4, 6, 8, 3, 6, 9, 12, 4, 8, 12, 16,
+ 5, 10, 15, 20, 6, 12, 18, 24, 7, 14, 21, 28, 8, 16, 24, 32}})
+ .testcaseName("einsum_no_reduce1_sep2ellipsis"),
+ Builder{}
+ .inputs({{ET, {1, 5}, std::vector<T>{1, 2, 3, 4, 5}},
+ {ET, {1, 1, 2, 1}, std::vector<T>{1, 2}},
+ {ET, {2, 2, 1, 4}, std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}},
+ {ET, {}, std::vector<T>{2}},
+ {ET, {2, 1, 1}, std::vector<T>{1, 2}}})
+ .equation("a...b,b...,aacd,,...dd->da...c")
+ .expectedResult(
+ {ET, {4, 2, 1, 2, 2, 1}, std::vector<T>{30, 60, 60, 120, 390, 780, 780, 1560, 60, 120, 120,
+ 240, 420, 840, 840, 1680, 90, 180, 180, 360, 450, 900,
+ 900, 1800, 120, 240, 240, 480, 480, 960, 960, 1920}})
+ .testcaseName("einsum_multi_input_broadcasting")
+
};
return params;
}
@@ -161,6 +431,7 @@ std::vector<EinsumParams> generateParams() {
std::vector<EinsumParams> generateCombinedParams() {
const std::vector<std::vector<EinsumParams>> generatedParams{
generateParams<element::Type_t::i32>(),
+ generateParams<element::Type_t::f16>(),
generateParams<element::Type_t::f32>(),
};
std::vector<EinsumParams> combinedParams;
diff --git a/tests/model_hub_tests/pytorch/hf_transformers_models b/tests/model_hub_tests/pytorch/hf_transformers_models
index 3d05a430a16..c861c0cb6c6 100644
--- a/tests/model_hub_tests/pytorch/hf_transformers_models
+++ b/tests/model_hub_tests/pytorch/hf_transformers_models
@@ -88,7 +88,7 @@ hifigan,microsoft/speecht5_hifigan,xfail,Load error: The size of tensor a (100)
hubert,facebook/hubert-large-ls960-ft
hybridbert,gokuls/bert_12_layer_model_v1
ibert,DunnBC22/ibert-roberta-base-Abusive_Or_Threatening_Speech
-idefics,HuggingFaceM4/tiny-random-idefics,xfail,aten::einsum Different input dimensions indicated by the same labels for Einsum must be compatible
+idefics,HuggingFaceM4/tiny-random-idefics
imagegpt,openai/imagegpt-small
informer,huggingface/informer-tourism-monthly,xfail,Load error: mat1 and mat2 shapes cannot be multiplied
instructblip,Salesforce/instructblip-vicuna-7b
@@ -106,7 +106,7 @@ levit,facebook/levit-128S,xfail,Trace error: Cannot insert a Tensor that require
lilt,nielsr/lilt-xlm-roberta-base
llama_with_landmark,Leooyii/Landmark_512_Slimpajama_1B
longformer,allenai/longformer-base-4096
-longt5,pszemraj/long-t5-tglobal-base-16384-book-summary,xfail,(CVS-148676) Compile error: unsupported Einsum
+longt5,pszemraj/long-t5-tglobal-base-16384-book-summary
luke,oshizo/sbert-jsnli-luke-japanese-base-lite
lxmert,unc-nlp/lxmert-base-uncased
m2m_100,facebook/nllb-200-distilled-600M
@@ -119,7 +119,7 @@ mbart,facebook/mbart-large-50-many-to-many-mmt
mctct,speechbrain/m-ctc-t-large
mega,Bingsu/mega-150m-arch,xfail,Trace error: Cannot insert a Tensor that requires grad as a constant
megatron-bert,UFNLP/gatortron-base
-mgp-str,alibaba-damo/mgp-str-base,xfail,(CVS-148676) Compile error: unsupported Einsum
+mgp-str,alibaba-damo/mgp-str-base
mobilebert,google/mobilebert-uncased
mobilenet_v1,google/mobilenet_v1_0.75_192
mobilenet_v2,google/mobilenet_v2_1.0_224