Skip to content

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

[CPU] Refactor GatherMatmul to implement executor design (#35812)

Maksim Kutakov0b0029efc950
diff --git a/src/plugins/intel_cpu/src/cpu_types.cpp b/src/plugins/intel_cpu/src/cpu_types.cpp
index 989a7b3dd26..673338fd661 100644
--- a/src/plugins/intel_cpu/src/cpu_types.cpp
+++ b/src/plugins/intel_cpu/src/cpu_types.cpp
@@ -489,6 +489,8 @@ std::string algToString(const Algorithm alg) {
CASE(FullyConnectedCompressed);
CASE(FullyConnectedQuantized);
CASE(FullyConnectedQuantizedLegacy);
+ CASE(GatherMatmulDefault);
+ CASE(GatherMatmulCompressed);
CASE(ROIPoolingMax);
CASE(ROIPoolingBilinear);
CASE(ROIAlignMax);
diff --git a/src/plugins/intel_cpu/src/cpu_types.h b/src/plugins/intel_cpu/src/cpu_types.h
index cbc58f6e04b..e25678b27f8 100644
--- a/src/plugins/intel_cpu/src/cpu_types.h
+++ b/src/plugins/intel_cpu/src/cpu_types.h
@@ -228,6 +228,10 @@ enum class Algorithm : uint8_t {
FullyConnectedQuantized,
FullyConnectedQuantizedLegacy,
+ // GatherMatmul algorithms
+ GatherMatmulDefault,
+ GatherMatmulCompressed,
+
// FakeQuantize algorithms
FQCommon,
FQQuantization,
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp
new file mode 100644
index 00000000000..68bc9488dec
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.cpp
@@ -0,0 +1,680 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include "dnnl_gathermatmul_executor.hpp"
+
+#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 <tuple>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+#include "nodes/common/blocked_desc_creator.h"
+#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)
+# include <cpu/x64/cpu_isa_traits.hpp>
+#endif
+#include "cpu_memory.h"
+#include "cpu_types.h"
+#include "dnnl_extension_utils.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 "nodes/executors/dnnl/dnnl_utils.hpp"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
+#include "onednn/iml_type_mapper.h"
+#include "openvino/core/except.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "thread_pool_imp.hpp"
+#include "utils/general_utils.h"
+
+namespace ov::intel_cpu {
+
+// ---- InnerProductKey ---------------------------------------------------------
+
+struct InnerProductKey {
+ dnnl::memory::desc src_md;
+ dnnl::memory::desc weights_md;
+ dnnl::memory::desc bias_md;
+ VectorDims scale_shape;
+ VectorDims zp_shape;
+
+ [[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 = hash_combine(seed, get_md_hash(*bias_md.get()));
+ seed = get_vector_hash(seed, scale_shape);
+ seed = get_vector_hash(seed, zp_shape);
+ return seed;
+ }
+
+ bool operator==(const InnerProductKey& rhs) const {
+ return src_md == rhs.src_md && weights_md == rhs.weights_md && bias_md == rhs.bias_md &&
+ scale_shape == rhs.scale_shape && zp_shape == rhs.zp_shape;
+ }
+};
+
+// ---- InnerProduct (oneDNN inner_product wrapper) ----------------------------
+
+class GatherMatmulDnnlExecutor::InnerProduct {
+public:
+ InnerProduct() = delete;
+ InnerProduct(const InnerProduct&) = delete;
+ InnerProduct(InnerProduct&&) = delete;
+ InnerProduct& operator=(const InnerProduct&) = delete;
+ InnerProduct& operator=(InnerProduct&&) = delete;
+
+ InnerProduct(const dnnl::engine& eng, const std::shared_ptr<ThreadPool>& threadPool, const InnerProductKey& key)
+ : m_stream(make_stream(eng, threadPool)) {
+ 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);
+
+ const auto& bias_md = key.bias_md;
+
+ auto ip_prim_desc = dnnl::inner_product_forward::primitive_desc(eng,
+ dnnl::prop_kind::forward_inference,
+ m_input_md,
+ weights_md,
+ bias_md,
+ m_output_md,
+ m_attr);
+
+ m_impl_type = parse_impl_name(ip_prim_desc.impl_info_str());
+ m_wei_md = ip_prim_desc.weights_desc();
+ m_prim = dnnl::inner_product_forward(ip_prim_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 (!bias_md.is_zero()) {
+ 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);
+ }
+ m_args = make_args(inp_memory, out_memory, wei_memory, bias_memory, scale_memory, zp_memory);
+ }
+
+ void exec(void* src, void* dst, void* weight, void* bias = nullptr, void* scale = nullptr, void* zp = nullptr) {
+ m_args[DNNL_ARG_SRC].set_data_handle(src);
+ m_args[DNNL_ARG_DST].set_data_handle(dst);
+ m_args[DNNL_ARG_WEIGHTS].set_data_handle(weight);
+ if (bias) {
+ m_args[DNNL_ARG_BIAS].set_data_handle(bias);
+ }
+ if (scale) {
+ m_args[DNNL_ARG_ATTR_SCALES | DNNL_ARG_WEIGHTS].set_data_handle(scale);
+ }
+ if (zp) {
+ m_args[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS].set_data_handle(zp);
+ }
+ m_prim.execute(m_stream, m_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]] 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);
+ m_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);
+ m_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::stream m_stream;
+ 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 m_attr;
+ std::unordered_map<int, dnnl::memory> m_args;
+ impl_desc_type m_impl_type = impl_desc_type::unknown;
+};
+
+// ---- OffsetHelper ------------------------------------------------------------
+
+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};
+ }
+ return createOffsetHelper(*mem);
+ }
+
+ static OffsetHelper createOffsetHelper(const IMemory& mem) {
+ std::bitset<2> broadcast_mask;
+ 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);
+ 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);
+ 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;
+};
+
+// ---- normalizeM helper -------------------------------------------------------
+
+Dim normalizeM(Dim M) {
+ if (M < 512) {
+ M = rnd_up(M, 16);
+ } else if (M < 1024) {
+ M = rnd_up(M, 32);
+ } else {
+ M = rnd_up(M, 256);
+ }
+ return M;
+}
+
+// ---- GatherMatmulDnnlExecutor -----------------------------------------------
+
+dnnl::memory::desc makeBiasMd(dnnl::memory::dim N, const MemoryPtr& biasMem) {
+ if (!biasMem || biasMem->getDesc().empty()) {
+ return {};
+ }
+ const auto bias_precision = biasMem->getDesc().getPrecision();
+ return dnnl::memory::desc(dnnl::memory::dims({N}),
+ DnnlExtensionUtils::ElementTypeToDataType(bias_precision),
+ dnnl::memory::format_tag::a);
+}
+} // namespace
+
+bool GatherMatmulDnnlExecutor::supports([[maybe_unused]] const GatherMatmulConfig& config) {
+#ifdef OPENVINO_ARCH_X86_64
+ // Allow empty (dynamic) src descriptor — actual type is resolved at createPrimitive time
+ if ((config.descs.count(ARG_SRC) != 0U) && !config.descs.at(ARG_SRC)->empty()) {
+ const auto src_prc = config.descs.at(ARG_SRC)->getPrecision();
+ if (!any_of(src_prc, ov::element::f32, ov::element::bf16)) {
+ return false;
+ }
+ }
+ // For compressed (int) weights, require AVX2
+ if ((config.descs.count(ARG_WEI) != 0U) && !config.descs.at(ARG_WEI)->empty()) {
+ const auto wei_prc = config.descs.at(ARG_WEI)->getPrecision();
+ if (any_of(wei_prc, ov::element::u8, ov::element::i8, ov::element::u4, ov::element::i4)) {
+ if (!dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2)) {
+ return false;
+ }
+ }
+ }
+ return true;
+#else
+ return false;
+#endif
+}
+
+GatherMatmulDnnlExecutor::GatherMatmulDnnlExecutor([[maybe_unused]] const GatherMatmulAttrs& attrs,
+ const MemoryArgs& memory,
+ const ExecutorContext::CPtr& context)
+ : m_context(context) {
+ const auto& weightsMemory = memory.at(ARG_WEI);
+ const auto& srcMemory = memory.at(ARG_SRC);
+
+ auto src_precision = srcMemory->getDesc().getPrecision();
+ auto weights_precision = weightsMemory->getDesc().getPrecision();
+#ifdef OPENVINO_ARCH_X86_64
+ m_bf16AmxMode =
+ (src_precision == ov::element::bf16 && dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx));
+#endif
+
+ const auto& weiDims = weightsMemory->getShape().getStaticDims();
+ const dnnl::memory::dim N = weiDims[weiDims.size() - 2];
+ const dnnl::memory::dim K = weiDims[weiDims.size() - 1];
+
+ // Determine scale/zp shapes (per-group, removing the leading batch/gather dim)
+ VectorDims scale_shape{};
+ VectorDims zp_shape{};
+
+ const auto& scalesMem = memory.at(ARG_SRC_3);
+ if (scalesMem && !scalesMem->getDesc().empty()) {
+ const auto& fullScalesShape = scalesMem->getShape().getStaticDims();
+ if (1 == fullScalesShape.size()) {
+ OPENVINO_ASSERT(fullScalesShape[0] == 1, "Expect broadcastable scales shape.");
+ scale_shape.push_back(fullScalesShape[0]);
+ } else {
+ scale_shape.assign(fullScalesShape.begin() + 1, fullScalesShape.end());
+ }
+ }
+
+ const auto& zpMem = memory.at(ARG_SRC_4);
+ if (zpMem && !zpMem->getDesc().empty()) {
+ const auto& fullZpShape = zpMem->getShape().getStaticDims();
+ if (1 == fullZpShape.size()) {
+ OPENVINO_ASSERT(fullZpShape[0] == 1, "Expect broadcastable zero points shape.");
+ zp_shape.push_back(fullZpShape[0]);
+ } else {
+ zp_shape.assign(fullZpShape.begin() + 1, fullZpShape.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);
+
+ InnerProductKey key{src_md, weights_md, makeBiasMd(N, memory.at(ARG_BIAS)), scale_shape, zp_shape};
+
+ const auto& eng = context->getEngine();
+ const auto threadPool = context->getThreadPool();
+ auto cache = context->getRuntimeCache();
+ std::tie(m_gemvImpl, std::ignore) = cache->getOrCreate(key, [&eng, &threadPool](const InnerProductKey& k) {
+ return std::make_shared<InnerProduct>(eng, threadPool, k);
+ });
+
+ // Repack weights: convert from [G, K, N] to [G, (packed_N, K)] format expected by oneDNN
+ auto gemvWeightsDesc =
+ MemoryDescUtils::convertToBlockedMemoryDesc(DnnlExtensionUtils::makeDescriptor(m_gemvImpl->get_weights_md()));
+
+ 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();
+ 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]);
+ auto srcWeightsDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weightsMemory->getDescPtr());
+
+ m_weightsMemory = utils::prepareWeightsMemory(srcWeightsDesc,
+ targetWeightsDesc,
+ weightsMemory,
+ eng,
+ cache,
+ context->getWeightsCache(),
+ context->getPrivateWeightCache(),
+ threadPool);
+
+ if (!scale_shape.empty()) {
+ auto expectedScaleMemDesc =
+ MemoryDescUtils::convertToDnnlMemoryDesc(DnnlExtensionUtils::makeDescriptor(m_gemvImpl->get_scale_md()));
+ const auto& scDims = scalesMem->getShape().getStaticDims();
+ expectedScaleMemDesc =
+ addBatchDim(MemoryDescUtils::convertToBlockedMemoryDesc(expectedScaleMemDesc), scDims[0]);
+ if (expectedScaleMemDesc->isCompatible(scalesMem->getDesc())) {
+ m_scalesMemory = std::const_pointer_cast<IMemory>(scalesMem);
+ } else {
+ m_scalesMemory = std::make_shared<Memory>(eng, expectedScaleMemDesc);
+ m_scalesMemory->load(*scalesMem, false, false);
+ }
+ }
+
+ if (!zp_shape.empty()) {
+ auto expectedZpMemDesc =
+ MemoryDescUtils::convertToDnnlMemoryDesc(DnnlExtensionUtils::makeDescriptor(m_gemvImpl->get_zp_md()));
+ const auto& zpDims = zpMem->getShape().getStaticDims();
+ expectedZpMemDesc = addBatchDim(MemoryDescUtils::convertToBlockedMemoryDesc(expectedZpMemDesc), zpDims[0]);
+ if (expectedZpMemDesc->isCompatible(zpMem->getDesc())) {
+ m_zpMemory = std::const_pointer_cast<IMemory>(zpMem);
+ } else {
+ m_zpMemory = std::make_shared<Memory>(eng, expectedZpMemDesc);
+ m_zpMemory->load(*zpMem, false, false);
+ }
+ }
+
+ m_implType = m_gemvImpl->get_impl_type();
+}
+
+bool GatherMatmulDnnlExecutor::update(const MemoryArgs& memory) {
+ if (!m_bf16AmxMode) {
+ return true;
+ }
+
+ const auto& srcMem = memory.at(ARG_SRC);
+ const auto& srcShape = srcMem->getStaticDims();
+ // srcShape is [B, M, K]
+ if (Dim{1} == srcShape[1]) {
+ // If M is 1, we can skip the temporary buffer and execute GEMV in-place on the src buffer
+ return true;
+ }
+ const Dim M = normalizeM(srcShape[1]);
+ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();
+ const auto srcPrc = srcMem->getDesc().getPrecision();
+
+ const auto& dstMem = memory.at(ARG_DST);
+ const auto& dstShape = dstMem->getStaticDims();
+
+ m_tmpInputDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, srcShape[2]}));
+ m_tmpOutputDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, dstShape[2]}));
+
+ const size_t srcSize = rnd_up(m_tmpInputDesc->getCurrentMemSize(), 64);
+ const size_t totalSize = srcSize + m_tmpOutputDesc->getCurrentMemSize();
+ auto scratchPadDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(ov::element::u8, Shape({totalSize}));
+ m_tmpInpBuffer = m_context->getScratchPad()->createScratchPadMem(scratchPadDesc);
+
+ OPENVINO_ASSERT(m_gemvImpl, "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 = m_gemvImpl->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());
+ }
+ }
+
+ InnerProductKey key{src_md,
+ weights_md,
+ makeBiasMd(static_cast<dnnl::memory::dim>(weights_md.get_dims()[0]), memory.at(ARG_BIAS)),
+ scale_shape,
+ zp_shape};
+ const auto& eng = m_context->getEngine();
+ const auto threadPool = m_context->getThreadPool();
+ auto cache = m_context->getRuntimeCache();
+ std::tie(m_gemmImpl, std::ignore) = cache->getOrCreate(key, [&eng, &threadPool](const InnerProductKey& k) {
+ return std::make_shared<InnerProduct>(eng, threadPool, k);
+ });
+ return true;
+}
+
+void GatherMatmulDnnlExecutor::execute(const MemoryArgs& memory) {
+ const auto& cpu_parallel = m_context->getCpuParallel();
+ const auto& srcMem = memory.at(ARG_SRC);
+ const auto& biasMem = memory.at(ARG_BIAS);
+ const auto& indexMem = memory.at(ARG_SRC_1);
+ const auto& dstMem = memory.at(ARG_DST);
+
+ const auto& indexShape = indexMem->getStaticDims();
+ size_t M = indexShape[0];
+ size_t indices_size = indexShape[1];
+
+ 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);
+
+ const size_t gather_axis_size = m_weightsMemory->getStaticDims()[0];
+
+ if (M > 1) {
+ 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];
+ OPENVINO_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 (m_bf16AmxMode) {
+ OPENVINO_ASSERT(m_tmpInpBuffer, "Temporary input/output memory is not created");
+ OPENVINO_ASSERT(m_tmpInputDesc, "Temporary input memory desc is not created");
+ OPENVINO_ASSERT(m_tmpOutputDesc, "Temporary output memory desc is not created");
+
+ const auto element_size = m_tmpInputDesc->getPrecision().size();
+ const auto K_size = m_tmpInputDesc->getShape().getStaticDims()[1];
+ const auto M_size = m_tmpInputDesc->getShape().getStaticDims()[0];
+ const auto N_size = dstMem->getStaticDims()[2];
+
+ auto* input_ptr = m_tmpInpBuffer->getDataAs<uint8_t>();
+ auto* output_ptr = input_ptr + rnd_up(m_tmpInputDesc->getCurrentMemSize(), 64);
+
+ Memory tmpInput(m_context->getEngine(), m_tmpInputDesc, input_ptr);
+ Memory tmpOutput(m_context->getEngine(), m_tmpOutputDesc, output_ptr);
+
+ auto tmp_input_offset = OffsetHelper::createOffsetHelper(tmpInput);
+ auto tmp_dst_offset = OffsetHelper::createOffsetHelper(tmpOutput);
+
+ OPENVINO_ASSERT(m_gemmImpl, "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;
+ }
+
+ cpu_parallel->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 {
+ 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);
+ m_gemmImpl->exec(src, dst, wei, bias, scale, zp);
+
+ cpu_parallel->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 {
+ OPENVINO_ASSERT(m_gemvImpl, "GEMV 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);
+ m_gemvImpl->exec(src, dst, wei, bias, scale, zp);
+ }
+ }
+ }
+ } else {
+ OPENVINO_ASSERT(m_gemvImpl, "GEMV 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];
+ OPENVINO_ASSERT(gather_axis_index >= 0 && static_cast<size_t>(gather_axis_index) < gather_axis_size,
+ "Invalid gather_id ",
+ gather_axis_index,
+ " for i ",
+ 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);
+ m_gemvImpl->exec(src, dst, wei, bias, scale, zp);
+ }
+ }
+}
+
+impl_desc_type GatherMatmulDnnlExecutor::implType() const {
+ return m_implType;
+}
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp
new file mode 100644
index 00000000000..e09f0bd6a0c
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp
@@ -0,0 +1,52 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include <memory>
+#include <oneapi/dnnl/dnnl.hpp>
+
+#include "cpu_memory.h"
+#include "memory_desc/cpu_memory_desc.h"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
+#include "onednn/iml_type_mapper.h"
+
+namespace ov::intel_cpu {
+
+class GatherMatmulDnnlExecutor : public Executor {
+public:
+ static bool supports(const GatherMatmulConfig& config);
+
+ GatherMatmulDnnlExecutor(const GatherMatmulAttrs& attrs,
+ const MemoryArgs& memory,
+ const ExecutorContext::CPtr& context);
+
+ bool update(const MemoryArgs& memory) override;
+ void execute(const MemoryArgs& memory) override;
+ [[nodiscard]] impl_desc_type implType() const override;
+
+private:
+ class InnerProduct;
+ using InnerProductPtr = std::shared_ptr<InnerProduct>;
+
+ ExecutorContext::CPtr m_context;
+
+ MemoryPtr m_weightsMemory;
+ MemoryPtr m_scalesMemory;
+ MemoryPtr m_zpMemory;
+
+ InnerProductPtr m_gemvImpl;
+ InnerProductPtr m_gemmImpl;
+
+ MemoryPtr m_tmpInpBuffer;
+ MemoryDescPtr m_tmpInputDesc;
+ MemoryDescPtr m_tmpOutputDesc;
+
+ bool m_bf16AmxMode = false;
+ impl_desc_type m_implType = impl_desc_type::unknown;
+};
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor.hpp
index 5346ffcf83e..b7790175b93 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/executor.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/executor.hpp
@@ -41,7 +41,7 @@ enum class ExecutorType : uint8_t {
Kleidiai,
};
-enum class OperationType : uint8_t { FullyConnected, MatMul, Convolution, Eltwise };
+enum class OperationType : uint8_t { FullyConnected, MatMul, Convolution, Eltwise, GatherMatmul };
std::string ExecutorTypeToString(ExecutorType type);
ExecutorType ExecutorTypeFromString(const std::string& typeStr);
diff --git a/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_config.hpp
new file mode 100644
index 00000000000..ac7bcc5aeb8
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_config.hpp
@@ -0,0 +1,15 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#pragma once
+
+#include "executor_config.hpp"
+
+namespace ov::intel_cpu {
+
+struct GatherMatmulAttrs {};
+
+using GatherMatmulConfig = executor::Config<GatherMatmulAttrs>;
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_implementations.cpp b/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_implementations.cpp
new file mode 100644
index 00000000000..78794bcbc02
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/gathermatmul_implementations.cpp
@@ -0,0 +1,107 @@
+// Copyright (C) 2018-2026 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <vector>
+
+#include "nodes/executors/executor_implementation.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
+#include "nodes/executors/implementations.hpp"
+#include "utils/arch_macros.h"
+
+#if defined(OV_CPU_WITH_DNNL) && defined(OPENVINO_ARCH_X86_64)
+# include <optional>
+
+# include "cpu/x64/cpu_isa_traits.hpp"
+# include "debug_messages.hpp"
+# include "implementation_utils.hpp"
+# include "memory_desc/cpu_memory_desc.h"
+# include "nodes/executors/dnnl/dnnl_gathermatmul_executor.hpp"
+# include "nodes/executors/executor.hpp"
+# include "nodes/executors/executor_config.hpp"
+# include "nodes/executors/memory_arguments.hpp"
+# include "nodes/executors/precision_translation.hpp"
+# include "nodes/executors/type_mask.hpp"
+# include "openvino/core/type/element_type.hpp"
+#endif
+namespace ov::intel_cpu {
+
+#if defined(OV_CPU_WITH_DNNL) && defined(OPENVINO_ARCH_X86_64)
+
+using namespace ov::element;
+using namespace TypeMaskAlias;
+using namespace executor;
+
+using LayoutConfig = std::vector<LayoutType>;
+
+// GatherMatmul always uses plain (ncsp) layout for all four standard arguments
+static const LayoutConfig dnnlGatherMatmulLayoutConfig{LayoutType::ncsp,
+ LayoutType::ncsp,
+ LayoutType::ncsp,
+ LayoutType::ncsp};
+
+template <dnnl::impl::cpu::x64::cpu_isa_t ISA>
+struct Require {
+ bool operator()() {
+ return dnnl::impl::cpu::x64::mayiuse(ISA);
+ }
+};
+
+// clang-format off
+static const TypeMapping dnnlGatherMatmulTypeMapping {
+ // {src, wei, bia, dst} pt<src, wei, bias, dst>
+ // float precision paths
+ {{_bf16, _bf16, _any, _bf16 | _f32}, {bypass(), bypass(), use<3>(), bypass()}},
+ // oneDNN inner_product does not support mixed bf16/f32 or bf16/f16: align weights precision to src
+ {{_bf16, _f16 | _f32, _any, _bf16 | _f32}, {bypass(), use<0>(), use<3>(), bypass()}},
+ {{_f32, _f32, _any, _f32}, {bypass(), bypass(), use<3>(), bypass()}},
+ // compresses float weights which do not match input data precision
+ {{_f32, _half_float, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ // compressed int weights with float activations
+ {{_f32, _u8 | _i8 | _u4 | _i4, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ {{_bf16, _u8 | _i8 | _u4 | _i4, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()},
+ Require<dnnl::impl::cpu::x64::avx512_core_bf16>()},
+ {{_bf16, _u8 | _i8 | _u4 | _i4, _any, _any}, {just<f32>(), bypass(), just<f32>(), just<f32>()}},
+ // fallback
+ {{_any, _any, _any, _any}, {just<f32>(), just<f32>(), just<f32>(), just<f32>()}},
+};
+// clang-format on
+
+static const MappingNotation gatherMatmulMappingNotation{
+ {ARG_SRC, 0},
+ {ARG_WEI, 1},
+ {ARG_BIAS, 2},
+ {ARG_DST, 3},
+};
+
+#endif
+
+// clang-format off
+template <>
+const std::vector<ExecutorImplementation<GatherMatmulAttrs>>& getImplementations() {
+ static const std::vector<ExecutorImplementation<GatherMatmulAttrs>> gathermatmulImplementations{
+ OV_CPU_INSTANCE_DNNL_X64(
+ "gathermatmul_dnnl",
+ ExecutorType::Dnnl,
+ OperationType::GatherMatmul,
+ // supports
+ [](const GatherMatmulConfig& config) -> bool {
+ VERIFY(GatherMatmulDnnlExecutor::supports(config), UNSUPPORTED_BY_EXECUTOR);
+ return true;
+ },
+ // createOptimalConfig
+ [](const GatherMatmulConfig& config) -> std::optional<executor::Config<GatherMatmulAttrs>> {
+ return createOptimalConfigCommon(config,
+ dnnlGatherMatmulTypeMapping,
+ dnnlGatherMatmulLayoutConfig,
+ gatherMatmulMappingNotation);
+ },
+ AcceptsAnyShape<GatherMatmulAttrs>,
+ CreateDefault<GatherMatmulDnnlExecutor, GatherMatmulAttrs>{}
+ )
+ };
+ return gathermatmulImplementations;
+}
+// clang-format on
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp b/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp
index c0ac6e9ac9c..88f1f1db3a5 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp
@@ -11,6 +11,7 @@
#include "nodes/executors/eltwise_config.hpp"
#include "nodes/executors/executor_implementation.hpp"
#include "nodes/executors/fullyconnected_config.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
#include "nodes/executors/matmul_config.hpp"
namespace ov::intel_cpu {
@@ -37,6 +38,10 @@ const std::vector<ExecutorImplementation<ConvAttrs>>& getImplementations();
template <>
const std::vector<ExecutorImplementation<EltwiseAttrs>>& getImplementations();
+// GatherMatmul
+template <>
+const std::vector<ExecutorImplementation<GatherMatmulAttrs>>& getImplementations();
+
// MatMul
template <>
const std::vector<ExecutorImplementation<MatMulAttrs>>& getImplementations();
diff --git a/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp b/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp
index ed01a20109e..e764b9784bb 100644
--- a/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp
+++ b/src/plugins/intel_cpu/src/nodes/gathermatmul.cpp
@@ -4,37 +4,27 @@
#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"
+#if defined(OPENVINO_ARCH_X86) || defined(OPENVINO_ARCH_X86_64)
+# include "cpu/x64/cpu_isa_traits.hpp"
+#endif
#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 "nodes/executors/executor.hpp"
+#include "nodes/executors/executor_factory.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
#include "onednn/iml_type_mapper.h"
#include "openvino/core/except.hpp"
#include "openvino/core/node.hpp"
@@ -45,204 +35,11 @@
#include "ov_ops/gather_matmul_compressed.hpp"
#include "shape_inference/custom/gathermatmul.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 GatherMatmul or GatherMatmulCompressed
const bool isGatherMatmul = ov::is_type<ov::op::internal::GatherMatmul>(op);
const bool isGatherMatmulCompressed = ov::is_type<ov::op::internal::GatherMatmulCompressed>(op);
@@ -252,13 +49,11 @@ bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& o
return false;
}
- // Check that weights input (port 1) is constant
if (!ov::op::util::is_on_path<ov::op::v0::Constant>(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 (isGatherMatmulCompressed) {
if (op->get_input_size() > WEIGHT_SCALES) {
if (!ov::op::util::is_on_path<ov::op::v0::Constant>(op->input_value(WEIGHT_SCALES))) {
@@ -266,7 +61,6 @@ bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& o
return false;
}
}
-
if (op->get_input_size() > WEIGHT_ZERO_POINTS) {
if (!ov::op::util::is_on_path<ov::op::v0::Constant>(op->input_value(WEIGHT_ZERO_POINTS))) {
errorMessage = "Only constant weight zero points are supported for GatherMatmul operation";
@@ -275,10 +69,8 @@ bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& o
}
}
- // 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_path<ov::op::v0::Constant>(biasInput)) {
errorMessage = "Only constant bias is supported for GatherMatmul operation";
@@ -286,11 +78,9 @@ bool GatherMatmul::isSupportedOperation(const std::shared_ptr<const ov::Node>& o
}
}
}
-
} catch (...) {
return false;
}
-
return true;
}
@@ -300,7 +90,6 @@ bool GatherMatmul::isSupportedCompressedOperation([[maybe_unused]] const std::sh
[[maybe_unused]] size_t G,
[[maybe_unused]] const Config& config) noexcept {
#ifdef OPENVINO_ARCH_X86_64
- // copy paste from FullyConnected
try {
std::string errorMessage;
if (!isSupportedOperation(op, errorMessage)) {
@@ -348,7 +137,6 @@ bool GatherMatmul::isSupportedCompressedOperation([[maybe_unused]] const std::sh
ov::element::TypeVector GatherMatmul::getSupportedCompressedWeightsTypes([[maybe_unused]] bool apply_fp8) {
using ov::element::Type_t;
-
#ifdef OPENVINO_ARCH_X86_64
return {Type_t::u8, Type_t::i8, Type_t::u4, Type_t::i4};
#else
@@ -370,485 +158,100 @@ GatherMatmul::GatherMatmul(const std::shared_ptr<ov::Node>& op, const GraphConte
OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);
}
- // Determine the algorithm type
- if (ov::is_type<ov::op::internal::GatherMatmulCompressed>(op)) {
- algorithm = Algorithm::GatherMatmulCompressed;
- } else {
- algorithm = Algorithm::GatherMatmulDefault;
+ algorithm = ov::is_type<ov::op::internal::GatherMatmulCompressed>(op) ? Algorithm::GatherMatmulCompressed
+ : Algorithm::GatherMatmulDefault;
+
+ m_atoi[ARG_SRC] = DATA;
+ m_atoi[ARG_WEI] = WEIGHTS;
+ m_atoi[ARG_SRC_1] = INDICES;
+ m_atoi[ARG_BIAS] = BIAS;
+ if (algorithm == Algorithm::GatherMatmulCompressed) {
+ m_atoi[ARG_SRC_3] = WEIGHT_SCALES;
+ m_atoi[ARG_SRC_4] = WEIGHT_ZERO_POINTS;
}
}
void GatherMatmul::initSupportedPrimitiveDescriptors() {
const auto& srcTypes = getOriginalInputPrecisions();
auto dstTypes = getOriginalOutputPrecisions();
-
if (!fusedWith.empty()) {
dstTypes = fusedWith.back()->getOriginalOutputPrecisions();
}
- NodeConfig nodeConfig;
+ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();
- 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;
- }
+ auto makeSrcDesc = [&](size_t port) -> MemoryDescPtr {
+ if (port >= srcTypes.size() || srcTypes[port] == ov::element::dynamic) {
+ return MemoryDescUtils::makeEmptyDesc();
+ }
+ return creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcTypes[port], getInputShapeAtPort(port));
+ };
- 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;
+ MemoryDescArgs descs;
+ descs[ARG_SRC] = makeSrcDesc(DATA);
+ descs[ARG_WEI] = makeSrcDesc(WEIGHTS);
+ descs[ARG_SRC_1] = makeSrcDesc(INDICES);
+ descs[ARG_BIAS] = makeSrcDesc(BIAS);
+ descs[ARG_SRC_3] =
+ algorithm == Algorithm::GatherMatmulCompressed ? makeSrcDesc(WEIGHT_SCALES) : MemoryDescUtils::makeEmptyDesc();
+ descs[ARG_SRC_4] = algorithm == Algorithm::GatherMatmulCompressed ? makeSrcDesc(WEIGHT_ZERO_POINTS)
+ : MemoryDescUtils::makeEmptyDesc();
+ descs[ARG_DST] = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(dstTypes.front(), getOutputShapeAtPort(0));
+
+ auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);
+ m_factory = std::make_shared<ExecutorFactory<GatherMatmulAttrs>>(m_attrs, executionContext, descs);
+
+ const auto nodeDescriptorsList = m_factory->getProperMemoryDescriptors(descs);
+ for (const auto& nodeDescriptors : nodeDescriptorsList) {
+ NodeConfig nodeConfig;
+ nodeConfig.inConfs.resize(srcTypes.size());
+
+ for (const auto& [argId, portId] : m_atoi) {
+ if (nodeDescriptors.count(argId)) {
+ nodeConfig.inConfs[portId] = PortConfig{nodeDescriptors.at(argId)};
+ }
}
- 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);
- }
+ nodeConfig.outConfs.emplace_back(nodeDescriptors.at(ARG_DST));
- supportedPrimitiveDescriptors.emplace_back(nodeConfig, impl_desc_type::undef);
+ 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;
+ for (const auto& [argId, portId] : m_atoi) {
+ m_memory[argId] = getSrcMemoryAtPort(portId);
}
- 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 (algorithm != Algorithm::GatherMatmulCompressed) {
+ m_memory[ARG_SRC_3] = MemoryDescUtils::makeEmptyMemory(context);
+ m_memory[ARG_SRC_4] = MemoryDescUtils::makeEmptyMemory(context);
}
+ m_memory[ARG_DST] = getDstMemoryAtPort(0);
- 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);
- }
- }
+ m_executor = m_factory->make(m_memory);
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;
+ getSelectedPrimitiveDescriptor()->setImplementationType(m_executor->implType());
}
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();
-
- m_tmpInputDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, srcShape[2]}));
- m_tmpOutputDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcPrc, Shape({M, dstShape[2]}));
-
- const size_t srcSize = rnd_up(m_tmpInputDesc->getCurrentMemSize(), 64); // 64 bytes is the cache line size
- const size_t totalSize = srcSize + m_tmpOutputDesc->getCurrentMemSize();
- auto scratchPadDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(ov::element::u8, Shape({totalSize}));
- m_tmpInpBuffer = getScratchPadMem(scratchPadDesc);
-
- 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());
- }
+ for (const auto& [argId, portId] : m_atoi) {
+ m_memory[argId] = getSrcMemoryAtPort(portId);
}
+ m_memory[ARG_DST] = getDstMemoryAtPort(0);
- 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);
- });
+ m_executor->update(m_memory);
+ getSelectedPrimitiveDescriptor()->setImplementationType(m_executor->implType());
}
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};
- }
- return createOffsetHelper(*mem);
- }
-
- static OffsetHelper createOffsetHelper(const IMemory& mem) {
- std::bitset<2> broadcast_mask;
- 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& cpu_parallel = context->getCpuParallel();
- 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_tmpInpBuffer, "Temporary input/output memory is not created");
- CPU_NODE_ASSERT(m_tmpInputDesc, "Temporary input memory desc is not created");
- CPU_NODE_ASSERT(m_tmpOutputDesc, "Temporary output memory desc is not created");
-
- const auto element_size = m_tmpInputDesc->getPrecision().size();
- const auto K_size = m_tmpInputDesc->getShape().getStaticDims()[1];
- const auto M_size = m_tmpInputDesc->getShape().getStaticDims()[0];
- const auto N_size = dstMem->getStaticDims()[2];
-
- auto* input_ptr = m_tmpInpBuffer->getDataAs<uint8_t>();
- auto* output_ptr =
- input_ptr + rnd_up(m_tmpInputDesc->getCurrentMemSize(), 64); // 64 bytes is the cache line size
-
- Memory tmpInput(getEngine(), m_tmpInputDesc, input_ptr);
- Memory tmpOutput(getEngine(), m_tmpOutputDesc, output_ptr);
-
- auto tmp_input_offset = OffsetHelper::createOffsetHelper(tmpInput);
- auto tmp_dst_offset = OffsetHelper::createOffsetHelper(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;
- }
-
- cpu_parallel->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
- cpu_parallel->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::execute(const dnnl::stream& /*strm*/) {
+ m_executor->execute(m_memory);
}
void GatherMatmul::executeDynamicImpl(const dnnl::stream& strm) {
diff --git a/src/plugins/intel_cpu/src/nodes/gathermatmul.h b/src/plugins/intel_cpu/src/nodes/gathermatmul.h
index fcfee15c8f9..cf941e89cef 100644
--- a/src/plugins/intel_cpu/src/nodes/gathermatmul.h
+++ b/src/plugins/intel_cpu/src/nodes/gathermatmul.h
@@ -7,10 +7,15 @@
#include <memory>
#include <oneapi/dnnl/dnnl.hpp>
#include <string>
+#include <unordered_map>
#include "cpu_memory.h"
+#include "cpu_types.h"
#include "graph_context.h"
#include "node.h"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/executor_factory.hpp"
+#include "nodes/executors/gathermatmul_config.hpp"
#include "nodes/executors/memory_arguments.hpp"
#include "openvino/core/node.hpp"
@@ -25,7 +30,6 @@ public:
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;
@@ -43,8 +47,6 @@ public:
static ov::element::TypeVector getSupportedCompressedActivationsTypes();
private:
- enum class Algorithm : uint8_t { GatherMatmulDefault, GatherMatmulCompressed };
-
enum InputId : uint8_t {
DATA = 0,
WEIGHTS,
@@ -54,24 +56,13 @@ private:
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;
- MemoryDescPtr m_tmpInputDesc = nullptr;
- MemoryDescPtr m_tmpOutputDesc = nullptr;
- bool bf16_amx_mode = false;
+ GatherMatmulAttrs m_attrs;
+ ExecutorFactoryPtr<GatherMatmulAttrs> m_factory;
+ ExecutorPtr m_executor;
+ MemoryArgs m_memory;
+ std::unordered_map<int, int> m_atoi; // executor arg-id → input port mapping
};
} // namespace ov::intel_cpu::node