OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU] Introduce GatherMatmul operation to optimize MoE pattern (#32450)
Maksim Kutakovb56011e442f3
diff --git a/src/common/transformations/include/transformations/op_conversions/convert_fc_to_compressed.hpp b/src/common/transformations/include/transformations/op_conversions/convert_fc_to_compressed.hppindex 8a10fcc1939..ef9e57457a8 100644--- a/src/common/transformations/include/transformations/op_conversions/convert_fc_to_compressed.hpp+++ b/src/common/transformations/include/transformations/op_conversions/convert_fc_to_compressed.hpp@@ -4,8 +4,14 @@#pragma once+#include <memory>+#include <tuple>+#include <vector>+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/matcher.hpp"#include "ov_ops/fully_connected.hpp"+#include "transformations/pattern_blocks/compressed_weights_block.hpp"#include "transformations_visibility.hpp"namespace ov {@@ -27,4 +33,26 @@ public:const std::vector<ov::element::Type>& supported_weights_types,SupportsPredicate supports_config = nullptr,bool convert_u4zp_to_u8 = false);++ /**+ * @brief Processes compressed weights from a pattern block and prepares them for compressed operations.+ *+ * @param weights_block The CompressedWeightsBlock pattern containing the weight compression graph+ * @param pattern_map The pattern value map from the matcher containing matched nodes+ * @param convert_u4zp_to_u8 Flag indicating whether to convert u4 zero points to u8+ * @param has_transpose Flag indicating whether the weights require transpose operation+ * @param grouped Flag indicating whether the compression uses grouped quantization+ * @param batched_weights Flag indicating whether the weights have a batch dimension+ * @param result_nodes Output vector to collect intermediate nodes created during processing+ *+ * @return A tuple containing processed compressed weights, decompression scales, and decompression zero points.+ */+ static std::tuple<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>>+ process_compressed_weights(const std::shared_ptr<ov::pass::pattern::op::CompressedWeightsBlock>& weights_block,+ const ov::pass::pattern::PatternValueMap& pattern_map,+ bool convert_u4zp_to_u8,+ bool has_transpose,+ bool grouped,+ bool batched_weights,+ std::vector<std::shared_ptr<ov::Node>>& result_nodes);};diff --git a/src/common/transformations/include/transformations/pattern_blocks/compressed_weights_block.hpp b/src/common/transformations/include/transformations/pattern_blocks/compressed_weights_block.hppnew file mode 100644index 00000000000..5b606910478--- /dev/null+++ b/src/common/transformations/include/transformations/pattern_blocks/compressed_weights_block.hpp@@ -0,0 +1,22 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/op/block.hpp"+#include "ov_ops/fully_connected.hpp"+#include "transformations_visibility.hpp"++namespace ov::pass::pattern::op {++class TRANSFORMATIONS_API CompressedWeightsBlock;++} // namespace ov::pass::pattern::op++class ov::pass::pattern::op::CompressedWeightsBlock : public ov::pass::pattern::op::Block {+public:+ CompressedWeightsBlock(const std::vector<ov::element::Type>& supported_weights_types,+ const std::set<size_t>& supported_weights_ranks);+};diff --git a/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp b/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cppindex 399c3aa5538..b9c71b1b054 100644--- a/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp+++ b/src/common/transformations/src/transformations/op_conversions/convert_fc_to_compressed.cpp@@ -6,6 +6,7 @@#include <algorithm>#include <memory>+#include <tuple>#include "openvino/core/graph_util.hpp"#include "openvino/core/rt_info.hpp"@@ -21,151 +22,155 @@#include "openvino/pass/pattern/op/wrap_type.hpp"#include "ov_ops/fully_connected.hpp"#include "ov_ops/fully_connected_compressed.hpp"+#include "transformations/pattern_blocks/compressed_weights_block.hpp"#include "transformations/utils/utils.hpp"-ov::pass::ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyConnectedCompressed(- const std::vector<ov::element::Type>& supported_activation_types,- const std::vector<ov::element::Type>& supported_weights_types,- SupportsPredicate supports_config,- bool convert_u4zp_to_u8) {- using namespace ov::pass::pattern;+std::tuple<std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>, std::shared_ptr<ov::Node>>+ov::pass::ConvertFullyConnectedToFullyConnectedCompressed::process_compressed_weights(+ const std::shared_ptr<ov::pass::pattern::op::CompressedWeightsBlock>& weights_block,+ const ov::pass::pattern::PatternValueMap& pattern_map,+ bool convert_u4zp_to_u8,+ bool has_transpose,+ bool grouped,+ bool batched_weights,+ std::vector<std::shared_ptr<ov::Node>>& result_nodes) {+ const size_t final_weights_rank = batched_weights ? 3 : 2;+ auto combine_groups = [has_transpose, grouped, final_weights_rank](std::shared_ptr<ov::Node> node) {+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);+ OPENVINO_ASSERT(constant != nullptr);+ const auto& current_shape = constant->get_shape();+ if (current_shape.size() <= final_weights_rank) {+ return constant;+ }- auto reshape_3d_to_2d = [](const ov::Output<ov::Node>& output) {- auto in_ps = output.get_node()->get_input_partial_shape(0);- auto out_ps = output.get_node()->get_output_partial_shape(0);- return in_ps.rank().is_static() && out_ps.rank().is_static() && in_ps.size() == 3 && out_ps.size() == 2;+ OPENVINO_ASSERT(current_shape.size() == final_weights_rank + 1);+ ov::Shape new_shape(current_shape.begin(), current_shape.begin() + final_weights_rank);+ if (has_transpose || !grouped) {+ // [n_groups, group_size, OC] -> [IC, OC]+ const auto& n_groups = *(current_shape.rbegin() + 2);+ const auto& group_size = *(current_shape.rbegin() + 1);+ const auto& OC = *(current_shape.rbegin());+ auto& new_IC = *(new_shape.rbegin() + 1);+ auto& new_OC = *(new_shape.rbegin());+ new_IC = n_groups * group_size;+ new_OC = OC;+ } else {+ // [OC, n_groups, group_size] -> [OC, IC]+ const auto& n_groups = *(current_shape.rbegin() + 1);+ const auto& group_size = *(current_shape.rbegin());+ const auto& OC = *(current_shape.rbegin() + 2);+ auto& new_OC = *(new_shape.rbegin() + 1);+ auto& new_IC = *new_shape.rbegin();+ new_OC = OC;+ new_IC = n_groups * group_size;+ }+ return std::make_shared<ov::op::v0::Constant>(*constant, new_shape);};- auto activation_m = any_input(ov::pass::pattern::type_matches_any(supported_activation_types));- auto weights_m = wrap_type<ov::op::v0::Constant>(ov::pass::pattern::type_matches_any(supported_weights_types));- auto convert_m = wrap_type<ov::op::v0::Convert>({weights_m});+ auto convert_u4const_to_u8 = [convert_u4zp_to_u8](std::shared_ptr<ov::Node> node) -> std::shared_ptr<ov::Node> {+ auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);+ if (constant->get_element_type() != ov::element::u4 || !convert_u4zp_to_u8)+ return std::dynamic_pointer_cast<ov::Node>(constant);+ return std::make_shared<ov::op::v0::Convert>(node, ov::element::u8);+ };- auto sub_const_m = wrap_type<ov::op::v0::Constant>();- auto sub_convert_const_m = wrap_type<ov::op::v0::Convert>({sub_const_m});- auto sub_with_convert_m = wrap_type<ov::op::v1::Subtract>({convert_m, sub_convert_const_m});- auto sub_no_convert_m = wrap_type<ov::op::v1::Subtract>({convert_m, sub_const_m});- auto subtract_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{sub_with_convert_m, sub_no_convert_m});+ const auto& scale =+ combine_groups(weights_block->get_anchor("mul_const", pattern_map).value().get_node_shared_ptr());+ std::shared_ptr<ov::Node> optional_zero_point = nullptr;++ const bool with_zero_point = weights_block->get_anchor("sub_no_convert", pattern_map) ||+ weights_block->get_anchor("sub_with_convert", pattern_map);+ if (with_zero_point) {+ // WA: Convert ZP to u8 for OneDNN case to avoid u4 reorder+ optional_zero_point = convert_u4const_to_u8(+ combine_groups(weights_block->get_anchor("sub_const", pattern_map).value().get_node_shared_ptr()));+ }++ std::shared_ptr<ov::Node> fc_input_b =+ combine_groups(weights_block->get_anchor("weights", pattern_map).value().get_node_shared_ptr());+ std::shared_ptr<ov::Node> fc_input_scale = scale;+ std::shared_ptr<ov::Node> fc_input_zp = optional_zero_point;++ if (has_transpose) {+ const auto& transpose = weights_block->get_anchor("transpose", pattern_map).value().get_node_shared_ptr();+ std::shared_ptr<ov::Node> transpose_const =+ weights_block->get_anchor("transpose_const", pattern_map).value().get_node_shared_ptr();+ if (ov::shape_size(transpose_const->get_shape()) != fc_input_b->get_output_partial_shape(0).size()) {+ std::vector<int32_t> new_order(fc_input_b->get_output_partial_shape(0).size());+ std::iota(new_order.begin(), new_order.end(), 0);+ std::swap(new_order[new_order.size() - 1], new_order[new_order.size() - 2]);+ transpose_const =+ std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{new_order.size()}, new_order);+ }- auto mul_const_m = wrap_type<ov::op::v0::Constant>();- auto mul_convert_const_m = wrap_type<ov::op::v0::Convert>({mul_const_m});- auto mul_scale_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{mul_const_m, mul_convert_const_m});+ fc_input_b = transpose->clone_with_new_inputs({fc_input_b->output(0), transpose_const});+ ov::disable_constant_folding(fc_input_b);+ result_nodes.push_back(fc_input_b);+ fc_input_scale = transpose->clone_with_new_inputs({scale->output(0), transpose_const});+ ov::disable_constant_folding(fc_input_scale);+ result_nodes.push_back(fc_input_scale);+ if (with_zero_point && ov::shape_size(optional_zero_point->output(0).get_shape()) > 1) {+ fc_input_zp = transpose->clone_with_new_inputs({optional_zero_point->output(0), transpose_const});+ ov::disable_constant_folding(fc_input_zp);+ result_nodes.push_back(fc_input_zp);+ }+ }- auto mul_with_sub_m = wrap_type<ov::op::v1::Multiply>({subtract_m, mul_scale_m});- auto mul_no_sub_m = wrap_type<ov::op::v1::Multiply>({convert_m, mul_scale_m});- auto mul_m = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{mul_with_sub_m, mul_no_sub_m});+ fc_input_zp =+ with_zero_point ? fc_input_zp : std::make_shared<ov::op::v0::Constant>(ov::element::dynamic, ov::Shape{0});+ ov::disable_constant_folding(fc_input_zp);+ result_nodes.push_back(fc_input_zp);- auto reshape_const_m = wrap_type<ov::op::v0::Constant>();- auto reshape_m = wrap_type<ov::op::v1::Reshape>({mul_m, reshape_const_m}, reshape_3d_to_2d);+ return std::make_tuple(fc_input_b, fc_input_scale, fc_input_zp);+}- auto transpose_input = std::make_shared<ov::pass::pattern::op::Or>(OutputVector{reshape_m, mul_m});- auto transpose_const_m = wrap_type<ov::op::v0::Constant>();- auto transpose_m = wrap_type<ov::op::v1::Transpose>({transpose_input, transpose_const_m});+ov::pass::ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedToFullyConnectedCompressed(+ const std::vector<ov::element::Type>& supported_activation_types,+ const std::vector<ov::element::Type>& supported_weights_types,+ SupportsPredicate supports_config,+ bool convert_u4zp_to_u8) {+ using namespace ov::pass::pattern;- auto bias_m = any_input();- auto weights_input_m = std::make_shared<ov::pass::pattern::op::Or>(ov::OutputVector{reshape_m, transpose_m, mul_m});- auto fully_connected_m = wrap_type<ov::op::internal::FullyConnected>({activation_m, weights_input_m, bias_m});+ auto weights_block =+ std::make_shared<ov::pass::pattern::op::CompressedWeightsBlock>(supported_weights_types, std::set<size_t>{2});+ auto activation = any_input(type_matches_any(supported_activation_types));+ auto bias = any_input();+ auto fully_connected = wrap_type<ov::op::internal::FullyConnected>({activation, weights_block, bias});- ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {const auto& pattern_map = m.get_pattern_value_map();- OPENVINO_ASSERT(pattern_map.count(fully_connected_m));- OPENVINO_ASSERT(pattern_map.count(mul_const_m));- OPENVINO_ASSERT(pattern_map.count(weights_m));- OPENVINO_ASSERT(pattern_map.count(bias_m));- OPENVINO_ASSERT(pattern_map.count(convert_m));auto fc =- ov::as_type_ptr<ov::op::internal::FullyConnected>(pattern_map.at(fully_connected_m).get_node_shared_ptr());+ ov::as_type_ptr<ov::op::internal::FullyConnected>(pattern_map.at(fully_connected).get_node_shared_ptr());if (!fc || transformation_callback(fc)) {return false;}- bool has_transpose = pattern_map.count(transpose_m);- auto scale_shape = pattern_map.at(mul_const_m).get_shape();+ bool has_transpose = weights_block->get_anchor("transpose", pattern_map).has_value();+ const auto& weights_shape = fc->get_input_shape(1);+ bool batched_weights = weights_shape.size() == 3 && weights_shape[0] > 1;+ auto scale_shape = weights_block->get_anchor("mul_const", pattern_map).value().get_shape();bool grouped = std::count_if(scale_shape.begin(), scale_shape.end(), [](size_t d) {return d > 1;- }) > 1;-- auto weights_shape = fc->get_input_shape(1);- const size_t IC = *(weights_shape.rbegin());- const size_t OC = *(weights_shape.rbegin() + 1);-- const size_t G = grouped ? (has_transpose ? *(scale_shape.rbegin() + 2) : *(scale_shape.rbegin() + 1)) : 1;-- auto reshape_const_to_2d = [has_transpose, grouped](std::shared_ptr<ov::Node> node) {- auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);- OPENVINO_ASSERT(constant != nullptr);- ov::Shape current_shape = constant->get_shape();- if (current_shape.size() <= 2)- return constant;-- OPENVINO_ASSERT(current_shape.size() == 3);-- auto new_shape = (has_transpose || !grouped)- ? ov::Shape{current_shape[0] * current_shape[1], current_shape[2]}- : ov::Shape{current_shape[0], current_shape[1] * current_shape[2]};-- return std::make_shared<ov::op::v0::Constant>(*constant, new_shape);- };-- auto convert_u4const_to_u8 = [convert_u4zp_to_u8](std::shared_ptr<ov::Node> node) -> std::shared_ptr<ov::Node> {- auto constant = ov::as_type_ptr<ov::op::v0::Constant>(node);- if (constant->get_element_type() != ov::element::u4 || !convert_u4zp_to_u8)- return std::dynamic_pointer_cast<ov::Node>(constant);- return std::make_shared<ov::op::v0::Convert>(node, ov::element::u8);- };-- const ov::Output<Node>& fc_input_a = fc->input_value(0);- const auto& scale = reshape_const_to_2d(pattern_map.at(mul_const_m).get_node_shared_ptr());- std::shared_ptr<ov::Node> optional_zero_point = nullptr;-- const bool with_zero_point =- pattern_map.count(sub_no_convert_m) > 0 || pattern_map.count(sub_with_convert_m) > 0;- if (with_zero_point) {- // WA: Convert ZP to u8 for OneDNN case to avoid u4 reorder- optional_zero_point =- convert_u4const_to_u8(reshape_const_to_2d(pattern_map.at(sub_const_m).get_node_shared_ptr()));- }-- std::shared_ptr<ov::Node> fc_input_b = reshape_const_to_2d(pattern_map.at(weights_m).get_node_shared_ptr());- std::shared_ptr<ov::Node> fc_input_scale = scale;- std::shared_ptr<ov::Node> fc_input_zp = optional_zero_point;- std::shared_ptr<ov::Node> fc_input_bias = pattern_map.at(bias_m).get_node_shared_ptr();- std::vector<std::shared_ptr<ov::Node>> result_nodes = {};- if (has_transpose) {- const auto& transpose = pattern_map.at(transpose_m).get_node_shared_ptr();- std::shared_ptr<ov::Node> transpose_const = pattern_map.at(transpose_const_m).get_node_shared_ptr();- if (ov::shape_size(transpose_const->get_shape()) != fc_input_b->get_output_partial_shape(0).size()) {- std::vector<int32_t> new_order(fc_input_b->get_output_partial_shape(0).size());- std::iota(new_order.begin(), new_order.end(), 0);- std::swap(new_order[new_order.size() - 1], new_order[new_order.size() - 2]);- transpose_const =- std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{new_order.size()}, new_order);- }-- fc_input_b = transpose->clone_with_new_inputs({fc_input_b->output(0), transpose_const});- ov::disable_constant_folding(fc_input_b);- result_nodes.push_back(fc_input_b);- fc_input_scale = transpose->clone_with_new_inputs({scale->output(0), transpose_const});- ov::disable_constant_folding(fc_input_scale);- result_nodes.push_back(fc_input_scale);- if (with_zero_point && ov::shape_size(optional_zero_point->output(0).get_shape()) > 1) {- fc_input_zp = transpose->clone_with_new_inputs({optional_zero_point->output(0), transpose_const});- ov::disable_constant_folding(fc_input_zp);- result_nodes.push_back(fc_input_zp);- }- }-- fc_input_zp =- with_zero_point ? fc_input_zp : std::make_shared<ov::op::v0::Constant>(element::dynamic, Shape{0});- ov::disable_constant_folding(fc_input_zp);- result_nodes.push_back(fc_input_zp);-- auto new_fc = std::make_shared<ov::op::internal::FullyConnectedCompressed>(fc_input_a,+ }) > (batched_weights ? 2 : 1);+ ov::NodeVector result_nodes;+ const auto [fc_input_b, fc_input_scale, fc_input_zp] = process_compressed_weights(weights_block,+ pattern_map,+ convert_u4zp_to_u8,+ has_transpose,+ grouped,+ batched_weights,+ result_nodes);++ auto new_fc = std::make_shared<ov::op::internal::FullyConnectedCompressed>(pattern_map.at(activation),fc_input_b,- fc_input_bias,+ pattern_map.at(bias),fc_input_scale,fc_input_zp,fc->get_output_type());+ const size_t IC = *(weights_shape.rbegin());+ const size_t OC = *(weights_shape.rbegin() + 1);+ const size_t G = grouped ? (has_transpose ? *(scale_shape.rbegin() + 2) : *(scale_shape.rbegin() + 1)) : 1;if (supports_config && !supports_config(new_fc, IC, OC, G))return false;@@ -176,7 +181,6 @@ ov::pass::ConvertFullyConnectedToFullyConnectedCompressed::ConvertFullyConnectedreturn true;};- auto m = std::make_shared<ov::pass::pattern::Matcher>(fully_connected_m,- "ConvertFullyConnectedToFullyConnectedCompressed");+ auto m = std::make_shared<Matcher>(fully_connected, "ConvertFullyConnectedToFullyConnectedCompressed");this->register_matcher(m, callback);}\ No newline at end of filediff --git a/src/common/transformations/src/transformations/pattern_blocks/compressed_weights_block.cpp b/src/common/transformations/src/transformations/pattern_blocks/compressed_weights_block.cppnew file mode 100644index 00000000000..0e13df6dae0--- /dev/null+++ b/src/common/transformations/src/transformations/pattern_blocks/compressed_weights_block.cpp@@ -0,0 +1,81 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "transformations/pattern_blocks/compressed_weights_block.hpp"++#include <algorithm>+#include <memory>++#include "openvino/core/graph_util.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/convert.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/subtract.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/or.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "ov_ops/fully_connected.hpp"+#include "ov_ops/fully_connected_compressed.hpp"+#include "transformations/utils/utils.hpp"++using namespace ov::pass::pattern;+ov::pass::pattern::op::CompressedWeightsBlock::CompressedWeightsBlock(+ const std::vector<ov::element::Type>& supported_weights_types,+ const std::set<size_t>& supported_weights_ranks)+ : Block({}, {}, "CompressedWeightsBlock") {+ auto weights = wrap_type<ov::op::v0::Constant>(type_matches_any(supported_weights_types));+ auto convert = wrap_type<ov::op::v0::Convert>({weights});++ auto sub_const = wrap_type<ov::op::v0::Constant>();+ auto sub_convert_const = wrap_type<ov::op::v0::Convert>({sub_const});+ auto sub_with_convert = wrap_type<ov::op::v1::Subtract>({convert, sub_convert_const});+ auto sub_no_convert = wrap_type<ov::op::v1::Subtract>({convert, sub_const});+ auto subtract = sub_with_convert | sub_no_convert;++ auto mul_const = wrap_type<ov::op::v0::Constant>();+ auto mul_convert_const = wrap_type<ov::op::v0::Convert>({mul_const});+ auto mul_scale = mul_const | mul_convert_const;++ auto mul_with_sub = wrap_type<ov::op::v1::Multiply>({subtract, mul_scale});+ auto mul_no_sub = wrap_type<ov::op::v1::Multiply>({convert, mul_scale});+ auto mul = mul_with_sub | mul_no_sub;++ auto reshape_predicate = [supported_weights_ranks](const ov::Output<ov::Node>& output) {+ const auto& in_ps = output.get_node()->get_input_partial_shape(0);+ const auto& out_ps = output.get_node()->get_output_partial_shape(0);+ std::set<size_t> supported_weights_ranks_before_reshape;+ for (auto r : supported_weights_ranks) {+ supported_weights_ranks_before_reshape.insert(r + 1);+ }+ return in_ps.rank().is_static() && out_ps.rank().is_static() &&+ supported_weights_ranks_before_reshape.count(in_ps.size()) &&+ supported_weights_ranks.count(out_ps.size());+ };+ auto reshape_const = wrap_type<ov::op::v0::Constant>();+ auto reshape = wrap_type<ov::op::v1::Reshape>({mul, reshape_const}, reshape_predicate);++ auto transpose_input = reshape | mul;+ auto transpose_const = wrap_type<ov::op::v0::Constant>();+ auto transpose = wrap_type<ov::op::v1::Transpose>({transpose_input, transpose_const});++ auto weights_input = optional<ov::op::v0::Convert>({reshape | transpose | mul});++ // Block initialization+ m_inputs = ov::OutputVector{weights};+ m_outputs = ov::OutputVector{weights_input};+ REGISTER_ANCHORS(this,+ weights,+ convert,+ sub_const,+ sub_with_convert,+ sub_no_convert,+ mul_const,+ transpose,+ transpose_const);+}\ No newline at end of filediff --git a/src/core/include/openvino/pass/pattern/op/block.hpp b/src/core/include/openvino/pass/pattern/op/block.hppindex 6c4e3de82de..e39c842fd0c 100644--- a/src/core/include/openvino/pass/pattern/op/block.hpp+++ b/src/core/include/openvino/pass/pattern/op/block.hpp@@ -9,7 +9,7 @@namespace {// _MAKE_ANCHOR is an internal macro for REGISTER_ANCHORS that is not supposed to used separately.-#define _MAKE_ANCHOR(x) block->register_anchor(#x, x);+#define _MAKE_ANCHOR(block, x) (block)->register_anchor(#x, x);} // namespace@@ -23,9 +23,9 @@ namespace ov::pass::pattern::op {**/-#define REGISTER_ANCHORS(block, ...) \- do { \- FOR_EACH(_MAKE_ANCHOR, __VA_ARGS__) \+#define REGISTER_ANCHORS(block, ...) \+ do { \+ FOR_EACH(_MAKE_ANCHOR, block, __VA_ARGS__) \} while (0)/**@@ -95,10 +95,11 @@ public:return m_named_anchors;}-private:+protected:OutputVector m_inputs;OutputVector m_outputs;+private:std::map<std::string, Output<Node>> m_named_anchors;};diff --git a/src/core/include/openvino/pass/pattern/op/block_util.hpp b/src/core/include/openvino/pass/pattern/op/block_util.hppindex 9e334bc0f4e..72787e9e9f0 100644--- a/src/core/include/openvino/pass/pattern/op/block_util.hpp+++ b/src/core/include/openvino/pass/pattern/op/block_util.hpp@@ -3,36 +3,49 @@namespace {// FOR_EACH macros up to 16 arguments:-#define FOR_EACH_1(M, x1) M(x1)-#define FOR_EACH_2(M, x1, x2) M(x1) M(x2)-#define FOR_EACH_3(M, x1, x2, x3) M(x1) M(x2) M(x3)-#define FOR_EACH_4(M, x1, x2, x3, x4) M(x1) M(x2) M(x3) M(x4)-#define FOR_EACH_5(M, x1, x2, x3, x4, x5) M(x1) M(x2) M(x3) M(x4) M(x5)-#define FOR_EACH_6(M, x1, x2, x3, x4, x5, x6) M(x1) M(x2) M(x3) M(x4) M(x5) M(x6)-#define FOR_EACH_7(M, x1, x2, x3, x4, x5, x6, x7) M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7)-#define FOR_EACH_8(M, x1, x2, x3, x4, x5, x6, x7, x8) M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8)-#define FOR_EACH_9(M, x1, x2, x3, x4, x5, x6, x7, x8, x9) M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9)-#define FOR_EACH_10(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10)-#define FOR_EACH_11(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11)-#define FOR_EACH_12(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11) M(x12)-#define FOR_EACH_13(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11) M(x12) M(x13)-#define FOR_EACH_14(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11) M(x12) M(x13) M(x14)-#define FOR_EACH_15(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11) M(x12) M(x13) M(x14) M(x15)-#define FOR_EACH_16(M, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) \- M(x1) M(x2) M(x3) M(x4) M(x5) M(x6) M(x7) M(x8) M(x9) M(x10) M(x11) M(x12) M(x13) M(x14) M(x15) M(x16)+#define FOR_EACH_1(M, B, x1) M(B, x1)+#define FOR_EACH_2(M, B, x1, x2) M(B, x1) M(B, x2)+#define FOR_EACH_3(M, B, x1, x2, x3) M(B, x1) M(B, x2) M(B, x3)+#define FOR_EACH_4(M, B, x1, x2, x3, x4) M(B, x1) M(B, x2) M(B, x3) M(B, x4)+#define FOR_EACH_5(M, B, x1, x2, x3, x4, x5) M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5)+#define FOR_EACH_6(M, B, x1, x2, x3, x4, x5, x6) M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6)+#define FOR_EACH_7(M, B, x1, x2, x3, x4, x5, x6, x7) M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7)+#define FOR_EACH_8(M, B, x1, x2, x3, x4, x5, x6, x7, x8) \+ M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8)+#define FOR_EACH_9(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9) \+ M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9)+#define FOR_EACH_10(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10) \+ M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10)+#define FOR_EACH_11(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11) \+ M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11)+#define FOR_EACH_12(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12) \+ M(B, x1) M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11) M(B, x12)+#define FOR_EACH_13(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13) \+ M(B, x1) \+ M(B, x2) M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11) M(B, x12) M(B, x13)+#define FOR_EACH_14(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14) \+ M(B, x1) \+ M(B, x2) \+ M(B, x3) M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11) M(B, x12) M(B, x13) M(B, x14)+#define FOR_EACH_15(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15) \+ M(B, x1) \+ M(B, x2) \+ M(B, x3) \+ M(B, x4) M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11) M(B, x12) M(B, x13) M(B, x14) M(B, x15)+#define FOR_EACH_16(M, B, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16) \+ M(B, x1) \+ M(B, x2) \+ M(B, x3) \+ M(B, x4) \+ M(B, x5) M(B, x6) M(B, x7) M(B, x8) M(B, x9) M(B, x10) M(B, x11) M(B, x12) M(B, x13) M(B, x14) M(B, x15) M(B, x16)-#define GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, NAME, ...) NAME+#define GET_MACRO(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, NAME, ...) NAME#define EXPAND(x) x-#define FOR_EACH(M, ...) \- EXPAND(GET_MACRO(__VA_ARGS__, \+#define FOR_EACH(M, B, ...) \+ EXPAND(GET_MACRO(_0, \+ __VA_ARGS__, \FOR_EACH_16, \FOR_EACH_15, \FOR_EACH_14, \@@ -48,6 +61,6 @@ namespace {FOR_EACH_4, \FOR_EACH_3, \FOR_EACH_2, \- FOR_EACH_1)(M, __VA_ARGS__))+ FOR_EACH_1)(M, B, __VA_ARGS__))} // namespace\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cppindex be2329e486d..ffa2975138f 100644--- a/src/plugins/intel_cpu/src/cpu_types.cpp+++ b/src/plugins/intel_cpu/src/cpu_types.cpp@@ -265,7 +265,9 @@ static const TypeToNameMap& get_type_to_name_tbl() {{"QKVProjection", Type::QKVProjection},{"RMS", Type::RMS},{"SearchSorted", Type::SearchSorted},- {"LoraSubgraph", Type::LoRA}};+ {"LoraSubgraph", Type::LoRA},+ {"BatchGatherMatmul", Type::GatherMatmul},+ {"BatchGatherMatmulCompressed", Type::GatherMatmul}};return type_to_name_tbl;}@@ -400,6 +402,7 @@ std::string NameFromType(const Type type) {CASE(SearchSorted);CASE(SegmentMax);CASE(LoRA);+ CASE(GatherMatmul);CASE(Unknown);}#undef CASEdiff --git a/src/plugins/intel_cpu/src/cpu_types.h b/src/plugins/intel_cpu/src/cpu_types.hindex 95af24e5940..54d893c7f2b 100644--- a/src/plugins/intel_cpu/src/cpu_types.h+++ b/src/plugins/intel_cpu/src/cpu_types.h@@ -137,7 +137,8 @@ enum class Type : uint8_t {RMS,SearchSorted,SegmentMax,- LoRA+ LoRA,+ GatherMatmul};enum class Algorithm : uint8_t {diff --git a/src/plugins/intel_cpu/src/graph.cpp b/src/plugins/intel_cpu/src/graph.cppindex ed6a8ddb483..37b9ae9bbe5 100644--- a/src/plugins/intel_cpu/src/graph.cpp+++ b/src/plugins/intel_cpu/src/graph.cpp@@ -2009,6 +2009,7 @@ void Graph::EnforceInferencePrecision() {Type::Interpolate, // super resolution netsType::PagedAttention, // page attentionType::QKVProjection,+ Type::GatherMatmul,Type::LLMMLP)) {continue; // stop at significant nodes}diff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.h b/src/plugins/intel_cpu/src/nodes/fullyconnected.hindex decc4113844..909170fa118 100644--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.h+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.h@@ -91,9 +91,6 @@ public:this->attrs.weightsNonTransposed = weightsNonTransposed;}- void fuseDecompressionMultiply(const MemoryCPtr& memory);- void fuseDecompressionSubtract(const MemoryCPtr& memory);-protected:void toNumaNodeImpl(int numaID) override;diff --git a/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp b/src/plugins/intel_cpu/src/nodes/gathermatmul.cppnew file mode 100644index 00000000000..4a43bfc27bd--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp@@ -0,0 +1,854 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gathermatmul.h"++#include <oneapi/dnnl/dnnl_common_types.h>+#include <oneapi/dnnl/dnnl_types.h>++#include <bitset>+#include <common/primitive_hashing_utils.hpp>+#include <common/utils.hpp>+#include <cstddef>+#include <cstdint>+#include <cstring>+#include <memory>+#include <oneapi/dnnl/dnnl.hpp>+#include <oneapi/dnnl/dnnl_common.hpp>+#include <string>+#include <tuple>+#include <unordered_map>+#include <utility>+#include <vector>++#include "common/blocked_desc_creator.h"+#include "config.h"+#include "cpu/x64/cpu_isa_traits.hpp"+#include "cpu_memory.h"+#include "cpu_types.h"+#include "dnnl_extension_utils.h"+#include "graph_context.h"+#include "memory_desc/blocked_memory_desc.h"+#include "memory_desc/cpu_memory_desc.h"+#include "memory_desc/cpu_memory_desc_utils.h"+#include "memory_desc/dnnl_memory_desc.h"+#include "node.h"+#include "node_config.h"+#include "onednn/iml_type_mapper.h"+#include "openvino/core/except.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/parallel.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/type/element_type.hpp"+#include "shape_inference/custom/gathermatmul.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"+#include "transformations/utils/utils.hpp"+#include "utils/general_utils.h"++namespace ov::intel_cpu::node {++struct onednn_matmul_key {+ dnnl::memory::desc src_md;+ dnnl::memory::desc weights_md;+ VectorDims scale_shape;+ VectorDims zp_shape;+ bool has_bias;++ [[nodiscard]] size_t hash() const {+ using namespace dnnl::impl;+ using namespace dnnl::impl::primitive_hashing;++ size_t seed = 0;+ seed = hash_combine(seed, get_md_hash(*src_md.get()));+ seed = hash_combine(seed, get_md_hash(*weights_md.get()));+ seed = get_vector_hash(seed, scale_shape);+ seed = get_vector_hash(seed, zp_shape);+ seed = hash_combine(seed, has_bias);+ return seed;+ }++ bool operator==(const onednn_matmul_key& rhs) const {+ return src_md == rhs.src_md && weights_md == rhs.weights_md && scale_shape == rhs.scale_shape &&+ zp_shape == rhs.zp_shape && has_bias == rhs.has_bias;+ }+};++class GatherMatmul::onednn_matmul {+public:+ onednn_matmul() = delete;+ onednn_matmul(const onednn_matmul&) = delete;+ onednn_matmul(onednn_matmul&&) = delete;+ onednn_matmul& operator=(const onednn_matmul&) = delete;+ onednn_matmul& operator=(onednn_matmul&&) = delete;++ onednn_matmul(const dnnl::engine& eng, const onednn_matmul_key& key) : m_has_bias(key.has_bias) {+ const auto& src_md = key.src_md;+ const auto& weights_md = key.weights_md;+ auto scale_shape = key.scale_shape;+ auto zp_shape = key.zp_shape;++ const auto K = weights_md.get_dims()[1];+ const auto N = weights_md.get_dims()[0];+ const auto M = src_md.get_dims()[0];++ if (!scale_shape.empty()) {+ if (all_of(1U, scale_shape.size(), scale_shape[0])) {+ scale_shape.push_back(1);+ }+ OPENVINO_ASSERT(scale_shape.size() == 2, "Unsupported scale shape ", vec2str(scale_shape));+ const auto K_groups = scale_shape.back();+ OPENVINO_ASSERT((K % K_groups) == 0, "Incompatible number of groups ", K_groups, " for K ", K);+ init_w_scales(scale_shape);+ if (!zp_shape.empty()) {+ if (all_of(1U, zp_shape.size(), zp_shape[0])) {+ zp_shape.push_back(1);+ }+ OPENVINO_ASSERT(zp_shape.size() == 2, "Unsupported zero points shape ", vec2str(zp_shape));+ init_w_zp(zp_shape);+ }+ }++ m_input_md = src_md;+ m_output_md =+ dnnl::memory::desc(dnnl::memory::dims({M, N}), src_md.get_data_type(), dnnl::memory::format_tag::ab);++ dnnl::memory::desc bias_md;+ if (m_has_bias) {+ bias_md =+ dnnl::memory::desc(dnnl::memory::dims({N}), dnnl::memory::data_type::f32, dnnl::memory::format_tag::a);+ }++ auto inner_product_primitive_desc =+ dnnl::inner_product_forward::primitive_desc(eng,+ dnnl::prop_kind::forward_inference,+ m_input_md,+ weights_md,+ bias_md,+ m_output_md,+ attr);++ m_impl_type = parse_impl_name(inner_product_primitive_desc.impl_info_str());++ m_wei_md = inner_product_primitive_desc.weights_desc();+ m_prim = dnnl::inner_product_forward(inner_product_primitive_desc);++ dnnl::memory inp_memory(m_input_md, eng, DNNL_MEMORY_NONE);+ dnnl::memory out_memory(m_output_md, eng, DNNL_MEMORY_NONE);+ dnnl::memory wei_memory(m_wei_md, eng, DNNL_MEMORY_NONE);+ dnnl::memory bias_memory;+ if (m_has_bias) {+ bias_memory = dnnl::memory(bias_md, eng, DNNL_MEMORY_NONE);+ }+ dnnl::memory scale_memory;+ if (!scale_shape.empty()) {+ scale_memory = dnnl::memory(m_scale_md, eng, DNNL_MEMORY_NONE);+ }+ dnnl::memory zp_memory;+ if (!zp_shape.empty()) {+ zp_memory = dnnl::memory(m_zp_md, eng, DNNL_MEMORY_NONE);+ }+ args = make_args(inp_memory, out_memory, wei_memory, bias_memory, scale_memory, zp_memory);+ }++ void exec(const dnnl::stream& astream,+ void* src,+ void* dst,+ void* weight,+ void* bias = nullptr,+ void* scale = nullptr,+ void* zp = nullptr) {+ args[DNNL_ARG_SRC].set_data_handle(src);+ args[DNNL_ARG_DST].set_data_handle(dst);+ args[DNNL_ARG_WEIGHTS].set_data_handle(weight);+ if (bias) {+ args[DNNL_ARG_BIAS].set_data_handle(bias);+ }+ if (scale) {+ args[DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS].set_data_handle(scale);+ }+ if (zp) {+ args[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS].set_data_handle(zp);+ }+ m_prim.execute(astream, args);+ }++ [[nodiscard]] dnnl::memory::desc get_weights_md() const {+ return m_wei_md;+ }++ [[nodiscard]] dnnl::memory::desc get_scale_md() const {+ return m_scale_md;+ }++ [[nodiscard]] dnnl::memory::desc get_zp_md() const {+ return m_zp_md;+ }++ [[nodiscard]] ov::intel_cpu::impl_desc_type get_impl_type() const {+ return m_impl_type;+ }++private:+ void init_w_scales(const VectorDims& scale_shape) {+ constexpr auto data_type = dnnl::memory::data_type::f32;+ const auto scale_dims = DnnlExtensionUtils::convertToDnnlDims(scale_shape);+ attr.set_scales_dims(DNNL_ARG_WEIGHTS, scale_dims, data_type);+ m_scale_md = dnnl::memory::desc(scale_dims, data_type, dnnl::memory::format_tag::ba);+ }+ void init_w_zp(const VectorDims& zp_shape) {+ constexpr auto data_type = dnnl::memory::data_type::f32;+ const auto zp_dims = DnnlExtensionUtils::convertToDnnlDims(zp_shape);+ attr.set_zero_points_dims(DNNL_ARG_WEIGHTS, zp_dims, data_type);+ m_zp_md = dnnl::memory::desc(zp_dims, data_type, dnnl::memory::format_tag::ba);+ }+ static std::unordered_map<int, dnnl::memory> make_args(dnnl::memory& src,+ dnnl::memory& dst,+ dnnl::memory& weight,+ dnnl::memory& bias,+ dnnl::memory& scale,+ dnnl::memory& zp) {+ std::unordered_map<int, dnnl::memory> args;+ args.insert({DNNL_ARG_SRC, src});+ args.insert({DNNL_ARG_WEIGHTS, weight});+ args.insert({DNNL_ARG_DST, dst});+ if (bias) {+ args.insert({DNNL_ARG_BIAS, bias});+ }+ if (scale) {+ args.insert({DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS, scale});+ }+ if (zp) {+ args.insert({DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS, zp});+ }+ return args;+ }++ dnnl::primitive m_prim;+ dnnl::memory::desc m_input_md;+ dnnl::memory::desc m_output_md;+ dnnl::memory::desc m_wei_md;+ dnnl::memory::desc m_scale_md;+ dnnl::memory::desc m_zp_md;+ dnnl::primitive_attr attr;++ ov::intel_cpu::impl_desc_type m_impl_type = ov::intel_cpu::impl_desc_type::unknown;++ std::unordered_map<int, dnnl::memory> args;++ bool m_has_bias = false;+};++bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept {+ try {+ // Check if the operation is BatchGatherMatmul or BatchGatherMatmulCompressed+ const bool isBatchGatherMatmul = ov::is_type<ov::intel_cpu::BatchGatherMatmul>(op);+ const bool isBatchGatherMatmulCompressed = ov::is_type<ov::intel_cpu::BatchGatherMatmulCompressed>(op);++ if (!isBatchGatherMatmul && !isBatchGatherMatmulCompressed) {+ errorMessage = "Only BatchGatherMatmul and BatchGatherMatmulCompressed operations are supported. Got: " ++ std::string(op->get_type_info().name);+ return false;+ }++ // Check that weights input (port 1) is constant+ if (!ov::op::util::is_on_constant_path(op->input_value(WEIGHTS))) {+ errorMessage = "Only constant weights are supported for GatherMatmul operation";+ return false;+ }++ // For compressed variant, check that scales and zero points are constant+ if (isBatchGatherMatmulCompressed) {+ if (op->get_input_size() > WEIGHT_SCALES) {+ if (!ov::op::util::is_on_constant_path(op->input_value(WEIGHT_SCALES))) {+ errorMessage = "Only constant weight scales are supported for GatherMatmul operation";+ return false;+ }+ }++ if (op->get_input_size() > WEIGHT_ZERO_POINTS) {+ if (!ov::op::util::is_on_constant_path(op->input_value(WEIGHT_ZERO_POINTS))) {+ errorMessage = "Only constant weight zero points are supported for GatherMatmul operation";+ return false;+ }+ }+ }++ // Check that bias (if present) is constant+ if (op->get_input_size() > BIAS) {+ const auto& biasInput = op->input_value(BIAS);+ // Skip validation if bias is dynamic (empty constant)+ if (biasInput.get_element_type() != ov::element::dynamic) {+ if (!ov::op::util::is_on_constant_path(biasInput)) {+ errorMessage = "Only constant bias is supported for GatherMatmul operation";+ return false;+ }+ }+ }++ } catch (...) {+ return false;+ }++ return true;+}++bool GatherMatmul::isSupportedCompressedOperation([[maybe_unused]] const std::shared_ptr<ov::Node>& op,+ [[maybe_unused]] size_t IC,+ [[maybe_unused]] size_t OC,+ [[maybe_unused]] size_t G,+ [[maybe_unused]] const Config& config) noexcept {+#if defined(OPENVINO_ARCH_X86_64)+ // copy paste from FullyConnected+ try {+ std::string errorMessage;+ if (!isSupportedOperation(op, errorMessage)) {+ return false;+ }++ if (!dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2)) {+ return false;+ }++ if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx) &&+ config.inferencePrecision == ov::element::bf16) {+ // OneDNN AMX IP implementation has limited shapes support due to performance considerations. As a+ // current solution conditions below are copied from OneDNN to make sure correct IP impl will be+ // used since fallback one doesn't support weights decompression feature.+ constexpr size_t simdWidth = 16;+ constexpr size_t vnniFactor = 2;+ constexpr size_t maxSize = 512;+ constexpr size_t amxRow = vnniFactor * simdWidth;++ if ((IC <= amxRow && OC <= amxRow) || (IC <= maxSize && OC <= maxSize && IC % amxRow != 0)) {+ return false;+ }+ }++ if (IC % G != 0) {+ return false; // sanity check IC must be evenly divided by the group size+ }++ if (IC / G < 4) {+ return false; // minimal group size should be 4+ }++ if (OC == 1) {+ return false;+ }+ } catch (...) {+ return false;+ }+ return true;+#else+ return false;+#endif+}++ov::element::TypeVector GatherMatmul::getSupportedCompressedWeightsTypes([[maybe_unused]] bool apply_fp8) {+ using ov::element::Type_t;++#if defined(OPENVINO_ARCH_X86_64)+ return {Type_t::u8, Type_t::i8, Type_t::u4, Type_t::i4};+#else+ return {};+#endif+}++ov::element::TypeVector GatherMatmul::getSupportedCompressedActivationsTypes() {+ using ov::element::Type_t;+ // @todo enable for bf16 as well+ // after EnforceInferencePrecision is replaced with ConvertPrecision+ return {Type_t::f32};+}++GatherMatmul::GatherMatmul(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)+ : Node(op, context, GatherMatmulShapeInferFactory(op)) {+ std::string errorMessage;+ if (!isSupportedOperation(op, errorMessage)) {+ OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);+ }++ // Determine the algorithm type+ if (ov::is_type<ov::intel_cpu::BatchGatherMatmulCompressed>(op)) {+ algorithm = Algorithm::GatherMatmulCompressed;+ } else {+ algorithm = Algorithm::GatherMatmulDefault;+ }+}++void GatherMatmul::initSupportedPrimitiveDescriptors() {+ const auto& srcTypes = getOriginalInputPrecisions();+ auto dstTypes = getOriginalOutputPrecisions();++ if (!fusedWith.empty()) {+ dstTypes = fusedWith.back()->getOriginalOutputPrecisions();+ }++ NodeConfig nodeConfig;++ if (srcTypes.front() == ov::element::bf16 && dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx)) {+ // enable bf16 amx optimizations+ bf16_amx_mode = true;+ }++ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();+ for (size_t i = 0; i < srcTypes.size(); i++) {+ if (srcTypes[i] == element::dynamic) {+ nodeConfig.inConfs.emplace_back(MemoryDescUtils::makeEmptyDesc());+ continue;+ }+ const auto srcDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcTypes[i], getInputShapeAtPort(i));+ nodeConfig.inConfs.emplace_back(srcDesc);+ }++ for (size_t i = 0; i < dstTypes.size(); i++) {+ const auto dstDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(dstTypes[i], getOutputShapeAtPort(i));+ nodeConfig.outConfs.emplace_back(dstDesc);+ }++ supportedPrimitiveDescriptors.emplace_back(nodeConfig, impl_desc_type::undef);+}++void GatherMatmul::createPrimitive() {+ // we use gemv here and the shapes of this op in fact are determined as the weigths are const+ auto weightsMemoryDesc = getBaseMemDescAtInputPort(WEIGHTS);+ CPU_NODE_ASSERT(weightsMemoryDesc->isDefined(), "Weights memory descriptor is not defined");++ auto srcDesc = getBaseMemDescAtInputPort(DATA);+ auto biasDesc = getBaseMemDescAtInputPort(BIAS);+ auto dstDesc = getBaseMemDescAtOutputPort(0);++ // Now we construct memory descriptors for input as [1, K]+ // weights memory descriptor as [N, K] since the weights are expected to be transposed++ auto src_precision = srcDesc->getPrecision();+ auto weights_precision = weightsMemoryDesc->getPrecision();++ // onednn doesn't not support bf16+f16+ if (ov::element::bf16 == src_precision && any_of(weights_precision, ov::element::f16, ov::element::f32)) {+ weights_precision = ov::element::bf16;+ }++ const auto& weiDims = weightsMemoryDesc->getShape().getStaticDims();++ int N = weiDims[weiDims.size() - 2];+ int K = weiDims[weiDims.size() - 1];++ VectorDims scale_shape{};+ VectorDims zp_shape{};+ if (algorithm == Algorithm::GatherMatmulCompressed) {+ auto scaleDesc = getBaseMemDescAtInputPort(WEIGHT_SCALES);+ if (scaleDesc && !scaleDesc->empty()) {+ const auto& fullScalesShape = scaleDesc->getShape().getStaticDims();+ if (1 == fullScalesShape.size()) {+ CPU_NODE_ASSERT(fullScalesShape[0] == 1, "Expect broadcastable scales shape.");+ scale_shape.push_back(fullScalesShape[0]);+ } else {+ scale_shape.assign(fullScalesShape.begin() + 1, fullScalesShape.end());+ }+ }+ auto zpDesc = getBaseMemDescAtInputPort(WEIGHT_ZERO_POINTS);+ if (zpDesc && !zpDesc->empty()) {+ const auto& fullZeroPointsShape = zpDesc->getShape().getStaticDims();+ if (1 == fullZeroPointsShape.size()) {+ CPU_NODE_ASSERT(fullZeroPointsShape[0] == 1, "Expect broadcastable zero points shape.");+ zp_shape.push_back(fullZeroPointsShape[0]);+ } else {+ zp_shape.assign(fullZeroPointsShape.begin() + 1, fullZeroPointsShape.end());+ }+ }+ }++ dnnl::memory::desc src_md({1, K},+ DnnlExtensionUtils::ElementTypeToDataType(src_precision),+ dnnl::memory::format_tag::ab);++ dnnl::memory::desc weights_md({N, K},+ DnnlExtensionUtils::ElementTypeToDataType(weights_precision),+ dnnl::memory::format_tag::any);++ onednn_matmul_key key{src_md, weights_md, scale_shape, zp_shape, biasDesc && !biasDesc->empty()};++ auto cache = context->getParamsCache();+ const auto& eng = getEngine();+ std::tie(gemv_impl, std::ignore) = cache->getOrCreate(key, [&eng](const onednn_matmul_key& k) {+ return std::make_shared<onednn_matmul>(eng, k);+ });++ // repack weights+ // we build gemv impl, but in fact there is B weights to gather, so we have to process 3D weights, scales and zp+ // tensors+ auto gemvWeightsDesc =+ MemoryDescUtils::convertToBlockedMemoryDesc(DnnlExtensionUtils::makeDescriptor(gemv_impl->get_weights_md()));++ // now let's build 3d descriptors+ auto addBatchDim = [](const BlockedMemoryDescPtr& desc, size_t batchDim) -> DnnlMemoryDescPtr {+ const auto& weightsDims = desc->getShape().getStaticDims();+ const auto& weightsBlockDims = desc->getBlockDims();+ const auto& weightsOrder = desc->getOrder();+ // at this point we assume that the tensors are dense and have no padded dims+ VectorDims newDims = {batchDim};+ newDims.insert(newDims.end(), weightsDims.begin(), weightsDims.end());+ VectorDims newBlockDims = {batchDim};+ newBlockDims.insert(newBlockDims.end(), weightsBlockDims.begin(), weightsBlockDims.end());+ VectorDims newOrder(weightsOrder.size() + 1);+ newOrder[0] = 0;+ for (size_t i = 0; i < weightsOrder.size(); i++) {+ newOrder[i + 1] = weightsOrder[i] + 1;+ }+ auto targetDesc =+ std::make_shared<CpuBlockedMemoryDesc>(desc->getPrecision(), Shape(newDims), newBlockDims, newOrder);+ return MemoryDescUtils::convertToDnnlMemoryDesc(targetDesc);+ };++ auto targetWeightsDesc = addBatchDim(gemvWeightsDesc, weiDims[0]);++ m_weightsMemory =+ prepareWeightMemory(targetWeightsDesc, MemoryDescUtils::convertToDnnlMemoryDesc(weightsMemoryDesc));++ if (!scale_shape.empty()) {+ auto expectedScaleMemDesc =+ MemoryDescUtils::convertToDnnlMemoryDesc(DnnlExtensionUtils::makeDescriptor(gemv_impl->get_scale_md()));+ auto scales = getSrcMemoryAtPort(WEIGHT_SCALES);+ CPU_NODE_ASSERT(scales && scales->isDefined(), "Weight scales memory is not defined");+ const auto& scDims = scales->getShape().getStaticDims();+ expectedScaleMemDesc =+ addBatchDim(MemoryDescUtils::convertToBlockedMemoryDesc(expectedScaleMemDesc), scDims[0]);+ if (expectedScaleMemDesc->isCompatible(scales->getDesc())) {+ m_scalesMemory = scales;+ } else {+ m_scalesMemory = std::make_shared<Memory>(getEngine(), expectedScaleMemDesc);+ m_scalesMemory->load(*scales, false, false);+ }+ }++ if (!zp_shape.empty()) {+ auto expectedZpMemDesc =+ MemoryDescUtils::convertToDnnlMemoryDesc(DnnlExtensionUtils::makeDescriptor(gemv_impl->get_zp_md()));+ auto zps = getSrcMemoryAtPort(WEIGHT_ZERO_POINTS);+ CPU_NODE_ASSERT(zps && zps->isDefined(), "Weight zero points memory is not defined");+ const auto& zpDims = zps->getShape().getStaticDims();+ expectedZpMemDesc = addBatchDim(MemoryDescUtils::convertToBlockedMemoryDesc(expectedZpMemDesc), zpDims[0]);+ if (expectedZpMemDesc->isCompatible(zps->getDesc())) {+ m_zpMemory = zps;+ } else {+ m_zpMemory = std::make_shared<Memory>(getEngine(), expectedZpMemDesc);+ m_zpMemory->load(*zps, false, false);+ }+ }++ Node::createPrimitive();++ // set the actual implementation type+ getSelectedPrimitiveDescriptor()->setImplementationType(gemv_impl->get_impl_type());+}++bool GatherMatmul::needPrepareParams() const {+ if (bf16_amx_mode && Node::needPrepareParams()) {+ auto srcMem = getSrcMemoryAtPort(DATA);+ const auto& srcShape = srcMem->getStaticDims();+ const auto M = srcShape[1];+ if (M != 1) {+ return true;+ }+ }+ return false;+}++// AMX tile has 16 rows, so to avoid partial tiles it's better to pad M dimension to 16 multiple+static Dim normalizeM(Dim M) {+ if (M < 512) {+ M = rnd_up(M, 16);+ } else if (M < 1024) {+ M = rnd_up(M, 32); // 2 tile blocking - better tile register utilization+ } else {+ M = rnd_up(M, 256); // better L2 cache blocking+ }+ return M;+}++void GatherMatmul::prepareParams() {+ auto srcMem = getSrcMemoryAtPort(DATA);+ const auto& srcShape = srcMem->getStaticDims();+ const Dim M = normalizeM(srcShape[1]);+ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();++ const auto srcPrc = srcMem->getDesc().getPrecision();++ auto dstMem = getDstMemoryAtPort(0);+ const auto& dstShape = dstMem->getStaticDims();++ auto srcInterimDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, srcShape[2]}));+ auto dstInterimDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, dstShape[2]}));++ const size_t srcSize = rnd_up(srcInterimDesc->getCurrentMemSize(), 64); // 64 bytes is the cache line size+ const size_t totalSize = srcSize + dstInterimDesc->getCurrentMemSize();++ auto scratchPadDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(ov::element::u8, Shape({totalSize}));+ m_tmpInpBuffer = getScratchPadMem(scratchPadDesc);++ auto* scratchPadRawPtr = m_tmpInpBuffer->getDataAs<uint8_t>();++ m_tmpInput = std::make_shared<StaticMemory>(getEngine(), srcInterimDesc, scratchPadRawPtr);+ m_tmpOutput = std::make_shared<StaticMemory>(getEngine(), dstInterimDesc, scratchPadRawPtr + srcSize);++ CPU_NODE_ASSERT(gemv_impl, "GEMV implementation is not created");++ dnnl::memory::desc src_md({static_cast<dnnl::memory::dim>(M), static_cast<dnnl::memory::dim>(srcShape[2])},+ DnnlExtensionUtils::ElementTypeToDataType(srcPrc),+ dnnl::memory::format_tag::ab);+ auto weights_md = gemv_impl->get_weights_md();++ VectorDims scale_shape{};+ VectorDims zp_shape{};++ if (m_scalesMemory) {+ const auto& fullScaleDims = m_scalesMemory->getStaticDims();+ if (1 == fullScaleDims.size()) {+ scale_shape.push_back(fullScaleDims[0]);+ } else {+ scale_shape.assign(fullScaleDims.begin() + 1, fullScaleDims.end());+ }+ }++ if (m_zpMemory) {+ const auto& fullZpDims = m_zpMemory->getStaticDims();+ if (1 == fullZpDims.size()) {+ zp_shape.push_back(fullZpDims[0]);+ } else {+ zp_shape.assign(fullZpDims.begin() + 1, fullZpDims.end());+ }+ }++ auto biasMemory = getSrcMemoryAtPort(BIAS);+ const auto& biasDesc = biasMemory->getDesc();+ onednn_matmul_key key{src_md, weights_md, scale_shape, zp_shape, !biasDesc.empty()};++ auto cache = context->getParamsCache();+ const auto& eng = getEngine();+ std::tie(gemm_impl, std::ignore) = cache->getOrCreate(key, [&eng](const onednn_matmul_key& k) {+ return std::make_shared<onednn_matmul>(eng, k);+ });+}++bool GatherMatmul::isExecutable() const {+ return !isInputTensorAtPortEmpty(0); // only data shape matters+}++namespace {+class OffsetHelper {+public:+ static OffsetHelper createOffsetHelper(const MemoryPtr& mem) {+ static const VectorDims empty_dims;+ std::bitset<2> broadcast_mask;+ if (nullptr == mem || mem->getDesc().empty()) {+ return {nullptr, empty_dims, broadcast_mask, 0};+ }+ auto* base_ptr = static_cast<uint8_t*>(mem->getData());+ auto desc = mem->getDescWithType<BlockedMemoryDesc>();+ const auto& strides = desc->getStrides();+ const auto prc = desc->getPrecision();+ const auto& shape = desc->getShape().getStaticDims();+ for (size_t i = 0; i < shape.size() && i < 2; i++) {+ if (shape[i] == 1) {+ broadcast_mask.set(i);+ }+ }+ return {base_ptr, strides, broadcast_mask, prc.bitwidth()};+ }++ void* operator()(size_t i0) const {+ if (!m_base_ptr) {+ return nullptr;+ }+ if (m_broadcast_mask.test(0)) {+ i0 = 0;+ }+ const size_t offset_bits = i0 * m_strides[0] * m_num_bits;+ const size_t offset = div_up(offset_bits, 8); // 8 bits in byte+ return m_base_ptr + offset;+ }++ void* operator()(size_t i0, size_t i1) const {+ if (!m_base_ptr) {+ return nullptr;+ }+ if (m_broadcast_mask.test(0)) {+ i0 = 0;+ }+ if (m_broadcast_mask.test(1)) {+ i1 = 0;+ }+ const size_t offset_bits = i0 * m_strides[0] * m_num_bits + i1 * m_strides[1] * m_num_bits;+ const size_t offset = div_up(offset_bits, 8); // 8 bits in byte+ return m_base_ptr + offset;+ }++ [[nodiscard]] void* get_base() const {+ return m_base_ptr;+ }++private:+ OffsetHelper(uint8_t* base_ptr, const VectorDims& strides, std::bitset<2> broadcast_mask, size_t num_bits)+ : m_base_ptr(base_ptr),+ m_strides(strides),+ m_num_bits(num_bits),+ m_broadcast_mask(broadcast_mask) {}++ uint8_t* m_base_ptr = nullptr;+ const VectorDims& m_strides;+ size_t m_num_bits;+ std::bitset<2> m_broadcast_mask;+};+} // namespace++void GatherMatmul::execute(const dnnl::stream& strm) {+ const auto& srcMem = getParentEdgeAt(DATA)->getMemoryPtr();+ const auto& biasMem = getParentEdgeAt(BIAS)->getMemoryPtr();+ const auto& indexMem = getParentEdgeAt(INDICES)->getMemoryPtr();++ const auto& dstMem = getChildEdgeAt(0)->getMemoryPtr();++ const auto& indexShape = indexMem->getStaticDims();+ size_t M = indexShape[0];+ size_t indices_size = indexShape[1]; // number of elements to be gathered per each m index++ auto src_offset = OffsetHelper::createOffsetHelper(srcMem);+ auto dst_offset = OffsetHelper::createOffsetHelper(dstMem);+ auto wei_offset = OffsetHelper::createOffsetHelper(m_weightsMemory);+ auto bias_offset = OffsetHelper::createOffsetHelper(biasMem);+ auto scale_offset = OffsetHelper::createOffsetHelper(m_scalesMemory);+ auto zp_offset = OffsetHelper::createOffsetHelper(m_zpMemory);+ auto index_offset = OffsetHelper::createOffsetHelper(indexMem);++ // input 1 is a tensor A[B, M, K]+ // input 2 is a tensor B[G, K, N] (transposed) - G is the gather axis+ // input 3 is the gather indices I [M, B]+ // for each b in B and m in M:+ // gathered_weights = B[I[m,b], :, :] (has shape [K, N]^T)+ // output[b,m,:] = MatMul(A[b,m,:], gathered_weights)++ if (M > 1) {+ const size_t gather_axis_size = m_weightsMemory->getStaticDims()[0];++ // all the gather idx for corresponding m index+ std::vector<std::pair<int32_t, int32_t>> gather_idx_map(gather_axis_size * M);+ std::vector<int32_t> elements_per_gather_indx(gather_axis_size, 0);+ for (size_t m = 0; m < M; m++) {+ const auto* gather_ids = static_cast<const int32_t*>(index_offset(m));+ for (size_t i = 0; i < indices_size; i++) {+ int32_t gather_axis_index = gather_ids[i];+ CPU_NODE_ASSERT(gather_axis_index >= 0 && static_cast<size_t>(gather_axis_index) < gather_axis_size,+ "Invalid gather_id ",+ gather_axis_index,+ " for m ",+ m);+ auto& index = elements_per_gather_indx[gather_axis_index];+ gather_idx_map[gather_axis_index * M + index] = {m, i};+ index++;+ }+ }++ if (bf16_amx_mode) {+ // When AMX is available, we use GEMM for better performance+ // first we pack all the tokens corresponding to a specific expert into a temporary buffer+ // then we call GEMM for that expert on that temporary buffer+ // and finally scatter the results to result memory+ CPU_NODE_ASSERT(m_tmpInput, "Temporary input memory is not created");++ auto tmp_input_offset = OffsetHelper::createOffsetHelper(m_tmpInput);++ const auto element_size = m_tmpInput->getPrecision().size();+ const auto K_size = m_tmpInput->getStaticDims()[1];+ const auto M_size = m_tmpInput->getStaticDims()[0];+ const auto N_size = dstMem->getStaticDims()[2];++ auto tmp_dst_offset = OffsetHelper::createOffsetHelper(m_tmpOutput);++ CPU_NODE_ASSERT(gemm_impl, "GEMM implementation is not created");+ for (size_t gather_axis_index = 0; gather_axis_index < gather_axis_size; gather_axis_index++) {+ const size_t num_valid_rows = elements_per_gather_indx[gather_axis_index];+ if (0 == num_valid_rows) {+ continue;+ }++ parallel_for(M_size, [&](size_t m) {+ auto* dst_row = tmp_input_offset(m);++ if (m < num_valid_rows) {+ const auto row_id = gather_idx_map[gather_axis_index * M + m].first;+ const auto batch_index = gather_idx_map[gather_axis_index * M + m].second;+ const auto* src_data = src_offset(batch_index, row_id);+ std::memcpy(dst_row, src_data, K_size * element_size);+ } else {+ // Zero padding for rows beyond num_valid_tokens+ std::memset(dst_row, 0, K_size * element_size);+ }+ });++ auto* src = tmp_input_offset.get_base();+ auto* dst = tmp_dst_offset.get_base();+ auto* wei = wei_offset(gather_axis_index);+ auto* bias = bias_offset(gather_axis_index);+ auto* scale = scale_offset(gather_axis_index);+ auto* zp = zp_offset(gather_axis_index);+ gemm_impl->exec(strm, src, dst, wei, bias, scale, zp);++ // Immediately scatter results while they're hot in cache+ parallel_for(num_valid_rows, [&](size_t m) {+ const auto* src_row = tmp_dst_offset(m);+ const auto row_id = gather_idx_map[gather_axis_index * M + m].first;+ const auto batch_index = gather_idx_map[gather_axis_index * M + m].second;+ auto* dst_row = dst_offset(batch_index, row_id);+ std::memcpy(dst_row, src_row, N_size * element_size);+ });+ }+ } else {+ // For the default SIMD it's better to simply call GEMV+ CPU_NODE_ASSERT(gemv_impl, "GEMM implementation is not created");+ for (size_t gather_axis_index = 0; gather_axis_index < gather_axis_size; gather_axis_index++) {+ if (0 == elements_per_gather_indx[gather_axis_index]) {+ continue;+ }+ auto* wei = wei_offset(gather_axis_index);+ auto* bias = bias_offset(gather_axis_index);+ auto* scale = scale_offset(gather_axis_index);+ auto* zp = zp_offset(gather_axis_index);+ for (int32_t m = 0; m < elements_per_gather_indx[gather_axis_index]; ++m) {+ const auto row_id = gather_idx_map[gather_axis_index * M + m].first;+ const auto batch_index = gather_idx_map[gather_axis_index * M + m].second;+ auto* src = src_offset(batch_index, row_id);+ auto* dst = dst_offset(batch_index, row_id);+ gemv_impl->exec(strm, src, dst, wei, bias, scale, zp);+ }+ }+ }+ } else {+ CPU_NODE_ASSERT(gemv_impl, "GEMM implementation is not created");++ constexpr size_t m = 0;+ auto* gather_ids = static_cast<int32_t*>(index_offset(m));+ for (size_t i = 0; i < indices_size; i++) {+ int32_t gather_axis_index = gather_ids[i];+ auto* src = src_offset(i, m);+ auto* dst = dst_offset(i, m);+ auto* wei = wei_offset(gather_axis_index);+ auto* bias = bias_offset(gather_axis_index);+ auto* scale = scale_offset(gather_axis_index);+ auto* zp = zp_offset(gather_axis_index);+ gemv_impl->exec(strm, src, dst, wei, bias, scale, zp);+ }+ }+}++void GatherMatmul::executeDynamicImpl(const dnnl::stream& strm) {+ execute(strm);+}++bool GatherMatmul::created() const {+ return getType() == Type::GatherMatmul;+}++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes/gathermatmul.h b/src/plugins/intel_cpu/src/nodes/gathermatmul.hnew file mode 100644index 00000000000..b9ee938389e--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/gathermatmul.h@@ -0,0 +1,76 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>+#include <oneapi/dnnl/dnnl.hpp>+#include <string>++#include "cpu_memory.h"+#include "graph_context.h"+#include "node.h"+#include "nodes/executors/memory_arguments.hpp"+#include "openvino/core/node.hpp"++namespace ov::intel_cpu::node {++class GatherMatmul : public Node {+public:+ GatherMatmul(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);++ void getSupportedDescriptors() override {};+ void initSupportedPrimitiveDescriptors() override;+ void createPrimitive() override;+ void execute(const dnnl::stream& strm) override;+ void executeDynamicImpl(const dnnl::stream& strm) override;+ bool needPrepareParams() const override;+ void prepareParams() override;++ bool isExecutable() const override;++ bool created() const override;++ static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;++ static bool isSupportedCompressedOperation(const std::shared_ptr<ov::Node>& op,+ size_t IC,+ size_t OC,+ size_t G,+ const Config& config) noexcept;+ static ov::element::TypeVector getSupportedCompressedWeightsTypes(bool apply_fp8 = false);+ static ov::element::TypeVector getSupportedCompressedActivationsTypes();++private:+ enum class Algorithm : uint8_t { GatherMatmulDefault, GatherMatmulCompressed };++ enum InputId : uint8_t {+ DATA = 0,+ WEIGHTS,+ INDICES,+ BIAS,+ WEIGHT_SCALES,+ WEIGHT_ZERO_POINTS,+ };++ class onednn_matmul;++ using GemvImplPtr = std::shared_ptr<onednn_matmul>;++ Algorithm algorithm = Algorithm::GatherMatmulDefault;+ MemoryArgs memory;+ GemvImplPtr gemv_impl = nullptr;+ GemvImplPtr gemm_impl = nullptr;++ MemoryPtr m_weightsMemory = nullptr;+ MemoryPtr m_scalesMemory = nullptr;+ MemoryPtr m_zpMemory = nullptr;+ MemoryPtr m_tmpInpBuffer = nullptr;+ MemoryPtr m_tmpInput = nullptr;+ MemoryPtr m_tmpOutput = nullptr;++ bool bf16_amx_mode = false;+};++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes_factory.cpp b/src/plugins/intel_cpu/src/nodes_factory.cppindex f59dfd25b7e..8cbf1e31b44 100644--- a/src/plugins/intel_cpu/src/nodes_factory.cpp+++ b/src/plugins/intel_cpu/src/nodes_factory.cpp@@ -41,6 +41,7 @@#include "nodes/gather_elements.h"#include "nodes/gather_nd.h"#include "nodes/gather_tree.h"+#include "nodes/gathermatmul.h"#include "nodes/generate_proposals.h"#include "nodes/grn.h"#include "nodes/identity.hpp"@@ -240,6 +241,7 @@ Node::NodesFactory::NodesFactory() : Factory("NodesFactory") {INTEL_CPU_NODE(SearchSorted, Type::SearchSorted);INTEL_CPU_NODE(SegmentMax, Type::SegmentMax);INTEL_CPU_NODE(LoRA, Type::LoRA);+ INTEL_CPU_NODE(GatherMatmul, Type::GatherMatmul);#if defined(OPENVINO_ARCH_X86_64)INTEL_CPU_NODE(FakeQuantize, Type::FakeQuantize);INTEL_CPU_NODE(GridSample, Type::GridSample);diff --git a/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.cpp b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.cppnew file mode 100644index 00000000000..cb67b3d745b--- /dev/null+++ b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.cpp@@ -0,0 +1,113 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "gathermatmul.hpp"++#include <cstddef>+#include <functional>+#include <unordered_map>+#include <utility>+#include <vector>++#include "cpu_memory.h"+#include "cpu_types.h"+#include "openvino/core/except.hpp"+#include "shape_inference/shape_inference_status.hpp"+#include "utils/general_utils.h"++namespace ov::intel_cpu::node {++Result GatherMatmulShapeInfer::infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,+ [[maybe_unused]] const std::unordered_map<size_t, MemoryPtr>& data_dependency) {+ // Expected inputs:+ // 0: A - activations [group_size, M, K] (3D)+ // 1: B - weights [gather_axis, N, K] (3D)+ // 2: indices - gather indices [M, group_size] (2D)+ // Optional: 3: bias++ OPENVINO_DEBUG_ASSERT(input_shapes.size() >= 3,+ "GatherMatmul shape inference expects at least 3 inputs, got: ",+ input_shapes.size());++ const VectorDims& shapeA = input_shapes[0].get();+ const VectorDims& shapeB = input_shapes[1].get();+ const VectorDims& shapeIndices = input_shapes[2].get();++ // Validate input ranks+ OPENVINO_DEBUG_ASSERT(shapeA.size() == 3,+ "GatherMatmul input A must be 3D, got rank: ",+ shapeA.size(),+ " with shape: ",+ vec2str(shapeA));+ OPENVINO_DEBUG_ASSERT(shapeB.size() == 3,+ "GatherMatmul input B must be 3D, got rank: ",+ shapeB.size(),+ " with shape: ",+ vec2str(shapeB));+ OPENVINO_DEBUG_ASSERT(shapeIndices.size() == 2,+ "GatherMatmul indices must be 2D, got rank: ",+ shapeIndices.size(),+ " with shape: ",+ vec2str(shapeIndices));++ // Extract dimensions for matmul computation+ // A shape: [group, M, K]+ // B shape: [gather_axis, N, K]+ // We perform matmul on A[1:2] x B[1:2].T++ const size_t M = shapeA[1];+ const size_t K_A = shapeA[2];+ const size_t K = shapeB[1];+ const size_t N = shapeB[2];++ // Validate K-dimension compatibility++ const size_t k_lhs = m_transpose_a ? M : K_A;+ const size_t k_rhs = m_transpose_b ? N : K;++ OPENVINO_ASSERT(k_lhs == k_rhs,+ "GatherMatmul: incompatible matmul dimensions. ",+ "A shape: ",+ vec2str(shapeA),+ m_transpose_a ? " (transposed)" : "",+ ", B shape: ",+ vec2str(shapeB),+ m_transpose_b ? " (transposed)" : "",+ ". K dimension mismatch: ",+ k_lhs,+ " vs ",+ k_rhs);++ // Validate group dimension compatibility (A[0] can be 1 for broadcasting or match shapeIndices[1]])+ if (shapeA[0] != 1 && shapeA[0] != shapeIndices[1]) {+ OPENVINO_ASSERT(false,+ "GatherMatmul: incompatible group dimensions. ",+ "A[0] = ",+ shapeA[0],+ " must be 1 or equal to the indices group = ",+ shapeIndices[1]);+ }++ // Validate indices dimensions+ OPENVINO_ASSERT(shapeIndices[0] == M,+ "GatherMatmul: indices first dimension must match A's seq_len. ",+ "indices[0] = ",+ shapeIndices[0],+ ", A[1] = ",+ M);++ // Compute output shape from matmul+ // matmul([M, K], [N, K].T) = [M, N]+ const size_t matmul_M = m_transpose_a ? K_A : M;+ const size_t matmul_N = m_transpose_b ? K : N;++ // Output shape: [group_size, M, N]+ const size_t group_size = shapeIndices[1];++ VectorDims outputShape = {group_size, matmul_M, matmul_N};++ return {{std::move(outputShape)}, ShapeInferStatus::success};+}++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hpp b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hppnew file mode 100644index 00000000000..74ea0ce8f4f--- /dev/null+++ b/src/plugins/intel_cpu/src/shape_inference/custom/gathermatmul.hpp@@ -0,0 +1,55 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <cstddef>+#include <functional>+#include <memory>+#include <unordered_map>+#include <vector>++#include "cpu_memory.h"+#include "openvino/core/node.hpp"+#include "shape_inference/shape_inference_cpu.hpp"++namespace ov::intel_cpu::node {++using Result = IShapeInfer::Result;++class GatherMatmulShapeInfer : public ShapeInferEmptyPads {+public:+ GatherMatmulShapeInfer(bool transpose_a, bool transpose_b)+ : m_transpose_a(transpose_a),+ m_transpose_b(transpose_b) {}++ Result infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,+ const std::unordered_map<size_t, MemoryPtr>& data_dependency) override;++ [[nodiscard]] port_mask_t get_port_mask() const override {+ return EMPTY_PORT_MASK;+ }++private:+ bool m_transpose_a;+ bool m_transpose_b;+};++class GatherMatmulShapeInferFactory : public ShapeInferFactory {+public:+ explicit GatherMatmulShapeInferFactory(const std::shared_ptr<ov::Node>& op) : m_op(op) {}++ [[nodiscard]] ShapeInferPtr makeShapeInfer() const override {+ // BatchGatherMatmul has fixed transpose settings: transpose_a=false, transpose_b=true+ OPENVINO_DEBUG_ASSERT(m_op->get_output_partial_shape(0).rank().get_length() == 3,+ "GatherMatmul output must be 3D, got rank: ",+ m_op->get_output_partial_shape(0).rank().get_length());+ return std::make_shared<GatherMatmulShapeInfer>(false, true);+ }++private:+ std::shared_ptr<const ov::Node> m_op;+};++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cppnew file mode 100644index 00000000000..237cbf3d2f9--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.cpp@@ -0,0 +1,136 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "batch_gather_matmul.hpp"++#include <cstddef>+#include <memory>+#include <vector>++#include "matmul_shape_inference.hpp"+#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/core/partial_shape.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/op.hpp"+#include "transformations/itt.hpp"+#include "transformations/utils/utils.hpp"++namespace ov::intel_cpu {++BatchGatherMatmul::BatchGatherMatmul(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias)+ : Op({A, B, indices, bias}) {+ validate_and_infer_types();+}++BatchGatherMatmul::BatchGatherMatmul(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices)+ : BatchGatherMatmul(A, B, indices, std::make_shared<ov::op::v0::Constant>(element::dynamic, Shape{0})) {}++std::shared_ptr<ov::Node> BatchGatherMatmul::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ INTERNAL_OP_SCOPE(GroupGatherMatmul_with_new_inputs);+ check_new_args_count(this, new_args);+ return std::make_shared<ov::intel_cpu::BatchGatherMatmul>(new_args.at(0),+ new_args.at(1),+ new_args.at(2),+ new_args.at(3));+}++void BatchGatherMatmul::validate_and_infer_types() {+ INTERNAL_OP_SCOPE(GroupGatherMatmul_validate_and_infer_types);+ const auto input_size = get_input_size();+ NODE_VALIDATION_CHECK(this,+ input_size >= 4,+ "Number of inputs is incorrect. Current value is: ",+ input_size,+ ", expected at least 4.");++ // Check input B is on constant path+ NODE_VALIDATION_CHECK(this, ov::op::util::is_on_constant_path(input_value(1)), "Input B must be on constant path.");++ const auto& a_shape = get_input_partial_shape(0);+ const auto& b_shape = get_input_partial_shape(1);+ const auto& indices_shape = get_input_partial_shape(2);+ const auto& bias_shape = get_input_partial_shape(3);++ NODE_VALIDATION_CHECK(this, a_shape.rank().is_static(), "Input A rank must be static.");+ NODE_VALIDATION_CHECK(this, b_shape.rank().is_static(), "Input B rank must be static.");+ NODE_VALIDATION_CHECK(this, indices_shape.rank().is_static(), "Input indices rank must be static.");+ NODE_VALIDATION_CHECK(this, bias_shape.rank().is_static(), "Input bias rank must be static.");++ const size_t a_rank = a_shape.size();+ const size_t b_rank = b_shape.size();+ const size_t indices_rank = indices_shape.size();+ const size_t bias_rank = bias_shape.is_dynamic() ? 0 : bias_shape.size();++ NODE_VALIDATION_CHECK(this, a_rank == 3, "Input A rank must be exactly 3D. Got: ", a_rank, "D instead.");+ NODE_VALIDATION_CHECK(this, b_rank == 3, "Input B rank must be exactly 3D. Got: ", b_rank, "D instead.");+ NODE_VALIDATION_CHECK(this,+ indices_rank == 2,+ "Input indices rank must be exactly 2D. Got: ",+ indices_rank,+ "D instead.");+ NODE_VALIDATION_CHECK(this,+ (bias_rank == 1 || bias_rank == 0 || bias_rank == a_rank),+ "Input bias rank must be either 1D, scalar or same as Input A rank. Got: ",+ bias_rank,+ "D instead.");++ if (indices_shape[1].is_static()) {+ if (a_shape[0].is_static()) {+ NODE_VALIDATION_CHECK(this,+ a_shape[0] == 1 || a_shape[0] == indices_shape[1],+ "The first dimension of input A must be equal to number of activated experts. Got: ",+ a_shape[0],+ " and ",+ indices_shape[1],+ " instead.");+ }+ if (b_shape[0].is_static()) {+ NODE_VALIDATION_CHECK(+ this,+ indices_shape[1].get_length() <= b_shape[0].get_length(),+ "The second dimension of input indices must be less or equal to the first dimension of input B. "+ "Got: ",+ indices_shape[1],+ " and ",+ b_shape[0],+ " instead.");+ }+ }++ if (indices_shape[0].is_static() && a_shape[1].is_static()) {+ NODE_VALIDATION_CHECK(this,+ indices_shape[0] == a_shape[1],+ "The first dimension of input indices must be equal to the second dimension of input A. "+ "Got: ",+ indices_shape[0],+ " and ",+ a_shape[1],+ " instead.");+ }++ ov::op::v0::MatMul op;+ op.set_transpose_a(transp_a);+ op.set_transpose_b(transp_b);++ ov::PartialShape matmul_shape_a = {a_shape[1], a_shape[2]};+ ov::PartialShape matmul_shape_b = {b_shape[1], b_shape[2]};++ auto out_matmul_shape =+ (ov::op::v0::shape_infer(&op, std::vector<ov::PartialShape>{matmul_shape_a, matmul_shape_b})).front();++ ov::PartialShape output_shape = {indices_shape[1], out_matmul_shape[0], out_matmul_shape[1]};++ set_output_type(0, get_input_element_type(0), output_shape);+}++} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hppnew file mode 100644index 00000000000..67f1ead9188--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul.hpp@@ -0,0 +1,39 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/op/op.hpp"++namespace ov::intel_cpu {++class BatchGatherMatmul : public ov::op::Op {+public:+ OPENVINO_OP("BatchGatherMatmul", "cpu_plugin_opset");++ BatchGatherMatmul() = default;++ BatchGatherMatmul(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias);++ BatchGatherMatmul(const ov::Output<Node>& A, const ov::Output<Node>& B, const ov::Output<Node>& indices);++ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ void validate_and_infer_types() override;++private:+ // the weights matrix B is expected to have the transposed form [goup, N, K]+ static constexpr bool transp_a = false;+ static constexpr bool transp_b = true;+};++} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cppnew file mode 100644index 00000000000..9fe12d109d3--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.cpp@@ -0,0 +1,56 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "batch_gather_matmul_compressed.hpp"++#include <memory>++#include "batch_gather_matmul.hpp"+#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/core/type.hpp"+#include "openvino/op/constant.hpp"+#include "transformations/itt.hpp"++namespace ov::intel_cpu {++BatchGatherMatmulCompressed::BatchGatherMatmulCompressed(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias,+ const ov::Output<Node>& weight_scales,+ const ov::Output<Node>& weight_zero_points)+ : BatchGatherMatmul(A, B, indices, bias) {+ set_argument(4, weight_scales);+ set_argument(5, weight_zero_points);+ validate_and_infer_types();+}++std::shared_ptr<ov::Node> BatchGatherMatmulCompressed::clone_with_new_inputs(const ov::OutputVector& new_args) const {+ check_new_args_count(this, new_args);+ return std::make_shared<BatchGatherMatmulCompressed>(new_args.at(0),+ new_args.at(1),+ new_args.at(2),+ new_args.at(3),+ new_args.at(4),+ new_args.at(5));+}++void BatchGatherMatmulCompressed::validate_and_infer_types() {+ const auto input_size = get_input_size();+ NODE_VALIDATION_CHECK(this, input_size == 6, "Number of inputs is incorrect. Current value is: ", input_size);++ // check weight_scales and weight_zero_points are Const+ auto weight_scales = get_input_node_shared_ptr(4);+ NODE_VALIDATION_CHECK(this,+ ov::is_type<ov::op::v0::Constant>(weight_scales),+ "Input weight_scales must be a Constant node.");+ auto weight_zero_points = get_input_node_shared_ptr(5);+ NODE_VALIDATION_CHECK(this,+ ov::is_type<ov::op::v0::Constant>(weight_zero_points),+ "Input weight_zero_points must be a Constant node.");+ BatchGatherMatmul::validate_and_infer_types();+}+} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hppnew file mode 100644index 00000000000..2df249744b8--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp@@ -0,0 +1,35 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <memory>++#include "batch_gather_matmul.hpp"+#include "openvino/core/attribute_visitor.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/op/op.hpp"++namespace ov::intel_cpu {++class BatchGatherMatmulCompressed : public BatchGatherMatmul {+public:+ OPENVINO_OP("BatchGatherMatmulCompressed", "cpu_plugin_opset", BatchGatherMatmul);++ BatchGatherMatmulCompressed() = default;++ BatchGatherMatmulCompressed(const ov::Output<Node>& A,+ const ov::Output<Node>& B,+ const ov::Output<Node>& indices,+ const ov::Output<Node>& bias,+ const ov::Output<Node>& weight_scales,+ const ov::Output<Node>& weight_zero_points);++ std::shared_ptr<Node> clone_with_new_inputs(const ov::OutputVector& new_args) const override;++ void validate_and_infer_types() override;+};++} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cppnew file mode 100644index 00000000000..1388019d784--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.cpp@@ -0,0 +1,94 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "convert_batch_gather_matmul_to_compressed.hpp"++#include <algorithm>+#include <cstddef>+#include <memory>+#include <set>+#include <vector>++#include "openvino/core/graph_util.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/type.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "openvino/util/pp.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"+#include "transformations/op_conversions/convert_fc_to_compressed.hpp"+#include "transformations/pattern_blocks/compressed_weights_block.hpp"++ov::intel_cpu::ConvertBatchGatherMatmulToBatchGatherMatmulCompressed::+ ConvertBatchGatherMatmulToBatchGatherMatmulCompressed(+ const std::vector<ov::element::Type>& supported_activation_types,+ const std::vector<ov::element::Type>& supported_weights_types,+ const SupportsPredicate& supports_config,+ bool convert_u4zp_to_u8) {+ using namespace ov::pass::pattern;++ auto activation = any_input(type_matches_any(supported_activation_types));+ auto weights_block =+ std::make_shared<ov::pass::pattern::op::CompressedWeightsBlock>(supported_weights_types, std::set<size_t>{3});+ auto indices = any_input();+ auto bias = any_input();+ auto batch_gather_matmul = wrap_type<BatchGatherMatmul>({activation, weights_block, indices, bias});++ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ auto bgm = ov::as_type_ptr<BatchGatherMatmul>(pattern_map.at(batch_gather_matmul).get_node_shared_ptr());+ if (!bgm || transformation_callback(bgm)) {+ return false;+ }++ bool has_transpose = weights_block->get_anchor("transpose", pattern_map).has_value();+ const auto& weights_shape = bgm->get_input_shape(1);+ bool batched_weights = weights_shape.size() == 3 && weights_shape[0] > 1;+ auto scale_shape = weights_block->get_anchor("mul_const", pattern_map).value().get_shape();+ bool grouped = std::count_if(scale_shape.begin(), scale_shape.end(), [](size_t d) {+ return d > 1;+ }) > (batched_weights ? 2 : 1);++ ov::NodeVector result_nodes;+ const auto [bgm_input_b, bgm_input_scale, bgm_input_zp] =+ ov::pass::ConvertFullyConnectedToFullyConnectedCompressed::process_compressed_weights(weights_block,+ pattern_map,+ convert_u4zp_to_u8,+ has_transpose,+ grouped,+ batched_weights,+ result_nodes);++ auto new_bgm = std::make_shared<BatchGatherMatmulCompressed>(pattern_map.at(activation),+ bgm_input_b,+ pattern_map.at(indices),+ pattern_map.at(bias),+ bgm_input_scale,+ bgm_input_zp);++ const size_t IC = *(weights_shape.rbegin());+ const size_t OC = *(weights_shape.rbegin() + 1);+ size_t G = 1;+ if (grouped) {+ G = has_transpose ? *(scale_shape.rbegin() + 2) : *(scale_shape.rbegin() + 1);+ }+ if (supports_config && !supports_config(new_bgm, IC, OC, G)) {+ return false;+ }++ result_nodes.push_back(new_bgm);+ new_bgm->set_friendly_name(bgm->get_friendly_name());+ ov::copy_runtime_info(m.get_matched_nodes(), result_nodes);+ ov::replace_node(bgm, new_bgm);+ return true;+ };++ auto m = std::make_shared<Matcher>(batch_gather_matmul, "ConvertBatchGatherMatmulToBatchGatherMatmulCompressed");+ this->register_matcher(m, callback);+}\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hppnew file mode 100644index 00000000000..fee942d1351--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/convert_batch_gather_matmul_to_compressed.hpp@@ -0,0 +1,30 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <functional>+#include <memory>+#include <vector>++#include "openvino/pass/matcher_pass.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul_compressed.hpp"++namespace ov::intel_cpu {++class ConvertBatchGatherMatmulToBatchGatherMatmulCompressed : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("ConvertBatchGatherMatmulToBatchGatherMatmulCompressed");++ using SupportsPredicate =+ std::function<bool(const std::shared_ptr<ov::intel_cpu::BatchGatherMatmulCompressed>&, size_t, size_t, size_t)>;++ ConvertBatchGatherMatmulToBatchGatherMatmulCompressed(+ const std::vector<ov::element::Type>& supported_activation_types,+ const std::vector<ov::element::Type>& supported_weights_types,+ const SupportsPredicate& supports_config = nullptr,+ bool convert_u4zp_to_u8 = false);+};++} // namespace ov::intel_cpu\ No newline at end of filediff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cppnew file mode 100644index 00000000000..57c6e0ba308--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.cpp@@ -0,0 +1,303 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "moe_matmuls_fusion.hpp"++#include <initializer_list>+#include <memory>+#include <string>++#include "itt.hpp"+#include "openvino/cc/pass/itt.hpp"+#include "openvino/core/graph_util.hpp"+#include "openvino/core/node.hpp"+#include "openvino/core/node_output.hpp"+#include "openvino/core/rt_info.hpp"+#include "openvino/core/type/element_type.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/multiply.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/slice.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "openvino/pass/matcher_pass.hpp"+#include "openvino/pass/pattern/matcher.hpp"+#include "openvino/pass/pattern/op/label.hpp"+#include "openvino/pass/pattern/op/optional.hpp"+#include "openvino/pass/pattern/op/pattern.hpp"+#include "openvino/pass/pattern/op/wrap_type.hpp"+#include "transformations/cpu_opset/common/op/batch_gather_matmul.hpp"++using namespace ov::pass;+namespace {+// Note: intermediate nodes remain unchanged,+// but we need to explicitly call shape inference for them to keep shapes consistency+void validate_nodes(const pattern::PatternValueMap& map, const std::initializer_list<std::shared_ptr<ov::Node>> nodes) {+ for (const auto& node : nodes) {+ map.at(node).get_node_shared_ptr()->validate_and_infer_types();+ }+};++std::shared_ptr<ov::op::v0::Unsqueeze> introduce_n_experts_dim(const ov::Output<ov::Node>& data) {+ auto zero_const = std::make_shared<ov::op::v0::Constant>(ov::element::i32, ov::Shape{}, 0);+ auto unsqueeze = std::make_shared<ov::op::v0::Unsqueeze>(data, zero_const);+ ov::copy_runtime_info(data.get_node_shared_ptr(), {unsqueeze, zero_const});+ return unsqueeze;+}+} // namespace++ov::intel_cpu::MoE2GeMMFusion::MoE2GeMMFusion() {+ MATCHER_SCOPE(MoE2GeMMFusion);++ auto data_input = pattern::any_input(pattern::rank_equals(3) && pattern::has_static_rank());+ auto experts_input = pattern::wrap_type<ov::op::v1::Reshape>({data_input, pattern::any_input()});+ auto tile = pattern::wrap_type<ov::op::v0::Tile>({experts_input, pattern::any_input()});+ auto after_tile_reshape = pattern::wrap_type<ov::op::v1::Reshape>({tile, pattern::any_input()});+ auto gate_up_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},+ {{"transpose_a", false}, {"transpose_b", true}});+ auto gate_up_bias = pattern::wrap_const();+ auto gate_up_add = pattern::wrap_type<ov::op::v1::Add>({gate_up_matmul, gate_up_bias});++ // Branch 1: Slice_1 -> Clamp -> Add_1+ auto slice1 = pattern::wrap_type<ov::op::v8::Slice>(+ {gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto clamp = pattern::wrap_type<ov::op::v0::Clamp>({slice1});+ auto add1 = pattern::wrap_type<ov::op::v1::Add>({clamp, pattern::wrap_const()});++ // Branch 2: Slice_2 -> Minimum_1 -> Swish+ auto slice2 = pattern::wrap_type<ov::op::v8::Slice>(+ {gate_up_add, pattern::any_input(), pattern::any_input(), pattern::any_input(), pattern::any_input()});+ auto minimum1 = pattern::wrap_type<ov::op::v1::Minimum>({slice2, pattern::wrap_const()});+ auto swish_beta = pattern::wrap_const();+ auto swish = pattern::wrap_type<ov::op::v4::Swish>({minimum1, swish_beta});++ // Join: Multiply_2+ auto multiply2 = pattern::wrap_type<ov::op::v1::Multiply>({add1, swish});++ // Down projection+ auto down_proj_matmul = pattern::wrap_type<ov::op::v0::MatMul>({multiply2, pattern::any_input()},+ {{"transpose_a", false}, {"transpose_b", true}});+ auto down_proj_bias = pattern::wrap_const();+ auto down_proj_add = pattern::wrap_type<ov::op::v1::Add>({down_proj_matmul, down_proj_bias});+ auto end_reshape_target_shape = pattern::any_input();+ auto end_reshape = pattern::wrap_type<ov::op::v1::Reshape>({down_proj_add, end_reshape_target_shape});++ // Routing weights/mask+ auto zero_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));+ auto broadcasted_const = pattern::wrap_type<ov::op::v3::Broadcast>({zero_constant, pattern::any_input()}) |+ pattern::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>(+ {zero_constant, pattern::any_input(), pattern::any_input()});+ // Routing weights/mask+ auto router_topk_indices = pattern::any_input();+ auto chosen_experts = pattern::any_input();+ auto slice_begin = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 0"));+ auto slice_end = pattern::wrap_type<ov::op::v3::ShapeOf>({pattern::any_input()});+ auto slice_strides = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1, 1"));+ auto slice_axes = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0, 1"));+ auto slice =+ pattern::optional<ov::op::v8::Slice>({chosen_experts, slice_begin, slice_end, slice_strides, slice_axes});+ auto one_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));+ auto scatter_elements_update = pattern::wrap_type<ov::op::v3::ScatterElementsUpdate>(+ {broadcasted_const, router_topk_indices, chosen_experts, one_constant}) |+ pattern::wrap_type<ov::op::v12::ScatterElementsUpdate>(+ {broadcasted_const, router_topk_indices, chosen_experts, one_constant},+ {{"reduction", "none"}});++ auto router_transpose = pattern::wrap_type<ov::op::v1::Transpose>({scatter_elements_update, pattern::any_input()});+ auto router_reshape =+ pattern::wrap_type<ov::op::v1::Reshape>({router_transpose, pattern::any_input()},+ ov::pass::pattern::rank_equals(3) || ov::pass::pattern::rank_equals(4));+ auto unsqueeze_axis =+ pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("3") || pattern::value_matches("-1"));+ auto unsqueeze_routing_weights =+ pattern::optional<ov::op::v0::Unsqueeze>({router_reshape, unsqueeze_axis}, ov::pass::pattern::rank_equals(4));++ auto mul3 = pattern::wrap_type<ov::op::v1::Multiply>({end_reshape, unsqueeze_routing_weights});+ auto reduce_sum = pattern::wrap_type<ov::op::v1::ReduceSum>({mul3, pattern::any_input()}, {{"keep_dims", false}});++ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto& experts_subgraph_input = pattern_map.at(experts_input);+ const auto& active_indices = pattern_map.at(router_topk_indices);++ const auto gate_up_mm_node = pattern_map.at(gate_up_matmul).get_node_shared_ptr();+ const auto gate_up_add_node = pattern_map.at(gate_up_add).get_node_shared_ptr();+ const auto gate_up_bias_node = pattern_map.at(gate_up_bias).get_node_shared_ptr();++ // BatchGatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]+ // Number of activated experts is always 1 for the first BatchGatherMatmul+ const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);+ const auto gate_up_gathered_mm = std::make_shared<BatchGatherMatmul>(unsqueeze,+ gate_up_mm_node->input_value(1),+ active_indices,+ gate_up_bias_node);+ ov::replace_node_update_name(gate_up_add_node, gate_up_gathered_mm);++ validate_nodes(pattern_map, {slice1, clamp, add1, slice2, minimum1, swish, multiply2});++ const auto down_proj_mm_node = pattern_map.at(down_proj_matmul).get_node_shared_ptr();+ const auto down_proj_bias_node = pattern_map.at(down_proj_bias).get_node_shared_ptr();++ const auto down_gathered_mm = std::make_shared<BatchGatherMatmul>(pattern_map.at(multiply2),+ down_proj_mm_node->input_value(1),+ active_indices,+ down_proj_bias_node);+ const auto& chosen_experts_input = pattern_map.at(chosen_experts);+ const auto router_transpose_node = pattern_map.at(router_transpose).get_node_shared_ptr();+ const auto new_router_transpose =+ router_transpose_node->clone_with_new_inputs({chosen_experts_input, router_transpose_node->input_value(1)});++ const auto router_unsqueeze_const = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});+ const auto router_unsqueeze =+ std::make_shared<ov::op::v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);++ const auto final_mul_node = pattern_map.at(mul3).get_node_shared_ptr();+ const auto new_final_mul =+ final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});+ ov::replace_node_update_name(final_mul_node, new_final_mul);++ validate_nodes(pattern_map, {reduce_sum});++ const auto& reduce_sum_out = pattern_map.at(reduce_sum);+ const auto& end_reshape_out = pattern_map.at(end_reshape);+ const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();+ const auto& end_reshape_shape = pattern_map.at(end_reshape_target_shape);+ // n_all_experts dimension is cut off after ReduceSum+ const auto slice = std::make_shared<ov::op::v8::Slice>(+ end_reshape_shape,+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));++ const auto reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum_out, slice, true);+ ov::replace_output_update_name(reduce_sum_out, reshape->output(0));++ return true;+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(reduce_sum, matcher_name);+ this->register_matcher(m, callback);+}++ov::intel_cpu::MoE3GeMMFusion::MoE3GeMMFusion() {+ MATCHER_SCOPE(MoE3GeMMFusion);++ auto data_input = pattern::any_input(pattern::rank_equals(3) && pattern::has_static_rank());+ auto experts_input =+ pattern::wrap_type<ov::op::v1::Reshape>({data_input, pattern::any_input()}, pattern::rank_equals(2));+ auto tile = pattern::wrap_type<ov::op::v0::Tile>({experts_input, pattern::any_input()});+ auto after_tile_reshape = pattern::wrap_type<ov::op::v1::Reshape>({tile, pattern::any_input()});++ // First GEMM (activation gate)+ auto gate_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},+ {{"transpose_a", false}, {"transpose_b", true}});+ auto swish = pattern::wrap_type<ov::op::v4::Swish>({gate_matmul});+ // Second GEMM (up_projection)+ auto up_matmul = pattern::wrap_type<ov::op::v0::MatMul>({after_tile_reshape, pattern::any_input()},+ {{"transpose_a", false}, {"transpose_b", true}});+ // Join: Multiply (SwiGLU)+ auto swiglu = pattern::wrap_type<ov::op::v1::Multiply>({swish, up_matmul});++ // Third GEMM (down_projection)+ auto down_matmul = pattern::wrap_type<ov::op::v0::MatMul>({swiglu, pattern::any_input()},+ {{"transpose_a", false}, {"transpose_b", true}});+ auto end_reshape_target_shape = pattern::any_input();+ auto end_reshape = pattern::wrap_type<ov::op::v1::Reshape>({down_matmul, end_reshape_target_shape});++ auto zero_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("0"));+ auto broadcasted_const = pattern::wrap_type<ov::op::v3::Broadcast>({zero_constant, pattern::any_input()}) |+ pattern::wrap_type<ov::op::v1::Broadcast, ov::op::v3::Broadcast>(+ {zero_constant, pattern::any_input(), pattern::any_input()});+ // Routing weights/mask+ auto router_topk_indices = pattern::any_input();+ auto chosen_experts = pattern::any_input();+ auto one_constant = pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("1"));+ auto scatter_elements_update = pattern::wrap_type<ov::op::v3::ScatterElementsUpdate>(+ {broadcasted_const, router_topk_indices, chosen_experts, one_constant}) |+ pattern::wrap_type<ov::op::v12::ScatterElementsUpdate>(+ {broadcasted_const, router_topk_indices, chosen_experts, one_constant},+ {{"reduction", "none"}});++ auto router_transpose = pattern::wrap_type<ov::op::v1::Transpose>({scatter_elements_update, pattern::any_input()});+ auto router_reshape =+ pattern::wrap_type<ov::op::v1::Reshape>({router_transpose, pattern::any_input()},+ ov::pass::pattern::rank_equals(3) || ov::pass::pattern::rank_equals(4));+ auto unsqueeze_axis =+ pattern::wrap_type<ov::op::v0::Constant>(pattern::value_matches("3") || pattern::value_matches("-1"));+ auto unsqueeze_routing_weights =+ pattern::optional<ov::op::v0::Unsqueeze>({router_reshape, unsqueeze_axis}, ov::pass::pattern::rank_equals(4));++ auto mul3 = pattern::wrap_type<ov::op::v1::Multiply>({end_reshape, unsqueeze_routing_weights});+ auto reduce_sum = pattern::wrap_type<ov::op::v1::ReduceSum>({mul3, pattern::any_input()}, {{"keep_dims", false}});++ ov::matcher_pass_callback callback = [=](ov::pass::pattern::Matcher& m) {+ const auto& pattern_map = m.get_pattern_value_map();+ const auto& experts_subgraph_input = pattern_map.at(experts_input);+ const auto& active_indices = pattern_map.at(router_topk_indices);++ const auto gate_mm_node = pattern_map.at(gate_matmul).get_node_shared_ptr();+ const auto up_mm_node = pattern_map.at(up_matmul).get_node_shared_ptr();+ const auto down_mm_node = pattern_map.at(down_matmul).get_node_shared_ptr();++ // BatchGatherMatmul A shape: [n_activated_experts, batch_size * seq_length, hidden_size]+ // Number of activated experts is always 1 for the first BatchGatherMatmul+ const auto unsqueeze = introduce_n_experts_dim(experts_subgraph_input);+ const auto gate_gathered_mm =+ std::make_shared<BatchGatherMatmul>(unsqueeze, gate_mm_node->input_value(1), active_indices);+ const auto up_gathered_mm =+ std::make_shared<BatchGatherMatmul>(unsqueeze, up_mm_node->input_value(1), active_indices);+ ov::replace_node_update_name(gate_mm_node, gate_gathered_mm);+ ov::replace_node_update_name(up_mm_node, up_gathered_mm);++ validate_nodes(pattern_map, {swish, swiglu});++ const auto down_gathered_mm =+ std::make_shared<BatchGatherMatmul>(pattern_map.at(swiglu), down_mm_node->input_value(1), active_indices);+ const auto& chosen_experts_input = pattern_map.at(chosen_experts);+ const auto router_transpose_node = pattern_map.at(router_transpose).get_node_shared_ptr();+ const auto new_router_transpose =+ router_transpose_node->clone_with_new_inputs({chosen_experts_input, router_transpose_node->input_value(1)});++ const auto router_unsqueeze_const = ov::op::v0::Constant::create(ov::element::i32, ov::Shape{}, {-1});+ const auto router_unsqueeze =+ std::make_shared<ov::op::v0::Unsqueeze>(new_router_transpose, router_unsqueeze_const);++ const auto final_mul_node = pattern_map.at(mul3).get_node_shared_ptr();+ const auto new_final_mul =+ final_mul_node->clone_with_new_inputs({down_gathered_mm->output(0), router_unsqueeze->output(0)});+ ov::replace_node_update_name(final_mul_node, new_final_mul);++ validate_nodes(pattern_map, {reduce_sum});++ const auto& reduce_sum_out = pattern_map.at(reduce_sum);+ const auto& end_reshape_out = pattern_map.at(end_reshape);+ const auto end_reshape_rank = end_reshape_out.get_partial_shape().rank();+ const auto& end_reshape_shape = pattern_map.at(end_reshape_target_shape);+ // n_all_experts dimension is cut off after ReduceSum+ const auto slice = std::make_shared<ov::op::v8::Slice>(+ end_reshape_shape,+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {end_reshape_rank.get_length()}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {1}),+ ov::op::v0::Constant::create(ov::element::i32, ov::Shape{1}, {0}));++ const auto reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum_out, slice, true);+ ov::replace_output_update_name(reduce_sum_out, reshape->output(0));+ return true;+ };++ auto m = std::make_shared<ov::pass::pattern::Matcher>(reduce_sum, matcher_name);+ this->register_matcher(m, callback);+}diff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hppnew file mode 100644index 00000000000..33628f6b85e--- /dev/null+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/common/pass/moe_matmuls_fusion.hpp@@ -0,0 +1,33 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include "openvino/pass/graph_rewrite.hpp"+#include "openvino/pass/matcher_pass.hpp"++namespace ov::intel_cpu {++class MoE2GeMMFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("MoE2GeMMFusion");+ MoE2GeMMFusion();+};++class MoE3GeMMFusion : public ov::pass::MatcherPass {+public:+ OPENVINO_MATCHER_PASS_RTTI("MoE3GeMMFusion");+ MoE3GeMMFusion();+};++class MoEMatMulsFusion : public ov::pass::GraphRewrite {+public:+ OPENVINO_GRAPH_REWRITE_RTTI("MoEMatMulsFusion");+ MoEMatMulsFusion() {+ add_matcher<ov::intel_cpu::MoE2GeMMFusion>();+ add_matcher<ov::intel_cpu::MoE3GeMMFusion>();+ }+};++} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hppindex 9210fe4454e..be9935c6d00 100644--- a/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp+++ b/src/plugins/intel_cpu/src/transformations/cpu_opset/convert_to_cpu_specific_opset.hpp@@ -6,17 +6,20 @@#include <memory>#include "common/pass/align_matmul_input_ranks.hpp"+#include "common/pass/convert_batch_gather_matmul_to_compressed.hpp"#include "common/pass/convert_matmul_to_fc.hpp"#include "common/pass/convert_tile_to_seq_tiles.hpp"#include "common/pass/convert_to_leaky_relu.hpp"#include "common/pass/convert_to_power_static.hpp"#include "common/pass/convert_to_swish_cpu.hpp"#include "common/pass/fc_bias_fusion.hpp"+#include "common/pass/moe_matmuls_fusion.hpp"#include "common/pass/move_fc_reshape_to_weights.hpp"#include "common/pass/move_readvalue_inputs_to_subgraph.hpp"#include "common/pass/rnn_sequences_optimization.hpp"#include "config.h"#include "nodes/fullyconnected.h"+#include "nodes/gathermatmul.h"#include "openvino/cc/pass/itt.hpp"#include "openvino/core/model.hpp"#include "openvino/core/type/element_type.hpp"@@ -39,6 +42,20 @@ inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model>& model, const Cov::pass::Manager manager("CPU:ConvertToCPUSpecificOpset");manager.set_per_pass_validation(false);+ CPU_REGISTER_PASS_X64(manager, MoEMatMulsFusion);+ CPU_REGISTER_PASS_X64(manager, ov::pass::Validate);+ CPU_REGISTER_PASS_X64(+ manager,+ ConvertBatchGatherMatmulToBatchGatherMatmulCompressed,+ ov::intel_cpu::node::GatherMatmul::getSupportedCompressedActivationsTypes(),+ ov::intel_cpu::node::GatherMatmul::getSupportedCompressedWeightsTypes(),+ [&](const std::shared_ptr<ov::intel_cpu::BatchGatherMatmulCompressed>& gather_matmul,+ size_t IC,+ size_t OC,+ size_t G) {+ return ov::intel_cpu::node::GatherMatmul::isSupportedCompressedOperation(gather_matmul, IC, OC, G, config);+ });+CPU_REGISTER_PASS_COMMON(manager, ConvertMatMulToFC);CPU_REGISTER_PASS_COMMON(manager, FullyConnectedBiasFusion);diff --git a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cppindex a408b93bcf7..95c7f4cca4a 100644--- a/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp+++ b/src/plugins/intel_cpu/src/transformations/transformation_pipeline.cpp@@ -11,7 +11,6 @@#include <cstddef>#include <cstdint>#include <memory>-#include <ov_ops/gather_compressed.hpp>#include <set>#include <vector>@@ -50,6 +49,7 @@#include "openvino/op/swish.hpp"#include "openvino/op/transpose.hpp"#include "openvino/op/util/attr_types.hpp"+#include "ov_ops/gather_compressed.hpp"// Common transformations#include "openvino/pass/constant_folding.hpp"diff --git a/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cpp b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cppnew file mode 100644index 00000000000..4c71b6d9ada--- /dev/null+++ b/src/plugins/intel_cpu/tests/functional/custom/subgraph_tests/src/x64/moe.cpp@@ -0,0 +1,326 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <gtest/gtest.h>++#include <memory>+#include <sstream>+#include <vector>++#include "shared_test_classes/base/ov_subgraph.hpp"+#include "shared_test_classes/subgraph/moe_builders.hpp"+#include "shared_test_classes/subgraph/weights_decompression_builders.hpp"+#include "utils/cpu_test_utils.hpp"+#include "utils/fusing_test_utils.hpp"++using namespace CPUTestUtils;++namespace ov::test {++enum class MoEType { MoE2GeMM, MoE3GeMM };++inline std::ostream& operator<<(std::ostream& os, const MoEType& type) {+ switch (type) {+ case MoEType::MoE2GeMM:+ return os << "MoE2GeMM";+ case MoEType::MoE3GeMM:+ return os << "MoE3GeMM";+ default:+ OPENVINO_THROW("Unsupported MoEType");+ }+}++using MoeTestParams = std::tuple<MoePatternParams,+ MoEType, // MoE builder type+ ov::AnyMap>; // additional config++using MoeCompressedWeightsTestParams = std::tuple<MoePatternParams,+ MoEType, // MoE builder type+ ov::test::ElementType, // weights precision+ ov::test::ElementType, // decompression precision+ ov::test::ElementType, // scale precision+ DecompressionType, // decompression multiply type+ DecompressionType, // decompression subtract type+ bool, // reshape on decompression constants+ int, // decompression_group_size+ ov::AnyMap, // additional config+ bool>; // use_matmul_decompression_impl++class MoESubgraphTest : public testing::WithParamInterface<MoeTestParams>,+ virtual public SubgraphBaseTest,+ public CpuTestWithFusing {+public:+ static std::string generateBaseMoeTestName(const MoePatternParams& moe_params,+ const MoEType& moe_type,+ const ov::AnyMap& additional_config) {+ std::ostringstream result;+ result << "IS=" << ov::test::utils::partialShape2str({moe_params.data_shape.first}) << "_";+ result << "TS=";+ for (const auto& static_shape : moe_params.data_shape.second) {+ result << ov::test::utils::vec2str(static_shape) << ",";+ }+ result << "top_k_experts=" << moe_params.topk << "_";+ result << "total_experts=" << moe_params.number_of_experts << "_";+ result << "intermediate_size=" << moe_params.intermediate_size << "_";+ result << "moe_type=" << moe_type << "_";++ result << "config=(";+ for (const auto& configEntry : additional_config) {+ result << configEntry.first << "=" << configEntry.second.as<std::string>() << "_";+ }+ result << ")";++ return result.str();+ }+ static std::string getTestCaseName(const testing::TestParamInfo<MoeTestParams>& obj) {+ const auto& [moe_params, moe_type, additional_config] = obj.param;+ return generateBaseMoeTestName(moe_params, moe_type, additional_config);+ }++ static size_t get_expected_gather_mm_count(MoEType moe_type) {+ switch (moe_type) {+ case MoEType::MoE2GeMM:+ return 2;+ case MoEType::MoE3GeMM:+ return 3;+ default:+ OPENVINO_THROW("Unsupported MoEType");+ }+ }++ static std::set<std::shared_ptr<ov::Node>> get_gather_mm_nodes(const std::shared_ptr<const ov::Model>& model,+ MoEType moe_type) {+ const std::string expected_gather_mm_type = "GatherMatmul";+ std::set<std::shared_ptr<ov::Node>> gather_mm_nodes;+ for (const auto& node : model->get_ordered_ops()) {+ if (node->get_rt_info().at(ov::exec_model_info::LAYER_TYPE).as<std::string>() == expected_gather_mm_type) {+ gather_mm_nodes.insert(node);+ }+ }+ return gather_mm_nodes;+ }++protected:+ void SetUp() override {+ targetDevice = ov::test::utils::DEVICE_CPU;+ const auto& [shape_params, moe_type, additional_config] = GetParam();++ configuration.insert(additional_config.begin(), additional_config.end());+ init_input_shapes({shape_params.data_shape});+ inType = outType = ov::element::f32;++ auto itr = configuration.find(ov::hint::inference_precision.name());+ if (itr != configuration.end() && itr->second == ov::element::bf16) {+ rel_threshold = 0.1f;+ abs_threshold = 0.1f;+ inType = outType = ov::element::bf16;+ }++ if (moe_type == MoEType::MoE2GeMM) {+ function = initMoE2GeMMSubgraph(shape_params, ov::element::f32, ov::element::f32);+ } else if (moe_type == MoEType::MoE3GeMM) {+ function = initMoE3GeMMSubgraph(shape_params, ov::element::f32, ov::element::f32);+ } else {+ OPENVINO_THROW("Unsupported MoEType");+ }+ }++ void check_results() {+ const auto& moe_type = std::get<1>(GetParam());+ const auto& gather_mm_nodes = get_gather_mm_nodes(compiledModel.get_runtime_model(), moe_type);+ const size_t expected_gather_mm_count = get_expected_gather_mm_count(moe_type);+ EXPECT_EQ(gather_mm_nodes.size(), expected_gather_mm_count);+ }+};++class MoECompressedWeightsSubgraphTest : public testing::WithParamInterface<MoeCompressedWeightsTestParams>,+ virtual public SubgraphBaseTest,+ public CpuTestWithFusing {+public:+ static std::string getTestCaseName(const testing::TestParamInfo<MoeCompressedWeightsTestParams>& obj) {+ const auto& [moe_params,+ moe_type,+ weights_precision,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size,+ additional_config,+ use_matmul_decompression_impl] = obj.param;+ std::ostringstream result;+ result << MoESubgraphTest::generateBaseMoeTestName(moe_params, moe_type, additional_config) << "_";+ result << "_WP=" << weights_precision << "_";+ result << "DP=" << decompression_precision << "_";+ result << "SP=" << scale_precision << "_";+ result << "DM=" << decompression_multiply_type << "_";+ result << "DS=" << decompression_subtract_type << "_";+ result << "RD=" << reshape_on_decompression << "_";+ result << "GS=" << decompression_group_size << "_";+ result << "use_matmul_decompression_impl=" << use_matmul_decompression_impl << "_";+ return result.str();+ }++protected:+ void SetUp() override {+ targetDevice = ov::test::utils::DEVICE_CPU;++ rel_threshold = 5e-4f;+ abs_threshold = 5e-4f;++ const auto& [shape_params,+ moe_type,+ weights_precision,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size,+ additional_config,+ use_matmul_decompression_impl] = GetParam();++ configuration.insert(additional_config.begin(), additional_config.end());+ init_input_shapes({shape_params.data_shape});+ inType = outType = ov::element::f32;++ auto itr = configuration.find(ov::hint::inference_precision.name());+ if (itr != configuration.end() && itr->second == ov::element::bf16) {+ rel_threshold = 0.1f;+ abs_threshold = 0.1f;+ inType = outType = ov::element::bf16;+ }++ if (moe_type == MoEType::MoE2GeMM) {+ function = initMoE2GeMMSubgraph(shape_params,+ ov::element::f32,+ weights_precision,+ true,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);+ } else if (moe_type == MoEType::MoE3GeMM) {+ function = initMoE3GeMMSubgraph(shape_params,+ ov::element::f32,+ weights_precision,+ true,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);+ } else {+ OPENVINO_THROW("Unsupported MoEType");+ }+ }++ void generate_inputs(const std::vector<ov::Shape>& targetInputStaticShapes) override {+ inputs.clear();+ const auto& itTargetShape = targetInputStaticShapes.front();+ const auto& params = function->get_parameters();+ ASSERT_EQ(params.size(), 1);+ auto param = params.front();+ auto type = param->get_element_type();++ auto input_tensor =+ ov::test::utils::create_and_fill_tensor(type,+ itTargetShape,+ ov::test::utils::InputGenerateData(0.125, 2, 8, 1234));++ inputs.insert({param, input_tensor});+ }++ void check_results() {+ const auto& test_param = GetParam();+ const auto& moe_type = std::get<1>(GetParam());+ const auto& gather_mm_nodes = MoESubgraphTest::get_gather_mm_nodes(compiledModel.get_runtime_model(), moe_type);+ const size_t expected_gather_mm_count = MoESubgraphTest::get_expected_gather_mm_count(moe_type);+ EXPECT_EQ(gather_mm_nodes.size(), expected_gather_mm_count);++ const ov::element::Type compressed_weights_precision = std::get<2>(test_param);+ const bool use_matmul_decompression_impl = std::get<10>(test_param);+ for (const auto& gather_mm_node : gather_mm_nodes) {+ const auto& expected_weights_precision = use_matmul_decompression_impl+ ? compressed_weights_precision+ : gather_mm_node->get_input_element_type(0);+ EXPECT_EQ(gather_mm_node->get_input_element_type(1), expected_weights_precision);+ }+ }+};++TEST_P(MoESubgraphTest, CompareWithRefs) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+ run();+ check_results();+}++TEST_P(MoECompressedWeightsSubgraphTest, CompareWithRefs) {+ SKIP_IF_CURRENT_TEST_IS_DISABLED()+ run();+ check_results();+}++namespace {+const std::vector<MoEType> moe_types = {MoEType::MoE2GeMM, MoEType::MoE3GeMM};++const std::vector<MoePatternParams> moe_params_smoke = {+ {+ {{-1, -1, 256}, {{2, 15, 256}, {2, 1, 256}, {3, 8, 256}}}, // data_shape,+ // seq_len=dynamic, hidden_size=256+ 4, // topk+ 8, // number_of_experts+ 512 // intermediate_size+ },+ {+ {{-1, -1, 128}, {{1, 32, 128}, {1, 1, 128}, {1, 16, 128}}}, // Different seq length+ 2, // topk+ 4, // number_of_experts+ 256 // intermediate_size+ },+};++std::vector<ov::AnyMap> generate_additional_config() {+ std::vector<ov::AnyMap> additional_config = {{{ov::hint::inference_precision.name(), ov::element::f32}}};+ if (ov::with_cpu_x86_bfloat16()) {+ additional_config.push_back({{ov::hint::inference_precision.name(), ov::element::bf16}});+ }+ return additional_config;+}++} // namespace++INSTANTIATE_TEST_SUITE_P(smoke_MoESubgraph_basic,+ MoESubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::ValuesIn(moe_types),+ ::testing::ValuesIn(generate_additional_config())),+ MoESubgraphTest::getTestCaseName);++const std::vector<ov::test::ElementType> decompression_precisions = {ov::element::f32};+const std::vector<ov::test::ElementType> weights_precisions = {ov::element::u8,+ ov::element::i8,+ ov::element::u4,+ ov::element::i4};++INSTANTIATE_TEST_SUITE_P(smoke_MoeCompressedWeights,+ MoECompressedWeightsSubgraphTest,+ ::testing::Combine(::testing::ValuesIn(moe_params_smoke),+ ::testing::ValuesIn(moe_types),+ ::testing::ValuesIn(weights_precisions),+ ::testing::ValuesIn(decompression_precisions),+ ::testing::Values(ov::element::f32),+ ::testing::Values(DecompressionType::full),+ ::testing::Values(DecompressionType::full),+ ::testing::Values(false), // reshape on decompression+ ::testing::Values(16), // decompression group size+ ::testing::ValuesIn(generate_additional_config()),+ ::testing::Values(true)), // use_matmul_decompression_impl+ MoECompressedWeightsSubgraphTest::getTestCaseName);++} // namespace ov::testdiff --git a/src/plugins/intel_cpu/thirdparty/onednn b/src/plugins/intel_cpu/thirdparty/onednnindex 0cad963300c..a4ed4a789b6 160000--- a/src/plugins/intel_cpu/thirdparty/onednn+++ b/src/plugins/intel_cpu/thirdparty/onednn@@ -1 +1 @@-Subproject commit 0cad963300cd2b80c371cb66d435c60ad0e5edd7+Subproject commit a4ed4a789b6e0869e4f651bbfeff6878e91d388ediff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hppnew file mode 100644index 00000000000..dbd3cbfb623--- /dev/null+++ b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/moe_builders.hpp@@ -0,0 +1,48 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <iostream>+#include <memory>+#include <optional>+#include "openvino/core/model.hpp"+#include "openvino/core/type/element_type.hpp"+#include "shared_test_classes/base/ov_subgraph.hpp"+#include "shared_test_classes/subgraph/weights_decompression_builders.hpp"++namespace ov {+namespace test {++struct MoePatternParams {+ ov::test::InputShape data_shape;+ size_t topk;+ size_t number_of_experts;+ size_t intermediate_size;+};++std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression = false,+ const std::optional<ov::element::Type> decompression_precision = std::nullopt,+ const std::optional<ov::element::Type> scale_precision = std::nullopt,+ const std::optional<DecompressionType> decompression_multiply_type = std::nullopt,+ const std::optional<DecompressionType> decompression_subtract_type = std::nullopt,+ const std::optional<bool> reshape_on_decompression = std::nullopt,+ const std::optional<int> decompression_group_size = std::nullopt);++std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression = false,+ const std::optional<ov::element::Type> decompression_precision = std::nullopt,+ const std::optional<ov::element::Type> scale_precision = std::nullopt,+ const std::optional<DecompressionType> decompression_multiply_type = std::nullopt,+ const std::optional<DecompressionType> decompression_subtract_type = std::nullopt,+ const std::optional<bool> reshape_on_decompression = std::nullopt,+ const std::optional<int> decompression_group_size = std::nullopt);++} // namespace test+} // namespace ov\ No newline at end of filediff --git a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/weights_decompression_builders.hpp b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/weights_decompression_builders.hppindex a7fa3659b67..323e0aedad4 100644--- a/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/weights_decompression_builders.hpp+++ b/src/tests/functional/plugin/shared/include/shared_test_classes/subgraph/weights_decompression_builders.hpp@@ -6,6 +6,8 @@#include <iostream>#include <memory>+#include <optional>+#include "openvino/core/node.hpp"#include "shared_test_classes/base/ov_subgraph.hpp"@@ -50,13 +52,14 @@ struct GatherDecompressionShapeParams {std::ostream& operator<<(std::ostream& os, GatherDecompressionShapeParams type);enum class DecompressionType {- empty, // no decompression- scalar, // decompression with scalar shape- full // decompression with per-channel or grouped shape+ empty, // no decompression+ scalar, // decompression with scalar shape+ full // decompression with per-channel or grouped shape};std::ostream& operator<<(std::ostream& os, DecompressionType type);+// fill the weights and scales with random valuesstd::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(const ov::Shape& weights_shape,const int group_size,@@ -67,7 +70,24 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(const bool transpose_weights,const DecompressionType decompression_multiply_type,const DecompressionType decompression_subtract_type,- const bool reshape_on_decompression_constant);+ const bool reshape_on_decompression_constant,+ const std::optional<bool>& insert_transpose_node = std::nullopt,+ const size_t seed = 1);++// do real quantization of a random float tensor to get weights and scales+std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(+ const ov::Shape& weights_shape,+ const int group_size,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const ov::element::Type decompression_precision,+ const ov::element::Type scale_precision,+ const bool transpose_weights,+ const DecompressionType decompression_multiply_type,+ const DecompressionType decompression_subtract_type,+ const bool reshape_on_decompression_constant,+ const std::optional<bool>& insert_transpose_node = std::nullopt,+ const size_t seed = 1);std::shared_ptr<ov::Node> initGatherDecompressionSubgraph(const ov::Shape& data_shape,const int group_size,@@ -78,5 +98,5 @@ std::shared_ptr<ov::Node> initGatherDecompressionSubgraph(const ov::Shape& data_const bool per_tensor_zp,const bool per_tensor_scale);-} // namespace test-} // namespace ov+} // namespace test+} // namespace ovdiff --git a/src/tests/functional/plugin/shared/src/subgraph/moe_builders.cpp b/src/tests/functional/plugin/shared/src/subgraph/moe_builders.cppnew file mode 100644index 00000000000..ea9a5e713e4--- /dev/null+++ b/src/tests/functional/plugin/shared/src/subgraph/moe_builders.cpp@@ -0,0 +1,496 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "shared_test_classes/subgraph/moe_builders.hpp"++#include <limits>+#include <memory>+#include <vector>++#include "common_test_utils/node_builders/constant.hpp"+#include "openvino/core/model.hpp"+#include "openvino/core/node_vector.hpp"+#include "openvino/op/add.hpp"+#include "openvino/op/broadcast.hpp"+#include "openvino/op/clamp.hpp"+#include "openvino/op/concat.hpp"+#include "openvino/op/constant.hpp"+#include "openvino/op/divide.hpp"+#include "openvino/op/gather.hpp"+#include "openvino/op/matmul.hpp"+#include "openvino/op/minimum.hpp"+#include "openvino/op/multiply.hpp"+#include "openvino/op/parameter.hpp"+#include "openvino/op/reduce_sum.hpp"+#include "openvino/op/reshape.hpp"+#include "openvino/op/result.hpp"+#include "openvino/op/scatter_elements_update.hpp"+#include "openvino/op/shape_of.hpp"+#include "openvino/op/slice.hpp"+#include "openvino/op/softmax.hpp"+#include "openvino/op/swish.hpp"+#include "openvino/op/tile.hpp"+#include "openvino/op/topk.hpp"+#include "openvino/op/transpose.hpp"+#include "openvino/op/unsqueeze.hpp"+#include "shared_test_classes/subgraph/weights_decompression_builders.hpp"+#include "transformations/utils/utils.hpp"++namespace ov {+namespace test {++std::shared_ptr<ov::Node> build_matmul_weights(+ const ov::Shape& weights_shape,+ const ov::element::Type& weights_precision,+ const ov::element::Type& data_precision,+ size_t seed,+ bool use_weight_decompression,+ const std::optional<ov::element::Type>& decompression_precision = std::nullopt,+ const std::optional<ov::element::Type>& scale_precision = std::nullopt,+ const std::optional<DecompressionType>& decompression_multiply_type = std::nullopt,+ const std::optional<DecompressionType>& decompression_subtract_type = std::nullopt,+ const std::optional<bool>& reshape_on_decompression = std::nullopt,+ const std::optional<int>& decompression_group_size = std::nullopt) {+ if (!use_weight_decompression) {+ // Note: builder takes planar weights shape, but it is transposed here+ // since MoE matmuls are supported only in case of transpose_b=true+ auto transposed_weights_shape = weights_shape;+ std::swap(*transposed_weights_shape.rbegin(), *(transposed_weights_shape.rbegin() + 1));+ return ov::test::utils::make_constant(weights_precision,+ transposed_weights_shape,+ utils::InputGenerateData(0, 10, 1, seed));+ } else {+ OPENVINO_ASSERT(decompression_precision.has_value(),+ "decompression_precision must be set when use_weight_decompression is true");+ OPENVINO_ASSERT(scale_precision.has_value(),+ "scale_precision must be set when use_weight_decompression is true");+ OPENVINO_ASSERT(decompression_multiply_type.has_value(),+ "decompression_multiply_type must be set when use_weight_decompression is true");+ OPENVINO_ASSERT(decompression_subtract_type.has_value(),+ "decompression_subtract_type must be set when use_weight_decompression is true");+ OPENVINO_ASSERT(reshape_on_decompression.has_value(),+ "reshape_on_decompression must be set when use_weight_decompression is true");+ OPENVINO_ASSERT(decompression_group_size.has_value(),+ "decompression_group_size must be set when use_weight_decompression is true");+ return initMatMulDecompressionSubgraphQuantization(weights_shape,+ decompression_group_size.value(),+ data_precision,+ weights_precision,+ decompression_precision.value(),+ scale_precision.value(),+ true,+ decompression_multiply_type.value(),+ decompression_subtract_type.value(),+ reshape_on_decompression.value(),+ false,+ seed);+ }+}++std::shared_ptr<ov::Model> initMoE2GeMMSubgraph(const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression,+ const std::optional<ov::element::Type> decompression_precision,+ const std::optional<ov::element::Type> scale_precision,+ const std::optional<DecompressionType> decompression_multiply_type,+ const std::optional<DecompressionType> decompression_subtract_type,+ const std::optional<bool> reshape_on_decompression,+ const std::optional<int> decompression_group_size) {+ // Use parameters from shape_params - static shapes only+ const auto& data_shape = moe_params.data_shape;+ const size_t intermediate_size = moe_params.intermediate_size;+ const size_t topk = moe_params.topk;+ const size_t number_of_experts = moe_params.number_of_experts;++ const auto expert_alpha = 1.625f;+ const auto expert_beta = 7.0f;++ constexpr int64_t fusion_factor = 2; // property of GPT-OSS++ const auto& input_shape = data_shape.first;+ // Create input parameter with dynamic shape - batch and hidden_size are fixed, seq_len is dynamic+ auto input = std::make_shared<ov::op::v0::Parameter>(data_precision, input_shape);++ OPENVINO_ASSERT(input_shape[2].is_static());+ const auto hidden_size = static_cast<size_t>(input_shape[2].get_length());++ // Expert processing path - use -1 for dynamic reshape like in reference+ auto experts_reshape = std::make_shared<ov::op::v1::Reshape>(+ input,+ ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}), // -1 flattens batch*seq_len+ false);++ auto tile = std::make_shared<ov::op::v0::Tile>(+ experts_reshape,+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{static_cast<int64_t>(number_of_experts), 1}));++ auto after_tile_reshape = std::make_shared<ov::op::v1::Reshape>(+ tile,+ ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(number_of_experts), -1, static_cast<int64_t>(hidden_size)}),+ false);++ // Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape+ size_t seed = 1;+ auto gate_up_weights =+ build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size * fusion_factor},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto gate_up_matmul = std::make_shared<ov::op::v0::MatMul>(after_tile_reshape, gate_up_weights, false, true);++ gate_up_matmul->set_friendly_name("GateUpMatMul");++ auto gate_up_add = std::make_shared<ov::op::v1::Add>(+ gate_up_matmul,+ ov::test::utils::make_constant(data_precision,+ ov::Shape{number_of_experts, 1, intermediate_size * fusion_factor}));++ // Slice the last axis, every second element+ auto slice1 = std::make_shared<ov::op::v8::Slice>(+ gate_up_add,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}),+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{1},+ std::vector<int64_t>{std::numeric_limits<int64_t>::max()}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2}));+ auto clamp = std::make_shared<ov::op::v0::Clamp>(slice1, -expert_beta, expert_beta);+ auto add1 = std::make_shared<ov::op::v1::Add>(clamp, ov::test::utils::make_constant(data_precision, ov::Shape{1}));++ auto slice2 = std::make_shared<ov::op::v8::Slice>(+ gate_up_add,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}),+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{1},+ std::vector<int64_t>{std::numeric_limits<int64_t>::max()}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{2}));+ auto minimum1 =+ std::make_shared<ov::op::v1::Minimum>(slice2,+ ov::op::v0::Constant::create(data_precision, ov::Shape{1}, {10.0f}));+ auto swish_beta = ov::op::v0::Constant::create(data_precision, ov::Shape{}, std::vector<float>{expert_alpha});+ auto swish = std::make_shared<ov::op::v4::Swish>(minimum1, swish_beta);++ auto multiply2 = std::make_shared<ov::op::v1::Multiply>(add1, swish);++ // Down projection+ auto down_proj_weights = build_matmul_weights(ov::Shape{number_of_experts, intermediate_size, hidden_size},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto down_proj_matmul = std::make_shared<ov::op::v0::MatMul>(multiply2, down_proj_weights, false, true);++ down_proj_matmul->set_friendly_name("DownProjMatMul");++ auto down_proj_add = std::make_shared<ov::op::v1::Add>(+ down_proj_matmul,+ ov::test::utils::make_constant(data_precision, ov::Shape{number_of_experts, 1, hidden_size}));++ auto router_weights = build_matmul_weights(ov::Shape{hidden_size, number_of_experts},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto reshape_2nd_consumer_router_matmul =+ std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights, false, true);++ auto router_bias = std::make_shared<ov::op::v1::Add>(+ reshape_2nd_consumer_router_matmul,+ ov::test::utils::make_constant(data_precision, ov::Shape{1, number_of_experts}));++ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(router_bias,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);++ auto router_topk_values = router_topk_values_and_indices->output(0);+ auto router_topk_values_softmax = std::make_shared<ov::op::v1::Softmax>(router_topk_values, 1);+ auto router_topk_indices = router_topk_values_and_indices->output(1);+ auto slice3 = std::make_shared<ov::op::v8::Slice>(+ router_topk_values_softmax,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, 0}),+ std::make_shared<ov::op::v3::ShapeOf>(router_topk_indices),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 1}),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{0, 1}));++ auto shape_of = std::make_shared<ov::op::v0::ShapeOf>(router_bias);+ auto zero_const = ov::op::v0::Constant::create(slice3->get_output_element_type(0), ov::Shape{1}, {0});+ auto broadcast_zero = std::make_shared<ov::op::v3::Broadcast>(zero_const, shape_of);++ auto scatter_elements_update = std::make_shared<ov::op::v12::ScatterElementsUpdate>(+ broadcast_zero,+ router_topk_indices,+ slice3,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));++ auto router_transpose = std::make_shared<ov::op::v1::Transpose>(+ scatter_elements_update,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0}));++ const auto number_of_experts_const =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(number_of_experts)});+ auto first_in_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(input, {0});+ auto last_in_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(input, {2});+ auto minus_one = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});++ const auto router_shape =+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{number_of_experts_const, first_in_dim, minus_one}, 0);++ auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);++ auto unsqueeze_routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(+ router_reshape,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{3}));++ auto end_shape = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{number_of_experts_const, first_in_dim, minus_one, last_in_dim},+ 0);+ auto end_reshape = std::make_shared<ov::op::v1::Reshape>(down_proj_add, end_shape, true);++ auto mul3 = std::make_shared<ov::op::v1::Multiply>(end_reshape, unsqueeze_routing_weights);++ // ReduceSum - final node of the MOE pattern+ auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(+ mul3,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}),+ false);++ ov::ParameterVector params = {input};+ return std::make_shared<ov::Model>(ov::OutputVector{std::make_shared<ov::op::v0::Result>(reduce_sum)},+ params,+ "MoeSubgraph");+}++std::shared_ptr<ov::Model> initMoE3GeMMSubgraph(const MoePatternParams& moe_params,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const bool use_weight_decompression,+ const std::optional<ov::element::Type> decompression_precision,+ const std::optional<ov::element::Type> scale_precision,+ const std::optional<DecompressionType> decompression_multiply_type,+ const std::optional<DecompressionType> decompression_subtract_type,+ const std::optional<bool> reshape_on_decompression,+ const std::optional<int> decompression_group_size) {+ // Use parameters from shape_params - static shapes only+ const auto& data_shape = moe_params.data_shape;+ const size_t intermediate_size = moe_params.intermediate_size;+ const size_t topk = moe_params.topk;+ const size_t number_of_experts = moe_params.number_of_experts;++ const auto expert_alpha = 1.702f;++ const auto& input_shape = data_shape.first;+ // Create input parameter with dynamic shape - batch and hidden_size are fixed, seq_len is dynamic+ auto input = std::make_shared<ov::op::v0::Parameter>(data_precision, input_shape);++ OPENVINO_ASSERT(input_shape[2].is_static());+ const auto hidden_size = static_cast<size_t>(input_shape[2].get_length());++ // Expert processing path - use -1 for dynamic reshape like in reference+ auto experts_reshape = std::make_shared<ov::op::v1::Reshape>(+ input,+ ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{-1, static_cast<int64_t>(hidden_size)}), // -1 flattens batch*seq_len+ false);++ auto tile = std::make_shared<ov::op::v0::Tile>(+ experts_reshape,+ ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{static_cast<int64_t>(number_of_experts), 1}));++ auto after_tile_reshape = std::make_shared<ov::op::v1::Reshape>(+ tile,+ ov::op::v0::Constant::create(+ ov::element::i64,+ ov::Shape{3},+ std::vector<int64_t>{static_cast<int64_t>(number_of_experts), -1, static_cast<int64_t>(hidden_size)}),+ false);++ // Note: we need to use different seed to avoid the exact weights generation for the MatMuls with the same shape+ size_t seed = 1;+ auto gate_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto gate_matmul = std::make_shared<ov::op::v0::MatMul>(after_tile_reshape, gate_weights, false, true);++ gate_matmul->set_friendly_name("GateMatMul");++ // Apply Swish activation directly to gate+ auto swish = std::make_shared<ov::op::v4::Swish>(gate_matmul);++ // Second GEMM (up_projection)+ auto up_weights = build_matmul_weights(ov::Shape{number_of_experts, hidden_size, intermediate_size},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto up_matmul = std::make_shared<ov::op::v0::MatMul>(after_tile_reshape, up_weights, false, true);++ up_matmul->set_friendly_name("UpMatMul");++ // Join: Multiply (SwiGLU)+ auto swiglu = std::make_shared<ov::op::v1::Multiply>(swish, up_matmul);++ // Third GEMM (down_projection)+ auto down_weights_moe3 = build_matmul_weights(ov::Shape{number_of_experts, intermediate_size, hidden_size},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto down_matmul = std::make_shared<ov::op::v0::MatMul>(swiglu, down_weights_moe3, false, true);++ down_matmul->set_friendly_name("DownMatMul");++ // Router subgraph - this is crucial for the MoE pattern recognition+ auto router_weights_moe3 = build_matmul_weights(ov::Shape{hidden_size, number_of_experts},+ weights_precision,+ data_precision,+ seed++,+ use_weight_decompression,+ decompression_precision,+ scale_precision,+ decompression_multiply_type,+ decompression_subtract_type,+ reshape_on_decompression,+ decompression_group_size);++ auto reshape_2nd_consumer_router_matmul =+ std::make_shared<ov::op::v0::MatMul>(experts_reshape, router_weights_moe3, false, true);++ auto router_softmax = std::make_shared<ov::op::v1::Softmax>(reshape_2nd_consumer_router_matmul, 1);++ auto router_topk_values_and_indices =+ std::make_shared<ov::op::v11::TopK>(router_softmax,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{}, {topk}),+ -1,+ ov::op::v11::TopK::Mode::MAX,+ ov::op::v11::TopK::SortType::SORT_VALUES,+ ov::element::i64);++ auto router_topk_values_reduce = std::make_shared<ov::op::v1::ReduceSum>(+ router_topk_values_and_indices->output(0),+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1}),+ true);+ auto router_topk_values_normalization =+ std::make_shared<ov::op::v1::Divide>(router_topk_values_and_indices->output(0), router_topk_values_reduce);+ auto router_topk_indices = router_topk_values_and_indices->output(1);++ const auto number_of_experts_const =+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, {static_cast<int64_t>(number_of_experts)});++ auto zero_const =+ ov::op::v0::Constant::create(router_topk_values_normalization->get_output_element_type(0), ov::Shape{1}, {0});+ auto first_topk_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(router_topk_indices, {0});+ auto bcast_target_shape =+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{first_topk_dim, number_of_experts_const}, 0);+ auto broadcast_zero = std::make_shared<ov::op::v3::Broadcast>(zero_const, bcast_target_shape);++ auto scatter_elements_update = std::make_shared<ov::op::v12::ScatterElementsUpdate>(+ broadcast_zero,+ router_topk_indices,+ router_topk_values_normalization,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{1}));++ auto router_transpose = std::make_shared<ov::op::v1::Transpose>(+ scatter_elements_update,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{2}, std::vector<int64_t>{1, 0}));++ auto minus_one = ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{-1});+ const auto router_shape =+ std::make_shared<ov::op::v0::Concat>(ov::OutputVector{number_of_experts_const, first_topk_dim, minus_one}, 0);++ auto router_reshape = std::make_shared<ov::op::v1::Reshape>(router_transpose, router_shape, true);++ auto unsqueeze_routing_weights = std::make_shared<ov::op::v0::Unsqueeze>(+ router_reshape,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{3}));++ auto last_in_dim = ov::op::util::node_to_get_shape_value_of_indices_from_shape_source(input, {2});+ auto end_shape = std::make_shared<ov::op::v0::Concat>(+ ov::OutputVector{number_of_experts_const, first_topk_dim, minus_one, last_in_dim},+ 0);+ auto end_reshape = std::make_shared<ov::op::v1::Reshape>(down_matmul, end_shape, true);++ auto mul3 = std::make_shared<ov::op::v1::Multiply>(end_reshape, unsqueeze_routing_weights);++ auto reduce_sum = std::make_shared<ov::op::v1::ReduceSum>(+ mul3,+ ov::op::v0::Constant::create(ov::element::i64, ov::Shape{1}, std::vector<int64_t>{0}),+ false);++ // Note: here we imitate a real model scenario with special zero value+ auto final_reshape_const = ov::op::v0::Constant::create(ov::element::i64,+ ov::Shape{2},+ std::vector<int64_t>{0, static_cast<int64_t>(hidden_size)});+ auto final_reshape = std::make_shared<ov::op::v1::Reshape>(reduce_sum, final_reshape_const, true);++ ov::ParameterVector params = {input};+ return std::make_shared<ov::Model>(ov::OutputVector{std::make_shared<ov::op::v0::Result>(final_reshape)},+ params,+ "MoE3GeMMSubgraph");+}++} // namespace test+} // namespace ov\ No newline at end of filediff --git a/src/tests/functional/plugin/shared/src/subgraph/weights_decompression_builders.cpp b/src/tests/functional/plugin/shared/src/subgraph/weights_decompression_builders.cppindex 592861a50eb..a0570e09838 100644--- a/src/tests/functional/plugin/shared/src/subgraph/weights_decompression_builders.cpp+++ b/src/tests/functional/plugin/shared/src/subgraph/weights_decompression_builders.cpp@@ -3,14 +3,19 @@//#include "shared_test_classes/subgraph/weights_decompression_builders.hpp"-#include "openvino/opsets/opset10_decl.hpp"++#include <algorithm>+#include <limits>+#include "common_test_utils/node_builders/constant.hpp"-#include "transformations/rt_info/decompression.hpp"+#include "openvino/core/type/element_iterator.hpp"#include "openvino/op/convert.hpp"#include "openvino/op/multiply.hpp"#include "openvino/op/reshape.hpp"#include "openvino/op/subtract.hpp"#include "openvino/op/transpose.hpp"+#include "openvino/opsets/opset10_decl.hpp"+#include "transformations/rt_info/decompression.hpp"namespace ov {namespace test {@@ -46,17 +51,18 @@ std::ostream& operator<<(std::ostream& os, DecompressionType type) {return os;}-std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(- const ov::Shape& weights_shape,- const int group_size,- const ov::element::Type data_precision,- const ov::element::Type weights_precision,- const ov::element::Type decompression_precision,- const ov::element::Type scale_precision,- const bool transpose_weights,- const DecompressionType decompression_multiply_type,- const DecompressionType decompression_subtract_type,- const bool reshape_on_decompression_constant) {+std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(const ov::Shape& weights_shape,+ const int group_size,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const ov::element::Type decompression_precision,+ const ov::element::Type scale_precision,+ const bool transpose_weights,+ const DecompressionType decompression_multiply_type,+ const DecompressionType decompression_subtract_type,+ const bool reshape_on_decompression_constant,+ const std::optional<bool>& insert_transpose_node,+ const size_t seed) {auto transpose_if_necessary = [&](const ov::Shape& shape) {auto result_shape = shape;if (transpose_weights)@@ -72,16 +78,17 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(// N - number of groups// G - group sizeauto transformed_weights_shape = transpose_if_necessary(weights_shape);+ const auto IC = *(weights_shape.rbegin() + 1);if (group_decompression) {- OPENVINO_ASSERT(weights_shape[0] % group_size == 0,+ OPENVINO_ASSERT(IC % group_size == 0,"Weights output channels count (",- weights_shape[0],+ IC,") must be divisible by decompression group size (",group_size,").");auto in_channel_idx =transpose_weights ? transformed_weights_shape.size() - 1 : transformed_weights_shape.size() - 2;- transformed_weights_shape[in_channel_idx] = weights_shape[0] / group_size;+ transformed_weights_shape[in_channel_idx] = IC / group_size;transformed_weights_shape.insert(transformed_weights_shape.begin() + in_channel_idx + 1, group_size);}@@ -90,49 +97,51 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(auto weights_tensor =ov::test::utils::create_and_fill_tensor(weights_precision,transformed_weights_shape,- ov::test::utils::InputGenerateData(start_from, up_to));+ ov::test::utils::InputGenerateData(start_from, up_to, 1, seed));auto weights = std::make_shared<ov::op::v0::Constant>(weights_tensor);auto weights_convert = std::make_shared<ov::op::v0::Convert>(weights, decompression_precision);std::shared_ptr<ov::Node> mul_parent = weights_convert;- auto output_channels = *weights_shape.rbegin();+ const auto OC = weights_shape.back();// Decompression constants shape:// Ordinary decompression: [O, 1]// Group decompression: [O, N, 1]- ov::Shape scaleshift_target_shape{output_channels};- scaleshift_target_shape.insert(scaleshift_target_shape.begin(),- group_decompression ? weights_shape[0] / group_size : 1);+ ov::Shape scaleshift_target_shape{OC};+ scaleshift_target_shape.insert(scaleshift_target_shape.begin(), group_decompression ? IC / group_size : 1);scaleshift_target_shape = transpose_if_necessary(scaleshift_target_shape);if (group_decompression) {auto in_channel_idx =transpose_weights ? scaleshift_target_shape.size() - 1 : scaleshift_target_shape.size() - 2;scaleshift_target_shape.insert(scaleshift_target_shape.begin() + in_channel_idx + 1, 1);}+ const bool with_batch = weights_shape.size() == 3;+ if (with_batch) {+ scaleshift_target_shape.insert(scaleshift_target_shape.begin(), weights_shape[0]);+ }auto scaleshift_const_shape = scaleshift_target_shape;if (reshape_on_decompression_constant)scaleshift_const_shape.erase(std::remove(scaleshift_const_shape.begin(), scaleshift_const_shape.end(), 1),- scaleshift_const_shape.end());+ scaleshift_const_shape.end());if (decompression_subtract_type != DecompressionType::empty) {auto subtract_shape =decompression_subtract_type == DecompressionType::full ? scaleshift_const_shape : ov::Shape({});auto shift_const_tensor =ov::test::utils::create_and_fill_tensor(weights_precision,subtract_shape,- ov::test::utils::InputGenerateData(start_from, up_to));+ ov::test::utils::InputGenerateData(start_from, up_to, 1, seed));auto shift_const = std::make_shared<ov::op::v0::Constant>(shift_const_tensor);std::shared_ptr<ov::Node> shift_convert =std::make_shared<ov::op::v0::Convert>(shift_const, decompression_precision);if (reshape_on_decompression_constant) {auto subtract_target_shape = decompression_subtract_type == DecompressionType::full- ? scaleshift_target_shape- : ov::Shape(scaleshift_const_shape.size(), 1);- auto shift_reshape_const = ov::opset10::Constant::create(ov::element::i32,- {subtract_target_shape.size()},- subtract_target_shape);+ ? scaleshift_target_shape+ : ov::Shape(scaleshift_const_shape.size(), 1);+ auto shift_reshape_const =+ ov::opset10::Constant::create(ov::element::i32, {subtract_target_shape.size()}, subtract_target_shape);auto shift_reshape = std::make_shared<ov::opset10::Reshape>(shift_convert, shift_reshape_const, false);shift_convert = shift_reshape;}@@ -144,11 +153,8 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(if (decompression_multiply_type != DecompressionType::empty) {auto multiply_shape =decompression_multiply_type == DecompressionType::full ? scaleshift_const_shape : ov::Shape({});- auto scale_const_tensor = ov::test::utils::create_and_fill_tensor_real_distribution(scale_prc,- multiply_shape,- 0.001f,- 0.01f,- 1);+ auto scale_const_tensor =+ ov::test::utils::create_and_fill_tensor_real_distribution(scale_prc, multiply_shape, 0.001f, 0.01f, seed);std::shared_ptr<ov::Node> scale_const = std::make_shared<ov::op::v0::Constant>(scale_const_tensor);if (scale_prc != decompression_precision) {@@ -159,9 +165,10 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(if (reshape_on_decompression_constant) {auto multiply_target_shape = decompression_multiply_type == DecompressionType::full- ? scaleshift_target_shape- : ov::Shape(scaleshift_const_shape.size(), 1);- auto reshape_const = ov::opset10::Constant::create(ov::element::i32, {multiply_target_shape.size()}, multiply_target_shape);+ ? scaleshift_target_shape+ : ov::Shape(scaleshift_const_shape.size(), 1);+ auto reshape_const =+ ov::opset10::Constant::create(ov::element::i32, {multiply_target_shape.size()}, multiply_target_shape);auto scale_reshape = std::make_shared<ov::opset10::Reshape>(scale_const, reshape_const, false);scale_const = scale_reshape;}@@ -169,8 +176,359 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(}if (group_decompression) {- auto reshape_target_shape = transpose_weights ? std::vector<int>{-1, static_cast<int>(weights_shape[0])}- : std::vector<int>{static_cast<int>(weights_shape[0]), -1};+ auto reshape_target_shape =+ transpose_weights ? std::vector<int>{-1, static_cast<int>(IC)} : std::vector<int>{static_cast<int>(IC), -1};+ if (with_batch)+ reshape_target_shape.insert(reshape_target_shape.begin(), weights_shape[0]);+ auto target_shape_node =+ ov::opset10::Constant::create(ov::element::i32, {reshape_target_shape.size()}, reshape_target_shape);+ last_node = std::make_shared<ov::opset10::Reshape>(last_node, target_shape_node, false);+ }+ if (decompression_precision != data_precision) {+ last_node = std::make_shared<ov::opset10::Convert>(last_node, data_precision);+ ov::mark_as_decompression(last_node);+ }+ const bool insert_transpose = insert_transpose_node.value_or(transpose_weights);+ if (insert_transpose) {+ const size_t rank = last_node->get_output_partial_shape(0).size();+ std::vector<int> order(rank);+ std::iota(order.begin(), order.end(), 0);+ std::swap(*order.rbegin(), *(order.rbegin() + 1));+ auto transpose_constant = ov::opset10::Constant::create(ov::element::i32, {rank}, order);+ last_node = std::make_shared<ov::opset10::Transpose>(last_node, transpose_constant);+ }+ return last_node;+}++std::shared_ptr<ov::Node> initMatMulDecompressionSubgraphQuantization(+ const ov::Shape& weights_shape,+ const int group_size,+ const ov::element::Type data_precision,+ const ov::element::Type weights_precision,+ const ov::element::Type decompression_precision,+ const ov::element::Type scale_precision,+ const bool transpose_weights,+ const DecompressionType decompression_multiply_type,+ const DecompressionType decompression_subtract_type,+ const bool reshape_on_decompression_constant,+ const std::optional<bool>& insert_transpose_node,+ const size_t seed) {+ // Validate that the precision is supported for real quantization+ OPENVINO_ASSERT(weights_precision == ov::element::u2 || weights_precision == ov::element::u4 ||+ weights_precision == ov::element::i4 || weights_precision == ov::element::u8 ||+ weights_precision == ov::element::i8,+ "initMatMulDecompressionSubgraphQuantization only supports u2, u4, i4, u8, i8 precisions. Got: ",+ weights_precision);++ auto transpose_if_necessary = [&](const ov::Shape& shape) {+ auto result_shape = shape;+ if (transpose_weights)+ std::swap(*result_shape.rbegin(), *(result_shape.rbegin() + 1));+ return result_shape;+ };++ const bool group_decompression = group_size != -1;+ // Weights has shape [I, O], where+ // I - input channels+ // O - output channels+ // In case of group decompression, input channels dimension is split into 2: I -> [N, G], where+ // N - number of groups+ // G - group size+ auto transformed_weights_shape = transpose_if_necessary(weights_shape);+ const auto IC = *(weights_shape.rbegin() + 1);+ if (group_decompression) {+ OPENVINO_ASSERT(IC % group_size == 0,+ "Weights output channels count (",+ IC,+ ") must be divisible by decompression group size (",+ group_size,+ ").");+ auto in_channel_idx =+ transpose_weights ? transformed_weights_shape.size() - 1 : transformed_weights_shape.size() - 2;+ transformed_weights_shape[in_channel_idx] = IC / group_size;+ transformed_weights_shape.insert(transformed_weights_shape.begin() + in_channel_idx + 1, group_size);+ }++ // Step 1: Generate FP32 weights for real quantization+ auto fp32_weights_tensor =+ ov::test::utils::create_and_fill_tensor(ov::element::f32,+ transformed_weights_shape,+ ov::test::utils::InputGenerateData(1, 6, 8, seed));++ // Calculate quantization parameters+ const auto qmin = weights_precision == ov::element::u2 ? 0.0f+ : weights_precision == ov::element::i4 ? -8.0f+ : weights_precision == ov::element::u4 ? 0.0f+ : weights_precision.is_signed() ? -128.0f+ : 0.0f;+ const auto qmax = weights_precision == ov::element::u2 ? 3.0f+ : weights_precision == ov::element::i4 ? 7.0f+ : weights_precision == ov::element::u4 ? 15.0f+ : weights_precision.is_signed() ? 127.0f+ : 255.0f;++ auto* fp32_data = fp32_weights_tensor.data<float>();+ const size_t total_size = ov::shape_size(transformed_weights_shape);++ const auto OC = weights_shape.back();+ // Decompression constants shape:+ // Ordinary decompression: [O, 1]+ // Group decompression: [O, N, 1]+ ov::Shape scaleshift_target_shape{OC};+ scaleshift_target_shape.insert(scaleshift_target_shape.begin(), group_decompression ? IC / group_size : 1);+ scaleshift_target_shape = transpose_if_necessary(scaleshift_target_shape);+ if (group_decompression) {+ auto in_channel_idx =+ transpose_weights ? scaleshift_target_shape.size() - 1 : scaleshift_target_shape.size() - 2;+ scaleshift_target_shape.insert(scaleshift_target_shape.begin() + in_channel_idx + 1, 1);+ }+ const bool with_batch = weights_shape.size() == 3;+ if (with_batch) {+ scaleshift_target_shape.insert(scaleshift_target_shape.begin(), weights_shape[0]);+ }++ auto scaleshift_const_shape = scaleshift_target_shape;+ if (reshape_on_decompression_constant)+ scaleshift_const_shape.erase(std::remove(scaleshift_const_shape.begin(), scaleshift_const_shape.end(), 1),+ scaleshift_const_shape.end());++ // Step 2: Compute quantization parameters (scales and zero points) based on actual FP32 data+ const auto& scale_prc = scale_precision == ov::element::dynamic ? decompression_precision : scale_precision;++ // Determine number of quantization groups+ size_t num_groups = 1;+ if (decompression_multiply_type == DecompressionType::full ||+ decompression_subtract_type == DecompressionType::full) {+ num_groups = ov::shape_size(scaleshift_const_shape);+ }++ // Calculate group size for quantization+ size_t elements_per_group = total_size / num_groups;++ // Compute scales and zero points per group+ std::vector<float> scales(num_groups);+ std::vector<float> zero_points(num_groups);++ for (size_t g = 0; g < num_groups; ++g) {+ float min_val = std::numeric_limits<float>::max();+ float max_val = std::numeric_limits<float>::lowest();++ // Find min/max in the current group+ for (size_t i = 0; i < elements_per_group; ++i) {+ float val = fp32_data[g * elements_per_group + i];+ min_val = std::min(min_val, val);+ max_val = std::max(max_val, val);+ }++ // Compute scale and zero point+ float range = max_val - min_val;+ if (range < 1e-6f) {+ range = 1e-6f; // Avoid division by zero+ }++ scales[g] = range / (qmax - qmin);+ float zp = std::round(-min_val / scales[g] + qmin);+ // Clamp zero point to valid quantization range+ zero_points[g] = std::max(qmin, std::min(qmax, zp));+ }++ // Step 3: Quantize the weights+ ov::Tensor quantized_weights_tensor(weights_precision, transformed_weights_shape);++ auto quantize_value = [&](float val, float scale, float zp) -> float {+ float quantized = std::round(val / scale + zp);+ return std::max(qmin, std::min(qmax, quantized));+ };++ // Quantize based on weights_precision type+ if (weights_precision == ov::element::u2 || weights_precision == ov::element::u4) {+ // For sub-byte unsigned types, use element::iterator+ std::vector<uint8_t> quantized_buffer(total_size);+ for (size_t i = 0; i < total_size; ++i) {+ size_t group_idx = (num_groups == 1) ? 0 : (i / elements_per_group);+ quantized_buffer[i] =+ static_cast<uint8_t>(quantize_value(fp32_data[i], scales[group_idx], zero_points[group_idx]));+ }+ if (weights_precision == ov::element::u4) {+ auto iter = ov::element::iterator<ov::element::u4>(quantized_weights_tensor.data());+ std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);+ } else {+ auto iter = ov::element::iterator<ov::element::u2>(quantized_weights_tensor.data());+ std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);+ }+ } else if (weights_precision == ov::element::i4) {+ // For sub-byte signed types, use element::iterator+ std::vector<int8_t> quantized_buffer(total_size);+ for (size_t i = 0; i < total_size; ++i) {+ size_t group_idx = (num_groups == 1) ? 0 : (i / elements_per_group);+ quantized_buffer[i] =+ static_cast<int8_t>(quantize_value(fp32_data[i], scales[group_idx], zero_points[group_idx]));+ }+ auto iter = ov::element::iterator<ov::element::i4>(quantized_weights_tensor.data());+ std::copy(quantized_buffer.begin(), quantized_buffer.end(), iter);+ } else if (weights_precision == ov::element::u8) {+ auto* q_data = quantized_weights_tensor.data<uint8_t>();+ for (size_t i = 0; i < total_size; ++i) {+ size_t group_idx = (num_groups == 1) ? 0 : (i / elements_per_group);+ q_data[i] = static_cast<uint8_t>(quantize_value(fp32_data[i], scales[group_idx], zero_points[group_idx]));+ }+ } else if (weights_precision == ov::element::i8) {+ auto* q_data = quantized_weights_tensor.data<int8_t>();+ for (size_t i = 0; i < total_size; ++i) {+ size_t group_idx = (num_groups == 1) ? 0 : (i / elements_per_group);+ q_data[i] = static_cast<int8_t>(quantize_value(fp32_data[i], scales[group_idx], zero_points[group_idx]));+ }+ }++ // Step 4: Create constants with quantized data+ auto weights = std::make_shared<ov::op::v0::Constant>(quantized_weights_tensor);+ auto weights_convert = std::make_shared<ov::op::v0::Convert>(weights, decompression_precision);++ std::shared_ptr<ov::Node> mul_parent = weights_convert;++ // Create zero point (shift) constants if needed+ if (decompression_subtract_type != DecompressionType::empty) {+ auto subtract_shape =+ decompression_subtract_type == DecompressionType::full ? scaleshift_const_shape : ov::Shape({});++ ov::Tensor shift_tensor(weights_precision, subtract_shape);+ if (decompression_subtract_type == DecompressionType::scalar) {+ // Use average zero point for scalar+ float avg_zp = 0.0f;+ for (size_t g = 0; g < num_groups; ++g) {+ avg_zp += zero_points[g];+ }+ avg_zp /= num_groups;++ // Use element iterator for sub-byte types+ if (weights_precision == ov::element::u4) {+ auto iter = ov::element::iterator<ov::element::u4>(shift_tensor.data());+ *iter = static_cast<uint8_t>(std::round(avg_zp));+ } else if (weights_precision == ov::element::u2) {+ auto iter = ov::element::iterator<ov::element::u2>(shift_tensor.data());+ *iter = static_cast<uint8_t>(std::round(avg_zp));+ } else if (weights_precision == ov::element::i4) {+ auto iter = ov::element::iterator<ov::element::i4>(shift_tensor.data());+ *iter = static_cast<int8_t>(std::round(avg_zp));+ } else if (weights_precision.is_signed()) {+ shift_tensor.data<int8_t>()[0] = static_cast<int8_t>(std::round(avg_zp));+ } else {+ shift_tensor.data<uint8_t>()[0] = static_cast<uint8_t>(std::round(avg_zp));+ }+ } else {+ // Full zero points+ if (weights_precision == ov::element::u4) {+ std::vector<uint8_t> zp_buffer(num_groups);+ for (size_t i = 0; i < num_groups; ++i) {+ zp_buffer[i] = static_cast<uint8_t>(std::round(zero_points[i]));+ }+ auto iter = ov::element::iterator<ov::element::u4>(shift_tensor.data());+ std::copy(zp_buffer.begin(), zp_buffer.end(), iter);+ } else if (weights_precision == ov::element::u2) {+ std::vector<uint8_t> zp_buffer(num_groups);+ for (size_t i = 0; i < num_groups; ++i) {+ zp_buffer[i] = static_cast<uint8_t>(std::round(zero_points[i]));+ }+ auto iter = ov::element::iterator<ov::element::u2>(shift_tensor.data());+ std::copy(zp_buffer.begin(), zp_buffer.end(), iter);+ } else if (weights_precision == ov::element::i4) {+ std::vector<int8_t> zp_buffer(num_groups);+ for (size_t i = 0; i < num_groups; ++i) {+ zp_buffer[i] = static_cast<int8_t>(std::round(zero_points[i]));+ }+ auto iter = ov::element::iterator<ov::element::i4>(shift_tensor.data());+ std::copy(zp_buffer.begin(), zp_buffer.end(), iter);+ } else if (weights_precision.is_signed()) {+ auto* shift_data = shift_tensor.data<int8_t>();+ for (size_t i = 0; i < num_groups; ++i) {+ shift_data[i] = static_cast<int8_t>(std::round(zero_points[i]));+ }+ } else {+ auto* shift_data = shift_tensor.data<uint8_t>();+ for (size_t i = 0; i < num_groups; ++i) {+ shift_data[i] = static_cast<uint8_t>(std::round(zero_points[i]));+ }+ }+ }++ auto shift_const = std::make_shared<ov::op::v0::Constant>(shift_tensor);+ std::shared_ptr<ov::Node> shift_convert =+ std::make_shared<ov::op::v0::Convert>(shift_const, decompression_precision);+ if (reshape_on_decompression_constant) {+ auto subtract_target_shape = decompression_subtract_type == DecompressionType::full+ ? scaleshift_target_shape+ : ov::Shape(scaleshift_const_shape.size(), 1);+ auto shift_reshape_const =+ ov::opset10::Constant::create(ov::element::i32, {subtract_target_shape.size()}, subtract_target_shape);+ auto shift_reshape = std::make_shared<ov::opset10::Reshape>(shift_convert, shift_reshape_const, false);+ shift_convert = shift_reshape;+ }+ mul_parent = std::make_shared<ov::opset10::Subtract>(weights_convert, shift_convert);+ }++ // Create scale constants+ if (decompression_multiply_type != DecompressionType::empty) {+ auto multiply_shape =+ decompression_multiply_type == DecompressionType::full ? scaleshift_const_shape : ov::Shape({});++ ov::Tensor scale_tensor;+ if (decompression_multiply_type == DecompressionType::scalar) {+ scale_tensor = ov::Tensor(scale_prc, multiply_shape);+ // Use average scale for scalar+ float avg_scale = 0.0f;+ for (size_t g = 0; g < num_groups; ++g) {+ avg_scale += scales[g];+ }+ avg_scale /= num_groups;++ if (scale_prc == ov::element::f16) {+ scale_tensor.data<ov::float16>()[0] = ov::float16(avg_scale);+ } else {+ scale_tensor.data<float>()[0] = avg_scale;+ }+ } else {+ // Full scales+ scale_tensor = ov::Tensor(scale_prc, multiply_shape);+ if (scale_prc == ov::element::f16) {+ auto* scale_data = scale_tensor.data<ov::float16>();+ for (size_t i = 0; i < num_groups; ++i) {+ scale_data[i] = ov::float16(scales[i]);+ }+ } else {+ auto* scale_data = scale_tensor.data<float>();+ for (size_t i = 0; i < num_groups; ++i) {+ scale_data[i] = scales[i];+ }+ }+ }++ std::shared_ptr<ov::Node> scale_const = std::make_shared<ov::op::v0::Constant>(scale_tensor);++ if (scale_prc != decompression_precision) {+ const auto scale_convert = std::make_shared<ov::op::v0::Convert>(scale_const, decompression_precision);+ ov::mark_as_decompression(scale_convert);+ scale_const = scale_convert;+ }++ if (reshape_on_decompression_constant) {+ auto multiply_target_shape = decompression_multiply_type == DecompressionType::full+ ? scaleshift_target_shape+ : ov::Shape(scaleshift_const_shape.size(), 1);+ auto reshape_const =+ ov::opset10::Constant::create(ov::element::i32, {multiply_target_shape.size()}, multiply_target_shape);+ auto scale_reshape = std::make_shared<ov::opset10::Reshape>(scale_const, reshape_const, false);+ scale_const = scale_reshape;+ }+ mul_parent = std::make_shared<ov::opset10::Multiply>(mul_parent, scale_const);+ }++ std::shared_ptr<ov::Node> last_node = mul_parent;++ if (group_decompression) {+ auto reshape_target_shape =+ transpose_weights ? std::vector<int>{-1, static_cast<int>(IC)} : std::vector<int>{static_cast<int>(IC), -1};+ if (with_batch)+ reshape_target_shape.insert(reshape_target_shape.begin(), weights_shape[0]);auto target_shape_node =ov::opset10::Constant::create(ov::element::i32, {reshape_target_shape.size()}, reshape_target_shape);last_node = std::make_shared<ov::opset10::Reshape>(last_node, target_shape_node, false);@@ -179,7 +537,8 @@ std::shared_ptr<ov::Node> initMatMulDecompressionSubgraph(last_node = std::make_shared<ov::opset10::Convert>(last_node, data_precision);ov::mark_as_decompression(last_node);}- if (transpose_weights) {+ const bool insert_transpose = insert_transpose_node.value_or(transpose_weights);+ if (insert_transpose) {const size_t rank = last_node->get_output_partial_shape(0).size();std::vector<int> order(rank);std::iota(order.begin(), order.end(), 0);@@ -245,7 +604,9 @@ std::shared_ptr<ov::Node> initGatherDecompressionSubgraph(const ov::Shape& data_scaleshift_const_shape.end());if (add_subtract) {auto shift_tensor_shape = per_tensor_zp ? ov::Shape{1} : scaleshift_const_shape;- auto shift_tensor = ov::test::utils::create_and_fill_tensor(data_precision, shift_tensor_shape, ov::test::utils::InputGenerateData(0, up_to));+ auto shift_tensor = ov::test::utils::create_and_fill_tensor(data_precision,+ shift_tensor_shape,+ ov::test::utils::InputGenerateData(0, up_to));if (per_tensor_zp && data_precision.bitwidth() == 4) {static_cast<uint8_t*>(shift_tensor.data())[0] = 0x88;}@@ -291,5 +652,5 @@ std::shared_ptr<ov::Node> initGatherDecompressionSubgraph(const ov::Shape& data_return last_node;}-} // namespace test-} // namespace ov+} // namespace test+} // namespace ov