Skip to content

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

[CPU] Refactor mamtul node (#31696)

Egor Duplenskiid5dc21458fe6
diff --git a/src/plugins/intel_cpu/src/nodes/conv.cpp b/src/plugins/intel_cpu/src/nodes/conv.cpp
index 406dd49c3cb..ed55fcbb894 100644
--- a/src/plugins/intel_cpu/src/nodes/conv.cpp
+++ b/src/plugins/intel_cpu/src/nodes/conv.cpp
@@ -476,7 +476,7 @@ void Convolution::initSupportedPrimitiveDescriptors() {
m_attrs.isGraphQuantized = context->isGraphQuantized();
m_attrs.fcSemantic = false;
- m_attrs.nonConstantWeights = !getParentEdgeAt(WEIGHTS)->getParent()->isConstant();
+ m_attrs.constantWeights = getParentEdgeAt(WEIGHTS)->getParent()->isConstant();
m_attrs.weightsNonTransposed = false;
m_attrs.dqScales = getDQScales();
diff --git a/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp
index 96fcd47a23c..8b8faf9ca03 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp
@@ -32,7 +32,8 @@ struct ConvAttrs {
// @todo can we just check for port precisions instead?
bool isGraphQuantized = false;
bool fcSemantic = false;
- bool nonConstantWeights = false;
+ // there are models with non-constant weights
+ bool constantWeights = true;
ZeroPointsType inputZeroPointsType = ZeroPointsType::None;
std::vector<float> dqScales;
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.cpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.cpp
index a7f47f83c23..99b26c959ab 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.cpp
@@ -98,7 +98,7 @@ DnnlConvolutionPrimitive::IntermediateReorders::IntermediateReorders(const Key&
createIfNotEqual(key.dst->getDnnlDesc(), primDesc.dst_desc(), AllocateMemoryFor::Dst, engine);
}
- if (key.nonConstantWeights && key.wei->getDnnlDesc() != primDesc.weights_desc()) {
+ if (!key.constantWeights && key.wei->getDnnlDesc() != primDesc.weights_desc()) {
m_inputReorders[DNNL_ARG_WEIGHTS] =
createIfNotEqual(key.wei->getDnnlDesc(), primDesc.weights_desc(), AllocateMemoryFor::Dst, engine);
}
@@ -142,7 +142,7 @@ size_t DnnlConvolutionPrimitive::Key::hash() const {
seed = hash_combine(seed, get_attr_hash(*attr.get()));
seed = hash_combine(seed, fcSemantic);
- seed = hash_combine(seed, nonConstantWeights);
+ seed = hash_combine(seed, constantWeights);
return seed;
}
@@ -168,7 +168,7 @@ bool DnnlConvolutionPrimitive::Key::operator==(const Key& rhs) const {
result = result && *attr.get() == *rhs.attr.get();
result = result && fcSemantic == rhs.fcSemantic;
- result = result && nonConstantWeights == rhs.nonConstantWeights;
+ result = result && constantWeights == rhs.constantWeights;
return result;
}
@@ -858,7 +858,7 @@ std::shared_ptr<DnnlConvolutionPrimitive> DnnlConvolutionPrimitive::create(
paddingR,
shapeAgnosticData->m_primAttrs.attr,
attrs.fcSemantic,
- attrs.nonConstantWeights};
+ attrs.constantWeights};
const auto defaultImplType = shapeAgnosticData->m_implType;
@@ -879,8 +879,18 @@ std::shared_ptr<DnnlConvolutionPrimitive> DnnlConvolutionPrimitive::create(
DnnlMemoryDescPtr DnnlConvolutionPrimitive::makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed) {
- return DnnlFCPrimitive::makeTransposedWeightDescriptor(srcDesc, dstDesc, weightsNonTransposed);
+ const ConvAttrs& attrs) {
+ FCAttrs fcAttrs{};
+ fcAttrs.withBias = attrs.withBias;
+ fcAttrs.weightsNonTransposed = attrs.weightsNonTransposed;
+
+ return DnnlFCPrimitive::makeTransposedWeightDescriptor(srcDesc, dstDesc, fcAttrs);
+}
+
+DnnlMemoryDescPtr DnnlConvolutionPrimitive::makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
+ const DnnlMemoryDescPtr& dstDesc,
+ const FCAttrs& attrs) {
+ return DnnlFCPrimitive::makeTransposedWeightDescriptor(srcDesc, dstDesc, attrs);
}
std::tuple<size_t, size_t, size_t, size_t> DnnlConvolutionPrimitive::getChannelParams(const ConvConfig& config) {
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.hpp
index 8c2eeaad923..2f80c0c8460 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_convolution_primitive.hpp
@@ -40,8 +40,8 @@ class DnnlConvolutionPrimitive {
dnnl::primitive_attr attr;
- bool fcSemantic;
- bool nonConstantWeights;
+ bool fcSemantic = false;
+ bool constantWeights = true;
[[nodiscard]] size_t hash() const;
bool operator==(const Key& rhs) const;
@@ -92,7 +92,11 @@ public:
static DnnlMemoryDescPtr makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed);
+ const ConvAttrs& attrs);
+
+ static DnnlMemoryDescPtr makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
+ const DnnlMemoryDescPtr& dstDesc,
+ const FCAttrs& attrs);
static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const ConvAttrs& attrs,
const MemoryArgs& memory,
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_executor.hpp
similarity index 97%
rename from src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp
rename to src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_executor.hpp
index 531a6f22eaf..bd040548910 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_executor.hpp
@@ -126,7 +126,7 @@ private:
const PrimitivePtr currentPrimitive,
const PrimitivePtr newPrimitive,
const MemoryPtr& memory) {
- if (m_attrs.nonConstantWeights) { // non constant weights are handled by the primitive
+ if (!m_attrs.constantWeights) { // non constant weights are handled by the primitive
m_primArgs[DNNL_ARG_WEIGHTS] = memory->getPrimitive();
return;
}
@@ -137,8 +137,7 @@ private:
return;
}
- originalMemDesc =
- Primitive::makeTransposedWeightDescriptor(originalMemDesc, newPrimMemDesc, m_attrs.weightsNonTransposed);
+ originalMemDesc = Primitive::makeTransposedWeightDescriptor(originalMemDesc, newPrimMemDesc, m_attrs);
const auto weiMemory = utils::prepareWeightsMemory(originalMemDesc, newPrimMemDesc, memory, m_context, true);
m_primArgs[DNNL_ARG_WEIGHTS] = weiMemory->getPrimitive();
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.cpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.cpp
index 6308dc5b716..80eb97a4ced 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.cpp
@@ -120,8 +120,8 @@ std::shared_ptr<DnnlFCPrimitive> DnnlFCPrimitive::create(const MemoryArgs& memor
DnnlMemoryDescPtr DnnlFCPrimitive::makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
[[maybe_unused]] const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed) {
- if (!weightsNonTransposed) {
+ const FCAttrs& attrs) {
+ if (!attrs.weightsNonTransposed) {
return srcDesc;
}
@@ -446,7 +446,7 @@ DnnlShapeAgnosticDataPtr DnnlFCPrimitive::createShapeAgnosticData(const FCAttrs&
const auto weightsDesc = DnnlExtensionUtils::makeDescriptor(primDesc.weights_desc());
auto originalWeightsDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weiDesc);
- originalWeightsDesc = makeTransposedWeightDescriptor(originalWeightsDesc, weightsDesc, attrs.weightsNonTransposed);
+ originalWeightsDesc = makeTransposedWeightDescriptor(originalWeightsDesc, weightsDesc, attrs);
// ignore the result since we just need to put the packed weights into the cache
(void)utils::prepareWeightsMemory(originalWeightsDesc,
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp
index cafd80d696a..ed381da5559 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp
@@ -72,7 +72,7 @@ public:
static DnnlMemoryDescPtr makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed);
+ const FCAttrs& attrs);
static std::shared_ptr<DnnlFCPrimitive> create(const MemoryArgs& memory,
const FCAttrs& attrs,
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.cpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.cpp
index 404bdff3c4d..e4695ad7e2d 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.cpp
@@ -12,6 +12,7 @@
#include <common/primitive_hashing_utils.hpp>
#include <common/utils.hpp>
#include <cstddef>
+#include <iterator>
#include <memory>
#include <oneapi/dnnl/dnnl.hpp>
#include <oneapi/dnnl/dnnl_common.hpp>
@@ -24,6 +25,7 @@
#include "dnnl_postops_composer.h"
#include "dnnl_utils.hpp"
#include "memory_desc/cpu_memory_desc_utils.h"
+#include "memory_desc/dnnl_blocked_memory_desc.h"
#include "memory_desc/dnnl_memory_desc.h"
#include "nodes/executors/dnnl/dnnl_aliases.hpp"
#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"
@@ -63,6 +65,10 @@ size_t DnnlMatMulPrimitive::Key::hash() const {
}
seed = hash_combine(seed, get_attr_hash(*attr.get()));
+ seed = hash_combine(seed, implType);
+ seed = hash_combine(seed, transposeA);
+ seed = hash_combine(seed, transposeB);
+ seed = hash_combine(seed, fcSemantic);
return seed;
}
@@ -83,7 +89,8 @@ bool DnnlMatMulPrimitive::Key::operator==(const Key& rhs) const {
result = result && dst && rhs.dst && dst->getDnnlDesc() == rhs.dst->getDnnlDesc();
}
- result = result && *attr.get() == *rhs.attr.get();
+ result = result && *attr.get() == *rhs.attr.get() && implType == rhs.implType && fcSemantic == rhs.fcSemantic &&
+ transposeA == rhs.transposeA && transposeB == rhs.transposeB;
return result;
}
@@ -107,7 +114,7 @@ static dimsType normalizeToRank(const dimsType& vec, size_t rank) {
}
std::shared_ptr<DnnlMatMulPrimitive> DnnlMatMulPrimitive::create(const MemoryArgs& memory,
- [[maybe_unused]] const MatMulAttrs& attrs,
+ const MatMulAttrs& attrs,
const ExecutorContext::CPtr context,
const DnnlShapeAgnosticDataPtr& shapeAgnosticData) {
const auto& srcDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_SRC)->getDescPtr());
@@ -115,10 +122,23 @@ std::shared_ptr<DnnlMatMulPrimitive> DnnlMatMulPrimitive::create(const MemoryArg
const auto& biaDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_BIAS)->getDescPtr());
const auto& dstDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_DST)->getDescPtr());
- Key dnnlMatMulKey{srcDesc, weiDesc, biaDesc, dstDesc, shapeAgnosticData->m_primAttrs.attr};
-
- auto builder = [&context](const Key& dnnlKey) {
- return std::make_shared<DnnlMatMulPrimitive>(dnnlKey, context->getEngine(), context->getImplPriorities());
+ Key dnnlMatMulKey{srcDesc,
+ weiDesc,
+ biaDesc,
+ dstDesc,
+ shapeAgnosticData->m_primAttrs.attr,
+ shapeAgnosticData->m_implType,
+ attrs.transposeA,
+ attrs.transposeB,
+ attrs.fcSemantic};
+
+ const auto defaultImplType = shapeAgnosticData->m_implType;
+
+ auto builder = [&context, defaultImplType](const Key& dnnlKey) {
+ return std::make_shared<DnnlMatMulPrimitive>(dnnlKey,
+ context->getEngine(),
+ context->getImplPriorities(),
+ defaultImplType);
};
auto runtimeCache = context->getRuntimeCache();
@@ -131,21 +151,27 @@ std::shared_ptr<DnnlMatMulPrimitive> DnnlMatMulPrimitive::create(const MemoryArg
DnnlMemoryDescPtr DnnlMatMulPrimitive::makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed) {
+ const MatMulAttrs& attrs) {
+ if (!attrs.fcSemantic) {
+ return dstDesc;
+ }
+
+ const bool weightsNonTransposed = attrs.weightsNonTransposed;
const auto& weiDesc = srcDesc->getDnnlDesc();
auto wDims = weiDesc.get_dims();
- auto wDataType = weiDesc.get_data_type();
std::swap(wDims[wDims.size() - 1], wDims[wDims.size() - 2]);
- dnnl::memory::dims wDims2D = reshapeDownToRank<2>(wDims);
+ const dnnl::memory::dims wDims2D = reshapeDownToRank<2>(wDims);
const auto format = weightsNonTransposed ? dnnl::memory::format_tag::ab : dnnl::memory::format_tag::ba;
+ const auto wDataType = weiDesc.get_data_type();
const auto transposedWeiDesc = dnnl::memory::desc{wDims2D, wDataType, format};
+
const auto reshapedWeiDesc = transposedWeiDesc.reshape(dstDesc->getDnnlDesc().get_dims());
return DnnlExtensionUtils::makeDescriptor(reshapedWeiDesc);
}
-static DnnlPrimitiveAttrs createPrimitiveAttrs(const PostOps& postOps,
+static DnnlPrimitiveAttrs createPrimitiveAttrs(const MatMulAttrs& attrs,
const MemoryArgs& memory,
const ExecutorContext::CPtr& context,
bool useWeightsDecompression,
@@ -161,8 +187,19 @@ static DnnlPrimitiveAttrs createPrimitiveAttrs(const PostOps& postOps,
any_of(srcDesc->getPrecision(), ov::element::u8, ov::element::i8) && weiDesc->getPrecision() == ov::element::i8;
auto outputDataType = DnnlExtensionUtils::ElementTypeToDataType(dstDesc->getPrecision());
- DnnlPostOpsComposer
- dnnlpoc(postOps, context->getEngine(), dims, dims.size() - 1, isINT8, 1 << 0, memory, outputDataType);
+ DnnlPostOpsComposer dnnlpoc(attrs.postOps,
+ context->getEngine(),
+ dims,
+ dims.size() - 1,
+ isINT8,
+ 1 << 0,
+ memory,
+ outputDataType,
+ attrs.dqScales);
+
+ if (memory.count(ARG_WEI | ARG_ATTR_SCALES) == 0U) {
+ return dnnlpoc.compose();
+ }
const auto maxRank =
std::max({srcDesc->getShape().getRank(), weiDesc->getShape().getRank(), dstDesc->getShape().getRank()});
@@ -187,13 +224,13 @@ static DnnlPrimitiveAttrs createPrimitiveAttrs(const PostOps& postOps,
return primAttrs;
}
-static dnnl::matmul::primitive_desc createDescriptorInternal(const dnnl::memory::desc& inputDesc,
- const dnnl::memory::desc& weightDesc,
- const dnnl::memory::desc& biasDesc,
- const dnnl::memory::desc& outputDesc,
- const dnnl::primitive_attr& attr,
- const dnnl::engine& engine,
- const bool useWeightsDecompression) {
+static dnnl::matmul::primitive_desc createDescriptorInternalAsFc(const dnnl::memory::desc& inputDesc,
+ const dnnl::memory::desc& weightDesc,
+ const dnnl::memory::desc& biasDesc,
+ const dnnl::memory::desc& outputDesc,
+ const dnnl::primitive_attr& attr,
+ const dnnl::engine& engine,
+ const bool useWeightsDecompression) {
auto weiDims = weightDesc.get_dims();
std::swap(weiDims[weiDims.size() - 1], weiDims[weiDims.size() - 2]);
@@ -221,6 +258,41 @@ static dnnl::matmul::primitive_desc createDescriptorInternal(const dnnl::memory:
return {engine, inputsDesc, weightsDesc, newBiasDesc, outputsDesc, attr};
}
+static dnnl::matmul::primitive_desc createDescriptorInternal(const dnnl::memory::desc& inputDesc,
+ const dnnl::memory::desc& weightDesc,
+ const dnnl::memory::desc& biasDesc,
+ const dnnl::memory::desc& outputDesc,
+ const dnnl::primitive_attr& attr,
+ const dnnl::engine& engine,
+ const bool transposeA,
+ const bool transposeB) {
+ auto transposeDesc = [](const dnnl::memory::desc& md) {
+ auto dims = md.get_dims();
+ if (dims.size() < 2) {
+ return md;
+ }
+
+ auto strides = md.get_strides();
+ std::swap(dims[dims.size() - 1], dims[dims.size() - 2]);
+ std::swap(strides[strides.size() - 1], strides[strides.size() - 2]);
+
+ return dnnl::memory::desc(dims, md.get_data_type(), strides);
+ };
+
+ const dnnl::memory::desc& inputDescToUse = transposeA ? transposeDesc(inputDesc) : inputDesc;
+ const dnnl::memory::desc& weightDescToUse = transposeB ? transposeDesc(weightDesc) : weightDesc;
+
+ const size_t biasRank = biasDesc.get_ndims();
+ const size_t outputRank = outputDesc.get_ndims();
+ const dnnl::memory::desc& biasDescToUse = biasRank == outputRank
+ ? biasDesc
+ : dnnl::memory::desc(normalizeToRank(biasDesc.get_dims(), outputRank),
+ biasDesc.get_data_type(),
+ memory::format_tag::any);
+
+ return {engine, inputDescToUse, weightDescToUse, biasDescToUse, outputDesc, attr};
+}
+
static primitive_desc createPrimitiveDesc(const dnnl::memory::desc& inputDesc,
const dnnl::memory::desc& weightDesc,
const dnnl::memory::desc& biasDesc,
@@ -228,16 +300,64 @@ static primitive_desc createPrimitiveDesc(const dnnl::memory::desc& inputDesc,
const dnnl::primitive_attr& attr,
const dnnl::engine& engine,
const std::vector<impl_desc_type>& implPriorities,
+ const impl_desc_type defaultImplType,
+ const bool transposeA,
+ const bool transposeB,
[[maybe_unused]] const bool useSparseWeights,
- const bool useWeightsDecompression) {
- auto prim_desc =
- createDescriptorInternal(inputDesc, weightDesc, biasDesc, outputDesc, attr, engine, useWeightsDecompression);
+ const bool useWeightsDecompression,
+ const bool fcSemantic) {
+ if (defaultImplType == impl_desc_type::undef) {
+ struct PrimitiveDescWithPriority {
+ dnnl::primitive_desc prim_desc;
+ size_t priority = 0UL;
+ };
+
+ PrimitiveDescWithPriority prim_desc_w_priority{dnnl::primitive_desc(), implPriorities.size()};
+ const bool first_match = implPriorities.front() == impl_desc_type::unknown;
+
+ auto cur_desc =
+ createDescriptorInternal(inputDesc, weightDesc, biasDesc, outputDesc, attr, engine, transposeA, transposeB);
+
+ DnnlExtensionUtils::for_each_implementation(
+ cur_desc,
+ first_match,
+ [&](impl_desc_type implType) { // is acceptable implementation
+ return contains(implPriorities, implType);
+ },
+ [&](dnnl::primitive_desc& desc) { // is implementation with highest priority
+ const impl_desc_type descImplType = parse_impl_name(desc.impl_info_str());
+ const auto it = std::find(implPriorities.begin(), implPriorities.end(), descImplType);
+ const size_t priorityId = std::distance(implPriorities.begin(), it);
+ const size_t highestPriority = prim_desc_w_priority.priority;
+ if (priorityId < highestPriority) {
+ auto desc_copy = dnnl::primitive_desc(DnnlExtensionUtils::clone_primitive_desc(desc.get(true)));
+ prim_desc_w_priority = {desc_copy, priorityId};
+ }
+ });
+
+ return prim_desc_w_priority.prim_desc;
+ }
+
+ auto prim_desc = fcSemantic ? createDescriptorInternalAsFc(inputDesc,
+ weightDesc,
+ biasDesc,
+ outputDesc,
+ attr,
+ engine,
+ useWeightsDecompression)
+ : createDescriptorInternal(inputDesc,
+ weightDesc,
+ biasDesc,
+ outputDesc,
+ attr,
+ engine,
+ transposeA,
+ transposeB);
+
OPENVINO_ASSERT(prim_desc, "Failed to create matmul primitive descriptor");
auto first_desc = dnnl::matmul::primitive_desc(prim_desc.get());
- const bool found = DnnlExtensionUtils::find_implementation(prim_desc, [&](impl_desc_type implType) {
- return any_of_values(implPriorities, implType);
- });
+ const bool found = DnnlExtensionUtils::find_implementation(prim_desc, defaultImplType);
if (found) {
return std::move(prim_desc);
@@ -246,32 +366,108 @@ static primitive_desc createPrimitiveDesc(const dnnl::memory::desc& inputDesc,
return std::move(first_desc);
}
-static VectorDims makeDummyInputDims(const Shape& inShape, const Shape& wShape) {
- const auto& weightDims = wShape.getStaticDims();
+static std::pair<VectorDims, VectorDims> makeDummyInputDims(const Shape& in0,
+ const Shape& in1,
+ const Shape& out,
+ bool transposeA,
+ bool transposeB) {
+ OPENVINO_ASSERT(in0.getRank() >= 2 && in1.getRank() >= 2, "Can't create dummy inputs with rank less 2");
+ OPENVINO_ASSERT((in0.getRank() == in1.getRank()) && (in1.getRank() == out.getRank()),
+ "Can't create dummy inputs if argument shapes ranks are not equal");
+
+ auto swapTranspDims = [&](VectorDims& in0, VectorDims& in1) {
+ if (transposeA) {
+ std::swap(in0[in0.size() - 1], in0[in0.size() - 2]);
+ }
+ if (transposeB) {
+ std::swap(in1[in1.size() - 1], in1[in1.size() - 2]);
+ }
+ };
+
+ auto inDims0 = in0.getDims();
+ auto inDims1 = in1.getDims();
+ auto outDims = out.getDims();
+
+ auto minDims0 = in0.getMinDims();
+ auto maxDims0 = in0.getMaxDims();
+ auto minDims1 = in1.getMinDims();
+ auto maxDims1 = in1.getMaxDims();
+
+ swapTranspDims(inDims0, inDims1);
+ swapTranspDims(minDims0, minDims1);
+ swapTranspDims(maxDims0, maxDims1);
+
+ auto fillDummy = [&](size_t idx0, size_t idx1) {
+ if (inDims0[idx0] == Shape::UNDEFINED_DIM && inDims1[idx1] == Shape::UNDEFINED_DIM) {
+ inDims0[idx0] = inDims1[idx1] = std::min(std::min(maxDims0[idx0], maxDims1[idx1]),
+ std::max(std::max(minDims0[idx0], minDims1[idx1]),
+ static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
+ } else {
+ if (inDims0[idx0] == Shape::UNDEFINED_DIM && inDims1[idx1] != Shape::UNDEFINED_DIM) {
+ if (inDims1[idx1] == 1 && minDims0[idx0] != Shape::UNDEFINED_DIM) {
+ inDims0[idx0] = std::max<Dim>(minDims0[idx0], 1);
+ } else {
+ inDims0[idx0] = inDims1[idx1];
+ }
+ } else if (inDims0[idx0] != Shape::UNDEFINED_DIM && inDims1[idx1] == Shape::UNDEFINED_DIM) {
+ if (inDims0[idx0] == 1 && minDims1[idx1] != Shape::UNDEFINED_DIM) {
+ inDims1[idx1] = std::max<Dim>(minDims1[idx1], 1);
+ } else {
+ inDims1[idx1] = inDims0[idx0];
+ }
+ }
+ }
+ };
+
+ // fill k
+ fillDummy(inDims0.size() - 1, inDims1.size() - 2);
- auto inMinDims = inShape.getMinDims();
- auto inMaxDims = inShape.getMaxDims();
- inMinDims.back() = weightDims.back();
- inMaxDims.back() = weightDims.back();
+ // fill m, n
+ if (outDims[outDims.size() - 2] != Shape::UNDEFINED_DIM) {
+ inDims0[inDims0.size() - 2] = outDims[outDims.size() - 2];
+ } else if (inDims0[inDims0.size() - 2] == Shape::UNDEFINED_DIM) {
+ inDims0[inDims0.size() - 2] =
+ std::min(maxDims0[inDims0.size() - 2],
+ std::max(minDims0[inDims0.size() - 2], static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
+ }
- return MemoryDescUtils::makeDummyShape(Shape(inMinDims, inMaxDims)).getStaticDims();
+ if (outDims[outDims.size() - 1] != Shape::UNDEFINED_DIM) {
+ inDims1[inDims1.size() - 1] = outDims[outDims.size() - 1];
+ } else if (inDims1[inDims1.size() - 1] == Shape::UNDEFINED_DIM) {
+ inDims1[inDims1.size() - 1] =
+ std::min(maxDims1[inDims1.size() - 1],
+ std::max(minDims1[inDims1.size() - 1], static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
+ }
+
+ // fill batches
+ for (size_t i = 0; i < inDims0.size() - 2; i++) {
+ if (outDims[i] != Shape::UNDEFINED_DIM) {
+ inDims0[i] = outDims[i];
+ inDims1[i] = outDims[i];
+ } else {
+ fillDummy(i, i);
+ }
+ }
+
+ swapTranspDims(inDims0, inDims1);
+
+ return {inDims0, inDims1};
}
-static VectorDims makeDummyOutputDims(const VectorDims& inShape, const VectorDims& wShape, const size_t out_rank) {
- size_t activationRank = inShape.size();
- size_t channelRank = wShape.size() - 1;
- // activation weight output_shape
- // NCHW CoCHW NCo
- // TNC CoC TNCo
- // NC CoC NCo
- VectorDims outputShape(out_rank, 1);
- // set Co
- outputShape.back() = wShape[0];
- // set batch dims
- size_t batchRank = activationRank - channelRank;
- size_t startIdx = out_rank - batchRank - 1;
- for (size_t i = 0; i < batchRank; i++) {
- outputShape[i + startIdx] = inShape[i];
+static VectorDims makeDummyOutputDims(const VectorDims& inShape0,
+ const VectorDims& inShape1,
+ bool transposeA,
+ bool transposeB,
+ const size_t outRank) {
+ VectorDims outputShape(outRank, 1);
+ const size_t inRank0 = inShape0.size();
+ const size_t inRank1 = inShape1.size();
+ // fill m, n
+ outputShape[outRank - 2] = transposeA ? inShape0[inRank0 - 1] : inShape0[inRank0 - 2];
+ outputShape[outRank - 1] = transposeB ? inShape1[inRank1 - 2] : inShape1[inRank1 - 1];
+
+ for (size_t i = 0; i < outRank - 2; i++) {
+ outputShape[i] = std::max(inShape0[i], inShape1[i]);
}
return outputShape;
@@ -288,32 +484,44 @@ bool DnnlMatMulPrimitive::useWeightsDecompressionImpl(const ov::element::Type in
return (any_of(inputType, f32, bf16, f16) && any_of(weightsType, u8, i8, u4, i4));
}
-DnnlShapeAgnosticDataPtr DnnlMatMulPrimitive::createShapeAgnosticData(const FCAttrs& attrs,
+DnnlShapeAgnosticDataPtr DnnlMatMulPrimitive::createShapeAgnosticData(const FCAttrs& fcAttrs,
+ const MemoryArgs& memory,
+ const ExecutorContext::CPtr& context,
+ const bool cacheWeights) {
+ MatMulAttrs attrs;
+ attrs.postOps = fcAttrs.postOps;
+ attrs.weightsNonTransposed = fcAttrs.weightsNonTransposed;
+
+ return createShapeAgnosticData(attrs, memory, context, cacheWeights);
+}
+
+DnnlShapeAgnosticDataPtr DnnlMatMulPrimitive::createShapeAgnosticData(const MatMulAttrs& attrs,
const MemoryArgs& memory,
const ExecutorContext::CPtr& context,
const bool cacheWeights) {
DEBUG_LOG("Creating shape agnostic data");
auto srcDesc = memory.at(ARG_SRC)->getDescPtr();
- const auto& weiDesc = memory.at(ARG_WEI)->getDescPtr();
- const auto& biasDesc = memory.at(ARG_BIAS)->getDescPtr();
+ auto weiDesc = memory.at(ARG_WEI)->getDescPtr();
auto dstDesc = memory.at(ARG_DST)->getDescPtr();
+ const auto& biasDesc = memory.at(ARG_BIAS)->getDescPtr();
const auto useWeightsDecompression = useWeightsDecompressionImpl(srcDesc->getPrecision(), weiDesc->getPrecision());
const auto postOpData =
- createPrimitiveAttrs(attrs.postOps, memory, context, useWeightsDecompression, attrs.weightsNonTransposed);
-
- if (!cacheWeights) {
- return std::make_shared<DnnlShapeAgnosticData>(postOpData);
- }
-
- if (srcDesc->getShape().isDynamic()) {
- const auto& inShape = srcDesc->getShape();
- const auto& wShape = weiDesc->getShape();
- const auto& inDymmyDims = makeDummyInputDims(inShape, wShape);
- srcDesc = srcDesc->cloneWithNewDims(inDymmyDims);
- const auto& outDymmyDims =
- makeDummyOutputDims(inDymmyDims, wShape.getStaticDims(), dstDesc->getShape().getRank());
- dstDesc = dstDesc->cloneWithNewDims(outDymmyDims);
+ createPrimitiveAttrs(attrs, memory, context, useWeightsDecompression, attrs.weightsNonTransposed);
+
+ if (srcDesc->getShape().isDynamic() || weiDesc->getShape().isDynamic()) {
+ const auto& srcShape = srcDesc->getShape();
+ const auto& weiShape = weiDesc->getShape();
+ const auto& [inDymmyDims, weiDymmyDims] =
+ makeDummyInputDims(srcShape, weiShape, dstDesc->getShape(), attrs.transposeA, attrs.transposeB);
+ const auto& outDymmyDims = makeDummyOutputDims(inDymmyDims,
+ weiDymmyDims,
+ attrs.transposeA,
+ attrs.transposeB,
+ dstDesc->getShape().getRank());
+ srcDesc = std::make_shared<DnnlBlockedMemoryDesc>(srcDesc->getPrecision(), Shape(inDymmyDims));
+ weiDesc = std::make_shared<DnnlBlockedMemoryDesc>(weiDesc->getPrecision(), Shape(weiDymmyDims));
+ dstDesc = std::make_shared<DnnlBlockedMemoryDesc>(dstDesc->getPrecision(), Shape(outDymmyDims));
}
const dnnl::memory::desc srcDnnlDesc = MemoryDescUtils::convertToDnnlMemoryDesc(srcDesc)->getDnnlDesc();
@@ -328,17 +536,28 @@ DnnlShapeAgnosticDataPtr DnnlMatMulPrimitive::createShapeAgnosticData(const FCAt
postOpData.attr,
context->getEngine(),
context->getImplPriorities(),
+ impl_desc_type::undef,
+ attrs.transposeA,
+ attrs.transposeB,
false,
- useWeightsDecompression);
+ useWeightsDecompression,
+ attrs.fcSemantic);
+
+ if (attrs.constantWeights && cacheWeights) {
+ const auto weightsDesc = DnnlExtensionUtils::makeDescriptor(primDesc.weights_desc());
+ auto originalWeightsDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weiDesc);
- const auto weightsDesc = DnnlExtensionUtils::makeDescriptor(primDesc.weights_desc());
- auto originalWeightsDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weiDesc);
- originalWeightsDesc = makeTransposedWeightDescriptor(originalWeightsDesc, weightsDesc, attrs.weightsNonTransposed);
+ if (attrs.fcSemantic) {
+ originalWeightsDesc = makeTransposedWeightDescriptor(originalWeightsDesc, weightsDesc, attrs);
+ }
+
+ // ignore the result since we just need to put the packed weights into the cache
+ (void)utils::prepareWeightsMemory(originalWeightsDesc, weightsDesc, memory.at(ARG_WEI), context);
+ }
- // ignore the result since we just need to put the packed weights into the cache
- (void)utils::prepareWeightsMemory(originalWeightsDesc, weightsDesc, memory.at(ARG_WEI), context);
+ const auto defaultImpType = parse_impl_name(primDesc.impl_info_str());
- return std::make_shared<DnnlShapeAgnosticData>(postOpData);
+ return std::make_shared<DnnlShapeAgnosticData>(postOpData, defaultImpType);
}
static impl_desc_type implTypeFromPrimDesc(const dnnl::primitive_desc& primDesc) {
@@ -353,7 +572,8 @@ static impl_desc_type implTypeFromPrimDesc(const dnnl::primitive_desc& primDesc)
DnnlMatMulPrimitive::DnnlMatMulPrimitive(const Key& key,
const dnnl::engine& engine,
- const std::vector<impl_desc_type>& implPriorities)
+ const std::vector<impl_desc_type>& implPriorities,
+ const impl_desc_type defaultImplType)
: m_stream(dnnl::stream(engine)),
m_primDesc(createPrimitiveDesc(key.src->getDnnlDesc(),
key.wei->getDnnlDesc(),
@@ -362,8 +582,12 @@ DnnlMatMulPrimitive::DnnlMatMulPrimitive(const Key& key,
key.attr,
engine,
implPriorities,
+ defaultImplType,
+ key.transposeA,
+ key.transposeB,
false,
- useWeightsDecompressionImpl(key.src->getPrecision(), key.wei->getPrecision()))),
+ useWeightsDecompressionImpl(key.src->getPrecision(), key.wei->getPrecision()),
+ key.fcSemantic)),
m_implType(implTypeFromPrimDesc(m_primDesc)),
m_srcDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.src_desc())),
m_weiDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.weights_desc())),
diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.hpp
index 18eae7135e9..826e13e8ee3 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_matmul_primitive.hpp
@@ -29,13 +29,20 @@ class DnnlMatMulPrimitive {
DnnlMemoryDescCPtr bias;
DnnlMemoryDescCPtr dst;
dnnl::primitive_attr attr;
+ impl_desc_type implType;
+ bool transposeA = false;
+ bool transposeB = false;
+ bool fcSemantic = false;
[[nodiscard]] size_t hash() const;
bool operator==(const Key& rhs) const;
};
public:
- DnnlMatMulPrimitive(const Key& key, const dnnl::engine& engine, const std::vector<impl_desc_type>& implPriorities);
+ DnnlMatMulPrimitive(const Key& key,
+ const dnnl::engine& engine,
+ const std::vector<impl_desc_type>& implPriorities,
+ impl_desc_type defaultImplType);
void execute(const dnnl_primitive_args& primArgs) const;
@@ -61,14 +68,19 @@ public:
static bool useWeightsDecompressionImpl(ov::element::Type inputType, ov::element::Type weightsType);
- static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const FCAttrs& attrs,
+ static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const MatMulAttrs& attrs,
+ const MemoryArgs& memory,
+ const ExecutorContext::CPtr& context,
+ bool cacheWeights);
+
+ static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const FCAttrs& fcAttrs,
const MemoryArgs& memory,
const ExecutorContext::CPtr& context,
bool cacheWeights);
static DnnlMemoryDescPtr makeTransposedWeightDescriptor(const DnnlMemoryDescPtr& srcDesc,
const DnnlMemoryDescPtr& dstDesc,
- bool weightsNonTransposed);
+ const MatMulAttrs& attrs);
static std::shared_ptr<DnnlMatMulPrimitive> create(const MemoryArgs& memory,
const MatMulAttrs& attrs,
diff --git a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp
index b167cd3b243..3f5c8db44bc 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp
@@ -83,10 +83,14 @@ public:
* - Simple Executor, if there is only one available implementation
*
* @param memory memory arguments.
+ * @param initVariableExecutor whether to init first available implementation of variable executor or not.
+ * This option is mostly a workaround at the moment.
+ * In general it might be beneficial to initialize all the shape dependent implementations
+ * of the variable executor in advance to avoid first-time call delays.
*
* @return A shared pointer to the created Executor.
*/
- ExecutorPtr make(const MemoryArgs& memory) {
+ ExecutorPtr make(const MemoryArgs& memory, bool initVariableExecutor = true) {
std::vector<ExecutorImplementationRef> implementations;
auto acceptsConfig = [](const ExecutorImplementationRef& impl, const executor::Config<Attrs>& config) {
@@ -121,7 +125,11 @@ public:
return theOnlyImplementation.create(m_attrs, memory, m_context);
}
- return std::make_shared<VariableExecutor<Attrs>>(memory, m_attrs, m_context, implementations);
+ return std::make_shared<VariableExecutor<Attrs>>(memory,
+ m_attrs,
+ m_context,
+ implementations,
+ initVariableExecutor);
}
private:
diff --git a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp
index 03bda050cc2..834c243ce0a 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp
@@ -20,7 +20,7 @@ struct FCAttrs {
bool weightsNonTransposed = false;
bool sparseWeights = false;
uint64_t dynamicQuantizationGroupSize = 0;
- bool nonConstantWeights = false;
+ bool constantWeights = true;
ov::intel_cpu::Config::ModelType modelType = ov::intel_cpu::Config::ModelType::Unknown;
diff --git a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp
index b7b65797138..e1c2122c7d8 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp
@@ -11,7 +11,7 @@
#include "implementation_utils.hpp"
#include "memory_desc/cpu_memory_desc.h"
#include "nodes/executors/convolution_config.hpp"
-#include "nodes/executors/dnnl/dnnl_fullyconnected.hpp"
+#include "nodes/executors/dnnl/dnnl_executor.hpp"
#include "nodes/executors/dnnl/dnnl_fullyconnected_primitive.hpp"
#include "nodes/executors/dnnl/dnnl_matmul_primitive.hpp"
#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"
@@ -277,7 +277,7 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {
ConvAttrs convAttrs{{1}, {0}, {0}, {0},
AutoPaddingType::None, attrs.withBias, attrs.weightsNonTransposed,
false, false, fcSemantic, false, ZeroPointsType::None, {}, attrs.postOps};
-
+
auto primitive =
DefaultInstantiator<DnnlConvolutionPrimitive, ConvAttrs, DnnlShapeAgnosticData>{}(
memory,
@@ -285,10 +285,11 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {
context,
shareAgnosticData);
+ // only brgconv_avx512_1x1 primitive is acceptable from the performance perspective
if (!primitive || primitive->implType() != brgconv_avx512_1x1) {
- // only brgconv_avx512_1x1 primitive is acceptable from the performance perspective
return nullptr;
}
+
return primitive;
}
};
@@ -417,27 +418,16 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {
[](const FCAttrs& attrs,
const MemoryArgs& memory,
const ExecutorContext::CPtr& context) -> ExecutorPtr {
- struct MatMulInstantiator {
- std::shared_ptr<DnnlMatMulPrimitive> operator()(
- const MemoryArgs& memory,
- [[maybe_unused]] const FCAttrs& attrs,
- const ExecutorContext::CPtr& context,
- const std::shared_ptr<DnnlShapeAgnosticData>& shareAgnosticData) const {
- MatMulAttrs matMulAttrs{false,
- false};
- auto primitive =
- DefaultInstantiator<DnnlMatMulPrimitive, MatMulAttrs, DnnlShapeAgnosticData>{}(
- memory,
- matMulAttrs,
- context,
- shareAgnosticData);
- return primitive;
- }
- };
-
+ MatMulAttrs matMulAttrs{false,
+ false};
+ matMulAttrs.postOps = attrs.postOps;
+ matMulAttrs.transposeB = attrs.weightsNonTransposed;
+ matMulAttrs.constantWeights = true;
+
return std::make_shared<
- DnnlExecutor<DnnlMatMulPrimitive, FCAttrs, DnnlShapeAgnosticData, MatMulInstantiator>>(
- attrs,
+ DnnlExecutor<DnnlMatMulPrimitive, MatMulAttrs, DnnlShapeAgnosticData,
+ DefaultInstantiator<DnnlMatMulPrimitive, MatMulAttrs, DnnlShapeAgnosticData>>>(
+ matMulAttrs,
memory,
context,
false);
diff --git a/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp b/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp
index 3cbea3e6353..fb277a51164 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp
@@ -16,7 +16,7 @@
#include "memory_desc/dnnl_blocked_memory_desc.h"
#include "memory_format_filter.hpp"
#include "nodes/common/blocked_desc_creator.h"
-#include "nodes/executors/dnnl/dnnl_fullyconnected.hpp"
+#include "nodes/executors/dnnl/dnnl_executor.hpp"
#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"
#include "nodes/executors/executor.hpp"
#include "nodes/executors/executor_config.hpp"
diff --git a/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp b/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp
index 5ca24f153d1..4e8dd0c3e46 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/matmul_config.hpp"
namespace ov::intel_cpu {
@@ -27,11 +28,17 @@ const std::vector<ExecutorImplementation<Attrs>>& getImplementations() {
// FullyConnected
template <>
const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations();
+
// Convolution
template <>
const std::vector<ExecutorImplementation<ConvAttrs>>& getImplementations();
+
// Eltwise
template <>
const std::vector<ExecutorImplementation<EltwiseAttrs>>& getImplementations();
+// MatMul
+template <>
+const std::vector<ExecutorImplementation<MatMulAttrs>>& getImplementations();
+
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/matmul_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/matmul_config.hpp
index 9b2a69531a9..cba86fc1b65 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/matmul_config.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/matmul_config.hpp
@@ -4,13 +4,30 @@
#pragma once
+#include <cstdint>
+#include <vector>
+
#include "executor_config.hpp"
+#include "post_ops.hpp"
namespace ov::intel_cpu {
struct MatMulAttrs {
- bool transposeA;
- bool transposeB;
+ bool transposeA = false;
+ bool transposeB = false;
+ bool withBias = false;
+ bool weightsNonTransposed = false;
+ bool sparseWeights = false;
+ bool constantWeights = false;
+ bool fcSemantic = false;
+
+ uint64_t dynamicQuantizationGroupSize = 0;
+
+ // DQ scales for quantization
+ std::vector<float> dqScales;
+
+ // Post-operations for fused operations
+ PostOps postOps;
};
using MatMulConfig = executor::Config<MatMulAttrs>;
diff --git a/src/plugins/intel_cpu/src/nodes/executors/matmul_implementations.cpp b/src/plugins/intel_cpu/src/nodes/executors/matmul_implementations.cpp
new file mode 100644
index 00000000000..6eedcc18c5f
--- /dev/null
+++ b/src/plugins/intel_cpu/src/nodes/executors/matmul_implementations.cpp
@@ -0,0 +1,144 @@
+// Copyright (C) 2018-2025 Intel Corporation
+// SPDX-License-Identifier: Apache-2.0
+//
+
+#include <optional>
+#include <vector>
+
+#include "cpu/x64/cpu_isa_traits.hpp"
+#include "memory_desc/cpu_memory_desc.h"
+#include "nodes/executors/dnnl/dnnl_matmul_primitive.hpp"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/executor_config.hpp"
+#include "nodes/executors/executor_implementation.hpp"
+#include "nodes/executors/implementation_utils.hpp"
+#include "nodes/executors/implementations.hpp"
+#include "nodes/executors/matmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
+#include "nodes/executors/precision_matcher.hpp"
+#include "nodes/executors/precision_translation.hpp"
+#include "nodes/executors/type_mask.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/arch_macros.h"
+
+#ifdef OPENVINO_ARCH_X86_64
+# include <cstddef>
+
+# include "nodes/executors/x64/matmul_small.hpp"
+#endif
+
+namespace ov::intel_cpu {
+
+using namespace ov::element;
+using namespace TypeMaskAlias;
+using namespace executor;
+
+using LayoutConfig = std::vector<LayoutType>;
+static const LayoutConfig dnnlMatMulLayoutConfig{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 dnnlMatMulTypeMapping {
+ // {src, wei, bia, dst} pt<src, wei, bias, dst>
+ {{_bf16, _bf16 | _f32, _any, _bf16 | _f32}, {bypass(), bypass(), use<3>(), bypass()}},
+ {{_f16, _f16, _any, _f16 | _f32}, {bypass(), bypass(), use<3>(), bypass()}},
+ // integer precision outputs are not supported for float precision inputs
+ {{_f32 | _bf16 | _f16, _any, _any, _i8 | _u8}, {bypass(), bypass(), use<0>(), use<0>()}},
+ // compresses float weights which do not match input data precision
+ {{_f32, _half_float, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ {{_bf16, _f16, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ {{_f16, _bf16, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ // quantization configuration
+ {{_u8 | _i8, _i8, _u8|_i8|_i32|_bf16|_f16|_f32|_dynamic, _u8|_i8|_i32|_bf16|_f16|_f32}, {bypass(), bypass(), bypass(), bypass()}},
+ {{_u8 | _i8, _i8, _any, _any}, {bypass(), bypass(), just<f32>(), just<f32>()}},
+ // compresses int weights
+ {{_f32 | _bf16 | _f16, _u8 | _i8, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ // @todo should we fallback to FPXX instead of _f32?
+ {{_any, _any, _any, _any}, {just<f32>(), just<f32>(), just<f32>(), just<f32>()}},
+};
+
+#if defined(OV_CPU_WITH_ACL)
+static const TypeMapping aclMatMulTypeMapping {
+ // {src, wei, bia, dst} pt<src, wei, bias, dst>
+ {{_f32 | _f16, _f32 | _f16, _any, _any}, {bypass(), bypass(), use<0>(), use<0>()}},
+ {{_any, _any, _any, _any}, {just<f32>(), just<f32>(), just<f32>(), just<f32>()}}
+};
+#endif
+
+static const MappingNotation matmulMappingNotation {
+ {ARG_SRC, 0},
+ {ARG_WEI, 1},
+ {ARG_BIAS, 2},
+ {ARG_DST, 3}
+};
+
+// clang-format on
+struct CreateOptimalConfigDefault {
+ std::optional<MatMulConfig> operator()(const MatMulConfig& config) const {
+ return createOptimalConfigCommon(config, dnnlMatMulTypeMapping, dnnlMatMulLayoutConfig, matmulMappingNotation);
+ }
+};
+
+// clang-format off
+template <>
+const std::vector<ExecutorImplementation<MatMulAttrs>>& getImplementations() {
+ static const std::vector<ExecutorImplementation<MatMulAttrs>> matmulImplementations {
+ OV_CPU_INSTANCE_X64(
+ "matmul_small_x64",
+ ExecutorType::Jit,
+ OperationType::MatMul,
+ // supports
+ [](const MatMulConfig& config) -> bool {
+ return MatMulSmallExecutor::supports(config);
+ },
+ HasNoOptimalConfig<MatMulAttrs>{},
+ []([[maybe_unused]] const MatMulAttrs& attrs, const MemoryArgs& memory) -> bool {
+ const auto& srcDesc0 = memory.at(ARG_SRC)->getDescPtr();
+ const auto& srcDesc1 = memory.at(ARG_WEI)->getDescPtr();
+ const auto& srcShape0 = srcDesc0->getShape().getStaticDims();
+ const auto& srcShape1 = srcDesc1->getShape().getStaticDims();
+ const auto srcRank0 = srcShape0.size();
+ const auto srcRank1 = srcShape1.size();
+
+ for (size_t i = 0; i < srcRank0 - 2; i++) {
+ if (srcShape0[i] != srcShape1[i]) {
+ return false;
+ }
+ }
+
+ return (srcShape0[srcRank0 - 1] <= 2) && (srcShape0[srcRank0 - 2] <= 2) &&
+ (srcShape1[srcRank1 - 1] <= 2) && (srcShape1[srcRank1 - 2] <= 2);
+ },
+ CreateDefault<MatMulSmallExecutor, MatMulAttrs>{}
+ )
+ OV_CPU_INSTANCE_DNNL(
+ "matmul_dnnl",
+ ExecutorType::Dnnl,
+ OperationType::MatMul,
+ SupportsAnyConfig<MatMulAttrs>{},
+ // createOptimalConfig
+ [](const MatMulConfig& config) -> std::optional<executor::Config<MatMulAttrs>> {
+ return createOptimalConfigCommon(config,
+ dnnlMatMulTypeMapping,
+ dnnlMatMulLayoutConfig,
+ matmulMappingNotation);
+ },
+ AcceptsAnyShape<MatMulAttrs>,
+ CreateDnnlDefault<DnnlMatMulPrimitive, MatMulAttrs>{true, true}
+ )
+ };
+
+ return matmulImplementations;
+}
+// clang-format on
+
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp
index d1bc8670cde..d5c794501be 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp
@@ -29,17 +29,20 @@ class VariableExecutor : public Executor {
public:
using ExecutorImplementationRef = std::reference_wrapper<const ExecutorImplementation<Attrs>>;
- VariableExecutor(const MemoryArgs& memory,
+ VariableExecutor(const MemoryArgs& memory [[maybe_unused]],
Attrs attrs,
ExecutorContext::CPtr context,
- std::vector<ExecutorImplementationRef> suitableImplementations)
+ std::vector<ExecutorImplementationRef> suitableImplementations,
+ bool init)
: m_attrs(std::move(attrs)),
m_context(std::move(context)),
m_suitableImplementations(std::move(suitableImplementations)),
m_executors(m_suitableImplementations.size()) {
- const size_t implId = select(memory, 0);
- m_executors[implId] = create(implId, memory);
- m_implId = implId;
+ if (init) {
+ const size_t implId = select(memory, 0);
+ m_executors[implId] = create(implId, memory);
+ m_implId = implId;
+ }
}
bool update(const MemoryArgs& memory) override {
@@ -107,7 +110,7 @@ private:
std::vector<ExecutorImplementationRef> m_suitableImplementations;
// executors cache
std::vector<ExecutorPtr> m_executors;
- size_t m_implId;
+ size_t m_implId = 0;
};
} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.cpp b/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.cpp
index ca98038122c..7f5177081c8 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.cpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.cpp
@@ -13,69 +13,140 @@
#include <memory>
#include <numeric>
#include <oneapi/dnnl/dnnl.hpp>
-#include <oneapi/dnnl/dnnl_common.hpp>
#include <unordered_map>
-#include <utility>
#include "dnnl_extension_utils.h"
-#include "memory_desc/dnnl_memory_desc.h"
+#include "nodes/executors/debug_messages.hpp"
+#include "nodes/executors/dnnl/dnnl_matmul_primitive.hpp"
+#include "nodes/executors/dnnl/dnnl_post_op_data.hpp"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/implementation_utils.hpp"
+#include "nodes/executors/matmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
#include "nodes/kernels/x64/jit_matmul_small.hpp"
#include "openvino/core/except.hpp"
#include "openvino/core/parallel.hpp"
+#include "openvino/core/type/element_type.hpp"
+#include "utils/general_utils.h"
using namespace dnnl;
using namespace dnnl::impl;
namespace ov::intel_cpu {
-MatMulSmallExecutor::MatMulSmallExecutor(MatMulSmallAttrs attrs) : m_matmul_attrs(std::move(attrs)) {
- auto jcp = jit_matmul_small_config_params();
- jcp.M = m_matmul_attrs.M;
- jcp.N = m_matmul_attrs.N;
- jcp.K = m_matmul_attrs.K;
+MatMulSmallExecutor::MatMulSmallExecutor(const MatMulAttrs& attrs,
+ const MemoryArgs& memory,
+ const ExecutorContext::CPtr& context)
+ : shapeAgnosticData(DnnlMatMulPrimitive::createShapeAgnosticData(attrs, memory, context, false)) {}
+
+// Extract post ops args from primArgs
+// comply Eltwise::appendPostOps and depthwise injector prepare_binary_args() on how to map
+void MatMulSmallExecutor::prepare_binary_args(const DnnlPrimitiveAttrs& primAttrs) {
+ std::unordered_map<int, dnnl::memory> c_args = primAttrs.dnnlArgs;
+ m_post_ops_args.clear();
+ auto* dnnlPrimitiveAttr = shapeAgnosticData->m_primAttrs.attr.get();
+ const auto& attr = *dnnlPrimitiveAttr;
+ const auto& post_ops = attr.post_ops_;
+ m_post_ops_args.reserve(post_ops.entry_.size());
+ unsigned idx = 0;
+ for (const auto& post_op : post_ops.entry_) {
+ if (post_op.is_binary() || post_op.is_depthwise() || post_op.is_quantization()) {
+ m_post_ops_args.emplace_back(
+ c_args[DNNL_ARG_ATTR_MULTIPLE_POST_OP(idx) | DNNL_ARG_SRC_1].get_data_handle());
+ }
+ ++idx;
+ }
+}
+
+[[maybe_unused]] static inline bool noWeightsDecompression(const MatMulConfig& config) {
+ return !DnnlMatMulPrimitive::useWeightsDecompressionImpl(srcType(config), weiType(config));
+}
+
+[[maybe_unused]] static inline bool noSparseDecompression(const MatMulConfig& config) {
+ return !(config.attrs.sparseWeights);
+}
+
+bool MatMulSmallExecutor::supports(const MatMulConfig& config) {
+ VERIFY(noSparseDecompression(config), UNSUPPORTED_SPARSE_WEIGHTS);
+ VERIFY(noWeightsDecompression(config), UNSUPPORTED_WEIGHTS_DECOMPRESSION);
+
+ VERIFY(!config.attrs.transposeA && !config.attrs.transposeB, "unsupported strides");
+ VERIFY(all_of(ov::element::f32, srcType(config), weiType(config), dstType(config)), UNSUPPORTED_SRC_PRECISIONS);
+
+ const auto& biasDesc = config.descs.at(ARG_BIAS);
+ VERIFY(biasDesc->empty(), "bias is not supported");
+
+ const auto& srcDesc0 = config.descs.at(ARG_SRC);
+ const auto& srcDesc1 = config.descs.at(ARG_WEI);
+ const auto srcRank0 = srcDesc0->getShape().getRank();
+ const auto srcRank1 = srcDesc1->getShape().getRank();
+
+ VERIFY(srcRank0 >= 2, UNSUPPORTED_SRC_RANK);
+ VERIFY(srcRank0 == srcRank1, UNSUPPORTED_SRC_RANK);
+
+ return true;
+}
+
+bool MatMulSmallExecutor::update(const MemoryArgs& memory) {
+ const auto& srcDesc = memory.at(ARG_SRC)->getDescPtr();
+ const auto& weiDesc = memory.at(ARG_WEI)->getDescPtr();
+
+ const auto& shape_in0 = srcDesc->getShape().getStaticDims();
+ const auto& shape_in1 = weiDesc->getShape().getStaticDims();
+
+ m_matmul_attrs.M = *++shape_in0.rbegin();
+ m_matmul_attrs.K = *shape_in0.rbegin();
+ m_matmul_attrs.N = *shape_in1.rbegin();
+
+ jit_matmul_small_config_params jcp{m_matmul_attrs.M, m_matmul_attrs.K, m_matmul_attrs.N};
+
+ m_matmul_attrs.WA =
+ std::accumulate(shape_in0.begin(), shape_in0.end() - 2, static_cast<size_t>(1), std::multiplies<>());
+
+ auto* dnnlPrimitiveAttr = shapeAgnosticData->m_primAttrs.attr.get();
if (mayiuse(cpu::x64::avx512_core)) {
m_matmul_kernel =
- std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::avx512_core>>(jcp, *m_matmul_attrs.attr.get());
+ std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::avx512_core>>(jcp, *dnnlPrimitiveAttr);
} else if (mayiuse(cpu::x64::avx2)) {
- m_matmul_kernel =
- std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::avx2>>(jcp, *m_matmul_attrs.attr.get());
+ m_matmul_kernel = std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::avx2>>(jcp, *dnnlPrimitiveAttr);
} else if (mayiuse(cpu::x64::sse41)) {
- m_matmul_kernel =
- std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::sse41>>(jcp, *m_matmul_attrs.attr.get());
+ m_matmul_kernel = std::make_shared<jit_uni_matmul_small_kernel_f32<cpu::x64::sse41>>(jcp, *dnnlPrimitiveAttr);
} else {
OPENVINO_THROW("Can't create jit jit_uni_matmul_small_kernel_f32 kernel");
}
- if (m_matmul_kernel) {
- m_matmul_kernel->create_ker();
- }
-}
+ m_matmul_kernel->create_ker();
-void MatMulSmallExecutor::exec(const std::unordered_map<int, dnnl::memory>& primArgs,
- [[maybe_unused]] const dnnl::stream& strm) {
- const auto& in1 = primArgs.at(DNNL_ARG_SRC_0);
- const auto& in2 = primArgs.at(DNNL_ARG_WEIGHTS_0);
- const auto& out = primArgs.at(DNNL_ARG_DST);
// prepare_binary_args
- if (!(*m_matmul_attrs.attr.get()).post_ops_.entry_.empty()) {
- prepare_binary_args(primArgs);
+ if (!shapeAgnosticData->m_primAttrs.attr.get()->post_ops_.entry_.empty()) {
+ prepare_binary_args(shapeAgnosticData->m_primAttrs);
}
- const auto& src_shape = in1.get_desc().get_dims();
- const auto& wei_shape = in2.get_desc().get_dims();
- const auto* src_data = static_cast<float*>(in1.get_data_handle());
- const auto* wei_data = static_cast<float*>(in2.get_data_handle());
- auto* dst_data = static_cast<float*>(out.get_data_handle());
- const auto& M = src_shape[src_shape.size() - 2];
- const auto& K = src_shape[src_shape.size() - 1];
- const auto& N = wei_shape[wei_shape.size() - 1];
- const auto& out_shape = out.get_desc().get_dims();
+
+ return true;
+}
+
+void MatMulSmallExecutor::execute(const MemoryArgs& memory) {
+ const auto& in1 = memory.at(ARG_SRC);
+ const auto& in2 = memory.at(ARG_WEI);
+ const auto& out = memory.at(ARG_DST);
+
+ const auto* src_data = in1->getDataAs<const float>();
+ const auto* wei_data = in2->getDataAs<const float>();
+ auto* dst_data = out->getDataAs<float>();
+
+ const auto M = m_matmul_attrs.M;
+ const auto K = m_matmul_attrs.K;
+ const auto N = m_matmul_attrs.N;
+
+ const auto& out_shape = out->getDesc().getShape().getStaticDims();
const auto& OC = out_shape.size() >= 3 ? out_shape[out_shape.size() - 3] : 1;
- const auto& src_spatial_size = M * K;
- const auto& wei_spatial_size = K * N;
- const auto& dst_spatial_size = M * N;
+
+ const auto src_spatial_size = M * K;
+ const auto wei_spatial_size = K * N;
+ const auto dst_spatial_size = M * N;
+ const size_t wa = m_matmul_attrs.WA;
const size_t threads_num = parallel_get_max_threads();
- const size_t wa =
- std::accumulate(src_shape.begin(), src_shape.end() - 2, static_cast<size_t>(1), std::multiplies<>());
+
parallel_nt(threads_num, [&](const int ithr, [[maybe_unused]] const int nthr) {
size_t start = 0, end = 0;
splitter(wa, nthr, ithr, start, end);
@@ -91,28 +162,4 @@ void MatMulSmallExecutor::exec(const std::unordered_map<int, dnnl::memory>& prim
});
}
-// Extract post ops args from primArgs
-// comply Eltwise::appendPostOps and depthwise injector prepare_binary_args() on how to map
-void MatMulSmallExecutor::prepare_binary_args(const std::unordered_map<int, dnnl::memory>& primArgs) {
- std::unordered_map<int, dnnl::memory> c_args = primArgs;
- m_post_ops_args.clear();
- const auto& attr = *m_matmul_attrs.attr.get();
- const auto& post_ops = attr.post_ops_;
- m_post_ops_args.reserve(post_ops.entry_.size());
- unsigned idx = 0;
- for (const auto& post_op : post_ops.entry_) {
- if (post_op.is_binary() || post_op.is_depthwise() || post_op.is_quantization()) {
- m_post_ops_args.emplace_back(
- c_args[DNNL_ARG_ATTR_MULTIPLE_POST_OP(idx) | DNNL_ARG_SRC_1].get_data_handle());
- }
- ++idx;
- }
-}
-
-DnnlMemoryDescPtr MatMulSmallExecutor::getScratchPadDesc() const {
- dnnl::memory::dims dims;
- dnnl::memory::desc zero_md{dims, dnnl::memory::data_type::u8, dnnl::memory::format_tag::undef};
- return DnnlExtensionUtils::makeDescriptor(zero_md);
-}
-
-} // namespace ov::intel_cpu
\ No newline at end of file
+} // namespace ov::intel_cpu
diff --git a/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.hpp b/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.hpp
index 5ef0f5fa5af..9afe0f894fc 100644
--- a/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.hpp
+++ b/src/plugins/intel_cpu/src/nodes/executors/x64/matmul_small.hpp
@@ -4,10 +4,18 @@
#pragma once
+#include <cstddef>
+#include <memory>
#include <oneapi/dnnl/dnnl.hpp>
+#include <unordered_map>
+#include <vector>
-#include "nodes/executors/matmul.hpp"
+#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/matmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
#include "nodes/kernels/x64/jit_matmul_small.hpp"
+#include "onednn/iml_type_mapper.h"
namespace ov::intel_cpu {
@@ -15,19 +23,28 @@ struct MatMulSmallAttrs {
size_t M = 0UL;
size_t N = 0UL;
size_t K = 0UL;
- dnnl::primitive_attr attr;
+ size_t WA = 0UL;
};
-class MatMulSmallExecutor : public IMatmulExecutor {
+class MatMulSmallExecutor : public Executor {
public:
- explicit MatMulSmallExecutor(MatMulSmallAttrs attrs);
- void exec(const std::unordered_map<int, dnnl::memory>& primArgs, const dnnl::stream& strm) override;
- [[nodiscard]] DnnlMemoryDescPtr getScratchPadDesc() const override;
+ MatMulSmallExecutor(const MatMulAttrs& attrs, const MemoryArgs& memory, const ExecutorContext::CPtr& context);
+ void execute(const MemoryArgs& memory) override;
+ [[nodiscard]] impl_desc_type implType() const override {
+ // @todo distinguish cpu plugin jit from dnnl jit
+ return impl_desc_type::unknown;
+ }
+
+ // offloads execution data preparation from the exec call
+ bool update(const MemoryArgs& memory) override;
+
+ static bool supports(const MatMulConfig& config);
private:
// set post_ops_args based on primArgs and post_ops
- void prepare_binary_args(const std::unordered_map<int, dnnl::memory>& primArgs);
+ void prepare_binary_args(const DnnlPrimitiveAttrs& primAttrs);
+ DnnlShapeAgnosticDataPtr shapeAgnosticData;
MatMulSmallAttrs m_matmul_attrs;
std::shared_ptr<jit_uni_matmul_small_kernel> m_matmul_kernel;
std::vector<const void*> m_post_ops_args;
diff --git a/src/plugins/intel_cpu/src/nodes/matmul.cpp b/src/plugins/intel_cpu/src/nodes/matmul.cpp
index 869fde0afe5..9e59a3ba80a 100644
--- a/src/plugins/intel_cpu/src/nodes/matmul.cpp
+++ b/src/plugins/intel_cpu/src/nodes/matmul.cpp
@@ -4,37 +4,29 @@
#include "matmul.h"
-#include <oneapi/dnnl/dnnl_types.h>
-
#include <algorithm>
-#include <common/utils.hpp>
+#include <cassert>
+#include <cpu/x64/cpu_isa_traits.hpp>
#include <cstddef>
#include <memory>
-#include <oneapi/dnnl/dnnl.hpp>
#include <oneapi/dnnl/dnnl_common.hpp>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
-#include "common/primitive_attr.hpp"
-#include "common/primitive_hashing_utils.hpp"
-#include "cpu/x64/cpu_isa_traits.hpp"
#include "cpu_shape.h"
#include "cpu_types.h"
-#include "dnnl_extension_utils.h"
-#include "dnnl_postops_composer_legacy.h"
#include "eltwise.h"
-#include "fake_quantize.h"
#include "graph_context.h"
-#include "memory_desc/cpu_blocked_memory_desc.h"
#include "memory_desc/cpu_memory_desc.h"
#include "memory_desc/cpu_memory_desc_utils.h"
-#include "memory_desc/dnnl_blocked_memory_desc.h"
-#include "memory_desc/dnnl_memory_desc.h"
#include "node.h"
+#include "nodes/common/blocked_desc_creator.h"
#include "nodes/executors/eltwise_config.hpp"
-#include "nodes/executors/matmul.hpp"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/executor_factory.hpp"
+#include "nodes/executors/memory_arguments.hpp"
#include "nodes/node_config.h"
#include "onednn/iml_type_mapper.h"
#include "openvino/core/except.hpp"
@@ -42,65 +34,12 @@
#include "openvino/core/type.hpp"
#include "openvino/core/type/element_type.hpp"
#include "openvino/op/matmul.hpp"
+#include "post_ops.hpp"
#include "shape_inference/custom/matmul.hpp"
#include "utils/debug_capabilities.h"
#include "utils/general_utils.h"
-#ifdef OPENVINO_ARCH_X86_64
-# include "executors/x64/matmul_small.hpp"
-#endif
-
-using namespace dnnl;
namespace ov::intel_cpu::node {
-namespace {
-
-struct MatMulKey {
- DnnlMemoryDescCPtr inp0;
- DnnlMemoryDescCPtr inp1;
- DnnlMemoryDescCPtr bias;
- DnnlMemoryDescCPtr out;
- dnnl::primitive_attr attr;
- impl_desc_type implType;
-
- [[nodiscard]] size_t hash() const;
- bool operator==(const MatMulKey& rhs) const;
-};
-
-size_t MatMulKey::hash() const {
- using namespace dnnl::impl;
- using namespace dnnl::impl::primitive_hashing;
-
- size_t seed = 0;
-
- for (const auto& ptr : {inp0, inp1, bias, out}) {
- if (ptr) {
- seed = hash_combine(seed, get_md_hash(*ptr->getDnnlDesc().get()));
- }
- }
-
- seed = hash_combine(seed, get_attr_hash(*attr.get()));
- seed = hash_combine(seed, implType);
- return seed;
-}
-
-bool MatMulKey::operator==(const MatMulKey& rhs) const {
- bool retVal = true;
- if (inp0 != rhs.inp0) {
- retVal = retVal && inp0 && rhs.inp0 && inp0->getDnnlDesc() == rhs.inp0->getDnnlDesc();
- }
- if (inp1 != rhs.inp1) {
- retVal = retVal && inp1 && rhs.inp1 && inp1->getDnnlDesc() == rhs.inp1->getDnnlDesc();
- }
- if (bias != rhs.bias) {
- retVal = retVal && bias && rhs.bias && bias->getDnnlDesc() == rhs.bias->getDnnlDesc();
- }
- if (out != rhs.out) {
- retVal = retVal && out && rhs.out && out->getDnnlDesc() == rhs.out->getDnnlDesc();
- }
- retVal = retVal && *attr.get() == *rhs.attr.get() && implType == rhs.implType;
- return retVal;
-}
-} // namespace
bool MatMul::canBeExecutedInInt8() const {
auto firstInputPrecision = getOriginalInputPrecisionAtPort(0);
@@ -155,13 +94,16 @@ MatMul::MatMul(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& co
" is not an instance of MatMul from v0");
}
- transposeIn[0] = matMul->get_transpose_a();
- transposeIn[1] = matMul->get_transpose_b();
+ m_attrs.transposeA = matMul->get_transpose_a();
+ m_attrs.transposeB = matMul->get_transpose_b();
+
+ m_atoi[ARG_SRC] = 0;
+ m_atoi[ARG_WEI] = 1;
}
bool MatMul::canFuse(const NodePtr& node) const {
// WA for CVS-84056: oneDNN brgemm impl has problem with per-OC binary-postOps for MatMul with 6D inputs
- if (impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core)) {
+ if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core)) {
if (auto* eltwiseNode = dynamic_cast<Eltwise*>(node.get())) {
if (eltwiseNode->getBroadcastingPolicy() == EltwiseBroadcastingPolicy::PerChannel) {
auto rank = getInputShapeAtPort(0).getRank();
@@ -188,602 +130,183 @@ bool MatMul::canFuse(const NodePtr& node) const {
return canFuseSimpleOperation(node);
}
-void MatMul::setPostOps(dnnl::primitive_attr& attr, const VectorDims& dims, [[maybe_unused]] bool initWeights = false) {
- dnnl::post_ops ops;
-
- dnnl::memory::data_type outputDataType = dnnl::memory::data_type::undef;
- if (outDataDesc) {
- outputDataType = outDataDesc->getDataType();
- }
-
- bool isINT8 = canBeExecutedInInt8();
-
- DnnlPostOpsComposerLegacy dnnlpoc(getEngine(),
- attr,
- ops,
- postOpsArgs,
- dims,
- dims.size() - 1,
- isINT8,
- 1 << (dims.size() - 1),
- getDQScales(),
- withBiases);
+std::tuple<VecMemoryDescs, MemoryDescPtr> MatMul::initMemoryDescriptors(ov::element::Type dstType) const {
+ const auto& srcTypes = getOriginalInputPrecisions();
- for (size_t i = 0; i < fusedWith.size(); ++i) {
- auto& node = fusedWith[i];
- bool isLastPostOp = (i == (fusedWith.size() - 1));
-
- if (auto* eltwiseNode = dynamic_cast<Eltwise*>(node.get())) {
- eltwiseNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType);
- continue;
- }
-
- if (auto* fakeQuantizeNode = dynamic_cast<FakeQuantize*>(node.get())) {
- fakeQuantizeNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType);
+ VecMemoryDescs srcDescs;
+ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();
+ for (size_t i = 0; i < srcTypes.size(); i++) {
+ if (srcTypes[i] == ov::element::dynamic) {
+ srcDescs.push_back(MemoryDescUtils::makeEmptyDesc());
continue;
}
-
- CPU_NODE_THROW("Fusing of ",
- NameFromType(node->getType()),
- " operation to ",
- NameFromType(this->getType()),
- " node is not implemented");
+ auto srcDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcTypes[i], getInputShapeAtPort(i));
+ srcDescs.push_back(srcDesc);
}
- attr.set_post_ops(ops);
-}
-
-Node::AttrPtr MatMul::initPrimitiveAttr(const VectorDims& dims) {
- auto attr = std::make_shared<dnnl::primitive_attr>(dnnl::primitive_attr());
-
- setPostOps(*attr, dims, true);
+ auto dstDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(dstType, getOutputShapeAtPort(0));
- (*attr).set_scratchpad_mode(dnnl::scratchpad_mode::user);
-
- return attr;
+ return {srcDescs, dstDesc};
}
-Node::AttrPtr MatMul::initPrimitiveAttr() {
- auto outputShape = getOutputShapeAtPort(0);
- for (auto&& node : fusedWith) {
- outputShape = mergeShapes(outputShape, node->getOutputShapeAtPort(0));
- }
- auto dummyShape = MemoryDescUtils::makeDummyShape(outputShape);
- return initPrimitiveAttr(dummyShape.getStaticDims());
+ExecutorFactoryPtr<MatMulAttrs> MatMul::createExecutorFactory(const MemoryDescArgs& descs, const MatMulAttrs& attrs) {
+ auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);
+ return std::make_shared<ExecutorFactory<MatMulAttrs>>(attrs, executionContext, descs, memoryFormatFilter);
}
-/* Example MatMul:
- * 2x128x512(T) * 2x128x512 = 2x512x512
- * First input 2x128x512(T) should be transposed
- * oneDNN requires memory::desc for this input to:
- * - change shapes configuration as if input already transposed (2x128x512) -> (2x512x128)
- * - provide transposed strides (66536, 128, 1) -> (66536, 1, 512)
- */
-static VectorDims getStridesAndModifyShape(Shape& shape, const bool transpose) {
- const auto getRank = shape.getRank();
-
- VectorDims strides(getRank, 1);
- const auto& staticDims = shape.getStaticDims();
- for (size_t i = 1; i < getRank; i++) {
- strides[getRank - i - 1] = strides[getRank - i] * staticDims[getRank - i];
- }
-
- if (transpose && getRank > 1) {
- // form new shape
- auto dims = staticDims;
- std::swap(dims[getRank - 2], dims[getRank - 1]);
- shape = Shape{dims};
- // update strides
- strides[getRank - 1] = staticDims[getRank - 2];
- strides[getRank - 2] = 1;
+void MatMul::initSupportedPrimitiveDescriptors() {
+ m_attrs.withBias = getOriginalInputsNumber() == 3;
+ if (m_attrs.withBias) {
+ m_atoi[ARG_BIAS] = 2;
}
- return strides;
-}
-
-dnnl::memory::desc MatMul::getBiasDescFrom(const DnnlMemoryDescCPtr& outMemDesc) {
- // oneDNN matmul requires shape for bias desc to be the same rank
- VectorDims biasDims(outMemDesc->getShape().getRank(), 1);
- const auto outDims = outMemDesc->getShape().getStaticDims();
- const auto chIdx = getFusingAxis();
- biasDims[chIdx] = outDims[chIdx];
- const auto bdt = DnnlExtensionUtils::ElementTypeToDataType(getOriginalInputPrecisionAtPort(2));
-
- return {DnnlExtensionUtils::convertToDnnlDims(biasDims), bdt, memory::format_tag::any};
-}
-
-void MatMul::getSupportedDescriptors() {
- CPU_NODE_ASSERT(getParentEdges().size() == getOriginalInputsNumber(),
- "has incorrect number of input edges for layer ",
- getName());
- CPU_NODE_ASSERT(!getChildEdges().empty(), "has incorrect number of output edges for layer ", getName());
-
- withBiases = getOriginalInputsNumber() == 3;
-
- auto firstInPortPrec = getOriginalInputPrecisionAtPort(0);
- auto secondInPortPrec = getOriginalInputPrecisionAtPort(1);
- auto outPortPrec = getOriginalOutputPrecisionAtPort(0);
-
- if (firstInPortPrec.size() != secondInPortPrec.size()) {
- firstInPortPrec = secondInPortPrec = getMaxPrecision(getOriginalInputPrecisions());
- }
+ m_attrs.dqScales = getDQScales();
+ m_attrs.postOps = getPostOps(fusedWith, ov::element::dynamic);
- // fallback to fp32 for any precision that cannot be handled natively
- if ((none_of(firstInPortPrec,
- ov::element::u8,
- ov::element::i8,
- ov::element::bf16,
- ov::element::f16,
- ov::element::f32) ||
- none_of(secondInPortPrec, ov::element::i8, ov::element::bf16, ov::element::f16, ov::element::f32))) {
- outPortPrec = firstInPortPrec = secondInPortPrec = ov::element::f32;
- }
+ auto dstType = getOriginalOutputPrecisionAtPort(0);
- ov::element::Type postOpsPrec = outPortPrec;
+ // make sure dst type is equal to the output type of the last fused node
if (!fusedWith.empty()) {
- postOpsPrec = fusedWith[fusedWith.size() - 1]->getOriginalOutputPrecisionAtPort(0);
- }
-
- if (canBeExecutedInInt8()) {
- // INT8 mode support wide range of output precisions
- outPortPrec = postOpsPrec;
- // INT8 matmul do not support fp16 output
- if (outPortPrec == ov::element::f16) {
- outPortPrec = ov::element::f32;
- }
- } else if (postOpsPrec == ov::element::f32) {
- // all non-INT8 modes support fp32 output precision
- outPortPrec = postOpsPrec;
- } else {
- // otherwise we ignore postOpsPrec and stay with getOriginalOutputPrecisionAtPort(0)
- }
-
- const auto& inputShape0 = getInputShapeAtPort(0);
- const auto& inputShape1 = getInputShapeAtPort(1);
- auto outputShape = getOutputShapeAtPort(0);
-
- CPU_NODE_ASSERT(all_of(inputShape0.getRank(), inputShape1.getRank(), outputShape.getRank()),
- "has invalid dims count");
-
- const int nDims = inputShape0.getRank();
- const auto xAxis = nDims - 1;
- const auto yAxis = nDims - 2;
- const auto xAxis0 = transposeIn[0] ? yAxis : xAxis;
- const auto yAxis0 = transposeIn[0] ? xAxis : yAxis;
- const auto xAxis1 = transposeIn[1] ? yAxis : xAxis;
- const auto yAxis1 = transposeIn[1] ? xAxis : yAxis;
-
- const auto& inDims0 = getInputShapeAtPort(0).getDims();
- const auto& inDims1 = getInputShapeAtPort(1).getDims();
- const auto& outDims = getOutputShapeAtPort(0).getDims();
-
- // coverity[copy_paste_error]
- if (!dimsEqualWeak(inDims0[xAxis0], inDims1[yAxis1]) || !dimsEqualWeak(inDims0[yAxis0], outDims[yAxis]) ||
- !dimsEqualWeak(inDims1[xAxis1], outDims[xAxis])) {
- CPU_NODE_THROW("has incorrect spatial input and output dimensions");
- }
-
- for (int dim_idx = nDims - 3; dim_idx >= 0; dim_idx--) {
- if ((!dimsEqualWeak(inDims0[dim_idx], outDims[dim_idx]) && !dimsEqualWeak(inDims0[dim_idx], 1)) ||
- (!dimsEqualWeak(inDims1[dim_idx], outDims[dim_idx]) && !dimsEqualWeak(inDims1[dim_idx], 1))) {
- CPU_NODE_THROW("has incorrect input batch dimensions");
- }
- }
-
- for (auto&& node : fusedWith) {
- outputShape = mergeShapes(outputShape, node->getOutputShapeAtPort(0));
+ dstType = fusedWith.back()->getOriginalOutputPrecisionAtPort(0);
}
- std::vector<Shape> staticInputShapes{inputShape0, inputShape1};
- if (inputShape0.isDynamic() || inputShape1.isDynamic()) {
- std::tie(staticInputShapes[0], staticInputShapes[1]) =
- makeDummyInputShapes(inputShape0, inputShape1, outputShape);
- }
+ auto [srcDescs, dstDesc] = initMemoryDescriptors(dstType);
- auto staticOutputShape = outputShape.isStatic() ? outputShape : Shape(shapeInferGeneric(staticInputShapes).front());
+ MemoryDescArgs descs{
+ {ARG_SRC, srcDescs[0]},
+ {ARG_WEI, srcDescs[1]},
+ {ARG_BIAS, m_attrs.withBias ? srcDescs[2] : MemoryDescUtils::makeEmptyDesc()},
+ {ARG_DST, dstDesc},
+ };
- const VectorDims inStrides0 = getStridesAndModifyShape(staticInputShapes[0], transposeIn[0]);
- const VectorDims inStrides1 = getStridesAndModifyShape(staticInputShapes[1], transposeIn[1]);
+ m_factory = createExecutorFactory(descs, m_attrs);
- inDataDesc[0] = std::make_shared<DnnlBlockedMemoryDesc>(firstInPortPrec, staticInputShapes[0], inStrides0);
- inDataDesc[1] = std::make_shared<DnnlBlockedMemoryDesc>(secondInPortPrec, staticInputShapes[1], inStrides1);
- outDataDesc = std::make_shared<DnnlBlockedMemoryDesc>(outPortPrec, staticOutputShape);
+ const std::vector<MemoryDescArgs> nodeDescriptorsList = m_factory->getProperMemoryDescriptors(descs);
- createDescriptor({inDataDesc[0], inDataDesc[1]}, {outDataDesc});
-}
+ for (const auto& nodeDescriptors : nodeDescriptorsList) {
+ NodeConfig nodeConfig;
+ nodeConfig.inConfs.resize(srcDescs.size());
-std::pair<Shape, Shape> MatMul::makeDummyInputShapes(const Shape& in0, const Shape& in1, const Shape& out) const {
- CPU_NODE_ASSERT(in0.getRank() >= 2 && in1.getRank() >= 2, "Can't create dummy inputs with rank less 2");
- CPU_NODE_ASSERT(all_of(in1.getRank(), in0.getRank(), out.getRank()),
- "Can't create dummy inputs if argument shapes ranks are not equal");
+ auto getBlockedMask = [](const std::shared_ptr<MemoryDesc>& memDesc) {
+ if (memDesc->getType() & MemoryDescType::Blocked) {
+ return BlockedMemoryDesc::EMPTY_MASK;
+ }
+ return BlockedMemoryDesc::FULL_MASK;
+ };
- auto swapTranspDims = [&](VectorDims& in0, VectorDims& in1) {
- if (transposeIn[0]) {
- std::swap(in0[in0.size() - 1], in0[in0.size() - 2]);
- }
- if (transposeIn[1]) {
- std::swap(in1[in1.size() - 1], in1[in1.size() - 2]);
+ for (const auto& desc : nodeDescriptors) {
+ if (auto it = m_atoi.find(desc.first); it != m_atoi.end()) {
+ const auto& inputDesc = desc.second;
+ nodeConfig.inConfs[it->second] = PortConfig{inputDesc, getBlockedMask(inputDesc)};
+ }
}
- };
- auto inDims0 = in0.getDims();
- auto inDims1 = in1.getDims();
- auto outDims = out.getDims();
-
- auto minDims0 = in0.getMinDims();
- auto maxDims0 = in0.getMaxDims();
- auto minDims1 = in1.getMinDims();
- auto maxDims1 = in1.getMaxDims();
-
- swapTranspDims(inDims0, inDims1);
- swapTranspDims(minDims0, minDims1);
- swapTranspDims(maxDims0, maxDims1);
-
- auto fillDummy = [&](size_t idx0, size_t idx1) {
- if (all_of(Shape::UNDEFINED_DIM, inDims0[idx0], inDims1[idx1])) {
- inDims0[idx0] = inDims1[idx1] = std::min(std::min(maxDims0[idx0], maxDims1[idx1]),
- std::max(std::max(minDims0[idx0], minDims1[idx1]),
- static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
- } else {
- if (inDims0[idx0] == Shape::UNDEFINED_DIM && inDims1[idx1] != Shape::UNDEFINED_DIM) {
- if (inDims1[idx1] == 1 && minDims0[idx0] != Shape::UNDEFINED_DIM) {
- inDims0[idx0] = std::max<Dim>(minDims0[idx0], 1);
- } else {
- inDims0[idx0] = inDims1[idx1];
- }
- } else if (inDims0[idx0] != Shape::UNDEFINED_DIM && inDims1[idx1] == Shape::UNDEFINED_DIM) {
- if (inDims0[idx0] == 1 && minDims1[idx1] != Shape::UNDEFINED_DIM) {
- inDims1[idx1] = std::max<Dim>(minDims1[idx1], 1);
- } else {
- inDims1[idx1] = inDims0[idx0];
- }
- }
+ for (size_t i = 3; i < srcDescs.size(); i++) {
+ nodeConfig.inConfs[i] = PortConfig{srcDescs[i]};
}
- };
- // fill k
- fillDummy(inDims0.size() - 1, inDims1.size() - 2);
+ const auto& outputDesc = nodeDescriptors.at(ARG_DST);
+ nodeConfig.outConfs.emplace_back(outputDesc, getBlockedMask(outputDesc), -1);
- // fill m, n
- if (outDims[outDims.size() - 2] != Shape::UNDEFINED_DIM) {
- inDims0[inDims0.size() - 2] = outDims[outDims.size() - 2];
- } else if (inDims0[inDims0.size() - 2] == Shape::UNDEFINED_DIM) {
- inDims0[inDims0.size() - 2] =
- std::min(maxDims0[inDims0.size() - 2],
- std::max(minDims0[inDims0.size() - 2], static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
+ supportedPrimitiveDescriptors.emplace_back(nodeConfig, impl_desc_type::undef);
}
+}
- if (outDims[outDims.size() - 1] != Shape::UNDEFINED_DIM) {
- inDims1[inDims1.size() - 1] = outDims[outDims.size() - 1];
- } else if (inDims1[inDims1.size() - 1] == Shape::UNDEFINED_DIM) {
- inDims1[inDims1.size() - 1] =
- std::min(maxDims1[inDims1.size() - 1],
- std::max(minDims1[inDims1.size() - 1], static_cast<Dim>(MemoryDescUtils::DEFAULT_DUMMY_VAL)));
- }
+bool MatMul::created() const {
+ return getType() == Type::MatMul;
+}
- // fill batches
- for (size_t i = 0; i < inDims0.size() - 2; i++) {
- if (outDims[i] != Shape::UNDEFINED_DIM) {
- inDims0[i] = outDims[i];
- inDims1[i] = outDims[i];
- } else {
- fillDummy(i, i);
+ov::element::Type MatMul::getRuntimePrecision() const {
+ std::vector<ov::element::Type> inputPrecisions;
+ // Don't take bias precision into account
+ size_t inputsNumLimit = 2;
+ for (size_t i = 0; i < std::min(getParentEdges().size(), inputsNumLimit); i++) {
+ auto parentEdge = getParentEdgeAt(i);
+ if (parentEdge && parentEdge->getStatus() == Edge::Status::Validated) {
+ inputPrecisions.emplace_back(parentEdge->getMemory().getDesc().getPrecision());
}
}
- swapTranspDims(inDims0, inDims1);
-
- return {Shape(inDims0), Shape(inDims1)};
+ return getMaxPrecision(inputPrecisions);
}
-void MatMul::createDescriptor([[maybe_unused]] const std::vector<MemoryDescPtr>& inputDesc,
- [[maybe_unused]] const std::vector<MemoryDescPtr>& outputDesc) {
- const auto attr = initPrimitiveAttr();
- dnnl::matmul::primitive_desc matmul_desc;
- if (withBiases) {
- matmul_desc = matmul::primitive_desc(getEngine(),
- inDataDesc[0]->getDnnlDesc(),
- inDataDesc[1]->getDnnlDesc(),
- getBiasDescFrom(outDataDesc),
- outDataDesc->getDnnlDesc(),
- *attr);
- } else {
- matmul_desc = matmul::primitive_desc(getEngine(),
- inDataDesc[0]->getDnnlDesc(),
- inDataDesc[1]->getDnnlDesc(),
- outDataDesc->getDnnlDesc(),
- *attr);
- }
+const std::vector<impl_desc_type>& MatMul::getDefaultImplPriority() {
+ static const std::vector<impl_desc_type> priorities = {
+ impl_desc_type::unknown, impl_desc_type::brgemm_avx512_amx,
+ impl_desc_type::brgemm_avx512, impl_desc_type::brgemm_avx2,
+ impl_desc_type::gemm_acl, impl_desc_type::gemm_blas,
+ impl_desc_type::gemm_avx512, impl_desc_type::gemm_avx2,
+ impl_desc_type::gemm_avx, impl_desc_type::gemm_sse42,
+ impl_desc_type::gemm_any, impl_desc_type::gemm,
+ impl_desc_type::jit_gemm, impl_desc_type::jit_uni_dw,
+ impl_desc_type::jit_uni_1x1, impl_desc_type::jit_uni,
+ impl_desc_type::jit_avx512_dw, impl_desc_type::jit_avx512_1x1,
+ impl_desc_type::jit_avx512, impl_desc_type::jit_avx2_dw,
+ impl_desc_type::jit_avx2_1x1, impl_desc_type::jit_avx2,
+ impl_desc_type::jit_avx_dw, impl_desc_type::jit_avx_1x1,
+ impl_desc_type::jit_avx, impl_desc_type::jit_sse42_dw,
+ impl_desc_type::jit_sse42_1x1, impl_desc_type::jit_sse42,
+ impl_desc_type::ref,
+ };
- descs.emplace_back(matmul_desc);
+ return priorities;
}
-void MatMul::initSupportedPrimitiveDescriptors() {
- if (!supportedPrimitiveDescriptors.empty()) {
- return;
+void MatMul::createPrimitive() {
+ for (const auto& entry : m_atoi) {
+ const auto argumentId = entry.first;
+ const auto inputId = entry.second;
+ m_memory[argumentId] = getSrcMemoryAtPort(inputId);
}
- auto addSupportedPrimitiveDescriptor = [&](const dnnl::primitive_desc& prim_desc) {
- std::vector<PortConfig> inConfs;
- std::vector<PortConfig> outConfs;
- const int inPlaceOutPort = canBeInPlace() ? 0 : -1;
-
- for (size_t i = 0; i < descInputNumbers(); i++) {
- auto desc = getSrcMemDesc(prim_desc, i);
-
- inConfs.emplace_back(desc);
- }
-
- for (size_t i = 0; i < descOutputNumbers(); i++) {
- auto desc = getDstMemDesc(prim_desc, i);
-
- outConfs.emplace_back(desc, BlockedMemoryDesc::FULL_MASK, inPlaceOutPort);
- }
-
- const NodeConfig config(inConfs, outConfs);
- const impl_desc_type impl_type = parse_impl_name(prim_desc.impl_info_str());
-
- supportedPrimitiveDescriptors.emplace_back(config, impl_type);
- };
-#ifdef CPU_DEBUG_CAPS
- {
- if (!customImplPriorities.empty()) {
- DEBUG_LOG("#",
- getName(),
- " customImplPriorities [",
- 0,
- "/",
- customImplPriorities.size(),
- "]: ",
- impl_type_to_string(customImplPriorities[0]));
- }
- }
-#endif
- for (auto& desc : descs) {
- auto first_desc = dnnl::primitive_desc(DnnlExtensionUtils::clone_primitive_desc(desc.get()));
- const bool first_match = customImplPriorities.empty();
- DEBUG_LOG("#",
- getName(),
- ", itpd.impl_info_str(): ",
- desc.impl_info_str(),
- ", parsed imp_type: ",
- impl_type_to_string(parse_impl_name(desc.impl_info_str())),
- ", first_match: ",
- first_match ? "true" : "false");
- DnnlExtensionUtils::for_each_implementation(
- desc,
- first_match,
- [&](impl_desc_type implType) {
- return contains(getImplPriority(), implType);
- },
- [&](dnnl::primitive_desc& desc) {
- addSupportedPrimitiveDescriptor(desc);
- });
-
- // fallback. if none of the primitive types is present in the priority list just add first implementation
- // @todo this fallback is not necessary if primitive priority list is filled correctly
- if (supportedPrimitiveDescriptors.empty()) {
- addSupportedPrimitiveDescriptor(first_desc);
- }
+ if (!m_attrs.withBias) {
+ m_memory[ARG_BIAS] = MemoryDescUtils::makeEmptyMemory(context);
}
-}
-
-MemoryDescPtr MatMul::getSrcMemDesc(const dnnl::primitive_desc& prim_desc, size_t idx) const {
- auto desc = idx > 0 ? prim_desc.weights_desc(idx - 1) : prim_desc.src_desc(idx);
- if (idx < 2) { // inputs
- return std::make_shared<CpuBlockedMemoryDesc>(
- DnnlExtensionUtils::DataTypeToElementType(desc.get_data_type()),
- getInputShapeAtPort(idx)); /* provide initial shapes, so hide transpose effect */
- } // bias
- return DnnlExtensionUtils::makeDescriptor(desc);
-}
+ m_memory[ARG_DST] = getDstMemoryAtPort(0);
-bool MatMul::created() const {
- return getType() == Type::MatMul;
-}
+ m_executor = m_factory->make(m_memory, false);
-ov::element::Type MatMul::getRuntimePrecision() const {
- return getMaxPrecision(getInputPrecisions());
+ Node::createPrimitive();
}
void MatMul::prepareParams() {
- auto dstMemPtr = getDstMemoryAtPort(0);
- auto src0MemPtr = getSrcMemoryAtPort(0);
- auto src1MemPtr = getSrcMemoryAtPort(1);
- CPU_NODE_ASSERT(dstMemPtr && dstMemPtr->isDefined(), "has undefined destination memory");
- CPU_NODE_ASSERT(src0MemPtr && src0MemPtr->isDefined() && src1MemPtr && src1MemPtr->isDefined(),
- "has undefined input memory");
-
// check for a degenerate case. In this context the degenerate case is a matrix multiplication where the
// collapsing dimension is zero, e.g., AB=C, where A has the shape [10, 0] and B has the shape [0, 20],
// consequently C has shape [10, 20]. In this scenario C is a null matrix (a matrix filled with zeroes)
// according to the empty sum convention.
- if (src0MemPtr->getDesc().getShape().hasZeroDims() && src0MemPtr->getDesc().getShape().hasZeroDims() &&
- !dstMemPtr->getDesc().getShape().hasZeroDims()) {
+ if (m_memory[ARG_SRC]->getDesc().getShape().hasZeroDims() &&
+ m_memory[ARG_WEI]->getDesc().getShape().hasZeroDims() &&
+ !m_memory[ARG_DST]->getDesc().getShape().hasZeroDims()) {
// todo: obviously we need a special executor that would process fused ops providing a correct result
- CPU_NODE_ASSERT(!withBiases && fusedWith.empty(),
- "Matmul doesn't support a degenerate case when other ops are fused");
- // reset executor
- execPtr.reset();
+ CPU_NODE_ASSERT(m_memory[ARG_BIAS]->getDesc().empty(),
+ "Matmul doesn't support a degenerate case when bias is provided");
+ CPU_NODE_ASSERT(fusedWith.empty(), "Matmul doesn't support a degenerate case when other ops are fused");
return;
}
- const NodeDesc* selected_pd = getSelectedPrimitiveDescriptor();
- CPU_NODE_ASSERT(selected_pd, "did not set preferable primitive descriptor");
-
- DnnlMemoryDescPtr src0TransposedDesc;
- DnnlMemoryDescPtr src1TransposedDesc;
-
- AttrPtr attr;
-
- if (isDynamicNode()) {
- attr = initPrimitiveAttr(dstMemPtr->getStaticDims());
-
- const auto& src0Desc = src0MemPtr->getDesc();
- const auto& src1Desc = src1MemPtr->getDesc();
-
- auto src0Shape = src0Desc.getShape();
- auto src0Strides = getStridesAndModifyShape(src0Shape, transposeIn[0]);
- src0TransposedDesc = std::make_shared<DnnlBlockedMemoryDesc>(src0Desc.getPrecision(), src0Shape, src0Strides);
-
- auto src1Shape = src1Desc.getShape();
- auto src1Strides = getStridesAndModifyShape(src1Shape, transposeIn[1]);
- src1TransposedDesc = std::make_shared<DnnlBlockedMemoryDesc>(src1Desc.getPrecision(), src1Shape, src1Strides);
- } else {
- attr = initPrimitiveAttr();
- src0TransposedDesc = inDataDesc[0];
- src1TransposedDesc = inDataDesc[1];
- }
-
- auto dstDnnlDesc = dstMemPtr->getDescWithType<DnnlMemoryDesc>();
-
- DnnlMemoryDescPtr dnnlBiasMemDesc = nullptr;
- if (withBiases) {
- auto biasMemory = getSrcMemoryAtPort(2);
- CPU_NODE_ASSERT(biasMemory && biasMemory->isDefined(), "has undefined bias memory");
- dnnlBiasMemDesc = biasMemory->getDescWithType<DnnlMemoryDesc>();
- }
-
- MatMulKey key = {src0TransposedDesc,
- src1TransposedDesc,
- dnnlBiasMemDesc,
- dstDnnlDesc,
- *attr,
- selected_pd->getImplementationType()};
-
- auto engine = getEngine();
-
- auto builder = [&engine](const MatMulKey& key) -> executorPtr {
-#ifdef OPENVINO_ARCH_X86_64
- const bool can_optimize = [&key]() -> bool {
- const auto& prec_in0 = key.inp0->getDataType();
- const auto& prec_in1 = key.inp1->getDataType();
- const auto& prec_out = key.out->getDataType();
- if (!all_of(dnnl::memory::data_type::f32, prec_in0, prec_in1, prec_out)) {
- return false;
- }
- const auto& stride_in0 = key.inp0->getDnnlDesc().get_strides();
- const auto& stride_in1 = key.inp1->getDnnlDesc().get_strides();
- if (stride_in0.back() != 1 || stride_in1.back() != 1) {
- return false;
- }
- if (key.bias != nullptr) {
- return false;
- }
- const auto& shape_src = key.inp0->getShape().getStaticDims();
- const auto& shape_wei = key.inp1->getShape().getStaticDims();
- auto src_rank = shape_src.size();
- auto wei_rank = shape_wei.size();
- if (src_rank < 2 || src_rank != wei_rank) {
- return false;
- }
- for (size_t i = 0; i < src_rank - 2; i++) {
- if (shape_src[i] != shape_wei[i]) {
- return false;
- }
- }
- return (shape_src[src_rank - 1] <= 2) && (shape_src[src_rank - 2] <= 2) && (shape_wei[wei_rank - 1] <= 2) &&
- (shape_wei[wei_rank - 2] <= 2);
- }();
- if (can_optimize) {
- MatMulSmallAttrs matmul_attr;
- const auto& shape_in0 = key.inp0->getShape().getStaticDims();
- const auto& shape_in1 = key.inp1->getShape().getStaticDims();
- matmul_attr.M = *++shape_in0.rbegin();
- matmul_attr.K = *shape_in0.rbegin();
- matmul_attr.N = *shape_in1.rbegin();
- matmul_attr.attr = key.attr;
- return std::make_shared<MatMulSmallExecutor>(matmul_attr);
- }
-#endif
- dnnl::matmul::primitive_desc prim_desc;
-
- if (key.bias) {
- prim_desc = matmul::primitive_desc(engine,
- key.inp0->getDnnlDesc(),
- key.inp1->getDnnlDesc(),
- key.bias->getDnnlDesc(),
- key.out->getDnnlDesc(),
- key.attr);
- } else {
- prim_desc = matmul::primitive_desc(engine,
- key.inp0->getDnnlDesc(),
- key.inp1->getDnnlDesc(),
- key.out->getDnnlDesc(),
- key.attr);
- }
-
- auto first_desc = dnnl::matmul::primitive_desc(prim_desc.get());
- const bool found = DnnlExtensionUtils::find_implementation(prim_desc, key.implType);
-
- if (found) {
- return std::make_shared<DnnlMatmulExecutor>(prim_desc);
- }
-
- // In case of dynamic shapes an implementation type chosen as optimal for a primitive_desc with
- // undefined input shapes, is not necessarily available for the primitive_desc with defined shape.
- // Example: brgemm_avx512_amx (Intel Sapphire Rapids Platform) is available for a primitive with
- // undefined input shapes but not available for primitive_desc with input batch 1.
- return std::make_shared<DnnlMatmulExecutor>(first_desc);
- };
-
- auto cache = context->getParamsCache();
- auto result = cache->getOrCreate(key, builder);
-
- execPtr = result.first;
- OPENVINO_ASSERT(execPtr, "Primitive descriptor was not found for node ", getName(), ".");
-
- auto schratchpadMem = getScratchPadMem(execPtr->getScratchPadDesc());
-
- primArgs[DNNL_ARG_SCRATCHPAD] = schratchpadMem->getPrimitive();
- primArgs[DNNL_ARG_SRC_0] = src0MemPtr->getPrimitive();
- primArgs[DNNL_ARG_WEIGHTS_0] = src1MemPtr->getPrimitive();
- primArgs[DNNL_ARG_DST] = dstMemPtr->getPrimitive();
- if (withBiases) {
- primArgs[DNNL_ARG_BIAS] = getSrcMemoryAtPort(2)->getPrimitive();
- }
-
- appendPostOpArgs(*attr, primArgs, postOpsArgs);
+ const auto& executor = m_executor;
+ assert(executor);
+ executor->update(m_memory);
+ getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());
}
-void MatMul::execute(const dnnl::stream& strm) {
- if (execPtr) {
- execPtr->exec(primArgs, strm);
- } else if (hasEmptyInputTensors()) {
- // this is a degenerate case, fill output with zeroes
+void MatMul::execute(const dnnl::stream& /*strm*/) {
+ if (hasEmptyInputTensors()) { // this is a degenerate case, fill output with zeroes
getDstMemoryAtPort(0)->nullify();
- } else {
- CPU_NODE_THROW("doesn't have an initialized executor");
+ return;
}
+
+ const auto& executor = m_executor;
+ assert(executor);
+
+ executor->execute(m_memory);
}
void MatMul::executeDynamicImpl(const dnnl::stream& strm) {
execute(strm);
}
-const std::vector<impl_desc_type>& MatMul::getDefaultImplPriority() {
- static const std::vector<impl_desc_type> priorities = {
- impl_desc_type::unknown, impl_desc_type::brgemm_avx512_amx,
- impl_desc_type::brgemm_avx512, impl_desc_type::brgemm_avx2,
- impl_desc_type::gemm_acl, impl_desc_type::gemm_blas,
- impl_desc_type::gemm_avx512, impl_desc_type::gemm_avx2,
- impl_desc_type::gemm_avx, impl_desc_type::gemm_sse42,
- impl_desc_type::gemm_any, impl_desc_type::gemm,
- impl_desc_type::jit_gemm, impl_desc_type::jit_uni_dw,
- impl_desc_type::jit_uni_1x1, impl_desc_type::jit_uni,
- impl_desc_type::jit_avx512_dw, impl_desc_type::jit_avx512_1x1,
- impl_desc_type::jit_avx512, impl_desc_type::jit_avx2_dw,
- impl_desc_type::jit_avx2_1x1, impl_desc_type::jit_avx2,
- impl_desc_type::jit_avx_dw, impl_desc_type::jit_avx_1x1,
- impl_desc_type::jit_avx, impl_desc_type::jit_sse42_dw,
- impl_desc_type::jit_sse42_1x1, impl_desc_type::jit_sse42,
- impl_desc_type::ref,
- };
-
- return priorities;
-}
-
bool MatMul::neverExecute() const {
return getSelectedPrimitiveDescriptor()->hasZeroOutputDims();
}
diff --git a/src/plugins/intel_cpu/src/nodes/matmul.h b/src/plugins/intel_cpu/src/nodes/matmul.h
index 7ab5a8827db..dd895f4f02f 100644
--- a/src/plugins/intel_cpu/src/nodes/matmul.h
+++ b/src/plugins/intel_cpu/src/nodes/matmul.h
@@ -4,25 +4,21 @@
#pragma once
-#include <array>
-#include <cstddef>
#include <memory>
-#include <oneapi/dnnl/dnnl.hpp>
#include <oneapi/dnnl/dnnl_common.hpp>
#include <string>
+#include <tuple>
+#include <unordered_map>
#include <utility>
-#include "common/dnnl_executor.h"
-#include "cpu_types.h"
-#include "executors/matmul.hpp"
#include "graph_context.h"
#include "memory_desc/cpu_memory_desc.h"
-#include "memory_desc/dnnl_blocked_memory_desc.h"
-#include "memory_desc/dnnl_memory_desc.h"
#include "node.h"
-#include "onednn/iml_type_mapper.h"
+#include "nodes/executors/executor.hpp"
+#include "nodes/executors/executor_factory.hpp"
+#include "nodes/executors/matmul_config.hpp"
+#include "nodes/executors/memory_arguments.hpp"
#include "openvino/core/node.hpp"
-#include "openvino/core/shape.hpp"
#include "openvino/core/type/element_type.hpp"
namespace ov::intel_cpu::node {
@@ -31,55 +27,47 @@ class MatMul : public Node {
public:
MatMul(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);
- void getSupportedDescriptors() override;
- void createDescriptor(const std::vector<MemoryDescPtr>& inputDesc,
- const std::vector<MemoryDescPtr>& outputDesc) override;
+ void getSupportedDescriptors() override {}
void initSupportedPrimitiveDescriptors() override;
- [[nodiscard]] MemoryDescPtr getSrcMemDesc(const dnnl::primitive_desc& prim_desc, size_t idx) const override;
[[nodiscard]] bool canFuse(const NodePtr& node) const override;
[[nodiscard]] bool created() const override;
[[nodiscard]] ov::element::Type getRuntimePrecision() const override;
- size_t descInputNumbers() override {
- return getOriginalInputsNumber();
- }
+ [[nodiscard]] const std::vector<impl_desc_type>& getDefaultImplPriority() override;
[[nodiscard]] int getFusingAxis() const override {
return getOutputShapeAtPort(0).getRank() - 1;
}
+ void createPrimitive() override;
void prepareParams() override;
void execute(const dnnl::stream& strm) override;
void executeDynamicImpl(const dnnl::stream& strm) override;
static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;
- const std::vector<impl_desc_type>& getDefaultImplPriority() override;
[[nodiscard]] bool canBeExecutedInInt8() const override;
[[nodiscard]] bool neverExecute() const override;
[[nodiscard]] bool isExecutable() const override;
-protected:
- AttrPtr initPrimitiveAttr() override;
- AttrPtr initPrimitiveAttr(const VectorDims& dims);
-
private:
- using executorPtr = std::shared_ptr<IMatmulExecutor>;
- executorPtr execPtr = nullptr;
- dnnl::memory::desc getBiasDescFrom(const DnnlMemoryDescCPtr& outMemDesc);
- [[nodiscard]] std::pair<Shape, Shape> makeDummyInputShapes(const Shape& in0,
- const Shape& in1,
- const Shape& out) const;
+ std::tuple<VecMemoryDescs, MemoryDescPtr> initMemoryDescriptors(ov::element::Type dstType) const;
+ ExecutorFactoryPtr<MatMulAttrs> createExecutorFactory(const MemoryDescArgs& descs, const MatMulAttrs& attrs);
+
+ // Attributes structure for MatMul node
+ MatMulAttrs m_attrs;
- bool withBiases = false;
+ // Factory for creating executors
+ ExecutorFactoryPtr<MatMulAttrs> m_factory;
- void setPostOps(dnnl::primitive_attr& attr, const VectorDims& dims, bool initWeights);
+ // Executor instance
+ ExecutorPtr m_executor;
- /* whether to transpose input */
- std::array<bool, 2> transposeIn{};
+ // Memory arguments mapping
+ MemoryArgs m_memory;
- std::array<DnnlBlockedMemoryDescPtr, 2> inDataDesc;
- DnnlBlockedMemoryDescPtr outDataDesc;
+ // Argument to input port mapping
+ std::unordered_map<int, int> m_atoi;
};
} // namespace ov::intel_cpu::node