Skip to content

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

[Op] GroupedMatMul init (#35215)

Katarzyna Mitrus0733e871726a
diff --git a/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/matrix/grouped-matmul-17.rst b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/matrix/grouped-matmul-17.rst
new file mode 100644
index 00000000000..194089b96fe
--- /dev/null
+++ b/docs/articles_en/documentation/openvino-ir-format/operation-sets/operation-specs/matrix/grouped-matmul-17.rst
@@ -0,0 +1,149 @@
+GroupedMatMul
+=============
+
+
+.. meta::
+ :description: Learn about GroupedMatMul-17 - a grouped matrix multiplication operation
+ for Mixture of Experts (MoE) workloads.
+
+**Versioned name**: *GroupedMatMul-17*
+
+**Category**: *Matrix multiplication*
+
+**Short description**: Grouped matrix multiplication for Mixture of Experts (MoE).
+
+**Detailed description**
+
+*GroupedMatMul* operation computes multiple matrix multiplications where each group processes
+a subset of the input data. This operation is optimized for Mixture of Experts (MoE) workloads
+where tokens are routed to different expert networks.
+
+The operation supports two input combinations based on tensor dimensions:
+
+**Case 1: 2D × 3D (MoE Forward Pass)**
+
+Used for computing expert outputs from routed tokens:
+
+* ``mat_a``: Shape ``[total_tokens, K]`` - all tokens packed contiguously
+* ``mat_b``: Shape ``[G, N, K]`` - per-group (expert) weight matrices (stored transposed)
+* ``offsets``: Shape ``[G]`` - cumulative token boundaries
+
+For group ``i``, computes: ``output[start:end] = mat_a[start:end] @ mat_b[i].T``
+
+where ``start = offsets[i-1]`` (or 0 for i=0) and ``end = offsets[i]``.
+
+Output shape: ``[total_tokens, N]``
+
+**Case 2: 3D × 3D (Batched Uniform Groups)**
+
+Used when all groups have the same number of tokens:
+
+* ``mat_a``: Shape ``[G, M, K]`` - per-group inputs
+* ``mat_b``: Shape ``[G, N, K]`` - per-group weights (stored transposed)
+* ``offsets``: Not used (ignored if provided)
+
+For each group ``i``, computes: ``output[i] = mat_a[i] @ mat_b[i].T``
+
+Output shape: ``[G, M, N]``
+
+**Offsets Format**
+
+The ``offsets`` tensor contains cumulative token counts. For G groups:
+``offsets = [M0, M0+M1, M0+M1+M2, ..., total_tokens]``
+
+where ``Mi`` is the number of tokens for group ``i``.
+
+For example, with tokens per group ``[3, 5, 2]``, offsets would be ``[3, 8, 10]``.
+
+**Attributes**
+
+*GroupedMatMul* operation has no attributes.
+
+**Inputs**
+
+* **1**: ``mat_a`` - Tensor of type *T* with first operand. Required.
+
+ * Case 1 (2D×3D): Shape ``[total_tokens, K]``
+ * Case 2 (3D×3D): Shape ``[G, M, K]``
+
+* **2**: ``mat_b`` - Tensor of type *T* with second operand. Required.
+
+ * Case 1 (2D×3D): Shape ``[G, N, K]``
+ * Case 2 (3D×3D): Shape ``[G, N, K]``
+
+* **3**: ``offsets`` - 1D tensor of type *T_IDX* with group boundaries. Optional.
+
+ * Shape: ``[G]`` containing cumulative offsets
+ * Required for case (2D×3D)
+ * Ignored if provided for case (3D×3D)
+
+**Outputs**
+
+* **1**: Tensor of type *T* with matrix multiplication results.
+
+ * Case (2D×3D): Shape ``[total_tokens, N]``
+ * Case (3D×3D): Shape ``[G, M, N]``
+
+**Types**
+
+* *T*: any supported floating-point or integer type.
+* *T_IDX*: ``int32`` or ``int64``.
+
+**Example**
+
+*MoE Forward Pass (Case: 2D × 3D)*
+
+.. code-block:: xml
+ :force:
+
+ <layer ... type="GroupedMatMul" version="opset17">
+ <input>
+ <port id="0"> <!-- mat_a: 10 tokens, K=64 -->
+ <dim>10</dim>
+ <dim>64</dim>
+ </port>
+ <port id="1"> <!-- mat_b: 3 experts, N=128, K=64 -->
+ <dim>3</dim>
+ <dim>128</dim>
+ <dim>64</dim>
+ </port>
+ <port id="2"> <!-- offsets: [3, 8, 10] -->
+ <dim>3</dim>
+ </port>
+ </input>
+ <output>
+ <port id="3"> <!-- output: 10 tokens, N=128 -->
+ <dim>10</dim>
+ <dim>128</dim>
+ </port>
+ </output>
+ </layer>
+
+*Batched Uniform (Case: 3D × 3D)*
+
+.. code-block:: xml
+ :force:
+
+ <layer ... type="GroupedMatMul" version="opset17">
+ <input>
+ <port id="0"> <!-- mat_a: 3 groups, M=4, K=64 -->
+ <dim>3</dim>
+ <dim>4</dim>
+ <dim>64</dim>
+ </port>
+ <port id="1"> <!-- mat_b: 3 groups, N=128, K=64 -->
+ <dim>3</dim>
+ <dim>128</dim>
+ <dim>64</dim>
+ </port>
+ </input>
+ <output>
+ <port id="2"> <!-- output: 3 groups, M=4, N=128 -->
+ <dim>3</dim>
+ <dim>4</dim>
+ <dim>128</dim>
+ </port>
+ </output>
+ </layer>
+
+
diff --git a/src/common/transformations/include/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp b/src/common/transformations/include/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp
new file mode 100644
index 00000000000..b6c14dd5a9a
--- /dev/null
+++ b/src/common/transformations/include/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp
@@ -0,0 +1,43 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/pass/matcher_pass.hpp"
+#include "transformations_visibility.hpp"
+
+namespace ov::pass {
+
+/// @brief Converts the public op v17::GroupedMatMul into the internal op
+/// ov::op::internal::GatherMatmul, which is the form consumed by the CPU/GPU
+/// `GatherMatmul` nodes.
+///
+/// Supported cases (matching the GroupedMatMul-17 spec):
+/// * Case (3D x 3D, no offsets):
+/// A:[G,M,K], B:[G,N,K] -> out:[G,M,N]
+/// Mapped as:
+/// A' = A // [G, M, K]
+/// B' = B // [G, N, K] (transp_b=true already)
+/// indices = Broadcast(Range(0,G), [M, G]) // indices[m,g] = g
+/// out = GatherMatmul(A', B', indices) // [G, M, N]
+///
+/// * Case (2D x 3D with offsets):
+/// A:[T,K], B:[G,N,K], offs:[G] -> out:[T,N]
+/// Mapped as:
+/// A' = Unsqueeze(A, 0) // [1, T, K]
+/// B' = B // [G, N, K]
+/// idx1d = SearchSorted(offsets, Range(0,T), right=true) // [T]
+/// indices = Unsqueeze(idx1d, -1) // [T, 1]
+/// gm = GatherMatmul(A', B', indices) // [1, T, N]
+/// out = Squeeze(gm, 0) // [T, N]
+///
+/// The pass requires the weights tensor (input B) to be a Constant (or reachable
+/// through a constant-foldable chain).
+class TRANSFORMATIONS_API ConvertGroupedMatMulToGatherMatmul : public ov::pass::MatcherPass {
+public:
+ OPENVINO_MATCHER_PASS_RTTI("ConvertGroupedMatMulToGatherMatmul");
+ ConvertGroupedMatMulToGatherMatmul();
+};
+
+} // namespace ov::pass
diff --git a/src/common/transformations/src/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.cpp b/src/common/transformations/src/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.cpp
new file mode 100644
index 00000000000..f717ece6402
--- /dev/null
+++ b/src/common/transformations/src/transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.cpp
@@ -0,0 +1,167 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp"
+
+#include <memory>
+
+#include "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/broadcast.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/grouped_matmul.hpp"
+#include "openvino/op/range.hpp"
+#include "openvino/op/search_sorted.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/node_registry.hpp"
+#include "openvino/pass/pattern/matcher.hpp"
+#include "openvino/pass/pattern/op/or.hpp"
+#include "openvino/pass/pattern/op/pattern.hpp"
+#include "openvino/pass/pattern/op/predicate.hpp"
+#include "openvino/pass/pattern/op/wrap_type.hpp"
+#include "ov_ops/gather_matmul.hpp"
+#include "transformations/utils/utils.hpp"
+
+namespace ov::pass {
+
+namespace {
+
+namespace v0 = ov::op::v0;
+namespace v1 = ov::op::v1;
+namespace v3 = ov::op::v3;
+namespace v4 = ov::op::v4;
+namespace v8 = ov::op::v8;
+namespace v15 = ov::op::v15;
+namespace v17 = ov::op::v17;
+
+using ov::op::internal::GatherMatmul;
+
+// Build the identity-per-group `indices` for 3Dx3D:
+// indices = Broadcast(Range(0, G), [M, G])
+// The G and M dimensions are taken dynamically from ShapeOf(mat_a).
+ov::Output<ov::Node> build_indices_for_3dx3d(const ov::Output<ov::Node>& mat_a, NodeRegistry& rg) {
+ auto i32 = ov::element::i32;
+ auto zero = rg.make<v0::Constant>(i32, ov::Shape{}, 0);
+ auto shape_a = rg.make<v3::ShapeOf>(mat_a, i32); // [G, M, K]
+
+ // Single Gather produces the Broadcast target shape [M, G] directly
+ auto mg_idx = rg.make<v0::Constant>(i32, ov::Shape{2}, std::vector<int32_t>{1, 0});
+ auto target_shape = rg.make<v8::Gather>(shape_a, mg_idx, zero); // [M, G]
+
+ // Scalar G for Range stop (index 0 along axis 0).
+ auto g_scalar = rg.make<v8::Gather>(shape_a, zero, zero);
+ auto one = rg.make<v0::Constant>(i32, ov::Shape{}, 1);
+ auto range = rg.make<v4::Range>(zero, g_scalar, one, i32); // [G]
+
+ // Broadcast right-aligns [G] against the target [M, G]
+ auto indices = rg.make<v3::Broadcast>(range, target_shape);
+ return indices;
+}
+
+// Build per-token expert indices from `offsets` for 2Dx3D:
+// positions = Range(0, T) [T]
+// idx_1d = SearchSorted(offsets, positions, right=true) [T]
+// indices = Unsqueeze(idx_1d, -1) [T, 1]
+//
+// `offsets` may be i32 or i64; we Convert to i32 only when needed and use i32
+ov::Output<ov::Node> build_indices_for_2dx3d(const ov::Output<ov::Node>& mat_a,
+ const ov::Output<ov::Node>& offsets,
+ NodeRegistry& rg) {
+ auto i32 = ov::element::i32;
+ auto zero = rg.make<v0::Constant>(i32, ov::Shape{}, 0);
+
+ // SearchSorted requires the sorted sequence and probe values to share an element
+ // type; convert `offsets` to i32 only when it isn't already i32.
+ ov::Output<ov::Node> offsets_i32 = offsets;
+ if (offsets.get_element_type() != i32) {
+ offsets_i32 = rg.make<v0::Convert>(offsets, i32);
+ }
+
+ auto shape_a = rg.make<v3::ShapeOf>(mat_a, i32); // [T, K]
+ auto t_scalar = rg.make<v8::Gather>(shape_a, zero, zero); // scalar T
+ auto one = rg.make<v0::Constant>(i32, ov::Shape{}, 1);
+ auto positions = rg.make<v4::Range>(zero, t_scalar, one, i32); // [T]
+ auto idx_1d = rg.make<v15::SearchSorted>(offsets_i32, positions, /*right_mode=*/true, i32);
+ auto unsqueeze_axis = rg.make<v0::Constant>(i32, ov::Shape{1}, -1);
+ auto indices = rg.make<v0::Unsqueeze>(idx_1d, unsqueeze_axis);
+ return indices;
+}
+
+} // namespace
+
+ConvertGroupedMatMulToGatherMatmul::ConvertGroupedMatMulToGatherMatmul() {
+ MATCHER_SCOPE(ConvertGroupedMatMulToGatherMatmul);
+ using namespace ov::pass::pattern;
+
+ // Common pattern for second input
+ auto matrix_b_3d = any_input(rank_equals(3));
+
+ // ---- 3Dx3D: no offsets ----
+ // A:[G,M,K] B:[G,N,K]
+ auto matrix_a_3d = any_input(rank_equals(3));
+ auto gmm_3d_3d = wrap_type<v17::GroupedMatMul>({matrix_a_3d, matrix_b_3d});
+
+ // ---- 2Dx3D: with offsets ----
+ // A:[T,K] B:[G,N,K] offsets:[G]
+ auto matrix_a_2d = any_input(rank_equals(2));
+ auto offsets = any_input(rank_equals(1));
+ auto gmm_2d_3d = wrap_type<v17::GroupedMatMul>({matrix_a_2d, matrix_b_3d, offsets});
+
+ auto gmm_pattern = gmm_3d_3d | gmm_2d_3d;
+
+ ov::matcher_pass_callback callback = [OV_CAPTURE_CPY_AND_THIS](ov::pass::pattern::Matcher& m) {
+ auto gmm = ov::as_type_ptr<v17::GroupedMatMul>(m.get_match_root());
+ if (!gmm || transformation_callback(gmm)) {
+ return false;
+ }
+ const auto mat_a = gmm->input_value(0);
+ const auto mat_b = gmm->input_value(1);
+
+ // GatherMatmul requires the weights tensor (input B) to be a Constant
+ // (or reachable through a constant-foldable chain).
+ if (!ov::op::util::is_on_path<v0::Constant>(mat_b)) {
+ return false;
+ }
+
+ NodeRegistry rg;
+ std::shared_ptr<ov::Node> replacement;
+ const auto& pattern_map = m.get_pattern_value_map();
+ if (pattern_map.count(gmm_3d_3d)) {
+ // ---- 3Dx3D: no offsets ----
+ // A:[G,M,K] B:[G,N,K] -> GatherMatmul(A, B, indices=[M,G]) -> [G,M,N]
+ auto indices = build_indices_for_3dx3d(mat_a, rg);
+ replacement = rg.make<GatherMatmul>(mat_a, mat_b, indices);
+ } else if (pattern_map.count(gmm_2d_3d)) {
+ // ---- 2Dx3D: with offsets ----
+ // A:[T,K] B:[G,N,K] offs:[G] -> Squeeze(GatherMatmul(Unsqueeze(A,0), B, idx[T,1]), 0) -> [T,N]
+ const auto offsets = gmm->input_value(2);
+ auto a_unsq_axis = rg.make<v0::Constant>(ov::element::i32, ov::Shape{1}, 0);
+ auto a_3d = rg.make<v0::Unsqueeze>(mat_a, a_unsq_axis);
+ auto indices = build_indices_for_2dx3d(mat_a, offsets, rg);
+ auto gm = rg.make<GatherMatmul>(a_3d, mat_b, indices); // [1, T, N]
+ auto squeeze_axis = rg.make<v0::Constant>(ov::element::i32, ov::Shape{1}, 0);
+ replacement = rg.make<v0::Squeeze>(gm, squeeze_axis); // [T, N]
+ } else {
+ return false;
+ }
+
+ replacement->set_friendly_name(gmm->get_friendly_name());
+ ov::copy_runtime_info(gmm, rg.get());
+ ov::replace_node(gmm, replacement);
+ return true;
+ };
+
+ auto matcher = std::make_shared<ov::pass::pattern::Matcher>(gmm_pattern, matcher_name);
+ register_matcher(matcher, callback);
+}
+
+} // namespace ov::pass
diff --git a/src/common/transformations/tests/op_conversions/convert_grouped_matmul_to_gather_matmul_test.cpp b/src/common/transformations/tests/op_conversions/convert_grouped_matmul_to_gather_matmul_test.cpp
new file mode 100644
index 00000000000..5f43e09e6a3
--- /dev/null
+++ b/src/common/transformations/tests/op_conversions/convert_grouped_matmul_to_gather_matmul_test.cpp
@@ -0,0 +1,167 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp"
+
+#include <gtest/gtest.h>
+
+#include <memory>
+
+#include "common_test_utils/ov_test_utils.hpp"
+#include "openvino/core/model.hpp"
+#include "openvino/op/broadcast.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/gather.hpp"
+#include "openvino/op/grouped_matmul.hpp"
+#include "openvino/op/parameter.hpp"
+#include "openvino/op/range.hpp"
+#include "openvino/op/search_sorted.hpp"
+#include "openvino/op/shape_of.hpp"
+#include "openvino/op/squeeze.hpp"
+#include "openvino/op/unsqueeze.hpp"
+#include "openvino/pass/manager.hpp"
+#include "ov_ops/gather_matmul.hpp"
+
+namespace v0 = ov::op::v0;
+namespace v3 = ov::op::v3;
+namespace v4 = ov::op::v4;
+namespace v8 = ov::op::v8;
+namespace v15 = ov::op::v15;
+namespace v17 = ov::op::v17;
+
+using GatherMatmul = ov::op::internal::GatherMatmul;
+
+namespace {
+
+constexpr auto f32 = ov::element::f32;
+constexpr auto i32 = ov::element::i32;
+constexpr auto i64 = ov::element::i64;
+
+ov::Output<ov::Node> ref_3dx3d_indices(const ov::Output<ov::Node>& mat_a) {
+ auto zero = v0::Constant::create(i32, ov::Shape{}, {0});
+ auto shape_a = std::make_shared<v3::ShapeOf>(mat_a, i32);
+ auto mg_idx = v0::Constant::create(i32, ov::Shape{2}, {1, 0});
+ auto target_shape = std::make_shared<v8::Gather>(shape_a, mg_idx, zero);
+ auto g_scalar = std::make_shared<v8::Gather>(shape_a, zero, zero);
+ auto one = v0::Constant::create(i32, ov::Shape{}, {1});
+ auto range = std::make_shared<v4::Range>(zero, g_scalar, one, i32);
+ return std::make_shared<v3::Broadcast>(range, target_shape);
+}
+
+ov::Output<ov::Node> ref_2dx3d_indices(const ov::Output<ov::Node>& mat_a, const ov::Output<ov::Node>& offsets) {
+ auto zero = v0::Constant::create(i32, ov::Shape{}, {0});
+
+ ov::Output<ov::Node> offsets_i32 = offsets;
+ if (offsets.get_element_type() != i32) {
+ offsets_i32 = std::make_shared<v0::Convert>(offsets, i32);
+ }
+
+ auto shape_a = std::make_shared<v3::ShapeOf>(mat_a, i32);
+ auto t_scalar = std::make_shared<v8::Gather>(shape_a, zero, zero);
+ auto one = v0::Constant::create(i32, ov::Shape{}, {1});
+ auto positions = std::make_shared<v4::Range>(zero, t_scalar, one, i32);
+ auto idx_1d = std::make_shared<v15::SearchSorted>(offsets_i32, positions, /*right_mode=*/true, i32);
+ auto unsqueeze_axis = v0::Constant::create(i32, ov::Shape{1}, {-1});
+ return std::make_shared<v0::Unsqueeze>(idx_1d, unsqueeze_axis);
+}
+
+} // namespace
+
+// 3Dx3D: A:[G,M,K] B:[G,N,K] -> GatherMatmul(A, B, indices)
+TEST_F(TransformationTestsF, ConvertGroupedMatMulToGatherMatmul_3Dx3D) {
+ constexpr size_t G = 2, M = 4, K = 8, N = 16;
+
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{G, M, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto gmm = std::make_shared<v17::GroupedMatMul>(mat_a, mat_b);
+ model = std::make_shared<ov::Model>(ov::OutputVector{gmm}, ov::ParameterVector{mat_a});
+
+ manager.register_pass<ov::pass::ConvertGroupedMatMulToGatherMatmul>();
+ }
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{G, M, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto indices = ref_3dx3d_indices(mat_a);
+ auto gm = std::make_shared<GatherMatmul>(mat_a, mat_b, indices);
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{gm}, ov::ParameterVector{mat_a});
+ }
+}
+
+// 2Dx3D with i32 offsets: no Convert is inserted
+TEST_F(TransformationTestsF, ConvertGroupedMatMulToGatherMatmul_2Dx3D_i32Offsets) {
+ constexpr size_t T = 6, K = 8, G = 2, N = 16;
+
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{T, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto offsets = v0::Constant::create(i32, ov::Shape{G}, {3, 6});
+ auto gmm = std::make_shared<v17::GroupedMatMul>(mat_a, mat_b, offsets);
+ model = std::make_shared<ov::Model>(ov::OutputVector{gmm}, ov::ParameterVector{mat_a});
+
+ manager.register_pass<ov::pass::ConvertGroupedMatMulToGatherMatmul>();
+ }
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{T, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto offsets = v0::Constant::create(i32, ov::Shape{G}, {3, 6});
+
+ auto a_unsq_axis = v0::Constant::create(i32, ov::Shape{1}, {0});
+ auto a_3d = std::make_shared<v0::Unsqueeze>(mat_a, a_unsq_axis);
+ auto indices = ref_2dx3d_indices(mat_a, offsets);
+ auto gm = std::make_shared<GatherMatmul>(a_3d, mat_b, indices);
+ auto squeeze_axis = v0::Constant::create(i32, ov::Shape{1}, {0});
+ auto out = std::make_shared<v0::Squeeze>(gm, squeeze_axis);
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{mat_a});
+ }
+}
+
+// 2Dx3D with i64 offsets: a Convert to i32 is inserted before SearchSorted
+TEST_F(TransformationTestsF, ConvertGroupedMatMulToGatherMatmul_2Dx3D_i64OffsetsInsertsConvert) {
+ constexpr size_t T = 6, K = 8, G = 2, N = 16;
+
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{T, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto offsets = v0::Constant::create(i64, ov::Shape{G}, {3, 6});
+ auto gmm = std::make_shared<v17::GroupedMatMul>(mat_a, mat_b, offsets);
+ model = std::make_shared<ov::Model>(ov::OutputVector{gmm}, ov::ParameterVector{mat_a});
+
+ manager.register_pass<ov::pass::ConvertGroupedMatMulToGatherMatmul>();
+ }
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{T, K});
+ auto mat_b = v0::Constant::create(f32, ov::Shape{G, N, K}, {1.0f});
+ auto offsets = v0::Constant::create(i64, ov::Shape{G}, {3, 6});
+
+ auto a_unsq_axis = v0::Constant::create(i32, ov::Shape{1}, {0});
+ auto a_3d = std::make_shared<v0::Unsqueeze>(mat_a, a_unsq_axis);
+ auto indices = ref_2dx3d_indices(mat_a, offsets); // inserts Convert internally
+ auto gm = std::make_shared<GatherMatmul>(a_3d, mat_b, indices);
+ auto squeeze_axis = v0::Constant::create(i32, ov::Shape{1}, {0});
+ auto out = std::make_shared<v0::Squeeze>(gm, squeeze_axis);
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{out}, ov::ParameterVector{mat_a});
+ }
+}
+
+// Input B is not a Constant -> no conversion
+TEST_F(TransformationTestsF, ConvertGroupedMatMulToGatherMatmul_NonConstantWeightsNoChange) {
+ constexpr size_t G = 2, M = 4, K = 8, N = 16;
+
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{G, M, K});
+ auto mat_b = std::make_shared<v0::Parameter>(f32, ov::Shape{G, N, K});
+ auto gmm = std::make_shared<v17::GroupedMatMul>(mat_a, mat_b);
+ model = std::make_shared<ov::Model>(ov::OutputVector{gmm}, ov::ParameterVector{mat_a, mat_b});
+
+ manager.register_pass<ov::pass::ConvertGroupedMatMulToGatherMatmul>();
+ }
+ {
+ auto mat_a = std::make_shared<v0::Parameter>(f32, ov::Shape{G, M, K});
+ auto mat_b = std::make_shared<v0::Parameter>(f32, ov::Shape{G, N, K});
+ auto gmm = std::make_shared<v17::GroupedMatMul>(mat_a, mat_b);
+ model_ref = std::make_shared<ov::Model>(ov::OutputVector{gmm}, ov::ParameterVector{mat_a, mat_b});
+ }
+}
diff --git a/src/core/dev_api/openvino/op/ops_decl.hpp b/src/core/dev_api/openvino/op/ops_decl.hpp
index f18794b2340..aea086c0c7d 100644
--- a/src/core/dev_api/openvino/op/ops_decl.hpp
+++ b/src/core/dev_api/openvino/op/ops_decl.hpp
@@ -293,4 +293,5 @@ class SparseFillEmptyRows;
namespace ov::op::v17 {
class ErfInv;
+class GroupedMatMul;
} // namespace ov::op::v17
diff --git a/src/core/include/openvino/op/grouped_matmul.hpp b/src/core/include/openvino/op/grouped_matmul.hpp
new file mode 100644
index 00000000000..66e167af552
--- /dev/null
+++ b/src/core/include/openvino/op/grouped_matmul.hpp
@@ -0,0 +1,51 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/op/op.hpp"
+
+namespace ov::op::v17 {
+/// \brief Grouped Matrix Multiplication operation for Mixture of Experts (MoE).
+///
+/// Computes multiple matrix multiplications where each group processes a subset
+/// of the input data. This operation supports two input combinations:
+///
+/// - **Case 1 (2D × 3D)**: MoE forward pass
+/// - mat_a: (total_tokens, K) - rows partitioned by offsets
+/// - mat_b: (G, N, K) - per-group weights (stored transposed)
+/// - output: (total_tokens, N) - each group's output in corresponding rows
+///
+/// - **Case 2 (3D × 3D)**: Batched uniform (no offsets needed)
+/// - mat_a: (G, M, K) - per-group inputs
+/// - mat_b: (G, N, K) - per-group weights (stored transposed)
+/// - output: (G, M, N) - per-group outputs
+///
+/// \ingroup ov_ops_cpp_api
+class OPENVINO_API GroupedMatMul : public ov::op::Op {
+public:
+ OPENVINO_OP("GroupedMatMul", "opset17", ov::op::Op);
+
+ GroupedMatMul() = default;
+
+ /// \brief Constructs a GroupedMatMul operation without offsets (3D × 3D case).
+ ///
+ /// \param mat_a First input tensor (G, M, K)
+ /// \param mat_b Second input tensor (G, N, K)
+ GroupedMatMul(const Output<Node>& mat_a, const Output<Node>& mat_b);
+
+ /// \brief Constructs a GroupedMatMul operation with offsets (2D × 3D).
+ ///
+ /// \param mat_a First input tensor
+ /// \param mat_b Second input tensor
+ /// \param offsets Cumulative offsets tensor of shape (G,) indicating group boundaries.
+ /// For 2D×3D: partitions rows of mat_a.
+ GroupedMatMul(const Output<Node>& mat_a, const Output<Node>& mat_b, const Output<Node>& offsets);
+
+ bool visit_attributes(AttributeVisitor& visitor) override;
+ void validate_and_infer_types() override;
+ std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
+};
+
+} // namespace ov::op::v17
diff --git a/src/core/include/openvino/op/ops.hpp b/src/core/include/openvino/op/ops.hpp
index 8d7e94360f7..da700ed58e8 100644
--- a/src/core/include/openvino/op/ops.hpp
+++ b/src/core/include/openvino/op/ops.hpp
@@ -84,6 +84,7 @@
#include "openvino/op/grn.hpp"
#include "openvino/op/group_conv.hpp"
#include "openvino/op/group_normalization.hpp"
+#include "openvino/op/grouped_matmul.hpp"
#include "openvino/op/gru_cell.hpp"
#include "openvino/op/gru_sequence.hpp"
#include "openvino/op/hard_sigmoid.hpp"
diff --git a/src/core/include/openvino/opsets/opset17_tbl.hpp b/src/core/include/openvino/opsets/opset17_tbl.hpp
index 70470ecf2f7..cd9b674a750 100644
--- a/src/core/include/openvino/opsets/opset17_tbl.hpp
+++ b/src/core/include/openvino/opsets/opset17_tbl.hpp
@@ -15,3 +15,4 @@ _OPENVINO_OP_REG(ShapeOf, ov::op::v3)
// New operations added in opset17
_OPENVINO_OP_REG(ErfInv, ov::op::v17)
+_OPENVINO_OP_REG(GroupedMatMul, ov::op::v17)
diff --git a/src/core/reference/include/openvino/reference/grouped_matmul.hpp b/src/core/reference/include/openvino/reference/grouped_matmul.hpp
new file mode 100644
index 00000000000..811bace702f
--- /dev/null
+++ b/src/core/reference/include/openvino/reference/grouped_matmul.hpp
@@ -0,0 +1,127 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <cmath>
+#include <cstddef>
+#include <numeric>
+#include <vector>
+
+#include "openvino/core/shape.hpp"
+
+namespace ov::reference {
+namespace func {
+
+/// @brief Simple 2D matmul with transposed B: out = A @ B^T
+/// @param A Input matrix A of shape (M, K)
+/// @param B Input matrix B of shape (N, K) -- stored as [N, K], i.e. B transposed
+/// @param out Output matrix of shape (M, N) - must be pre-zeroed
+/// @param M Number of rows in A
+/// @param N Number of rows in B (= columns in the logical B^T)
+/// @param K Shared dimension
+template <typename T>
+void simple_matmul_transposed_b(const T* A, const T* B, T* out, size_t M, size_t N, size_t K) {
+ for (size_t i = 0; i < M; ++i) {
+ for (size_t j = 0; j < N; ++j) {
+ for (size_t k = 0; k < K; ++k) {
+ out[i * N + j] += A[i * K + k] * B[j * K + k];
+ }
+ }
+ }
+}
+
+} // namespace func
+
+/// @brief 3D × 3D batched uniform groups (no offsets).
+template <typename T>
+void grouped_matmul_3d_3d(const T* mat_a, const T* mat_b, T* out, const Shape& mat_a_shape, const Shape& mat_b_shape) {
+ const size_t G = mat_a_shape[0];
+ const size_t M = mat_a_shape[1];
+ const size_t K = mat_a_shape[2];
+ const size_t N = mat_b_shape[1]; // mat_b is [G, N, K]
+
+ const size_t mat_a_group_stride = M * K;
+ const size_t mat_b_group_stride = N * K;
+ const size_t out_group_stride = M * N;
+
+ for (size_t g = 0; g < G; ++g) {
+ const T* a_ptr = mat_a + g * mat_a_group_stride;
+ const T* b_ptr = mat_b + g * mat_b_group_stride;
+ T* out_ptr = out + g * out_group_stride;
+
+ std::fill(out_ptr, out_ptr + out_group_stride, T{0});
+ func::simple_matmul_transposed_b(a_ptr, b_ptr, out_ptr, M, N, K);
+ }
+}
+
+/// @brief 2D × 3D MoE forward pass with offsets.
+template <typename T, typename TIdx>
+void grouped_matmul_2d_3d(const T* mat_a,
+ const T* mat_b,
+ const TIdx* offsets,
+ T* out,
+ const Shape& mat_a_shape,
+ const Shape& mat_b_shape) {
+ const size_t total_rows = mat_a_shape[0];
+ const size_t K = mat_a_shape[1];
+ const size_t G = mat_b_shape[0];
+ const size_t N = mat_b_shape[1]; // mat_b is [G, N, K]
+
+ const size_t mat_b_group_stride = N * K;
+
+ std::fill(out, out + total_rows * N, T{0});
+
+ size_t start = 0;
+ for (size_t g = 0; g < G; ++g) {
+ const size_t end = static_cast<size_t>(offsets[g]);
+ const size_t num_rows = end - start;
+
+ if (num_rows > 0) {
+ const T* a_ptr = mat_a + start * K;
+ const T* b_ptr = mat_b + g * mat_b_group_stride;
+ T* out_ptr = out + start * N;
+ func::simple_matmul_transposed_b(a_ptr, b_ptr, out_ptr, num_rows, N, K);
+ }
+ start = end;
+ }
+}
+
+/// @brief Reference kernel for GroupedMatMul computation.
+///
+/// Supports two input combinations:
+/// - 2D × 3D: MoE forward pass with offsets
+/// - 3D × 3D: Batched uniform groups, no offsets
+///
+/// @tparam T Data type of input and output tensors.
+/// @tparam TIdx Data type for offset indices.
+///
+/// @param mat_a Pointer to first input tensor.
+/// @param mat_b Pointer to second input tensor.
+/// @param offsets Pointer to offsets tensor (nullptr for 3D×3D case).
+/// @param out Pointer to output tensor (pre-allocated).
+/// @param mat_a_shape Shape of mat_a.
+/// @param mat_b_shape Shape of mat_b.
+/// @param out_shape Shape of output.
+/// @param num_groups Number of groups (inferred from offsets or mat_b).
+template <typename T, typename TIdx = int32_t>
+void grouped_matmul(const T* mat_a,
+ const T* mat_b,
+ const TIdx* offsets,
+ T* out,
+ const Shape& mat_a_shape,
+ const Shape& mat_b_shape,
+ const Shape& out_shape,
+ size_t num_groups) {
+ const auto a_ndim = mat_a_shape.size();
+ const auto b_ndim = mat_b_shape.size();
+
+ if (a_ndim == 3 && b_ndim == 3) {
+ grouped_matmul_3d_3d(mat_a, mat_b, out, mat_a_shape, mat_b_shape);
+ } else if (a_ndim == 2 && b_ndim == 3) {
+ grouped_matmul_2d_3d(mat_a, mat_b, offsets, out, mat_a_shape, mat_b_shape);
+ }
+}
+
+} // namespace ov::reference
diff --git a/src/core/shape_inference/include/grouped_matmul_shape_inference.hpp b/src/core/shape_inference/include/grouped_matmul_shape_inference.hpp
new file mode 100644
index 00000000000..cf6bd9ea3d6
--- /dev/null
+++ b/src/core/shape_inference/include/grouped_matmul_shape_inference.hpp
@@ -0,0 +1,97 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "openvino/op/grouped_matmul.hpp"
+#include "utils.hpp"
+
+namespace ov::op::v17 {
+
+template <class TShape, class TRShape = result_shape_t<TShape>>
+std::vector<TRShape> shape_infer(const GroupedMatMul* op,
+ const std::vector<TShape>& input_shapes,
+ const ITensorAccessor& tensor_accessor = make_tensor_accessor()) {
+ const auto num_inputs = input_shapes.size();
+ NODE_VALIDATION_CHECK(op, num_inputs == 2 || num_inputs == 3);
+
+ const auto& mat_a_shape = input_shapes[0];
+ const auto& mat_b_shape = input_shapes[1];
+
+ // Handle fully dynamic case
+ if (mat_a_shape.rank().is_dynamic() || mat_b_shape.rank().is_dynamic()) {
+ return {PartialShape::dynamic()};
+ }
+
+ const auto mat_a_rank = mat_a_shape.size();
+ const auto mat_b_rank = mat_b_shape.size();
+
+ using DimType = typename TShape::value_type;
+
+ // Case: 3D × 3D (batched, uniform group sizes) - no offsets needed
+ if (mat_a_rank == 3 && mat_b_rank == 3) {
+ const auto g_a = mat_a_shape[0];
+ const auto m = mat_a_shape[1];
+ const auto k_a = mat_a_shape[2];
+ const auto g_b = mat_b_shape[0];
+ const auto n = mat_b_shape[1];
+ const auto k_b = mat_b_shape[2];
+
+ auto merged_g = DimType();
+ auto merged_k = DimType();
+ NODE_VALIDATION_CHECK(op,
+ DimType::merge(merged_g, g_a, g_b),
+ "GroupedMatMul 3D×3D: batch dimension mismatch mat_a: ",
+ g_a,
+ ", mat_b: ",
+ g_b);
+ NODE_VALIDATION_CHECK(op,
+ DimType::merge(merged_k, k_a, k_b),
+ "GroupedMatMul 3D×3D: inner dimension mismatch mat_a: ",
+ k_a,
+ ", mat_b: ",
+ k_b);
+
+ return {TRShape{merged_g, m, n}};
+ }
+
+ // Case: 2D × 3D (MoE forward pass) - requires offsets
+ if (mat_a_rank == 2 && mat_b_rank == 3) {
+ NODE_VALIDATION_CHECK(op, num_inputs == 3, "GroupedMatMul 2D×3D case requires offsets input.");
+
+ const auto& offsets_shape = input_shapes[2];
+ NODE_VALIDATION_CHECK(op,
+ offsets_shape.rank().is_dynamic() || offsets_shape.size() == 1,
+ "GroupedMatMul offsets must be 1D tensor.");
+
+ const auto total_rows = mat_a_shape[0];
+ const auto k_a = mat_a_shape[1];
+ const auto g = mat_b_shape[0];
+ const auto n = mat_b_shape[1];
+ const auto k_b = mat_b_shape[2];
+
+ auto merged_k = DimType();
+ NODE_VALIDATION_CHECK(op,
+ DimType::merge(merged_k, k_a, k_b),
+ "GroupedMatMul 2D×3D: inner dimension mismatch mat_a: ",
+ k_a,
+ ", mat_b: ",
+ k_b);
+
+ // Output has same number of rows as mat_a
+ return {TRShape{total_rows, n}};
+ }
+
+ NODE_VALIDATION_CHECK(op,
+ false,
+ "GroupedMatMul unsupported combination: mat_a ",
+ mat_a_rank,
+ "D × mat_b ",
+ mat_b_rank,
+ "D. Supported: 2D×3D, 3D×3D.");
+
+ return {PartialShape::dynamic()};
+}
+
+} // namespace ov::op::v17
diff --git a/src/core/src/op/grouped_matmul.cpp b/src/core/src/op/grouped_matmul.cpp
new file mode 100644
index 00000000000..3c61424bb99
--- /dev/null
+++ b/src/core/src/op/grouped_matmul.cpp
@@ -0,0 +1,64 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/grouped_matmul.hpp"
+
+#include "grouped_matmul_shape_inference.hpp"
+#include "itt.hpp"
+
+namespace ov::op::v17 {
+
+GroupedMatMul::GroupedMatMul(const Output<Node>& mat_a, const Output<Node>& mat_b) : Op(OutputVector{mat_a, mat_b}) {
+ constructor_validate_and_infer_types();
+}
+
+GroupedMatMul::GroupedMatMul(const Output<Node>& mat_a, const Output<Node>& mat_b, const Output<Node>& offsets)
+ : Op(OutputVector{mat_a, mat_b, offsets}) {
+ constructor_validate_and_infer_types();
+}
+
+bool GroupedMatMul::visit_attributes(AttributeVisitor& visitor) {
+ OV_OP_SCOPE(v17_GroupedMatMul_visit_attributes);
+ return true;
+}
+
+void GroupedMatMul::validate_and_infer_types() {
+ OV_OP_SCOPE(v17_GroupedMatMul_validate_and_infer_types);
+
+ const auto& mat_a_et = get_input_element_type(0);
+ const auto& mat_b_et = get_input_element_type(1);
+
+ element::Type result_et;
+ NODE_VALIDATION_CHECK(this,
+ element::Type::merge(result_et, mat_a_et, mat_b_et),
+ "Arguments do not have the same element type (mat_a element type: ",
+ mat_a_et,
+ ", mat_b element type: ",
+ mat_b_et,
+ ").");
+
+ if (get_input_size() == 3) {
+ const auto& offsets_et = get_input_element_type(2);
+ NODE_VALIDATION_CHECK(this,
+ offsets_et.is_dynamic() || offsets_et == element::i32 || offsets_et == element::i64,
+ "Offsets element type must be i32 or i64. Got: ",
+ offsets_et);
+ }
+
+ const auto output_shapes = shape_infer(this, ov::util::get_node_input_partial_shapes(*this));
+ set_output_type(0, result_et, output_shapes[0]);
+}
+
+std::shared_ptr<Node> GroupedMatMul::clone_with_new_inputs(const OutputVector& new_args) const {
+ OV_OP_SCOPE(v17_GroupedMatMul_clone_with_new_inputs);
+ check_new_args_count(this, new_args);
+
+ if (new_args.size() == 2) {
+ return std::make_shared<GroupedMatMul>(new_args.at(0), new_args.at(1));
+ } else {
+ return std::make_shared<GroupedMatMul>(new_args.at(0), new_args.at(1), new_args.at(2));
+ }
+}
+
+} // namespace ov::op::v17
diff --git a/src/core/tests/opset.cpp b/src/core/tests/opset.cpp
index 105cfac0505..d1c0ab80f14 100644
--- a/src/core/tests/opset.cpp
+++ b/src/core/tests/opset.cpp
@@ -79,7 +79,7 @@ INSTANTIATE_TEST_SUITE_P(opset,
OpsetTestParams{ov::get_opset14, 188},
OpsetTestParams{ov::get_opset15, 199},
OpsetTestParams{ov::get_opset16, 203},
- OpsetTestParams{ov::get_opset17, 4}),
+ OpsetTestParams{ov::get_opset17, 5}),
OpsetTestNameGenerator{});
class MyOpOld : public ov::op::Op {
diff --git a/src/core/tests/type_prop/grouped_matmul.cpp b/src/core/tests/type_prop/grouped_matmul.cpp
new file mode 100644
index 00000000000..4443e2195a6
--- /dev/null
+++ b/src/core/tests/type_prop/grouped_matmul.cpp
@@ -0,0 +1,218 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/grouped_matmul.hpp"
+
+#include <gtest/gtest.h>
+
+#include "common_test_utils/test_assertions.hpp"
+#include "common_test_utils/type_prop.hpp"
+#include "openvino/op/constant.hpp"
+
+namespace ov::test {
+using op::v0::Constant, op::v0::Parameter;
+using testing::HasSubstr;
+
+class TypePropGroupedMatMulTest : public TypePropOpTest<op::v17::GroupedMatMul> {};
+
+// ==================== Default constructor ====================
+
+TEST_F(TypePropGroupedMatMulTest, default_ctor_2inputs) {
+ const auto op = make_op();
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+
+ op->set_arguments(OutputVector{mat_a, mat_b});
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_input_size(), 2);
+ EXPECT_EQ(op->get_output_size(), 1);
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 4, 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, default_ctor_3inputs) {
+ const auto op = make_op();
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::i32, PartialShape{3});
+
+ op->set_arguments(OutputVector{mat_a, mat_b, offsets});
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_input_size(), 3);
+ EXPECT_EQ(op->get_output_size(), 1);
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{16, 128}));
+}
+
+// ==================== Case 1: 2D × 3D (MoE forward) ====================
+
+TEST_F(TypePropGroupedMatMulTest, case1_2d_3d_basic) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::i32, PartialShape{3});
+
+ const auto op = make_op(mat_a, mat_b, offsets);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{16, 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case1_2d_3d_dynamic_rows) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{Dimension::dynamic(), 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::i32, PartialShape{3});
+
+ const auto op = make_op(mat_a, mat_b, offsets);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{Dimension::dynamic(), 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case1_2d_3d_f16) {
+ const auto mat_a = std::make_shared<Parameter>(element::f16, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f16, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::i64, PartialShape{3});
+
+ const auto op = make_op(mat_a, mat_b, offsets);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f16);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{16, 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case1_2d_3d_inner_dim_mismatch) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 32}); // K=32 != 64
+ const auto offsets = std::make_shared<Parameter>(element::i32, PartialShape{3});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b, offsets),
+ ov::NodeValidationFailure,
+ HasSubstr("inner dimension mismatch"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case1_2d_3d_missing_offsets) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b), ov::NodeValidationFailure, HasSubstr("requires offsets"));
+}
+
+// ==================== Case 2: 3D × 3D (batched) ====================
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_basic) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+
+ const auto op = make_op(mat_a, mat_b);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, 4, 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_bf16) {
+ const auto mat_a = std::make_shared<Parameter>(element::bf16, PartialShape{8, 4, 512});
+ const auto mat_b = std::make_shared<Parameter>(element::bf16, PartialShape{8, 2048, 512});
+
+ const auto op = make_op(mat_a, mat_b);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::bf16);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{8, 4, 2048}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_dynamic_batch) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{Dimension::dynamic(), 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{Dimension::dynamic(), 128, 64});
+
+ const auto op = make_op(mat_a, mat_b);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{Dimension::dynamic(), 4, 128}));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_batch_mismatch) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{5, 128, 64});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b),
+ ov::NodeValidationFailure,
+ HasSubstr("batch dimension mismatch"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_inner_dim_mismatch) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 32});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b),
+ ov::NodeValidationFailure,
+ HasSubstr("inner dimension mismatch"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, unsupported_ndim_combination) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{64, 128});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b),
+ ov::NodeValidationFailure,
+ HasSubstr("unsupported combination"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, dtype_mismatch) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f16, PartialShape{3, 128, 64});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b),
+ ov::NodeValidationFailure,
+ HasSubstr("do not have the same element type"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, invalid_offsets_dtype) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::f32, PartialShape{3});
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b, offsets),
+ ov::NodeValidationFailure,
+ HasSubstr("Offsets element type must be i32 or i64"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, offsets_not_1d) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(element::i32, PartialShape{3, 2}); // 2D, not 1D
+
+ OV_EXPECT_THROW(std::ignore = make_op(mat_a, mat_b, offsets),
+ ov::NodeValidationFailure,
+ HasSubstr("offsets must be 1D"));
+}
+
+TEST_F(TypePropGroupedMatMulTest, fully_dynamic_shapes) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape::dynamic());
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape::dynamic());
+
+ const auto op = make_op(mat_a, mat_b);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), PartialShape::dynamic());
+}
+
+TEST_F(TypePropGroupedMatMulTest, case2_3d_3d_partial_dynamic) {
+ const auto mat_a = std::make_shared<Parameter>(element::f32, PartialShape{3, Dimension::dynamic(), 64});
+ const auto mat_b = std::make_shared<Parameter>(element::f32, PartialShape{3, 128, Dimension::dynamic()});
+
+ const auto op = make_op(mat_a, mat_b);
+ op->validate_and_infer_types();
+
+ EXPECT_EQ(op->get_output_element_type(0), element::f32);
+ EXPECT_EQ(op->get_output_partial_shape(0), (PartialShape{3, Dimension::dynamic(), 128}));
+}
+
+} // namespace ov::test
diff --git a/src/core/tests/visitors/op/grouped_matmul.cpp b/src/core/tests/visitors/op/grouped_matmul.cpp
new file mode 100644
index 00000000000..3dbc63f1733
--- /dev/null
+++ b/src/core/tests/visitors/op/grouped_matmul.cpp
@@ -0,0 +1,41 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/grouped_matmul.hpp"
+
+#include <gtest/gtest.h>
+
+#include "visitors/visitors.hpp"
+
+namespace ov::test {
+using ov::op::v0::Parameter, ov::test::NodeBuilder;
+
+TEST(attributes, grouped_matmul_v17_3d_3d) {
+ NodeBuilder::opset().insert<ov::op::v17::GroupedMatMul>();
+ const auto mat_a = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{3, 128, 64});
+
+ const auto op = std::make_shared<ov::op::v17::GroupedMatMul>(mat_a, mat_b);
+ NodeBuilder builder(op, {mat_a, mat_b});
+ auto g_op = ov::as_type_ptr<ov::op::v17::GroupedMatMul>(builder.create());
+
+ EXPECT_EQ(g_op->get_output_partial_shape(0), op->get_output_partial_shape(0));
+ EXPECT_EQ(g_op->get_output_element_type(0), op->get_output_element_type(0));
+}
+
+TEST(attributes, grouped_matmul_v17_2d_3d_with_offsets) {
+ NodeBuilder::opset().insert<ov::op::v17::GroupedMatMul>();
+ const auto mat_a = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{16, 64});
+ const auto mat_b = std::make_shared<Parameter>(ov::element::f32, ov::PartialShape{3, 128, 64});
+ const auto offsets = std::make_shared<Parameter>(ov::element::i32, ov::PartialShape{3});
+
+ const auto op = std::make_shared<ov::op::v17::GroupedMatMul>(mat_a, mat_b, offsets);
+ NodeBuilder builder(op, {mat_a, mat_b, offsets});
+ auto g_op = ov::as_type_ptr<ov::op::v17::GroupedMatMul>(builder.create());
+
+ EXPECT_EQ(g_op->get_output_partial_shape(0), op->get_output_partial_shape(0));
+ EXPECT_EQ(g_op->get_output_element_type(0), op->get_output_element_type(0));
+}
+
+} // namespace ov::test
diff --git a/src/frontends/pytorch/src/op/grouped_mm.cpp b/src/frontends/pytorch/src/op/grouped_mm.cpp
new file mode 100644
index 00000000000..00bc7f75a87
--- /dev/null
+++ b/src/frontends/pytorch/src/op/grouped_mm.cpp
@@ -0,0 +1,83 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/frontend/pytorch/node_context.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/convert.hpp"
+#include "openvino/op/grouped_matmul.hpp"
+#include "openvino/op/transpose.hpp"
+#include "utils.hpp"
+
+namespace ov {
+namespace frontend {
+namespace pytorch {
+namespace op {
+
+using namespace ov::op;
+
+// torch._grouped_mm(Tensor self, Tensor mat2,
+// Tensor? offs=None, Tensor? bias=None, ScalarType? out_dtype=None) -> Tensor
+//
+// Maps directly to ov::op::v17::GroupedMatMul, which natively supports the
+// 3D x 3D batched case as well as the 2D x 3D and 2D x 2D MoE cases (the latter
+// two via `offs`).
+OutputVector translate_grouped_mm(const NodeContext& context) {
+ num_inputs_check(context, 2, 5);
+ auto a = context.get_input(0);
+ auto b = context.get_input(1);
+
+ const bool has_offs = context.get_input_size() > 2 && !context.input_is_none(2);
+ const bool has_bias = context.get_input_size() > 3 && !context.input_is_none(3);
+ const bool has_out_dtype = context.get_input_size() > 4 && !context.input_is_none(4);
+
+ PYTORCH_OP_CONVERSION_CHECK(!has_bias, "_grouped_mm: 'bias' argument is not supported.");
+
+ align_eltwise_input_types(context, a, b, false, false);
+
+ // PyTorch provides mat_b as [G, K, N] (3D) or [total_tokens, N] (2D).
+ // GroupedMatMul-17 expects [G, N, K] (3D) — N-first layout.
+ // If b is already a Transpose with the expected permutation, fold it by taking
+ // the input of that existing Transpose instead of stacking another one.
+ const auto b_rank = b.get_partial_shape().rank();
+ PYTORCH_OP_CONVERSION_CHECK(!b_rank.is_static() || b_rank.get_length() != 2,
+ "grouped_mm: 2D × 2D (weight gradient) case is not supported.");
+ if (b_rank.is_static() && b_rank.get_length() == 3) {
+ const std::vector<int32_t> expected_perm{0, 2, 1};
+ auto existing_transpose = ov::as_type_ptr<v1::Transpose>(b.get_node_shared_ptr());
+ auto existing_perm =
+ existing_transpose ? ov::as_type_ptr<v0::Constant>(existing_transpose->input_value(1).get_node_shared_ptr())
+ : nullptr;
+ if (existing_perm && existing_perm->cast_vector<int32_t>() == expected_perm) {
+ b = existing_transpose->input_value(0);
+ } else {
+ auto perm = context.mark_node(v0::Constant::create(element::i32, Shape{3}, expected_perm));
+ b = context.mark_node(std::make_shared<v1::Transpose>(b, perm));
+ }
+ }
+
+ Output<Node> result;
+ if (has_offs) {
+ auto offs = context.get_input(2);
+ // GroupedMatMul expects an integer offsets tensor; PyTorch typically
+ // provides int32, but normalize anything else to i32 to be safe.
+ if (offs.get_element_type().is_static() && offs.get_element_type() != element::i32 &&
+ offs.get_element_type() != element::i64) {
+ offs = context.mark_node(std::make_shared<v0::Convert>(offs, element::i32));
+ }
+ result = context.mark_node(std::make_shared<v17::GroupedMatMul>(a, b, offs));
+ } else {
+ result = context.mark_node(std::make_shared<v17::GroupedMatMul>(a, b));
+ }
+
+ if (has_out_dtype) {
+ result = apply_dtype(context, 4, result);
+ }
+
+ return {result};
+}
+
+} // namespace op
+} // namespace pytorch
+} // namespace frontend
+} // namespace ov
diff --git a/src/frontends/pytorch/src/op_table.cpp b/src/frontends/pytorch/src/op_table.cpp
index d98261aa2c2..58d04314a26 100644
--- a/src/frontends/pytorch/src/op_table.cpp
+++ b/src/frontends/pytorch/src/op_table.cpp
@@ -126,6 +126,7 @@ OP_CONVERTER(translate_get_attr);
OP_CONVERTER(translate_getitem);
OP_CONVERTER(translate_glu);
OP_CONVERTER(translate_grid_sampler);
+OP_CONVERTER(translate_grouped_mm);
OP_CONVERTER(translate_group_norm);
OP_CONVERTER(translate_gru);
OP_CONVERTER(translate_hann_window);
@@ -557,6 +558,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_ts() {
{"aten::gelu", op::translate_gelu},
{"aten::glu", op::translate_glu},
{"aten::grid_sampler", op::translate_grid_sampler},
+ {"aten::_grouped_mm", op::translate_grouped_mm},
{"aten::group_norm", op::translate_group_norm},
{"aten::gru", op::translate_gru},
{"aten::greater", op::translate_1to1_match_2_inputs_align_types<opset10::Greater>},
@@ -859,6 +861,7 @@ const std::unordered_map<std::string, CreatorFunction> get_supported_ops_fx() {
{"aten._embedding_bag_forward_only.default", op::translate_embedding_bag_fx},
{"aten._fake_quantize_per_tensor_affine_cachemask_tensor_qparams.default",
op::translate_fake_quantize_per_tensor_affine_fx},
+ {"aten._grouped_mm.default", op::translate_grouped_mm},
{"aten._local_scalar_dense.default", op::skip_node},
{"aten._log_softmax.default", op::translate_log_softmax_fx},
{"aten.__lshift__.Tensor", op::translate_bitwise_left_shift},
diff --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.hpp
index 41ddec85f22..e224c070296 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
@@ -36,6 +36,7 @@
#include "transformations/op_conversions/convert_fc_to_compressed.hpp"
#include "transformations/op_conversions/convert_fc_to_quantized_legacy.hpp"
#include "transformations/op_conversions/convert_gather_matmul_to_compressed.hpp"
+#include "transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp"
namespace ov::intel_cpu {
@@ -45,6 +46,10 @@ inline void ConvertToCPUSpecificOpset(std::shared_ptr<ov::Model>& model, const C
ov::pass::Manager manager("CPU:ConvertToCPUSpecificOpset");
manager.set_per_pass_validation(false);
+ // Convert public GroupedMatMul-17 into the internal GatherMatmul
+ // Must run before the compression pass.
+ CPU_REGISTER_PASS_COMMON(manager, ov::pass::ConvertGroupedMatMulToGatherMatmul);
+
// TransformMoeBlockToGatherMatmuls
CPU_REGISTER_PASS_X64(manager, ov::pass::ConvertTiledMoeBlockToGatherMatmuls);
CPU_REGISTER_PASS_X64(manager, ov::pass::Validate);
diff --git a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
index d7585f3af31..d326a3ad5c9 100644
--- a/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
+++ b/src/plugins/intel_gpu/include/intel_gpu/plugin/primitives_list.hpp
@@ -323,5 +323,6 @@ REGISTER_FACTORY(internal, MOECompressed);
REGISTER_FACTORY(internal, MoERouterFused);
REGISTER_FACTORY(internal, GatedDeltaNet);
REGISTER_FACTORY(internal, PagedCausalConv1D);
+REGISTER_FACTORY(internal, GatherMatmul);
REGISTER_FACTORY(internal, GatherMatmulCompressed);
REGISTER_FACTORY(internal, Atan2);
diff --git a/src/plugins/intel_gpu/src/plugin/ops/gather_matmul.cpp b/src/plugins/intel_gpu/src/plugin/ops/gather_matmul.cpp
index 4ce01eab114..7189c54f779 100644
--- a/src/plugins/intel_gpu/src/plugin/ops/gather_matmul.cpp
+++ b/src/plugins/intel_gpu/src/plugin/ops/gather_matmul.cpp
@@ -6,11 +6,34 @@
#include "intel_gpu/plugin/common_utils.hpp"
#include "intel_gpu/plugin/program_builder.hpp"
+#include "ov_ops/gather_matmul.hpp"
#include "ov_ops/gather_matmul_compressed.hpp"
namespace ov::intel_gpu {
using namespace cldnn;
+static void CreateGatherMatmulOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::GatherMatmul>& op) {
+ auto inputs = p.GetInputInfo(op);
+ // Inputs: A, B (transposed), indices, [bias]
+ validate_inputs_count(op, {3, 4});
+
+ const auto& a_shape = op->get_input_partial_shape(0);
+ OPENVINO_ASSERT(a_shape.rank().is_static() && a_shape.size() >= 1,
+ "GatherMatmul requires static input A rank, got shape ", a_shape);
+ // n_activated_experts is overridden at runtime from the actual input shape
+ // (see GatherMatmulOCLImpl::update_rt_params); pass 0 when dim[0] is dynamic.
+ const int32_t n_activated_experts =
+ a_shape[0].is_static() ? static_cast<int32_t>(a_shape[0].get_length()) : 0;
+
+ // Placeholder inputs have shape_size <= 1.
+ const bool has_bias = op->get_input_size() == 4 && ov::shape_size(op->get_input_shape(3)) > 1;
+
+ const std::string layerName = layer_type_name_ID(op);
+ const cldnn::gather_matmul bgm(layerName, inputs, has_bias, /*has_zp=*/false, n_activated_experts);
+
+ p.add_primitive(*op, bgm);
+}
+
static void CreateGatherMatmulCompressedOp(ProgramBuilder& p, const std::shared_ptr<ov::op::internal::GatherMatmulCompressed>& op) {
auto inputs = p.GetInputInfo(op);
// Inputs: A, B, indices, bias, scales, zp (placeholder when absent).
@@ -32,6 +55,7 @@ static void CreateGatherMatmulCompressedOp(ProgramBuilder& p, const std::shared_
p.add_primitive(*op, bgm);
}
+REGISTER_FACTORY_IMPL(internal, GatherMatmul);
REGISTER_FACTORY_IMPL(internal, GatherMatmulCompressed);
} // namespace ov::intel_gpu
diff --git a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
index 9b7f30d9a87..0e9b286a762 100644
--- a/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
+++ b/src/plugins/intel_gpu/src/plugin/transformations_pipeline.cpp
@@ -132,6 +132,7 @@
#include "transformations/common_optimizations/move_eltwise_up_data_movement.hpp"
#include "transformations/common_optimizations/mvn_fusion.hpp"
#include "transformations/common_optimizations/convert_tiled_moe_block_to_gather_matmuls.hpp"
+#include "transformations/op_conversions/convert_grouped_matmul_to_gather_matmul.hpp"
#include "transformations/common_optimizations/nop_elimination.hpp"
#include "transformations/common_optimizations/rms_fusion.hpp"
#include "transformations/common_optimizations/sdpa_scale_fusion.hpp"
@@ -597,6 +598,7 @@ void TransformationsPipeline::apply(std::shared_ptr<ov::Model> func) {
// Gated on supports_immad (systolic-only) and oneDNN (required for expert GEMM dispatch).
// Note: even though we are already inside `if (supports_immad)`, oneDNN can still be explicitly disabled by the user.
if (device_info.supports_immad && config.get_use_onednn()) {
+ manager.register_pass<ov::pass::ConvertGroupedMatMulToGatherMatmul>();
const std::vector<ov::element::Type> supported_compressed_weights_types{ov::element::u4,
ov::element::i4,
ov::element::i8,
diff --git a/src/plugins/template/backend/ops/grouped_matmul.cpp b/src/plugins/template/backend/ops/grouped_matmul.cpp
new file mode 100644
index 00000000000..9cd5c0e5a09
--- /dev/null
+++ b/src/plugins/template/backend/ops/grouped_matmul.cpp
@@ -0,0 +1,106 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/reference/grouped_matmul.hpp"
+
+#include "element_visitor.hpp"
+#include "evaluate_node.hpp"
+#include "grouped_matmul_shape_inference.hpp"
+#include "openvino/core/validation_util.hpp"
+#include "openvino/op/grouped_matmul.hpp"
+
+namespace {
+
+struct Evaluate : ov::element::NoAction<bool> {
+ using ov::element::NoAction<bool>::visit;
+
+ template <ov::element::Type_t ET, class T = ov::fundamental_type_for<ET>>
+ static result_type visit(const ov::Tensor& mat_a,
+ const ov::Tensor& mat_b,
+ const ov::Tensor* offsets_tensor,
+ ov::Tensor& out,
+ const ov::Shape& mat_a_shape,
+ const ov::Shape& mat_b_shape,
+ const ov::Shape& out_shape,
+ size_t num_groups) {
+ if (offsets_tensor) {
+ const auto offsets_et = offsets_tensor->get_element_type();
+ if (offsets_et == ov::element::i32) {
+ ov::reference::grouped_matmul(mat_a.data<const T>(),
+ mat_b.data<const T>(),
+ offsets_tensor->data<const int32_t>(),
+ out.data<T>(),
+ mat_a_shape,
+ mat_b_shape,
+ out_shape,
+ num_groups);
+ } else {
+ ov::reference::grouped_matmul(mat_a.data<const T>(),
+ mat_b.data<const T>(),
+ offsets_tensor->data<const int64_t>(),
+ out.data<T>(),
+ mat_a_shape,
+ mat_b_shape,
+ out_shape,
+ num_groups);
+ }
+ } else {
+ ov::reference::grouped_matmul<T, int32_t>(mat_a.data<const T>(),
+ mat_b.data<const T>(),
+ nullptr,
+ out.data<T>(),
+ mat_a_shape,
+ mat_b_shape,
+ out_shape,
+ num_groups);
+ }
+ return true;
+ }
+};
+
+} // namespace
+
+template <>
+bool evaluate_node<ov::op::v17::GroupedMatMul>(std::shared_ptr<ov::Node> node,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs) {
+ OPENVINO_ASSERT(outputs.size() == 1);
+
+ const auto op = ov::as_type_ptr<ov::op::v17::GroupedMatMul>(node);
+ const auto out_shapes = ov::op::v17::shape_infer(op.get(), ov::util::get_tensors_partial_shapes(inputs));
+ const auto out_shape = out_shapes[0].to_shape();
+ outputs[0].set_shape(out_shape);
+
+ const auto& mat_a_shape = inputs[0].get_shape();
+ const auto& mat_b_shape = inputs[1].get_shape();
+
+ size_t num_groups = 0;
+ const ov::Tensor* offsets_tensor = nullptr;
+
+ if (inputs.size() == 3) {
+ offsets_tensor = &inputs[2];
+ num_groups = inputs[2].get_shape()[0];
+ } else if (mat_a_shape.size() == 3) {
+ num_groups = mat_a_shape[0];
+ } else if (mat_b_shape.size() == 3) {
+ num_groups = mat_b_shape[0];
+ }
+
+ using namespace ov::element;
+ return IF_TYPE_OF_CONVERT_TENSORS(v17_GroupedMatMul_evaluate,
+ node.get(),
+ outputs,
+ inputs,
+ OV_PP_ET_LIST(f32, f16, bf16, i32, i64),
+ Evaluate,
+ inputs[0].get_element_type(),
+ inputs[0],
+ inputs[1],
+ offsets_tensor,
+ outputs[0],
+ mat_a_shape,
+ mat_b_shape,
+ out_shape,
+ num_groups);
+}
diff --git a/src/plugins/template/backend/ops/ops_evaluates.hpp b/src/plugins/template/backend/ops/ops_evaluates.hpp
index d0a7de9be75..713b19ba6f5 100644
--- a/src/plugins/template/backend/ops/ops_evaluates.hpp
+++ b/src/plugins/template/backend/ops/ops_evaluates.hpp
@@ -574,6 +574,10 @@ extern template bool evaluate_node<ov::op::v17::ErfInv>(std::shared_ptr<ov::Node
ov::TensorVector& outputs,
const ov::TensorVector& inputs);
+extern template bool evaluate_node<ov::op::v17::GroupedMatMul>(std::shared_ptr<ov::Node> node,
+ ov::TensorVector& outputs,
+ const ov::TensorVector& inputs);
+
extern template bool evaluate_node<ov::op::v16::Identity>(std::shared_ptr<ov::Node> node,
ov::TensorVector& outputs,
const ov::TensorVector& inputs);
diff --git a/src/plugins/template/backend/opset_int_tbl.hpp b/src/plugins/template/backend/opset_int_tbl.hpp
index ebc765a67bd..0139c1d1706 100644
--- a/src/plugins/template/backend/opset_int_tbl.hpp
+++ b/src/plugins/template/backend/opset_int_tbl.hpp
@@ -180,6 +180,7 @@ _OPENVINO_OP_REG(SearchSorted, ov::op::v15)
_OPENVINO_OP_REG(AvgPool, ov::op::v16)
_OPENVINO_OP_REG(ErfInv, ov::op::v17)
+_OPENVINO_OP_REG(GroupedMatMul, ov::op::v17)
_OPENVINO_OP_REG(Identity, ov::op::v16)
_OPENVINO_OP_REG(ISTFT, ov::op::v16)
_OPENVINO_OP_REG(SegmentMax, ov::op::v16)
diff --git a/src/plugins/template/tests/functional/op_reference/grouped_matmul.cpp b/src/plugins/template/tests/functional/op_reference/grouped_matmul.cpp
new file mode 100644
index 00000000000..bd90b2b5fc4
--- /dev/null
+++ b/src/plugins/template/tests/functional/op_reference/grouped_matmul.cpp
@@ -0,0 +1,203 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "openvino/op/grouped_matmul.hpp"
+
+#include <gtest/gtest.h>
+
+#include "base_reference_test.hpp"
+#include "openvino/op/constant.hpp"
+#include "openvino/op/parameter.hpp"
+
+using namespace reference_tests;
+using namespace ov;
+
+namespace {
+
+struct GroupedMatMulParams {
+ // Case: 2D × 3D with offsets
+ template <class T, class TIdx>
+ GroupedMatMulParams(const Shape& mat_a_shape,
+ const Shape& mat_b_shape,
+ const Shape& offsets_shape,
+ const Shape& expected_shape,
+ const element::Type_t& data_type,
+ const element::Type_t& offsets_type,
+ const std::vector<T>& mat_a_values,
+ const std::vector<T>& mat_b_values,
+ const std::vector<TIdx>& offsets_values,
+ const std::vector<T>& expected_values,
+ const std::string& test_name)
+ : m_mat_a_shape(mat_a_shape),
+ m_mat_b_shape(mat_b_shape),
+ m_offsets_shape(offsets_shape),
+ m_expected_shape(expected_shape),
+ m_data_type(data_type),
+ m_offsets_type(offsets_type),
+ m_has_offsets(true),
+ m_test_name(test_name) {
+ m_mat_a_tensor = CreateTensor(mat_a_shape, data_type, mat_a_values);
+ m_mat_b_tensor = CreateTensor(mat_b_shape, data_type, mat_b_values);
+ m_offsets_tensor = CreateTensor(offsets_shape, offsets_type, offsets_values);
+ m_expected_tensor = CreateTensor(expected_shape, data_type, expected_values);
+ }
+
+ // Case: 3D × 3D without offsets
+ template <class T>
+ GroupedMatMulParams(const Shape& mat_a_shape,
+ const Shape& mat_b_shape,
+ const Shape& expected_shape,
+ const element::Type_t& data_type,
+ const std::vector<T>& mat_a_values,
+ const std::vector<T>& mat_b_values,
+ const std::vector<T>& expected_values,
+ const std::string& test_name)
+ : m_mat_a_shape(mat_a_shape),
+ m_mat_b_shape(mat_b_shape),
+ m_expected_shape(expected_shape),
+ m_data_type(data_type),
+ m_has_offsets(false),
+ m_test_name(test_name) {
+ m_mat_a_tensor = CreateTensor(mat_a_shape, data_type, mat_a_values);
+ m_mat_b_tensor = CreateTensor(mat_b_shape, data_type, mat_b_values);
+ m_expected_tensor = CreateTensor(expected_shape, data_type, expected_values);
+ }
+
+ Shape m_mat_a_shape;
+ Shape m_mat_b_shape;
+ Shape m_offsets_shape;
+ Shape m_expected_shape;
+ element::Type_t m_data_type;
+ element::Type_t m_offsets_type;
+ bool m_has_offsets;
+ ov::Tensor m_mat_a_tensor;
+ ov::Tensor m_mat_b_tensor;
+ ov::Tensor m_offsets_tensor;
+ ov::Tensor m_expected_tensor;
+ std::string m_test_name;
+};
+
+class ReferenceGroupedMatMulTest : public testing::TestWithParam<GroupedMatMulParams>, public CommonReferenceTest {
+public:
+ void SetUp() override {
+ const auto& params = GetParam();
+ if (params.m_has_offsets) {
+ function = CreateFunction2D3D(params);
+ inputData = {params.m_mat_a_tensor, params.m_mat_b_tensor, params.m_offsets_tensor};
+ } else {
+ function = CreateFunction3D3D(params);
+ inputData = {params.m_mat_a_tensor, params.m_mat_b_tensor};
+ }
+ refOutData = {params.m_expected_tensor};
+ }
+
+ static std::string getTestCaseName(const testing::TestParamInfo<GroupedMatMulParams>& obj) {
+ return obj.param.m_test_name;
+ }
+
+private:
+ static std::shared_ptr<Model> CreateFunction2D3D(const GroupedMatMulParams& p) {
+ auto mat_a = std::make_shared<op::v0::Parameter>(p.m_data_type, p.m_mat_a_shape);
+ auto mat_b = std::make_shared<op::v0::Parameter>(p.m_data_type, p.m_mat_b_shape);
+ auto offsets = std::make_shared<op::v0::Parameter>(p.m_offsets_type, p.m_offsets_shape);
+ auto grouped_matmul = std::make_shared<op::v17::GroupedMatMul>(mat_a, mat_b, offsets);
+ return std::make_shared<Model>(grouped_matmul, ParameterVector{mat_a, mat_b, offsets});
+ }
+
+ static std::shared_ptr<Model> CreateFunction3D3D(const GroupedMatMulParams& p) {
+ auto mat_a = std::make_shared<op::v0::Parameter>(p.m_data_type, p.m_mat_a_shape);
+ auto mat_b = std::make_shared<op::v0::Parameter>(p.m_data_type, p.m_mat_b_shape);
+ auto grouped_matmul = std::make_shared<op::v17::GroupedMatMul>(mat_a, mat_b);
+ return std::make_shared<Model>(grouped_matmul, ParameterVector{mat_a, mat_b});
+ }
+};
+
+TEST_P(ReferenceGroupedMatMulTest, CompareWithRefs) {
+ Exec();
+}
+
+template <element::Type_t ET>
+std::vector<GroupedMatMulParams> generateParams() {
+ using T = typename element_type_traits<ET>::value_type;
+
+ std::vector<GroupedMatMulParams> params;
+ const std::string type_suffix = "_" + element::Type(ET).get_type_name();
+
+ // Case: 3D × 3D batched - simple 2 groups, 2×2 matmul each
+ // Group 0: [[1,2],[3,4]] @ [[1,2],[3,4]] = [[7,10],[15,22]]
+ // Group 1: [[5,6],[7,8]] @ [[5,6],[7,8]] = [[67,78],[91,106]]
+ // mat_b stored as [G, N, K]: group 0 = [[1,3],[2,4]], group 1 = [[5,7],[6,8]]
+ params.push_back(GroupedMatMulParams(Shape{2, 2, 2}, // mat_a: (G=2, M=2, K=2)
+ Shape{2, 2, 2}, // mat_b: (G=2, N=2, K=2)
+ Shape{2, 2, 2}, // output: (G=2, M=2, N=2)
+ ET,
+ std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8}, // mat_a
+ std::vector<T>{1, 3, 2, 4, 5, 7, 6, 8}, // mat_b (transposed per group)
+ std::vector<T>{7, 10, 15, 22, 67, 78, 91, 106}, // expected
+ "3D_3D_2groups_2x2" + type_suffix));
+
+ // Case: 3D × 3D - single group
+ // [[1,2,3],[4,5,6]] @ [[1,2],[3,4],[5,6]] = [[22,28],[49,64]]
+ // mat_b stored as [G, N, K]: group 0 = [[1,3,5],[2,4,6]]
+ params.push_back(GroupedMatMulParams(Shape{1, 2, 3}, // mat_a: (G=1, M=2, K=3)
+ Shape{1, 2, 3}, // mat_b: (G=1, N=2, K=3)
+ Shape{1, 2, 2}, // output: (G=1, M=2, N=2)
+ ET,
+ std::vector<T>{1, 2, 3, 4, 5, 6}, // mat_a
+ std::vector<T>{1, 3, 5, 2, 4, 6}, // mat_b (transposed)
+ std::vector<T>{22, 28, 49, 64}, // expected
+ "3D_3D_1group_2x3_3x2" + type_suffix));
+
+ // Case: 2D × 3D with offsets - 2 experts, [2,1] tokens per expert
+ // Expert 0 gets rows [0:2], Expert 1 gets rows [2:3]
+ // mat_a[:2] @ mat_b[0] = [[1,2],[3,4]] @ [[1,2],[3,4]] = [[7,10],[15,22]]
+ // mat_a[2:3] @ mat_b[1] = [[5,6]] @ [[5,6],[7,8]] = [[67,78]]
+ // mat_b stored as [G, N, K]: expert 0 = [[1,3],[2,4]], expert 1 = [[5,7],[6,8]]
+ params.push_back(GroupedMatMulParams(Shape{3, 2}, // mat_a: (total_tokens=3, K=2)
+ Shape{2, 2, 2}, // mat_b: (G=2, N=2, K=2)
+ Shape{2}, // offsets: cumulative [2, 3]
+ Shape{3, 2}, // output: (total_tokens=3, N=2)
+ ET,
+ element::i32,
+ std::vector<T>{1, 2, 3, 4, 5, 6}, // mat_a
+ std::vector<T>{1, 3, 2, 4, 5, 7, 6, 8}, // mat_b (transposed per group)
+ std::vector<int32_t>{2, 3}, // offsets
+ std::vector<T>{7, 10, 15, 22, 67, 78}, // expected
+ "2D_3D_2experts_offsets" + type_suffix));
+
+ // Case: 2D × 3D - 3 experts with varying tokens [1, 2, 1]
+ params.push_back(GroupedMatMulParams(
+ Shape{4, 2}, // mat_a: (total_tokens=4, K=2)
+ Shape{3, 2, 2}, // mat_b: (G=3, K=2, N=2)
+ Shape{3}, // offsets
+ Shape{4, 2}, // output
+ ET,
+ element::i64,
+ std::vector<T>{1, 0, 0, 1, 1, 1, 2, 2}, // mat_a: 4 tokens
+ std::vector<T>{1, 0, 0, 1, 2, 0, 0, 2, 3, 0, 0, 3}, // mat_b: 3 experts, each 2x2 identity-like
+ std::vector<int64_t>{1, 3, 4}, // offsets: [1, 3, 4]
+ std::vector<T>{1, 0, 0, 2, 2, 2, 6, 6}, // expected
+ "2D_3D_3experts_varying_tokens" + type_suffix));
+
+ return params;
+}
+
+std::vector<GroupedMatMulParams> generateCombinedParams() {
+ std::vector<std::vector<GroupedMatMulParams>> params_list;
+ params_list.push_back(generateParams<element::Type_t::f32>());
+ params_list.push_back(generateParams<element::Type_t::i32>());
+
+ std::vector<GroupedMatMulParams> combined;
+ for (auto& params : params_list) {
+ combined.insert(combined.end(), params.begin(), params.end());
+ }
+ return combined;
+}
+
+INSTANTIATE_TEST_SUITE_P(smoke_GroupedMatMul_With_Hardcoded_Refs,
+ ReferenceGroupedMatMulTest,
+ testing::ValuesIn(generateCombinedParams()),
+ ReferenceGroupedMatMulTest::getTestCaseName);
+
+} // namespace
diff --git a/src/tests/functional/plugin/conformance/test_runner/op_conformance_runner/src/op_impl_check/single_op_graph.cpp b/src/tests/functional/plugin/conformance/test_runner/op_conformance_runner/src/op_impl_check/single_op_graph.cpp
index 9dccea3402e..3d56e69e6c6 100644
--- a/src/tests/functional/plugin/conformance/test_runner/op_conformance_runner/src/op_impl_check/single_op_graph.cpp
+++ b/src/tests/functional/plugin/conformance/test_runner/op_conformance_runner/src/op_impl_check/single_op_graph.cpp
@@ -579,6 +579,15 @@ std::shared_ptr<ov::Model> generate(const std::shared_ptr<ov::op::v16::SparseFil
return std::make_shared<ov::Model>(results, ov::ParameterVector{values, indices, default_value}, "SparseFillEmptyRowsGraph");
}
+std::shared_ptr<ov::Model> generate(const std::shared_ptr<ov::op::v17::GroupedMatMul> &node) {
+ // Case: 3D × 3D (batched uniform groups)
+ const auto mat_a = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{3, 4, 64});
+ const auto mat_b = std::make_shared<ov::op::v0::Parameter>(ov::element::f32, ov::PartialShape{3, 128, 64});
+ const auto groupedMatMulNode = std::make_shared<ov::op::v17::GroupedMatMul>(mat_a, mat_b);
+ ov::ResultVector results{std::make_shared<ov::op::v0::Result>(groupedMatMulNode)};
+ return std::make_shared<ov::Model>(results, ov::ParameterVector{mat_a, mat_b}, "GroupedMatMulGraph");
+}
+
std::shared_ptr<ov::Model> generate(const std::shared_ptr<ov::op::v4::Interpolate> &node) {
using InterpolateAttrs = op::v4::Interpolate::InterpolateAttrs;
using InterpolateMode = op::v4::Interpolate::InterpolateMode;
diff --git a/tests/layer_tests/pytorch_tests/test_grouped_mm.py b/tests/layer_tests/pytorch_tests/test_grouped_mm.py
new file mode 100644
index 00000000000..d9974da045d
--- /dev/null
+++ b/tests/layer_tests/pytorch_tests/test_grouped_mm.py
@@ -0,0 +1,204 @@
+# Copyright (C) 2018-2026 Intel Corporation
+# SPDX-License-Identifier: Apache-2.0
+
+import pytest
+import openvino as ov
+
+from pytorch_layer_test_class import PytorchLayerTest
+
+
+class TestGroupedMMConstWeights(PytorchLayerTest):
+ """`torch._grouped_mm` with weights baked into the module as a buffer.
+
+ With the weights folded as a Constant in the IR, the CPU
+ `ConvertGroupedMatMulToGatherMatmul` pass can lower the op to the internal
+ `GatherMatmul` and the kernel `GatherMatmul::execute` should fire.
+ """
+
+ def _prepare_input(self, a_shape=(2, 3, 8)):
+ return (self.random.randn(*a_shape).astype("float32"),)
+
+ def create_model(self, b_shape=(2, 8, 16), bf16=False):
+ import torch
+ b_np = self.random.randn(*b_shape).astype("float32")
+
+ class aten_grouped_mm_const_b(torch.nn.Module):
+ def __init__(self, b, bf16):
+ super().__init__()
+ self.bf16 = bf16
+ self.register_buffer("b", torch.from_numpy(b).bfloat16() if bf16 else torch.from_numpy(b))
+
+ def forward(self, a):
+ if self.bf16:
+ return torch._grouped_mm(a.to(torch.bfloat16), self.b).to(torch.float32)
+ return torch._grouped_mm(a, self.b)
+
+ return aten_grouped_mm_const_b(b_np, bf16), "aten::_grouped_mm"
+
+ @pytest.mark.parametrize("a_shape,b_shape", [
+ ((2, 3, 8), (2, 8, 16)),
+ ((4, 1, 8), (4, 8, 8)),
+ ((1, 8, 16), (1, 16, 8)),
+ ((3, 7, 16), (3, 16, 8)),
+ ])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_torch_export
+ def test_grouped_mm_const_b(self, a_shape, b_shape, ie_device, precision, ir_version):
+ if ie_device.startswith("GPU"):
+ if self.use_torch_export():
+ pytest.skip("skip GPU BF16 torch export (FX) grouped_mm with no offsets")
+ caps = ov.Core().get_property(ie_device, ov.properties.device.capabilities)
+ if "GPU_HW_MATMUL" not in caps:
+ pytest.skip("not supported on GPU without GPU_HW_MATMUL (immad)")
+ if precision == "FP32":
+ pytest.skip("GPU gather_matmul kernel does not support FP32")
+ self._test(*self.create_model(b_shape=b_shape, bf16=self.use_torch_export()), ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"a_shape": a_shape},
+ trace_model=True)
+
+
+class TestGroupedMMOffsetsConstWeights(PytorchLayerTest):
+ """`torch._grouped_mm` with `offs` and weights baked in as a buffer."""
+
+ def _prepare_input(self, total_tokens=24, offsets=(8, 16, 24), k=8):
+ import numpy as np
+ return (
+ self.random.randn(total_tokens, k).astype("float32"),
+ np.asarray(offsets, dtype=np.int32),
+ )
+
+ def create_model(self, k=8, n=8, num_groups=3, bf16=False):
+ import torch
+ b_np = self.random.randn(num_groups, k, n).astype("float32")
+
+ class aten_grouped_mm_offs_const_b(torch.nn.Module):
+ def __init__(self, b, bf16):
+ super().__init__()
+ self.bf16 = bf16
+ self.register_buffer("b", torch.from_numpy(b).bfloat16() if bf16 else torch.from_numpy(b))
+
+ def forward(self, a, offs):
+ if self.bf16:
+ return torch._grouped_mm(a.to(torch.bfloat16), self.b, offs=offs).to(torch.float32)
+ return torch._grouped_mm(a, self.b, offs=offs)
+
+ return aten_grouped_mm_offs_const_b(b_np, bf16), "aten::_grouped_mm"
+
+ @pytest.mark.parametrize("total_tokens,k,n,offsets", [
+ (24, 8, 8, (8, 16, 24)),
+ (16, 16, 8, (8, 16)),
+ (8, 8, 16, (8,)),
+ ])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_torch_export
+ def test_grouped_mm_offs_const_b(self, total_tokens, k, n, offsets, ie_device, precision, ir_version):
+ if ie_device.startswith("GPU"):
+ caps = ov.Core().get_property(ie_device, ov.properties.device.capabilities)
+ if "GPU_HW_MATMUL" not in caps:
+ pytest.skip("not supported on GPU without GPU_HW_MATMUL (immad)")
+ if precision == "FP32":
+ pytest.skip("GPU gather_matmul kernel does not support FP32")
+ self._test(*self.create_model(k=k, n=n, num_groups=len(offsets), bf16=self.use_torch_export()),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"total_tokens": total_tokens, "offsets": offsets, "k": k},
+ trace_model=True)
+
+
+# ---------------------------------------------------------------------------
+# torch.nn.functional.grouped_mm (public API, delegates to aten::_grouped_mm)
+# ---------------------------------------------------------------------------
+
+class TestFunctionalGroupedMMConstWeights(PytorchLayerTest):
+ """`torch.nn.functional.grouped_mm` with weights baked in as a buffer (constant B)."""
+
+ def _prepare_input(self, a_shape=(2, 3, 8)):
+ return (self.random.randn(*a_shape).astype("float32"),)
+
+ def create_model(self, b_shape=(2, 8, 16), bf16=False):
+ import torch
+ b_np = self.random.randn(*b_shape).astype("float32")
+
+ class functional_grouped_mm_const_b(torch.nn.Module):
+ def __init__(self, b, bf16):
+ super().__init__()
+ self.bf16 = bf16
+ self.register_buffer("b", torch.from_numpy(b).bfloat16() if bf16 else torch.from_numpy(b))
+
+ def forward(self, a):
+ if self.bf16:
+ return torch.nn.functional.grouped_mm(a.to(torch.bfloat16), self.b).to(torch.float32)
+ return torch.nn.functional.grouped_mm(a, self.b)
+
+ return functional_grouped_mm_const_b(b_np, bf16), "aten::_grouped_mm"
+
+ @pytest.mark.parametrize("a_shape,b_shape", [
+ ((2, 3, 8), (2, 8, 16)),
+ ((4, 1, 8), (4, 8, 8)),
+ ((1, 8, 16), (1, 16, 8)),
+ ((3, 7, 16), (3, 16, 8)),
+ ])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_torch_export
+ def test_functional_grouped_mm_const_b(self, a_shape, b_shape, ie_device, precision, ir_version):
+ if ie_device.startswith("GPU"):
+ if self.use_torch_export():
+ pytest.skip("skip GPU BF16 torch export (FX) grouped_mm with no offsets")
+ caps = ov.Core().get_property(ie_device, ov.properties.device.capabilities)
+ if "GPU_HW_MATMUL" not in caps:
+ pytest.skip("not supported on GPU without GPU_HW_MATMUL (immad)")
+ if precision == "FP32":
+ pytest.skip("GPU gather_matmul kernel does not support FP32")
+ self._test(*self.create_model(b_shape=b_shape, bf16=self.use_torch_export()), ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"a_shape": a_shape},
+ trace_model=True)
+
+
+class TestFunctionalGroupedMMOffsetsConstWeights(PytorchLayerTest):
+ """`torch.nn.functional.grouped_mm` with `offs` and weights baked in as a buffer."""
+
+ def _prepare_input(self, total_tokens=24, offsets=(8, 16, 24), k=8):
+ import numpy as np
+ return (
+ self.random.randn(total_tokens, k).astype("float32"),
+ np.asarray(offsets, dtype=np.int32),
+ )
+
+ def create_model(self, k=8, n=8, num_groups=3, bf16=False):
+ import torch
+ b_np = self.random.randn(num_groups, k, n).astype("float32")
+
+ class functional_grouped_mm_offs_const_b(torch.nn.Module):
+ def __init__(self, b, bf16):
+ super().__init__()
+ self.bf16 = bf16
+ self.register_buffer("b", torch.from_numpy(b).bfloat16() if bf16 else torch.from_numpy(b))
+
+ def forward(self, a, offs):
+ if self.bf16:
+ return torch.nn.functional.grouped_mm(a.to(torch.bfloat16), self.b, offs=offs).to(torch.float32)
+ return torch.nn.functional.grouped_mm(a, self.b, offs=offs)
+
+ return functional_grouped_mm_offs_const_b(b_np, bf16), "aten::_grouped_mm"
+
+ @pytest.mark.parametrize("total_tokens,k,n,offsets", [
+ (24, 8, 8, (8, 16, 24)),
+ (16, 16, 8, (8, 16)),
+ (8, 8, 16, (8,)),
+ ])
+ @pytest.mark.nightly
+ @pytest.mark.precommit
+ @pytest.mark.precommit_torch_export
+ def test_functional_grouped_mm_offs_const_b(self, total_tokens, k, n, offsets, ie_device, precision, ir_version):
+ if ie_device.startswith("GPU"):
+ caps = ov.Core().get_property(ie_device, ov.properties.device.capabilities)
+ if "GPU_HW_MATMUL" not in caps:
+ pytest.skip("not supported on GPU without GPU_HW_MATMUL (immad)")
+ if precision == "FP32":
+ pytest.skip("GPU gather_matmul kernel does not support FP32")
+ self._test(*self.create_model(k=k, n=n, num_groups=len(offsets), bf16=self.use_torch_export()),
+ ie_device, precision, ir_version,
+ kwargs_to_prepare_input={"total_tokens": total_tokens, "offsets": offsets, "k": k},
+ trace_model=True)