OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[CPU] Refactor Convolution node using new executor architecture (#28436)
Egor Duplenskii6741b9a675d1
diff --git a/src/plugins/intel_cpu/src/cpu_memory.cpp b/src/plugins/intel_cpu/src/cpu_memory.cppindex d1685d153f4..a6f2812a2e2 100644--- a/src/plugins/intel_cpu/src/cpu_memory.cpp+++ b/src/plugins/intel_cpu/src/cpu_memory.cpp@@ -518,10 +518,7 @@ MemoryBlockPtr StaticMemory::getMemoryBlock() const {// oneDNN specifics for backward compatibilitydnnl::memory StaticMemory::getPrimitive() const {- if (!m_prim && !getDesc().empty()) { // for an empty memory m_prim is expected to be empty- OPENVINO_THROW("Couldn't create dnnl::memory object: ", dnnlErrorCtx);- }-+ OPENVINO_ASSERT(m_prim || getDesc().empty(), "Could not get dnnl::memory object ", dnnlErrorCtx);return m_prim;}diff --git a/src/plugins/intel_cpu/src/dnnl_extension_utils.h b/src/plugins/intel_cpu/src/dnnl_extension_utils.hindex 49da3835628..50f6e54b354 100644--- a/src/plugins/intel_cpu/src/dnnl_extension_utils.h+++ b/src/plugins/intel_cpu/src/dnnl_extension_utils.h@@ -17,8 +17,7 @@#include "onednn/iml_type_mapper.h"#include "openvino/core/type/element_type.hpp"-namespace ov {-namespace intel_cpu {+namespace ov::intel_cpu {class DnnlMemoryDesc;class DnnlBlockedMemoryDesc;@@ -83,8 +82,9 @@ public:return true;}- if (!itpd.next_impl())+ if (!itpd.next_impl()) {break;+ }}return false;@@ -99,12 +99,14 @@ public:if (comparator(descImplType)) {func(itpd);- if (first_match)+ if (first_match) {break;+ }}- if (!itpd.next_impl())+ if (!itpd.next_impl()) {break;+ }}return;@@ -126,5 +128,4 @@ public:const std::shared_ptr<DnnlMemoryDesc>& dstDesc);};-} // namespace intel_cpu-} // namespace ov+} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp b/src/plugins/intel_cpu/src/dnnl_postops_composer.cppindex 8b031ff0a6b..0de3ba08af8 100644--- a/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp+++ b/src/plugins/intel_cpu/src/dnnl_postops_composer.cpp@@ -8,15 +8,21 @@#include <common/primitive_attr.hpp>#include <cstddef>+#include <cstdint>#include <memory>#include <oneapi/dnnl/dnnl.hpp>+#include "cpu_memory.h"#include "cpu_types.h"+#include "dnnl_extension_utils.h"+#include "memory_desc/cpu_blocked_memory_desc.h"+#include "memory_desc/cpu_memory_desc_utils.h"#include "memory_desc/dnnl_blocked_memory_desc.h"#include "nodes/executors/common/common_utils.hpp"#include "nodes/executors/memory_arguments.hpp"#include "openvino/core/type/element_type.hpp"-#include "utils/cpu_utils.hpp"+#include "post_ops.hpp"+#include "utils/cpp/to_underlying.hpp"#include "utils/debug_capabilities.h"namespace ov::intel_cpu {@@ -28,20 +34,25 @@ DnnlPostOpsComposer::DnnlPostOpsComposer(const PostOps& postOps,const bool isInt8,const int weiScaleMaskPerChannel,const MemoryArgs& memory,- const dnnl::memory::data_type outDataType)+ const dnnl::memory::data_type outDataType,+ const std::vector<float>& legacyDqScales,+ bool useLegacyPostOps,+ bool useLegacyZeroPoints): engine(engine),postOps(postOps),outputDims(outputDims),idxOC(indexOfOutputChannelDim),isINT8(isInt8),weightScaleMaskPerChannel(weiScaleMaskPerChannel),- outDataType(outDataType) {- OPENVINO_ASSERT(idxOC < outputDims.size());+ outDataType(outDataType),+ useLegacyPostOps(useLegacyPostOps),+ useLegacyZeroPoints(useLegacyZeroPoints) {+ OPENVINO_ASSERT(idxOC >= 0 && static_cast<size_t>(idxOC) < outputDims.size());OC = outputDims[idxOC];dimsPerOC = dimsPerTensor = VectorDims(outputDims.size(), 1);dimsPerOC[idxOC] = OC;- const auto& DQScales = getDeQuantizedScales(memory);+ const auto& DQScales = !legacyDqScales.empty() ? legacyDqScales : getDeQuantizedScales(memory);// generalise dq scales, so extra logic is necessary here.if (isINT8) {wei_scale_values = DQScales.empty() ? std::vector<float>{1.0} : DQScales;@@ -59,9 +70,13 @@ DnnlPostOpsComposer::DnnlPostOpsComposer(const PostOps& postOps,DEBUG_LOG("Set DQ scales for None-INT8, scale size ", DQScales.size());appendScale(DQScales, false, true);}- // @todo does not look good to set scratchpad mode here- // but the reason is that oneDNN's primitive_attr structure is basically huge config structure- // which hold everything++ if (useLegacyZeroPoints) {+ appendZeroPointsLegacy(memory);+ } else {+ appendZeroPoints(memory);+ }+attr.set_scratchpad_mode(dnnl::scratchpad_mode::user);}@@ -104,6 +119,7 @@ static dnnl::algorithm convertToOneDnn(const ActivationPostOp::Type type) {case ActivationPostOp::Type::round_half_away_from_zero:return dnnl::algorithm::eltwise_round_half_away_from_zero;case ActivationPostOp::Type::linear:+ case ActivationPostOp::Type::powerstatic: // actually eltwise_pow + eltwise_linearreturn dnnl::algorithm::eltwise_linear;}@@ -113,6 +129,24 @@ static dnnl::algorithm convertToOneDnn(const ActivationPostOp::Type type) {bool DnnlPostOpsComposer::appendAttrPostOps(const ActivationPostOp& postOp,bool isLastPostOp,[[maybe_unused]] bool allowBinary) {+ if (postOp.type() == ActivationPostOp::Type::powerstatic) {+ const auto& scale = postOp.beta();+ const auto& shift = postOp.gamma();+ if (scale != 1.0f && shift != 0.0f) {+ return appendLinear({scale}, {shift}, isLastPostOp, allowBinary);+ }++ if (scale != 1.0f) { // Multiply if has scales+ return appendScale({scale}, isLastPostOp, allowBinary);+ }++ if (shift != 0.0f) { // Add only if has shifts+ return appendShift({shift}, allowBinary);+ }++ return true;+ }+if (postOp.type() == ActivationPostOp::Type::linear) {appendLinear({postOp.alpha()}, {postOp.beta()}, isLastPostOp);} else {@@ -136,15 +170,6 @@ bool DnnlPostOpsComposer::appendAttrPostOps(const ScaleShiftPostOp& postOp, boolreturn appendScale(scales, isLastPostOp, allowBinary);case ScaleShiftPostOp::Type::muladd:return appendLinear(scales, shifts, isLastPostOp, allowBinary);- case ScaleShiftPostOp::Type::powerstatic:- if (scales[0] != 1.0f && shifts[0] != 0.0f) {- return appendLinear(scales, shifts, isLastPostOp, allowBinary);- } else if (scales[0] != 1.0f) { // Multiply if has scales- return appendScale(scales, isLastPostOp, allowBinary);- } else if (shifts[0] != 0.0f) { // Add only if has shifts- return appendShift(shifts, allowBinary);- }- break;case ScaleShiftPostOp::Type::prelu:if (!allowBinary) {return false;@@ -152,7 +177,7 @@ bool DnnlPostOpsComposer::appendAttrPostOps(const ScaleShiftPostOp& postOp, boolappendBinary(dnnl::algorithm::binary_prelu, scales);break;default:- OPENVINO_THROW(postOp.type(), " as post operation is not supported");+ OPENVINO_THROW(to_underlying(postOp.type()), " as post operation is not supported");}return true;@@ -404,6 +429,7 @@ bool DnnlPostOpsComposer::appendAttrPostOps(const FakeQuantizePostOp& postOp,appendRoundHTE();}appendClip(f.clo, f.chi);+appendLinear(f.osc, f.osh, isLastPostOp, allowBinary);return true;@@ -442,7 +468,7 @@ void DnnlPostOpsComposer::updateDestScales() {void DnnlPostOpsComposer::appendBinary(const dnnl::algorithm alg, const std::vector<float>& data) {VectorDims* pdims = &dimsPerTensor;if (data.size() > 1) {- OPENVINO_ASSERT(data.size() == OC);+ OPENVINO_ASSERT(data.size() == OC, "data size: ", data.size(), " OC: ", OC);pdims = &dimsPerOC;}@@ -450,10 +476,10 @@ void DnnlPostOpsComposer::appendBinary(const dnnl::algorithm alg, const std::vecDnnlBlockedMemoryDesc memoryDesc(ov::element::f32, Shape(*pdims));ops.append_binary(alg, memoryDesc.getDnnlDesc());-// copy the data as argsauto mem = std::make_shared<Memory>(engine, memoryDesc);memcpy(mem->getData(), data.data(), data.size() * sizeof(float));+cpuArgs[DNNL_ARG_ATTR_MULTIPLE_POST_OP(ops.len() - 1) | DNNL_ARG_SRC_1] = mem;dnnlArgs[DNNL_ARG_ATTR_MULTIPLE_POST_OP(ops.len() - 1) | DNNL_ARG_SRC_1] = mem->getPrimitive();}@@ -463,6 +489,13 @@ void DnnlPostOpsComposer::appendEltwise(const dnnl::algorithm alg, float alpha,ops.append_eltwise(alg, alpha, beta);}+void DnnlPostOpsComposer::appendSum(float scale, int32_t zeroPoint, ov::element::Type dataType) {+ DEBUG_LOG("Append sum post op with scale: ", scale, " zero point: ", zeroPoint, " data type: ", dataType);+ auto sum_data_type = DnnlExtensionUtils::ElementTypeToDataType(dataType);++ ops.append_sum(scale, zeroPoint, sum_data_type);+}+void DnnlPostOpsComposer::appendRoundHTE() {appendEltwise(dnnl::algorithm::eltwise_round_half_to_even, 0, 0);}@@ -629,6 +662,47 @@ void DnnlPostOpsComposer::appendClip(const std::vector<float>& low, const std::v}}+void DnnlPostOpsComposer::appendDepthwiseConvolution(int inH,+ int inW,+ int kerH,+ int kerW,+ int strH,+ int strW,+ dnnl::memory::data_type inDataType) {+ DEBUG_LOG("Append DW convolution");+ ops.append_dw_conv(inH, inW, kerH, kerW, strH, strW, dnnl::memory::convert_to_c(inDataType));+}++void DnnlPostOpsComposer::appendZeroPoints(const MemoryArgs& memory) {+ if (const auto arg = memory.find(ARG_ATTR_ZERO_POINTS | ARG_SRC_3); arg != memory.end()) {+ const auto mem = arg->second;+ attr.set_zero_points_mask(DNNL_ARG_SRC, 0);+ }+}++void DnnlPostOpsComposer::appendZeroPointsLegacy(const MemoryArgs& memory) {+ const auto mask = 1 << idxOC; // through C dim++ auto numElements = [](const MemoryCPtr& mem) {+ return mem->getDesc().getShape().getElementsCount();+ };++ if (const auto arg = memory.find(ARG_ATTR_ZERO_POINTS | ARG_SRC); arg != memory.end()) {+ const auto mem = arg->second;+ attr.set_input_zero_points(numElements(mem), mask);+ }++ if (const auto arg = memory.find(ARG_ATTR_ZERO_POINTS | ARG_WEI); arg != memory.end()) {+ const auto mem = arg->second;+ attr.set_weights_zero_points(numElements(mem), mask);+ }++ if (const auto arg = memory.find(ARG_ATTR_ZERO_POINTS | ARG_DST); arg != memory.end()) {+ const auto mem = arg->second;+ attr.set_output_compensations(numElements(mem), mask);+ }+}+static MemoryPtr prepackDecompressionParams(const MemoryCPtr& paramsPtr,bool needTranspose,ov::element::Type dstPrc,@@ -764,18 +838,216 @@ void DnnlPostOpsComposer::setDynamicQuantizationParams(uint64_t groupSize) {attr.set_src_dyn_quant_params(groupSize);}+void DnnlPostOpsComposer::appendAttrPostOpsLegacy(const ActivationPostOp& postOp) {+ // powerstatic is not really an activation function but have similar semantics:+ // d = s^alpha + s*beta + gamma+ if (postOp.type() == ActivationPostOp::Type::powerstatic) {+ ops.append_eltwise(dnnl::algorithm::eltwise_linear, postOp.beta(), postOp.gamma());+ if (postOp.alpha() != 1.0f) {+ ops.append_eltwise(dnnl::algorithm::eltwise_pow, 1.0f, postOp.alpha());+ }+ return;+ }+ // for the rest of activation functions 'alpha' is usually a scale and 'beta' is a shift+ ops.append_eltwise(convertToOneDnn(postOp.type()), postOp.alpha(), postOp.beta());+}++void DnnlPostOpsComposer::appendAttrPostOpsLegacy(const ScaleShiftPostOp& postOp) {+ size_t channelSize = OC;++ size_t depthwiseDataSize = 2 * channelSize;+ std::vector<float> depthwiseData;+ const auto& scales = postOp.scales();+ const auto& shifts = postOp.shifts();++ depthwiseData.insert(depthwiseData.end(), scales.begin(), scales.end());+ if (scales.size() == 1) {+ depthwiseData.resize(channelSize, depthwiseData.back());+ } else if (scales.size() != channelSize) {+ OPENVINO_THROW("failed due to scales data size inconsistency");+ }+ depthwiseData.insert(depthwiseData.end(), shifts.begin(), shifts.end());+ if (shifts.empty()) {+ // in case of Prelu algorithm scales data is always empty+ depthwiseData.resize(2 * channelSize, 0);+ } else if (shifts.size() == 1) {+ depthwiseData.resize(2 * channelSize, depthwiseData.back());+ } else if (shifts.size() != channelSize) {+ OPENVINO_THROW("failed due to shifts data size inconsistency");+ }++ // always align for legacy scale/shift post ops+ constexpr int bufferAlignment = 16;+ int bufferPaddingSize = rnd_up(channelSize, bufferAlignment) - channelSize;+ depthwiseData.resize(depthwiseDataSize + bufferPaddingSize, 0);++ std::array<size_t, 2> offsets = {0};+ offsets[1] = offsets[0] + channelSize;++ // @todo legacy depthwise post ops are kept for now for performance reasons+ switch (postOp.type()) {+ case ScaleShiftPostOp::Type::add:+ case ScaleShiftPostOp::Type::subtract:+ case ScaleShiftPostOp::Type::multiply:+ case ScaleShiftPostOp::Type::divide:+ case ScaleShiftPostOp::Type::muladd:+ ops.append_depthwise(dnnl::algorithm::depthwise_scale_shift, offsets);+ break;+ case ScaleShiftPostOp::Type::prelu:+ ops.append_depthwise(dnnl::algorithm::depthwise_prelu, offsets);+ break;+ default:+ OPENVINO_THROW("as post operation is not supported");+ }++ DnnlBlockedMemoryDesc memoryDesc(ov::element::f32, {depthwiseData.size()});+ auto memory = std::make_shared<Memory>(engine, memoryDesc);+ memcpy(memory->getData(), depthwiseData.data(), depthwiseData.size() * sizeof(float));++ cpuArgs[DNNL_ARG_ATTR_MULTIPLE_POST_OP(ops.len() - 1) | DNNL_ARG_SRC_1] = memory;+}++void DnnlPostOpsComposer::appendAttrPostOpsLegacy(const FakeQuantizePostOp& postOp) {+ // try to map fakeQuantizeNode using output scale & eltwise first+ // if failed, fallback to append_quantization()++ // oneDNN quantization_injectors assumes that quantization data memory is always aligned on 16+ // by length of AVX512 vector register which is also enough for AVX2 and SSE42 implementations.+ // Otherwise it can lead to buffer over-read and performance penalties due to denormals.+ const size_t bufferAlignment = 16;++ if (postOp.type() == FakeQuantizePostOp::Type::binarization) {+ const auto realAxisSize = OC;+ const auto axisPaddedSize = rnd_up(realAxisSize, bufferAlignment);++ std::vector<float> binarizationThresholds;+ std::vector<uint32_t> binarizationOutputMask;++ binarizationThresholds.resize(axisPaddedSize, 0);+ binarizationOutputMask.resize(axisPaddedSize, 0);++ if (postOp.isInputLowBroadcast()) {+ std::fill(binarizationThresholds.begin() + 1,+ binarizationThresholds.begin() + realAxisSize,+ binarizationThresholds[0]);+ std::fill(binarizationThresholds.begin() + realAxisSize, binarizationThresholds.end(), 0.f);+ }+ if (postOp.isOutputHighBroadcast()) {+ std::fill(binarizationOutputMask.begin() + 1,+ binarizationOutputMask.begin() + realAxisSize,+ binarizationOutputMask[0]);+ std::fill(binarizationThresholds.begin() + realAxisSize, binarizationThresholds.end(), 0.f);+ }++ return ops.append_binarization(dnnl::algorithm::binarization_depthwise,+ (const float*)&binarizationThresholds[0],+ (const float*)&binarizationOutputMask[0]);+ }++ dnnl::algorithm alg = postOp.type() == FakeQuantizePostOp::Type::quantization_only+ ? dnnl::algorithm::quantization_quantize+ : dnnl::algorithm::quantization_quantize_dequantize;++ const auto& cropLow = postOp.cropLow();+ const auto& cropHigh = postOp.cropHigh();+ const auto& inputScale = postOp.inputScale();+ const auto& inputShift = postOp.inputShift();+ const auto& outputScale = postOp.outputScale();+ const auto& outputShift = postOp.outputShift();++ const size_t cropLowSize = cropLow.size();+ const size_t cropHighSize = cropHigh.size();+ const size_t inputScaleSize = inputScale.size();+ const size_t inputShiftSize = inputShift.size();+ const size_t outputScaleSize = outputScale.size();+ const size_t outputShiftSize = outputShift.size();++ std::array<bool, 6> per_channel = {cropLowSize > 1,+ cropHighSize > 1,+ inputScaleSize > 1,+ inputShiftSize > 1,+ outputScaleSize > 1,+ outputShiftSize > 1};++ std::array<bool, 6> all_default = {false};+ all_default[0] = std::all_of(cropLow.cbegin(), cropLow.cend(), [](float val) {+ return val == 0.f;+ });+ all_default[1] = std::all_of(cropHigh.cbegin(), cropHigh.cend(), [](float val) {+ return val == 0.f;+ });+ all_default[2] = std::all_of(inputScale.cbegin(), inputScale.cend(), [](float val) {+ return val == 1.f;+ });+ all_default[3] = std::all_of(inputShift.cbegin(), inputShift.cend(), [](float val) {+ return val == 0.f;+ });+ all_default[4] = std::all_of(outputScale.cbegin(), outputScale.cend(), [](float val) {+ return val == 1.f;+ });+ all_default[5] = std::all_of(outputShift.cbegin(), outputShift.cend(), [](float val) {+ return val == 0.f;+ });++ std::array<size_t, 6> offsets = {0};+ offsets[1] = offsets[0] + cropLowSize;+ offsets[2] = offsets[1] + cropHighSize;+ offsets[3] = offsets[2] + inputScaleSize;+ offsets[4] = offsets[3] + inputShiftSize;+ offsets[5] = offsets[4] + outputScaleSize;++ std::vector<float> quantizationData;+ quantizationData.insert(quantizationData.end(), cropLow.begin(), cropLow.end());+ quantizationData.insert(quantizationData.end(), cropHigh.begin(), cropHigh.end());+ quantizationData.insert(quantizationData.end(), inputScale.begin(), inputScale.end());+ quantizationData.insert(quantizationData.end(), inputShift.begin(), inputShift.end());+ quantizationData.insert(quantizationData.end(), outputScale.begin(), outputScale.end());+ quantizationData.insert(quantizationData.end(), outputShift.begin(), outputShift.end());++ DnnlBlockedMemoryDesc memoryDesc(ov::element::f32, {quantizationData.size()});+ auto memory = std::make_shared<Memory>(engine, memoryDesc);+ memcpy(memory->getData(), quantizationData.data(), quantizationData.size() * sizeof(float));+ ops.append_quantization(alg, per_channel, all_default, offsets);++ cpuArgs[DNNL_ARG_ATTR_MULTIPLE_POST_OP(ops.len() - 1) | DNNL_ARG_SRC_1] = memory;+}+DnnlPrimitiveAttrs DnnlPostOpsComposer::compose() {+ DEBUG_LOG("Composing dnnl postops");for (size_t i = 0; i < postOps.size(); ++i) {const auto& postOp = postOps[i];bool isLastPostOp = (i == (postOps.size() - 1));// @todo replace dynamic cast with an interface for appending to DNNL postopsif (const auto activation = std::dynamic_pointer_cast<ActivationPostOp>(postOp)) {- appendAttrPostOps(*activation, isLastPostOp);+ if (useLegacyPostOps) {+ // legacy depthwise post ops often outperform binary post ops+ // first try to make do with original post ops without binary+ if (appendAttrPostOps(*activation, isLastPostOp, false)) {+ DEBUG_LOG("Append as original post op without binary");+ continue;+ }+ // fallback to legacy if failed+ appendAttrPostOpsLegacy(*activation);+ } else {+ appendAttrPostOps(*activation, isLastPostOp, true);+ }+continue;}if (const auto ss = std::dynamic_pointer_cast<ScaleShiftPostOp>(postOp)) {- appendAttrPostOps(*ss, isLastPostOp);+ if (useLegacyPostOps) {+ // legacy depthwise post ops often outperform binary post ops+ // first try to make do with original post ops without binary+ if (appendAttrPostOps(*ss, isLastPostOp, false)) {+ DEBUG_LOG("Append as original post op without binary");+ continue;+ }+ // fallback to legacy if failed+ appendAttrPostOpsLegacy(*ss);+ } else {+ appendAttrPostOps(*ss, isLastPostOp, true);+ }continue;}@@ -783,11 +1055,57 @@ DnnlPrimitiveAttrs DnnlPostOpsComposer::compose() {// drop rounding one special residual pattern// TODO: validate this unsafe optimizationauto doRounding = [&]() {+ bool hasSubsequentSum = false;+ bool hasSubsequentFQ = false;+ for (size_t j = i + 1; j < postOps.size(); j++) {+ auto& nextNode = postOps[j];++ if (auto nextEltwiseNode = std::dynamic_pointer_cast<SumPostOp>(nextNode)) {+ hasSubsequentSum = true;+ }++ if (auto nextQuantizeNode = std::dynamic_pointer_cast<FakeQuantizePostOp>(nextNode)) {+ hasSubsequentFQ = true;+ }+ }++ if (hasSubsequentSum && hasSubsequentFQ) {+ return false;+ }+return true;};auto round = i == 0 ? doRounding() : true;- appendAttrPostOps(*fq, isLastPostOp, round);+ if (useLegacyPostOps) {+ // legacy depthwise post ops often outperform binary post ops+ // first try to make do with original post ops without binary+ if (appendAttrPostOps(*fq, isLastPostOp, round, false)) {+ DEBUG_LOG("Append as original post op without binary");+ continue;+ }+ DEBUG_LOG("Append as legacy post op");+ appendAttrPostOpsLegacy(*fq);+ } else {+ DEBUG_LOG("Append as original post op");+ appendAttrPostOps(*fq, isLastPostOp, round, true);+ }+ continue;+ }++ if (const auto sum = std::dynamic_pointer_cast<SumPostOp>(postOp)) {+ appendSum(sum->scale(), sum->zeroPoint(), sum->dataType());+ continue;+ }++ if (const auto conv = std::dynamic_pointer_cast<DepthwiseConvolutionPostOp>(postOp)) {+ appendDepthwiseConvolution(conv->ih(),+ conv->iw(),+ conv->kernel()[1],+ conv->kernel()[0],+ conv->strides()[1],+ conv->strides()[0],+ dnnl::memory::data_type::f32);continue;}@@ -800,7 +1118,7 @@ DnnlPrimitiveAttrs DnnlPostOpsComposer::compose() {dnnlArgs[args.first] = args.second->getPrimitive();}- return {attr, dnnlArgs, cpuArgs};+ return {attr, dnnlArgs, cpuArgs, useLegacyZeroPoints};}} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/dnnl_postops_composer.h b/src/plugins/intel_cpu/src/dnnl_postops_composer.hindex 0dbac5966ab..93f40e055ca 100644--- a/src/plugins/intel_cpu/src/dnnl_postops_composer.h+++ b/src/plugins/intel_cpu/src/dnnl_postops_composer.h@@ -11,6 +11,7 @@#include <dnnl_types.h>#include "cpu_memory.h"+#include "memory_desc/cpu_memory_desc.h"#include "nodes/executors/dnnl/dnnl_aliases.hpp"#include "nodes/executors/dnnl/dnnl_post_op_data.hpp"#include "post_ops.hpp"@@ -28,9 +29,11 @@ public:const bool isINT8,const int weiScaleMaskPerChannel,const MemoryArgs& memory,- const dnnl::memory::data_type outDataType);+ const dnnl::memory::data_type outDataType,+ const std::vector<float>& legacyDqScales = {},+ bool useLegacyPostOps = false,+ bool useLegacyZeroPoints = false);DnnlPrimitiveAttrs compose();-void appendDecompressionScales(const MemoryCPtr& scales_ptr,bool needTranspose,ov::element::Type dstPrecision,@@ -54,8 +57,12 @@ private:bool isLastPostOp,bool doRounding,bool allowBinary = true);+ void appendAttrPostOpsLegacy(const ActivationPostOp& postOp);+ void appendAttrPostOpsLegacy(const ScaleShiftPostOp& postOp);+ void appendAttrPostOpsLegacy(const FakeQuantizePostOp& postOp);void appendBinary(const dnnl::algorithm alg, const std::vector<float>& data);void appendEltwise(const dnnl::algorithm alg, float alpha, float beta);+ void appendSum(float scale, int32_t zeroPoint, ov::element::Type dataType);void appendRoundHTE();bool appendScale(const std::vector<float>& scale, bool isLastPostOp, bool allowBinary = true);bool appendShift(const std::vector<float>& shift, bool allowBinary = true);@@ -64,7 +71,15 @@ private:bool isLastPostOp,bool allowBinary = true);void appendClip(const std::vector<float>& low, const std::vector<float>& high);-+ void appendDepthwiseConvolution(int inH,+ int inW,+ int kerH,+ int kerW,+ int strH,+ int strW,+ dnnl::memory::data_type inDataType);+ void appendZeroPoints(const MemoryArgs& memory);+ void appendZeroPointsLegacy(const MemoryArgs& memory);const dnnl::engine& engine;const PostOps& postOps;const VectorDims outputDims;@@ -73,6 +88,8 @@ private:const int weightScaleMaskPerChannel;bool weightScaleAvailable = false;const dnnl::memory::data_type outDataType;+ bool useLegacyPostOps;+ bool useLegacyZeroPoints;dnnl::primitive_attr attr;MemoryArgs cpuArgs;diff --git a/src/plugins/intel_cpu/src/graph_optimizer.cpp b/src/plugins/intel_cpu/src/graph_optimizer.cppindex e6487d7fa94..068e7703c6c 100644--- a/src/plugins/intel_cpu/src/graph_optimizer.cpp+++ b/src/plugins/intel_cpu/src/graph_optimizer.cpp@@ -1084,6 +1084,7 @@ void GraphOptimizer::FuseConvolutionAndZeroPoints(Graph& graph) {dataEltwise->getName()," is optimized as zeropoint of Conv ##",conv->getName());+ conv->setOriginalInputPrecisionAtPort(0, dataEltwise->getOriginalInputPrecisionAtPort(0));graph.RemoveEdge(p_edge);graph.DropNode(dataEltwise);initializeOutputCompensation(conv);@@ -1314,7 +1315,12 @@ void GraphOptimizer::FuseConvolutionAndDWConvolution(Graph& graph) {OPENVINO_THROW("Cannot get convolution node ", parentNode->getName());}- if (!impl::cpu::x64::mayiuse(impl::cpu::x64::avx2) || impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core)) {+ if (!impl::cpu::x64::mayiuse(impl::cpu::x64::avx2)) {+ return false;+ }+ // there is no optimized implementation for avx512, so two avx512 convolutions+ // are expected to be faster than single fused avx2 convolution+ if (impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core)) {return false;}diff --git a/src/plugins/intel_cpu/src/memory_format_filter.hpp b/src/plugins/intel_cpu/src/memory_format_filter.hppnew file mode 100644index 00000000000..58d2a822c00--- /dev/null+++ b/src/plugins/intel_cpu/src/memory_format_filter.hpp@@ -0,0 +1,21 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <oneapi/dnnl/dnnl.hpp>+#include <vector>++namespace ov::intel_cpu {++struct MemoryFormatFilter {+ std::vector<dnnl::memory::format_tag> input;+ std::vector<dnnl::memory::format_tag> output;++ [[nodiscard]] bool empty() const {+ return input.empty() && output.empty();+ }+};++} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/node.cpp b/src/plugins/intel_cpu/src/node.cppindex a14e0ac1dc7..fe2190a264e 100644--- a/src/plugins/intel_cpu/src/node.cpp+++ b/src/plugins/intel_cpu/src/node.cpp@@ -147,7 +147,7 @@ Node::Node(const std::shared_ptr<ov::Node>& op, GraphContext::CPtr ctx, const Shif (str.substr(0, 4) != "cpu:") {continue;}- inputMemoryFormatsFilter.push_back(dnnl::utils::str2fmt(str.substr(4, str.size()).c_str()));+ memoryFormatFilter.input.push_back(dnnl::utils::str2fmt(str.substr(4, str.size()).c_str()));}}@@ -159,7 +159,7 @@ Node::Node(const std::shared_ptr<ov::Node>& op, GraphContext::CPtr ctx, const Shif (str.substr(0, 4) != "cpu:") {continue;}- outputMemoryFormatsFilter.push_back(dnnl::utils::str2fmt(str.substr(4, str.size()).c_str()));+ memoryFormatFilter.output.push_back(dnnl::utils::str2fmt(str.substr(4, str.size()).c_str()));}}@@ -962,7 +962,7 @@ void Node::initSupportedPrimitiveDescriptors() {}void Node::filterSupportedPrimitiveDescriptors() {- if (inputMemoryFormatsFilter.empty() && outputMemoryFormatsFilter.empty()) {+ if (memoryFormatFilter.empty()) {return;}@@ -975,27 +975,27 @@ void Node::filterSupportedPrimitiveDescriptors() {auto isNotSuitableDesc = [&](const NodeDesc& desc) {const auto& config = desc.getConfig();- if (inputMemoryFormatsFilter.size() > config.inConfs.size() ||- outputMemoryFormatsFilter.size() > config.outConfs.size()) {+ if (memoryFormatFilter.input.size() > config.inConfs.size() ||+ memoryFormatFilter.output.size() > config.outConfs.size()) {OPENVINO_THROW("Incorrect number of input or output memory formats");}- for (size_t i = 0; i < inputMemoryFormatsFilter.size(); i++) {- if (!areCompatible(*config.inConfs[i].getMemDesc(), inputMemoryFormatsFilter[i])) {+ for (size_t i = 0; i < memoryFormatFilter.input.size(); i++) {+ if (!areCompatible(*config.inConfs[i].getMemDesc(), memoryFormatFilter.input[i])) {DEBUG_LOG(getName()," input memory format filter: ",- inputMemoryFormatsFilter[i],+ memoryFormatFilter.input[i]," not matched. Erase desc from supported primitive descriptors: ",desc);return true;}}- for (size_t i = 0; i < outputMemoryFormatsFilter.size(); i++) {- if (!areCompatible(*config.outConfs[i].getMemDesc(), outputMemoryFormatsFilter[i])) {+ for (size_t i = 0; i < memoryFormatFilter.output.size(); i++) {+ if (!areCompatible(*config.outConfs[i].getMemDesc(), memoryFormatFilter.output[i])) {DEBUG_LOG(getName()," Output memory format filter: ",- outputMemoryFormatsFilter[i],+ memoryFormatFilter.output[i]," not matched. Erase desc from supported primitive descriptors: ",desc);return true;diff --git a/src/plugins/intel_cpu/src/node.h b/src/plugins/intel_cpu/src/node.hindex 8a701d895c6..13771c08291 100644--- a/src/plugins/intel_cpu/src/node.h+++ b/src/plugins/intel_cpu/src/node.h@@ -23,6 +23,7 @@#include "graph_context.h"#include "memory_desc/cpu_memory_desc.h"#include "memory_desc/dnnl_memory_desc.h"+#include "memory_format_filter.hpp"#include "nodes/executors/executor.hpp"#include "nodes/node_config.h"#include "onednn/dnnl.h"@@ -761,8 +762,7 @@ protected:std::string primitivesPriority;std::vector<impl_desc_type> customImplPriorities;- std::vector<dnnl::memory::format_tag> inputMemoryFormatsFilter;- std::vector<dnnl::memory::format_tag> outputMemoryFormatsFilter;+ MemoryFormatFilter memoryFormatFilter;bool enforceBF16evenForGraphTail = false;bool keepOriginalPrecision = false;diff --git a/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.cpp b/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.cppindex 7aec45da8c3..99e20e90c64 100644--- a/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.cpp+++ b/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.cpp@@ -7,7 +7,7 @@ using namespace dnnl;namespace ov::intel_cpu {-DnnlExecutor::DnnlExecutor(const dnnl::primitive_desc& pd) {+DnnlExecutorLegacy::DnnlExecutorLegacy(const dnnl::primitive_desc& pd) {execPrim = dnnl::primitive(pd);src_md = DnnlExtensionUtils::makeDescriptor(pd.src_desc());dst_md = DnnlExtensionUtils::makeDescriptor(pd.dst_desc());@@ -15,20 +15,20 @@ DnnlExecutor::DnnlExecutor(const dnnl::primitive_desc& pd) {scrch_md = DnnlExtensionUtils::makeDescriptor(pd.scratchpad_desc());}-DnnlExecutor::IntermReorder::IntermReorder(const dnnl::memory::desc& descSrc,- const dnnl::memory::desc& descDst,- const dnnl::engine& engine)+DnnlExecutorLegacy::IntermReorder::IntermReorder(const dnnl::memory::desc& descSrc,+ const dnnl::memory::desc& descDst,+ const dnnl::engine& engine): m_descSrc(descSrc),m_descDst(descDst) {auto reorderPd = dnnl::reorder::primitive_desc(engine, descSrc, engine, descDst);m_reorder = dnnl::reorder(reorderPd);}-void DnnlExecutor::IntermReorder::exec(dnnl::memory& memSrc, dnnl::memory& memDst, const dnnl::stream& strm) {+void DnnlExecutorLegacy::IntermReorder::exec(dnnl::memory& memSrc, dnnl::memory& memDst, const dnnl::stream& strm) {m_reorder.execute(strm, memSrc, memDst);}-void DnnlExecutor::exec(const std::unordered_map<int, dnnl::memory>& primArgs, const dnnl::stream& strm) {+void DnnlExecutorLegacy::exec(const std::unordered_map<int, dnnl::memory>& primArgs, const dnnl::stream& strm) {if (inputReorders.empty() && outputReorders.empty()) {execPrim.execute(strm, primArgs);} else {@@ -36,7 +36,7 @@ void DnnlExecutor::exec(const std::unordered_map<int, dnnl::memory>& primArgs, c}}-void DnnlExecutor::reorder_exec(std::unordered_map<int, dnnl::memory> primArgs, const dnnl::stream& strm) {+void DnnlExecutorLegacy::reorder_exec(std::unordered_map<int, dnnl::memory> primArgs, const dnnl::stream& strm) {for (auto& inReorder : inputReorders) {if (primArgs.count(inReorder.first)) {dnnl::memory memDst(inReorder.second.getDstDesc(), strm.get_engine());@@ -64,19 +64,19 @@ void DnnlExecutor::reorder_exec(std::unordered_map<int, dnnl::memory> primArgs,}}-bool DnnlExecutor::needReordering() const {+bool DnnlExecutorLegacy::needReordering() const {return !inputReorders.empty() || !outputReorders.empty();}-dnnl::primitive DnnlExecutor::getExecPrim() const {+dnnl::primitive DnnlExecutorLegacy::getExecPrim() const {return execPrim;}-const_dnnl_primitive_desc_t DnnlExecutor::getPrimitiveDesc() const {+const_dnnl_primitive_desc_t DnnlExecutorLegacy::getPrimitiveDesc() const {return execPrim.get_primitive_desc();}-impl_desc_type DnnlExecutor::getImplementationType() const {+impl_desc_type DnnlExecutorLegacy::getImplementationType() const {auto pd = getPrimitiveDesc();return parse_impl_name(DnnlExtensionUtils::query_impl_info_str(pd));}diff --git a/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.h b/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.hindex 86e8ab526fa..e1c28459819 100644--- a/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.h+++ b/src/plugins/intel_cpu/src/nodes/common/dnnl_executor.h@@ -9,19 +9,18 @@#include "memory_desc/dnnl_memory_desc.h"-namespace ov {-namespace intel_cpu {+namespace ov::intel_cpu {-class DnnlExecutor {+class DnnlExecutorLegacy {protected:class IntermReorder {public:IntermReorder(const dnnl::memory::desc& descSrc, const dnnl::memory::desc& descDst, const dnnl::engine& engine);void exec(dnnl::memory& memSrc, dnnl::memory& memDst, const dnnl::stream& strm);- const dnnl::memory::desc& getSrcDesc() const {+ [[nodiscard]] const dnnl::memory::desc& getSrcDesc() const {return m_descSrc;}- const dnnl::memory::desc& getDstDesc() const {+ [[nodiscard]] const dnnl::memory::desc& getDstDesc() const {return m_descDst;}@@ -32,10 +31,10 @@ protected:};public:- explicit DnnlExecutor(const dnnl::primitive_desc& pd);+ explicit DnnlExecutorLegacy(const dnnl::primitive_desc& pd);void exec(const std::unordered_map<int, dnnl::memory>& primArgs, const dnnl::stream& strm);bool needReordering() const;- virtual ~DnnlExecutor() = default;+ virtual ~DnnlExecutorLegacy() = default;dnnl::primitive getExecPrim() const;const_dnnl_primitive_desc_t getPrimitiveDesc() const;impl_desc_type getImplementationType() const;@@ -80,5 +79,4 @@ protected:DnnlMemoryDescPtr scrch_md;};-} // namespace intel_cpu-} // namespace ov+} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/conv.cpp b/src/plugins/intel_cpu/src/nodes/conv.cppindex f16b0fed833..69150e29760 100644--- a/src/plugins/intel_cpu/src/nodes/conv.cpp+++ b/src/plugins/intel_cpu/src/nodes/conv.cpp@@ -4,113 +4,40 @@#include "conv.h"+#include <cassert>#include <cstdlib>#include <memory>#include <string>+#include <utility>#include <vector>-#include "common/c_types_map.hpp"#include "common/cpu_convert.h"-#include "common/primitive_desc.hpp"-#include "common/primitive_desc_iface.hpp"-#include "common/primitive_hashing_utils.hpp"-#include "concat.h"-#include "cpu/cpu_primitive.hpp"#include "cpu/x64/cpu_isa_traits.hpp"-#include "cpu/x64/jit_generator.hpp"+#include "cpu_types.h"#include "dnnl_extension_utils.h"-#include "dnnl_types.h"#include "eltwise.h"-#include "fake_quantize.h"#include "graph.h"#include "input.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 "node.h"+#include "nodes/executors/convolution_config.hpp"+#include "nodes/executors/memory_arguments.hpp"#include "oneapi/dnnl/dnnl.hpp"#include "oneapi/dnnl/dnnl_common.hpp"-#include "oneapi/dnnl/dnnl_types.h"-#include "onednn/dnnl.h"+#include "openvino/core/type/element_type.hpp"#include "openvino/op/convolution.hpp"#include "openvino/op/group_conv.hpp"-#include "pooling.h"-#include "reorder.h"-#include "utils/cpu_utils.hpp"+#include "post_ops.hpp"+#include "shape_inference/custom/convolution.hpp"#include "utils/debug_capabilities.h"#include "utils/general_utils.h"using namespace dnnl;namespace ov::intel_cpu::node {-namespace {--struct ConvKey {- DnnlMemoryDescCPtr inp0;- DnnlMemoryDescCPtr inp1;- DnnlMemoryDescCPtr bias;- DnnlMemoryDescCPtr out;-- std::vector<size_t> stride;- std::vector<ptrdiff_t> dilation;- std::vector<ptrdiff_t> paddingL;- std::vector<ptrdiff_t> paddingR;-- dnnl::primitive_attr attr;- impl_desc_type implType;-- bool constWeight;-- [[nodiscard]] size_t hash() const;- bool operator==(const ConvKey& rhs) const;-};--size_t ConvKey::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 = get_vector_hash(seed, stride);- seed = get_vector_hash(seed, dilation);- seed = get_vector_hash(seed, paddingL);- seed = get_vector_hash(seed, paddingR);-- seed = hash_combine(seed, get_attr_hash(*attr.get()));- seed = hash_combine(seed, implType);- seed = hash_combine(seed, constWeight);- return seed;-}--bool ConvKey::operator==(const ConvKey& 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 && stride == rhs.stride;- retVal = retVal && dilation == rhs.dilation;- retVal = retVal && paddingL == rhs.paddingL;- retVal = retVal && paddingR == rhs.paddingR;-- retVal = retVal && *attr.get() == *rhs.attr.get() && implType == rhs.implType && constWeight == rhs.constWeight;- return retVal;-}--} // namespaceclass Convolution::FusedSubgraph {public:@@ -192,23 +119,21 @@ public:}[[nodiscard]] std::shared_ptr<Input> getInput(size_t idx) const {- if (idx < inputs.size()) {- return inputs[idx];- }- OPENVINO_THROW("OutOfBounds: Unexpected input index in Convolution::fusedSubgraph::getInput idx=",- idx,- " inputs.size()=",- inputs.size());+ OPENVINO_ASSERT(idx < inputs.size(),+ "OutOfBounds: Unexpected input index in Convolution::fusedSubgraph::getInput idx=",+ idx,+ " inputs.size()=",+ inputs.size());+ return inputs[idx];}[[nodiscard]] std::shared_ptr<Input> getOutput(size_t idx) const {- if (idx < outputs.size()) {- return outputs[idx];- }- OPENVINO_THROW("OutOfBounds: Unexpected output index in Convolution::fusedSubgraph::getInput idx=",- idx,- " inputs.size()=",- outputs.size());+ OPENVINO_ASSERT(idx < outputs.size(),+ "OutOfBounds: Unexpected output index in Convolution::fusedSubgraph::getInput idx=",+ idx,+ " outputs.size()=",+ outputs.size());+ return outputs[idx];}void infer() {@@ -245,11 +170,9 @@ bool Convolution::isSupportedOperation(const std::shared_ptr<const ov::Node>& op}Convolution::Convolution(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context)- : Node(op, context, NgraphShapeInferFactory(op)),- withBiases(false),+ : Node(op, context, ConvolutionShapeInferFactory(op)),withSum(false),withDWConv(false),- isGrouped(false),dw_conv_oc(0),dw_conv_ih(0),dw_conv_iw(0),@@ -257,13 +180,15 @@ Convolution::Convolution(const std::shared_ptr<ov::Node>& op, const GraphContextgroupNum(1lu),IC(1),groupIC(1),- groupOC(1),- eltwisePrecision(ov::element::f32) {+ groupOC(1) {std::string errorMessage;if (!isSupportedOperation(op, errorMessage)) {OPENVINO_THROW_NOT_IMPLEMENTED(errorMessage);}+ m_atoi[ARG_SRC] = DATA;+ m_atoi[ARG_WEI] = WEIGHTS;+auto convolutionOp = ov::as_type_ptr<ov::op::v1::Convolution>(op);auto groupConvolutionOp = ov::as_type_ptr<ov::op::v1::GroupConvolution>(op);@@ -271,49 +196,52 @@ Convolution::Convolution(const std::shared_ptr<ov::Node>& op, const GraphContextalgorithm = Algorithm::ConvolutionCommon;groupNum = 1;- isGrouped = false;+ m_attrs.isGrouped = false;- weightDims = convolutionOp->input_value(1).get_shape();+ const auto& weightDims = convolutionOp->input_value(1).get_shape();IC = weightDims[1];groupIC = IC;groupOC = weightDims[0];- expectedBiasDims = {groupOC};-for (size_t i : convolutionOp->get_strides()) {- stride.push_back(i);+ m_attrs.stride.push_back(i);}for (size_t i : convolutionOp->get_dilations()) {- dilation.push_back(static_cast<ptrdiff_t>(i) - 1);- }- paddingL = convolutionOp->get_pads_begin();- paddingR = convolutionOp->get_pads_end();- autoPadding = one_of(convolutionOp->get_auto_pad(), ov::op::PadType::SAME_UPPER, ov::op::PadType::SAME_LOWER);+ m_attrs.dilation.push_back(static_cast<ptrdiff_t>(i) - 1);+ }+ m_attrs.paddingL = convolutionOp->get_pads_begin();+ m_attrs.paddingR = convolutionOp->get_pads_end();+ m_attrs.autoPadding =+ convolutionOp->get_auto_pad() == ov::op::PadType::SAME_UPPER+ ? AutoPaddingType::SAME_UPPER+ : (convolutionOp->get_auto_pad() == ov::op::PadType::SAME_LOWER ? AutoPaddingType::SAME_LOWER+ : AutoPaddingType::None);} else if (groupConvolutionOp) {algorithm = Algorithm::ConvolutionGrouped;+ m_attrs.isGrouped = true;groupNum = groupConvolutionOp->input_value(1).get_shape()[0];- isGrouped = true;- weightDims = groupConvolutionOp->input_value(1).get_shape();+ const auto& weightDims = groupConvolutionOp->input_value(1).get_shape();groupIC = weightDims[2];IC = groupIC * groupNum;groupOC = weightDims[1];- expectedBiasDims = {groupOC * groupNum};-for (size_t i : groupConvolutionOp->get_strides()) {- stride.push_back(i);+ m_attrs.stride.push_back(i);}for (size_t i : groupConvolutionOp->get_dilations()) {- dilation.push_back(static_cast<ptrdiff_t>(i) - 1);+ m_attrs.dilation.push_back(i - 1);}- paddingL = groupConvolutionOp->get_pads_begin();- paddingR = groupConvolutionOp->get_pads_end();- autoPadding =- one_of(groupConvolutionOp->get_auto_pad(), ov::op::PadType::SAME_UPPER, ov::op::PadType::SAME_LOWER);+ m_attrs.paddingL = groupConvolutionOp->get_pads_begin();+ m_attrs.paddingR = groupConvolutionOp->get_pads_end();+ m_attrs.autoPadding =+ groupConvolutionOp->get_auto_pad() == ov::op::PadType::SAME_UPPER+ ? AutoPaddingType::SAME_UPPER+ : (groupConvolutionOp->get_auto_pad() == ov::op::PadType::SAME_LOWER ? AutoPaddingType::SAME_LOWER+ : AutoPaddingType::None);}// Only apply this heuristic logic on FP32 IR. IC=1 ,OC=1 would disable brgconv on avx2.const bool isAvx2FP32 = !dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core) &&@@ -337,25 +265,6 @@ bool Convolution::canBeExecutedInInt8() const {weightsDataType == memory::data_type::s8;}-ov::element::Type Convolution::fusedEltwisePrecision(const NodePtr& fusingNode) const {- if (sumPrc != ov::element::dynamic) {- return sumPrc;- }-- ov::element::Type eltwisePrecision;-- int fusingPort = fusingNode->getFusingPort();- if (fusingPort == 0) {- eltwisePrecision = fusingNode->getOriginalInputPrecisionAtPort(1);- } else if (fusingPort == 1) {- eltwisePrecision = fusingNode->getOriginalInputPrecisionAtPort(0);- } else {- THROW_CPU_NODE_ERR("Cannot determine Eltwise post op precision");- }-- return eltwisePrecision;-}-const std::vector<impl_desc_type>& Convolution::getDefaultImplPriority() {static const std::vector<impl_desc_type> priorities = {impl_desc_type::unknown,@@ -399,7 +308,9 @@ const std::vector<impl_desc_type>& Convolution::getDefaultImplPriority() {impl_desc_type::ref_any,impl_desc_type::ref,};- if (isBrgConvAvailable()) {+ // WA heuristic to avoid regressions introduced by avx2 brgconv.+ const bool isBrgConvAvailable = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2) && !useJitPlanar;+ if (isBrgConvAvailable) {return priorities;}@@ -413,409 +324,192 @@ const std::vector<impl_desc_type>& Convolution::getDefaultImplPriority() {return priorities_wo_brgemm;}-const bool Convolution::isBrgConvAvailable() {- // When avx2 brgconv heuristic case, disable brgconv to WA the regression.- const bool isBrgConvAvailable = dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2) && !useJitPlanar;- return isBrgConvAvailable;-}--void Convolution::getSupportedDescriptors() {- if (!descs.empty()) {- return;- }- if (!attrs.empty()) {- THROW_CPU_NODE_ERR("has a non-empty attrs vector");+void Convolution::selectOptimalPrimitiveDescriptor() {+ selectPreferPrimitiveDescriptor(getImplPriority(), true);+ /* preemptively create a fallback subgraph to include it into global memory reuse+ * pros:+ * - less total memory usage when fallback is actually needed (by size of intermediate memory)+ * - no runtime overhead of graph creation when fallback is needed for the first time+ * cons:+ * - more total memory usage when fallback is not needed (by size of a graph data structure itself)+ */+ if (withSum && isDynamicNode()) {+ subgraph = std::make_shared<FusedSubgraph>(fusedWith, *this, context);}+}- attrs.reserve(2);- withBiases = getOriginalInputsNumber() == 3;-- auto expectedInputEdgesNum = static_cast<int>(getOriginalInputsNumber());- for (auto& i : fusedWith) {- if (i->getType() == Type::Convolution) {- expectedInputEdgesNum += static_cast<int>(i->getOriginalInputsNumber()) - 1;- }-- if (i->getAlgorithm() == Algorithm::EltwiseAdd) {- auto* eltwiseNode = dynamic_cast<Eltwise*>(i.get());- if (eltwiseNode && eltwiseNode->isSpecialConvolutionAddFusing()) {- expectedInputEdgesNum++;- }- }+static MemoryDescPtr getSumMemDesc(const MemoryDescPtr& outputDesc, const Shape& sumShape) {+ if (outputDesc->getShape().isStatic()) {+ return outputDesc;}- auto inputDataType = DnnlExtensionUtils::ElementTypeToDataType(getOriginalInputPrecisionAtPort(0));- if (!legacyInputZeroPoints.empty()) {- inputDataType = memory::data_type::u8;+ // When we set the input shape with ranged dimensions, the sum node's input shape may mismatch with the output+ // shape, we just change ranged min value to 1 to meet this case. For example: Output shape = {1, 160, {128, 256},+ // {128, 256}} Sum input shape = {1, 160, 1, 1} Update sum shape to {1, 160, {1, 256}, {1, 256}}+ const auto& shape = outputDesc->getShape();+ if (shape.getRank() != sumShape.getRank()) {+ return outputDesc;}- outputDataType = DnnlExtensionUtils::ElementTypeToDataType(getOriginalOutputPrecisionAtPort(0));- eltwisePrecision = DnnlExtensionUtils::DataTypeToElementType(outputDataType);- if (!fusedWith.empty()) {- outputDataType = DnnlExtensionUtils::ElementTypeToDataType(- fusedWith[fusedWith.size() - 1]->getOriginalOutputPrecisionAtPort(0));- eltwisePrecision = DnnlExtensionUtils::DataTypeToElementType(outputDataType);- }+ const auto& sumDims = sumShape.getDims();+ const auto& maxDims = shape.getMaxDims();+ auto minDims = shape.getMinDims();- // We need to make sure that convolution output and second input of fused Eltwise operation- // have equal precision sizes since they use the same physical memory. In case precisions are different we upscale- // to FP32.- if (outputDataType != memory::data_type::f32 && outputDataType != memory::data_type::bf16 &&- outputDataType != memory::data_type::f16 && withSum) {- for (auto& i : fusedWith) {- if (i->getAlgorithm() == Algorithm::EltwiseAdd) {- auto* eltwiseNode = dynamic_cast<Eltwise*>(i.get());- if (eltwiseNode && eltwiseNode->isSpecialConvolutionAddFusing()) {- eltwisePrecision = fusedEltwisePrecision(i);- if (DnnlExtensionUtils::DataTypeToElementType(outputDataType).size() != eltwisePrecision.size()) {- eltwisePrecision = ov::element::f32;- outputDataType = memory::data_type::f32;- }- break;- }- }+ for (size_t i = 0; i < maxDims.size(); i++) {+ if ((maxDims[i] > minDims[i]) && sumDims[i] == 1) {+ minDims[i] = 1;}}- if (static_cast<int>(getParentEdges().size()) != expectedInputEdgesNum) {- THROW_CPU_NODE_ERR("Incorrect number of input edges, expected: ",- expectedInputEdgesNum,- " actual: ",- getParentEdges().size());- }- if (getChildEdges().empty()) {- THROW_CPU_NODE_ERR("Incorrect number of output edges");- }+ auto blockedOutputDesc = outputDesc->as<BlockedMemoryDesc>();- int ndims = getInputShapeAtPort(0).getRank();+ return std::make_shared<CpuBlockedMemoryDesc>(outputDesc->getPrecision(),+ Shape(minDims, maxDims),+ blockedOutputDesc->getBlockDims(),+ blockedOutputDesc->getOrder(),+ blockedOutputDesc->getOffsetPadding(),+ blockedOutputDesc->getOffsetPaddingToData(),+ blockedOutputDesc->getStrides());+}++std::tuple<VecMemoryDescs, MemoryDescPtr> Convolution::initMemoryDescriptors(ov::element::Type dstType) const {+ const auto& srcTypes = getOriginalInputPrecisions();- withDWConv = isFusedWith(Type::Convolution);- if (withDWConv && isDynamicNode()) {- THROW_CPU_NODE_ERR("DW convolution is fused into the node with dynamic shape.");+ VecMemoryDescs srcDescs;+ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();+ for (size_t i = 0; i < srcTypes.size(); i++) {+ if (srcTypes[i] == element::dynamic) {+ srcDescs.push_back(MemoryDescUtils::makeEmptyDesc());+ continue;+ }+ auto srcDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(srcTypes[i], getInputShapeAtPort(i));+ srcDescs.push_back(srcDesc);}- for (size_t i = 0; i < fusedWith.size(); i++) {- auto* convolutionNode = dynamic_cast<Convolution*>(fusedWith[i].get());- if (convolutionNode) {- auto& inActivationDims = convolutionNode->inputShapes[0].getStaticDims();- dw_conv_ih = inActivationDims[convolutionNode->inputShapes[0].getRank() - 2];- dw_conv_iw = inActivationDims[convolutionNode->inputShapes[0].getRank() - 1];-- auto& outDims = convolutionNode->outputShapes[0].getStaticDims();- dw_conv_oc = outDims[1];-- const auto& dwWeightsDims = convolutionNode->inputShapes[1].getStaticDims();- dw_conv_kernel.push_back(dwWeightsDims[dwWeightsDims.size() - 1]);- dw_conv_kernel.push_back(dwWeightsDims[dwWeightsDims.size() - 2]);- dw_conv_strides = convolutionNode->getStride();-- if (canBeExecutedInInt8()) {- if (i == 0) {- dw_conv_in_dt = DnnlExtensionUtils::ElementTypeToDataType(getOriginalOutputPrecisionAtPort(0));- } else {- dw_conv_in_dt = DnnlExtensionUtils::ElementTypeToDataType(- fusedWith[i - 1]->getOriginalOutputPrecisionAtPort(0));- }- } else {- dw_conv_in_dt = memory::data_type::f32;- }+ auto dstDesc = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(dstType, getOutputShapeAtPort(0));- for (size_t j = 0; j < paddingR.size(); j++) {- int with_group = isGrouped ? 1 : 0;- int krn = weightDims[with_group + 2 + j];- int src = getInputShapeAtPort(0).getStaticDims()[2 + j];- int dst = getOutputShapeAtPort(0).getStaticDims()[2 + j];+ return {srcDescs, dstDesc};+}- krn = (krn - 1) * (dilation[j] + 1) + 1;- int calc_dst = (src - krn + paddingL[j]) / stride[j] + 1;- paddingR[j] = (dst - calc_dst) * stride[j];- }- }- }+ExecutorFactoryPtr<ConvAttrs> Convolution::createExecutorFactory(const MemoryDescArgs& descs,+ const ConvAttrs& attrs,+ const PostOps& postOps) {+ auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);+ return std::make_shared<ExecutorFactory<ConvAttrs>>(attrs, postOps, executionContext, descs, memoryFormatFilter);+}- MemoryDescPtr in_candidate, out_candidate;- memory::format_tag nspc =- ndims == 3 ? memory::format_tag::nwc : (ndims == 4 ? memory::format_tag::nhwc : memory::format_tag::ndhwc);- [[maybe_unused]] memory::format_tag ncsp =- ndims == 3 ? memory::format_tag::ncw : (ndims == 4 ? memory::format_tag::nchw : memory::format_tag::ncdhw);- [[maybe_unused]] memory::format_tag nCsp8c =- ndims == 3 ? memory::format_tag::nCw8c- : (ndims == 4 ? memory::format_tag::nChw8c : memory::format_tag::nCdhw8c);- [[maybe_unused]] memory::format_tag nCsp16c =- ndims == 3 ? memory::format_tag::nCw16c- : (ndims == 4 ? memory::format_tag::nChw16c : memory::format_tag::nCdhw16c);-- if (canBeExecutedInInt8()) {- DEBUG_LOG(getName(), "Creating I8 descriptor");-- // so far oneDNN INT8 convolution only support s8,u8,s32,f32,bf16 output types- if (outputDataType == memory::data_type::f16) {- outputDataType = memory::data_type::f32;- eltwisePrecision = ov::element::f32;+std::tuple<ov::element::Type, ov::element::Type> Convolution::getDstAndSumPrecision() {+ auto getSumDataType = [](const std::shared_ptr<node::Eltwise>& eltwise) {+ int fusingPort = eltwise->getFusingPort();+ switch (fusingPort) {+ case 0:+ return eltwise->getOriginalInputPrecisionAtPort(1);+ case 1:+ return eltwise->getOriginalInputPrecisionAtPort(0);+ default:+ OPENVINO_THROW("Unexpected sum fusing port: ", fusingPort);}+ };- SetPostOpsAndZeroPoints(attrs);+ auto dstType = getOriginalOutputPrecisionAtPort(0);- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(getInputShapeAtPort(0), inputDataType, nspc);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(getOutputShapeAtPort(0), outputDataType, nspc);- createDescriptor({in_candidate}, {out_candidate});- return;+ // make sure dst type is equal to the output type of the last fused node+ if (!fusedWith.empty()) {+ dstType = fusedWith.back()->getOriginalOutputPrecisionAtPort(0);}- auto getSupportedDataType = [this, ndims](ov::element::Type originalPrec) {- auto originalDT = DnnlExtensionUtils::ElementTypeToDataType(originalPrec);- auto dt = memory::data_type::f32;+ auto ndims = getInputShapeAtPort(0).getRank();- // supported lower precisions: bf16, f16- if (one_of(originalDT, memory::data_type::bf16, memory::data_type::f16) && hasHardwareSupport(originalPrec)) {- dt = originalDT;+ // Make sure that convolution output and the Sum input have equal precision sizes+ // since they use the same physical memory. Upscale in case precisions are different+ for (auto& node : fusedWith) {+ if (node->getAlgorithm() != Algorithm::EltwiseAdd) {+ continue;}- // fallback to f32 on special case for performance reasons- if (isDepthWise() && ndims == 5) {- dt = memory::data_type::f32;- }- return dt;- };+ if (auto eltwiseNode = std::dynamic_pointer_cast<Eltwise>(node)) {+ if (!eltwiseNode->isSpecialConvolutionAddFusing()) {+ continue;+ }- inputDataType = getSupportedDataType(getOriginalInputPrecisionAtPort(0));- outputDataType = getSupportedDataType(getOriginalOutputPrecisionAtPort(0));+ ov::element::Type eltwisePrecision = getSumDataType(eltwiseNode);+ if (canBeExecutedInInt8() && dstType.size() != eltwisePrecision.size()) {+ return {ov::element::f32, ov::element::f32};+ }- eltwisePrecision = ov::element::f32;- for (auto& i : fusedWith) {- if (i->getAlgorithm() == Algorithm::EltwiseAdd) {- auto* eltwiseNode = dynamic_cast<Eltwise*>(i.get());- if (eltwiseNode && eltwiseNode->isSpecialConvolutionAddFusing()) {- eltwisePrecision = fusedEltwisePrecision(i);- // TODO(amalyshe): there might be situation when convolution can be executed in BF16,- // output is required in FP32 but eltwise inplace tensor would be in BF16- // currently we forcedly change output to the BF16 that will add reoreder after the node- // Another situation can be when we mark output as FP32 and Eltwise asPrecison (which stand- // for input of inplace tensor precision) to FP32. This will add reorder for that in-place tensor- // bofore the fused convolution. This behaviour might be more correct regarding expected markup- // of the graph but performance of first and second approaches might be different. Need to verify- outputDataType = getSupportedDataType(eltwisePrecision);- eltwisePrecision = DnnlExtensionUtils::DataTypeToElementType(outputDataType);+ if (isDepthWise() && ndims == 5) {+ return {ov::element::f32, ov::element::f32};+ }++ if (one_of(dstType, ov::element::f32, ov::element::bf16, ov::element::f16)) {+ return {dstType, dstType};}++ return {dstType, eltwisePrecision};}}- // correction for cases of FP32 input - we do not have FP32 convolution supported BF16 output- if (inputDataType == memory::data_type::f32 &&- (outputDataType == memory::data_type::bf16 || eltwisePrecision == ov::element::bf16 ||- outputDataType == memory::data_type::f16 || eltwisePrecision == ov::element::f16)) {- outputDataType = memory::data_type::f32;- eltwisePrecision = ov::element::f32;- }- SetPostOpsAndZeroPoints(attrs);- if (!one_of(ndims, 3, 4, 5)) {- return;- }+ return {dstType, ov::element::dynamic};+}- auto inputShape = getInputShapeAtPort(0);- auto outputShape = getOutputShapeAtPort(0);--#if defined(OPENVINO_ARCH_X86_64)- // nspc shows better performance only with brgconv implementation- bool nspcFirst = isBrgConvAvailable() &&- one_of(inputDataType, memory::data_type::f16, memory::data_type::bf16, memory::data_type::f32);- bool nspcAdded = false;- if (nspcFirst) {- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, nspc);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nspc);- createDescriptor({in_candidate}, {out_candidate});- nspcAdded = true;+void Convolution::initSupportedPrimitiveDescriptors() {+ m_attrs.withBias = getOriginalInputsNumber() == 3;+ if (m_attrs.withBias) {+ m_atoi[ARG_BIAS] = BIAS;}- if (IC == 1 && groupOC == 1) {- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, ncsp);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, ncsp);- createDescriptor({in_candidate}, {out_candidate});- } else if (IC < 4) {- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, ncsp);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nCsp16c);- createDescriptor({in_candidate}, {out_candidate});- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nCsp8c);- createDescriptor({in_candidate}, {out_candidate});- } else {- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, nCsp16c);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nCsp16c);- createDescriptor({in_candidate}, {out_candidate});- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, nCsp8c);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nCsp8c);- createDescriptor({in_candidate}, {out_candidate});- }+ m_attrs.isGraphQuantized = context->isGraphQuantized();+ m_attrs.fcSemantic = false;+ m_attrs.nonConstantWeights = !getParentEdgeAt(WEIGHTS)->getParent()->isConstant();+ m_attrs.weightsNonTransposed = false;+ m_attrs.dqScales = getDQScales();- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, ncsp);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, ncsp);- createDescriptor({in_candidate}, {out_candidate});+ const auto [dstType, sumType] = getDstAndSumPrecision();- if (!nspcAdded &&- (inputDataType != memory::data_type::bf16 && inputDataType != memory::data_type::f16 && isNspcAvailable())) {- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, nspc);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nspc);- createDescriptor({in_candidate}, {out_candidate});- }-#else+ m_postOps = getPostOps(fusedWith, sumType);- in_candidate = std::make_shared<DnnlBlockedMemoryDesc>(inputShape, inputDataType, nspc);- out_candidate = std::make_shared<DnnlBlockedMemoryDesc>(outputShape, outputDataType, nspc);- createDescriptor({in_candidate}, {out_candidate});-#endif-}+ auto [srcDescs, dstDesc] = initMemoryDescriptors(dstType);-void Convolution::setPostOps(dnnl::primitive_attr& attr,- const VectorDims& dims,- bool useLegacyPostOps,- bool initWeights) {- dnnl::post_ops ops;- auto& args = convPostOpsArgs[useLegacyPostOps];- bool isINT8 = canBeExecutedInInt8();- // Weight dims in NON-Group CONV: [OC, IC, KH, KW], perchannel weight scale applied on OC DIM,- // weiScaleMaskPerChannel = 1 << 0 Weight dims in Group CONV:[Group, OC, IC, KH, KW], perchannel weight scale- // applied on GROUP and OC DIM, weiScaleMaskPerChannel = ( 1 << 0 | 1<< 1) = 0x03- DnnlPostOpsComposerLegacy- dnnlpoc(getEngine(), attr, ops, args, dims, 1, isINT8, isGrouped ? 3 : 1 << 0, getDQScales(), withBiases);-- DEBUG_LOG(getName(), " useLegacyPostOps=", useLegacyPostOps, " initWeights=", initWeights);-- for (size_t i = 0; i < fusedWith.size(); ++i) {- auto& node = fusedWith[i];- bool isLastPostOp = (i == (fusedWith.size() - 1));-- if (node->getType() == Type::Split || node->getType() == Type::Concatenation) {- continue;- }+ MemoryDescArgs descs{+ {ARG_SRC, srcDescs[DATA]},+ {ARG_WEI, srcDescs[WEIGHTS]},+ {ARG_BIAS, m_attrs.withBias ? srcDescs[BIAS] : MemoryDescUtils::makeEmptyDesc()},+ {ARG_DST, dstDesc},+ };- if (auto* eltwiseNode = dynamic_cast<Eltwise*>(node.get())) {- if (eltwiseNode->isSpecialConvolutionAddFusing()) {- if (withSumBroadcast) {- break;- }- DEBUG_LOG(getName(), ": Append ", node->getName(), " as sum post op");- ops.append_sum(1.0, 0, DnnlExtensionUtils::ElementTypeToDataType(eltwisePrecision));- } else {- if (useLegacyPostOps) {- // try mapping with optimization w/o using binary postOps- if (eltwiseNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType, false)) {- DEBUG_LOG(getName(), ": Append ", node->getName(), " as original post op without binary");- continue;- }- DEBUG_LOG(getName(), ": Append ", node->getName(), " as legacy post op");- int channelAxis = 1;- eltwiseNode->appendPostOps(ops, dims, args, channelAxis);- } else {- DEBUG_LOG(getName(), ": Append ", node->getName(), " as original post op with binary");- eltwiseNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType);- }- }- continue;- }+ m_factory = createExecutorFactory(descs, m_attrs, m_postOps);- if (auto* fakeQuantizeNode = dynamic_cast<FakeQuantize*>(node.get())) {- // drop rounding one special residual pattern- // TODO: validate this unsafe optimization- bool do_rounding = true;- if (i == 0) {- bool hasSubsequentSum = false;- bool hasSubsequentFQ = false;- for (size_t j = i + 1; j < fusedWith.size(); j++) {- auto& nextNode = fusedWith[j];-- auto* nextEltwiseNode = dynamic_cast<Eltwise*>(nextNode.get());- if (nextEltwiseNode && nextEltwiseNode->isSpecialConvolutionAddFusing()) {- hasSubsequentSum = true;- }+ const std::vector<MemoryDescArgs> nodeDescriptorsList = m_factory->getProperMemoryDescriptors(descs);- auto* nextQuantizeNode = dynamic_cast<FakeQuantize*>(nextNode.get());- if (nextQuantizeNode) {- hasSubsequentFQ = true;- }- }- if (hasSubsequentSum && hasSubsequentFQ) {- do_rounding = false;- }- }+ for (const auto& nodeDescriptors : nodeDescriptorsList) {+ NodeConfig nodeConfig;+ nodeConfig.inConfs.resize(srcDescs.size());- if (useLegacyPostOps) {- // can we implement it without binary postOps?- if (fakeQuantizeNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType, false, do_rounding)) {- DEBUG_LOG(getName(), ": Append ", node->getName(), " as original post op without binary");- continue;- }- // fallback to legacy- DEBUG_LOG(getName(), ": Append ", node->getName(), " as legacy post op");- int channelAxis = 1;- fakeQuantizeNode->appendPostOps(ops, dims, args, channelAxis);- } else {- DEBUG_LOG(getName(), ": Append ", node->getName(), " as original post op with binary");- fakeQuantizeNode->appendAttrPostOps(dnnlpoc, isLastPostOp, outputDataType, true, do_rounding);+ auto getBlockedMask = [](const std::shared_ptr<MemoryDesc>& memDesc, const bool isGrouped) {+ if (memDesc->getType() & MemoryDescType::Blocked && !isGrouped) {+ return BlockedMemoryDesc::EMPTY_MASK;}- continue;- }+ return BlockedMemoryDesc::FULL_MASK;+ };- auto* convolutionNode = dynamic_cast<Convolution*>(node.get());- if (convolutionNode) {- if (initWeights) {- args[DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_WEIGHTS] = getSrcMemoryAtPort(getOriginalInputsNumber() + 0);- args[DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_BIAS] = getSrcMemoryAtPort(getOriginalInputsNumber() + 1);-- DEBUG_LOG(getName(), ": Append ", node->getName(), " as DW convolution");- // todo: rewrite onto append_dw_k3s2p1- ops.append_dw_conv(dw_conv_ih,- dw_conv_iw,- dw_conv_kernel[Y_AXIS],- dw_conv_kernel[X_AXIS],- dw_conv_strides[Y_AXIS],- dw_conv_strides[X_AXIS],- dnnl::memory::convert_to_c(dw_conv_in_dt));- } else {- DEBUG_LOG(getName(), ": Append ", node->getName(), " as DW convolution");- // todo: rewrite onto append_dw_k3s2p1- ops.append_dw_conv(dw_conv_ih,- dw_conv_iw,- dw_conv_kernel[Y_AXIS],- dw_conv_kernel[X_AXIS],- dw_conv_strides[Y_AXIS],- dw_conv_strides[X_AXIS],- dnnl::memory::convert_to_c(dw_conv_in_dt));+ for (const auto& desc : nodeDescriptors) {+ if (m_atoi.count(desc.first)) {+ const auto& inputDesc = desc.second;+ nodeConfig.inConfs[m_atoi[desc.first]] = {inputDesc, getBlockedMask(inputDesc, m_attrs.isGrouped)};}- continue;}- THROW_CPU_NODE_ERR("Fusing of ",- NameFromType(node->getType()),- " operation to ",- NameFromType(this->getType()),- " node is not implemented");- }-- attr.set_post_ops(ops);-}--void Convolution::initSupportedPrimitiveDescriptors() {- if (!supportedPrimitiveDescriptors.empty()) {- return;- }-- auto getBlockedMask = [](const std::shared_ptr<MemoryDesc>& memDesc, const bool isGrouped) {- if (memDesc->getType() & MemoryDescType::Blocked && !isGrouped) {- return BlockedMemoryDesc::EMPTY_MASK;+ for (size_t i = 3; i < srcDescs.size(); i++) {+ nodeConfig.inConfs[i] = srcDescs[i];}- return BlockedMemoryDesc::FULL_MASK;- };- auto addSupportedPrimitiveDescriptor = [&](const dnnl::primitive_desc& prim_desc) {- std::vector<PortConfig> inConfs, outConfs;const int inPlaceOutPort = withSum ? static_cast<int>(getParentEdges().size()) - 1 : -1;-- for (size_t i = 0; i < descInputNumbers(); i++) {- auto desc = getSrcMemDesc(prim_desc, i);-- inConfs.emplace_back(desc, getBlockedMask(desc, isGrouped));- }+ const auto& outputDesc = nodeDescriptors.at(ARG_DST);+ nodeConfig.outConfs.emplace_back(outputDesc, getBlockedMask(outputDesc, m_attrs.isGrouped), inPlaceOutPort);if (withDWConv) {+ constexpr size_t X_AXIS = 0;+ constexpr size_t Y_AXIS = 1;const std::vector<size_t> dwWeightsDims{dw_conv_oc, 1, 1, dw_conv_kernel[Y_AXIS], dw_conv_kernel[X_AXIS]};const std::vector<size_t> dwBiasesDims{dw_conv_oc};@@ -824,441 +518,34 @@ void Convolution::initSupportedPrimitiveDescriptors() {const auto dwWeightsDesc = std::make_shared<DnnlBlockedMemoryDesc>(Shape(dwWeightsDims),dwWeightsPrc,memory::format_tag::Goihw8g);- inConfs.emplace_back(dwWeightsDesc);+ nodeConfig.inConfs.emplace_back(dwWeightsDesc);const auto dwBiasPrc = memory::data_type::f32;const auto dwBiasDesc =std::make_shared<DnnlBlockedMemoryDesc>(Shape(dwBiasesDims), dwBiasPrc, memory::format_tag::x);- inConfs.emplace_back(dwBiasDesc);- }-- for (size_t i = 0; i < descOutputNumbers(); i++) {- auto desc = getDstMemDesc(prim_desc, i);-- outConfs.emplace_back(desc, getBlockedMask(desc, isGrouped), inPlaceOutPort);+ nodeConfig.inConfs.emplace_back(dwBiasDesc);}if (withSum) {- const auto outputPrecision = outConfs.back().getMemDesc()->getPrecision();- const auto sumDesc = getSumMemDesc(prim_desc)->cloneWithNewPrecision(outputPrecision);- inConfs.emplace_back(sumDesc);- }-- 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 (size_t dIdx = 0; dIdx < descs.size(); dIdx++) {- auto& desc = descs[dIdx];- auto primitive_desc = desc.get(true); // true mean allow empty- if (primitive_desc == nullptr) {- continue;- }- auto first_desc = dnnl::primitive_desc(DnnlExtensionUtils::clone_primitive_desc(primitive_desc));-- auto add_supported_desc = [&](dnnl::primitive_desc& desc) {- addSupportedPrimitiveDescriptor(desc);- descIdx.push_back(dIdx);- };-- const bool first_match = customImplPriorities.empty();- DEBUG_LOG("#",- getName(),- ",descIndex:",- dIdx + 1,- "/",- descs.size(),- ", 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);- },- add_supported_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()) {- add_supported_desc(first_desc);+ nodeConfig.inConfs.emplace_back(+ getSumMemDesc(nodeDescriptors.at(ARG_DST), getInputShapeAtPort(getParentEdges().size() - 1)),+ BlockedMemoryDesc::FULL_MASK,+ -1);}- }-}--void Convolution::selectOptimalPrimitiveDescriptor() {- selectPreferPrimitiveDescriptor(getImplPriority(), true);- /* preemptively create a fallback subgraph to include it into global memory reuse- * pros:- * - less total memory usage when fallback is actually needed (by size of intermediate memory)- * - no runtime overhead of graph creation when fallback is needed for the first time- * cons:- * - more total memory usage when fallback is not needed (by size of a graph data structure itself)- */- if (withSum && isDynamicNode()) {- subgraph = std::make_shared<FusedSubgraph>(fusedWith, *this, context);- }-}-int Convolution::registerToAllocationContext(int offset, AllocationContext& context) {- if (subgraph) {- return subgraph->RegisterToAllocationContext(offset, context);+ supportedPrimitiveDescriptors.emplace_back(nodeConfig, impl_desc_type::undef);}-- return Node::registerToAllocationContext(offset, context);-}--void Convolution::createPrimitive() {- if (subgraph) {- subgraph->Activate();- }-- Node::createPrimitive();}bool Convolution::created() const {return getType() == Type::Convolution;}-namespace {-dnnl::convolution_forward::primitive_desc createDescriptorInternal(const dnnl::engine& engine,- const dnnl::memory::desc& inputDesc,- const dnnl::memory::desc& weightDesc,- const dnnl::memory::desc& biasDesc,- const dnnl::memory::desc& outputDesc,- bool withBiases,- const std::vector<size_t>& stride,- const std::vector<ptrdiff_t>& dilation,- const std::vector<ptrdiff_t>& paddingL,- const std::vector<ptrdiff_t>& paddingR,- dnnl::algorithm alg,- const dnnl::primitive_attr& attr) {- if (withBiases) {- return dnnl::convolution_forward::primitive_desc(engine,- prop_kind::forward_inference,- alg,- inputDesc,- weightDesc,- biasDesc,- outputDesc,- dnnl::memory::dims(stride.begin(), stride.end()),- dnnl::memory::dims(dilation.begin(), dilation.end()),- dnnl::memory::dims(paddingL.begin(), paddingL.end()),- dnnl::memory::dims(paddingR.begin(), paddingR.end()),- attr,- true); // allow_empty- }- return dnnl::convolution_forward::primitive_desc(engine,- prop_kind::forward_inference,- alg,- inputDesc,- weightDesc,- outputDesc,- dnnl::memory::dims(stride.begin(), stride.end()),- dnnl::memory::dims(dilation.begin(), dilation.end()),- dnnl::memory::dims(paddingL.begin(), paddingL.end()),- dnnl::memory::dims(paddingR.begin(), paddingR.end()),- attr,- true); // allow_empty-}-} // namespace--static memory::data_type deriveWeightDataType(memory::data_type src_dt) {- memory::data_type wdt = src_dt;- if (one_of(src_dt, memory::data_type::s8, memory::data_type::u8)) {- wdt = memory::data_type::s8;- }- return wdt;-}--void Convolution::createDescriptor(const std::vector<MemoryDescPtr>& inputDesc,- const std::vector<MemoryDescPtr>& outputDesc) {- MemoryDescPtr inpDesc;- if (inputDesc[0]->isDefined()) {- inpDesc = inputDesc[0];- } else {- auto dummyInDims = makeInputDummyShape(inputDesc[0]->getShape());- inpDesc = inputDesc[0]->cloneWithNewDims(dummyInDims);- }- DnnlMemoryDescPtr definedInpMemDesc = MemoryDescUtils::convertToDnnlMemoryDesc(inpDesc);- DnnlMemoryDescPtr definedOutMemDesc;-- if (outputDesc[0]->isDefined()) {- definedOutMemDesc = MemoryDescUtils::convertToDnnlMemoryDesc(outputDesc[0]);- } else {- std::vector<Shape> shapes = {definedInpMemDesc->getShape(), Shape(weightDims)};- auto outDims = shapeInferGeneric(shapes);- definedOutMemDesc = MemoryDescUtils::convertToDnnlMemoryDesc(outputDesc[0]->cloneWithNewDims(outDims.front()));- }-- const auto& inDnnlDesc = definedInpMemDesc->getDnnlDesc();- const auto& outDnnlDesc = definedOutMemDesc->getDnnlDesc();-- memory::data_type wdt = deriveWeightDataType(inDnnlDesc.get_data_type());-- dnnl::memory::desc weightDnnlDesc(DnnlExtensionUtils::convertToDnnlDims(weightDims), wdt, memory::format_tag::any);- dnnl::memory::desc biasDnnlDesc;-- if (withBiases) {- // oneDNN ARM Convolution primitive supports only identical in/out data types-#if defined(OPENVINO_ARCH_ARM) || defined(OPENVINO_ARCH_ARM64)- memory::data_type bdt = outDnnlDesc.get_data_type();-#else- memory::data_type bdt = memory::data_type::f32;- /* brdgmm_dw_conv has more perf gain on bf16/fp16 inference.- brdgmm_dw_conv supports only bia_type the same as src_type or dst_type.- dw convolution support in onednn 3.5.- BF16:- kernel type | brgdconv | jit_uni_dw_convolution_fwd_t- support impl type | native bf16 ISA without AMX | avx512_core_bf16 or avx512_core- bias dt | oneof(src,dest) | oneof(src, dest, f32)- FP16:- kernel type | brgdconv | brgemm_convolution_fwd_t- impl type | native FP16 ISA without AMX | native FP16 ISA- bias type | oneof(src,dest) | oneof(src, dest, f32)- @todo: this bias type changes may have minor accuracy impact on some models, so when upstream ONEDNN extend this- kind of matrix support (ticket MFDNN-12936) we can continue use bdt = memory::data_type::f32 here;- */- auto out_dt = outDnnlDesc.get_data_type();- if (!canBeExecutedInInt8() && isDepthWise()) {- bool isF16BiasSupported = (out_dt == memory::data_type::f16) && hasHardwareSupport(ov::element::f16);- bool isBF16BiasSupported = (out_dt == memory::data_type::bf16) &&- (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_bf16) ||- dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2_vnni_2));-- if (isF16BiasSupported || isBF16BiasSupported) {- bdt = out_dt;- }- }-#endif- biasDnnlDesc =- dnnl::memory::desc(DnnlExtensionUtils::convertToDnnlDims(expectedBiasDims), bdt, memory::format_tag::any);- }-- std::vector<dnnl::algorithm> algorithms;-- algorithms.push_back(baseConvAlgorithm);-- updatePadding();-- for (const auto alg : algorithms) {- for (const auto& attr : attrs) {- const auto desc = createDescriptorInternal(getEngine(),- inDnnlDesc,- weightDnnlDesc,- biasDnnlDesc,- outDnnlDesc,- withBiases,- stride,- dilation,- paddingL,- paddingR,- alg,- attr);- descs.emplace_back(desc);- }- }-}--void Convolution::addZeroPoints(dnnl::primitive_attr& attr) {- if (inputZeroPoints.empty()) {- return;- }- DEBUG_LOG(getName(), ": Set original input zeropoints");- attr.set_zero_points_mask(DNNL_ARG_SRC, 0);-- if (!stockInputZeroPointsMemPtr) {- DnnlBlockedMemoryDesc memoryDesc(ov::element::i32, {inputZeroPoints.size()});- stockInputZeroPointsMemPtr = std::make_shared<Memory>(getEngine(), memoryDesc, inputZeroPoints.data());- }-}--void Convolution::addLegacyZeroPoints(dnnl::primitive_attr& attr) {- if (!legacyInputZeroPoints.empty()) {- DEBUG_LOG(getName(), ": Set legacy input zero points");- attr.set_input_zero_points(legacyInputZeroPoints.size(), 1 << 1 /*through C dim*/);- if (!legacyInputZeroPointsMemPtr) {- DnnlBlockedMemoryDesc memoryDesc(ov::element::u8, {legacyInputZeroPoints.size()});- legacyInputZeroPointsMemPtr =- std::make_shared<Memory>(getEngine(), memoryDesc, legacyInputZeroPoints.data());- }- }-- if (!legacyWeightsZeroPoints.empty()) {- DEBUG_LOG(getName(), ": Set legacy weights zero points");- attr.set_weights_zero_points(legacyWeightsZeroPoints.size(), 1 << 1 /*through C dim*/);-- if (!legacyWeightsZeroPointsMemPtr) {- DnnlBlockedMemoryDesc memoryDesc(ov::element::f32, {legacyWeightsZeroPoints.size()});- legacyWeightsZeroPointsMemPtr =- std::make_shared<Memory>(getEngine(), memoryDesc, legacyWeightsZeroPoints.data());- }- }-- if (!legacyOutputCompensation.empty()) {- DEBUG_LOG(getName(), ": Set legacy output compensationss");- attr.set_output_compensations(legacyOutputCompensation.size(), 1 << 1 /*through C dim*/);-- if (!legacyOutputCompensationMemPtr) {- DnnlBlockedMemoryDesc memoryDesc(ov::element::i32, {legacyOutputCompensation.size()});- legacyOutputCompensationMemPtr =- std::make_shared<Memory>(getEngine(), memoryDesc, legacyOutputCompensation.data());- }- }-}--static bool attrContainsPostOp(const dnnl::primitive_attr& attr, const dnnl::impl::primitive_kind_t kind) {- const auto ops = attr.get_post_ops();- return ops.get()->find(kind) != -1;-}--// See the src/plugins/intel_cpu/src/docs/convPostOps.md for details-void Convolution::SetPostOpsAndZeroPoints(std::vector<dnnl::primitive_attr>& attrs) {- attrs.resize(1);- auto outputShape = outputStaticShape();- // attr[0] - Legacy post ops + Legacy zero points.- DEBUG_LOG(getName(), ": set post ops, attr 0, useLegacyPostOps=true");- setPostOps(attrs[0], outputShape, true);- addLegacyZeroPoints(attrs[0]);-- // dw-conv would be fused into conv only on AVX2 platform. no need attr[1]. Avoid extra useless attribute.- if (attrContainsPostOp(attrs[0], dnnl::impl::primitive_kind::convolution)) {- return;- }-- // no matter if brgconv is available, 1 attribute is enough. Avoid duplicated attribute- if (inputZeroPointType == zpType::None && !attrContainsPostOp(attrs[0], dnnl::impl::primitive_kind::depthwise) &&- !attrContainsPostOp(attrs[0], dnnl::impl::primitive_kind::quantization)) {- return;- }- // Per channel zero point can only supported on attr[0].Avoid extra useless attribute.- if (inputZeroPointType == zpType::PerChannel) {- DEBUG_LOG(getName(), ": Per channel zero point can only supported on attr[0].Avoid extra useless attribute.");- return;- }- if (!isBrgConvAvailable()) {- DEBUG_LOG(getName(), ": brgconv is not available. Skip extra attribute");- return;- }- // Try 2 attributes.- attrs.resize(2);- if (inputZeroPointType == zpType::PerTensor &&- dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx)) {- // WR to ONEDNN limitation. attr[1] - legacy post ops + stock zero point.- //@todo:Unify to use binary postops+stock zero point when limitation is fixed.- // For now, have to adapt to JIT_AMX kernel for performance.- DEBUG_LOG(getName(), ": set post ops, attr 1, useLegacyPostOps=true");- setPostOps(attrs[1], outputShape, true);- } else {- DEBUG_LOG(getName(), ": set post ops, attr 1, useLegacyPostOps=false");- setPostOps(attrs[1], outputShape, false);- }- addZeroPoints(attrs[1]);-}--void Convolution::initDescriptor(const NodeConfig& config) {- auto* selectedPD = getSelectedPrimitiveDescriptor();-- if (!selectedPD) {- return;- }-- // attr[0] for legacy post ops;- // attr[1] is mostly for binaryPostops except when having per-tensor zp on AMX.- const int descId = descIdx[selectedPrimitiveDescriptorIndex];- int attrId = attrs.size() == 1 ? 0 : descId % 2 == 0 ? 0 : 1;-- preferLegacyPostOps = (attrId == 0 || (attrId == 1 && (inputZeroPointType == zpType::PerTensor) &&- dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx)));- // attr[0] for legacy zero point.- // attr[1] for stock per-tensor zero point.- preferLegacyZeroPoint = (attrId == 0);-- DEBUG_LOG(getName(),- " selectedPrimitiveDescriptorIndex: ",- selectedPrimitiveDescriptorIndex,- " DescIdx: ",- descId,- " Selected impl type: ",- selectedPD->getImplementationType(),- " Desc impl type: ",- parse_impl_name(descs[descId].impl_info_str()),- " preferLegacyPostOps: ",- preferLegacyPostOps,- " preferLegacyZeroPoint: ",- preferLegacyZeroPoint);-- auto updateNodeConfig = [&](const NodeConfig& cfg) {- auto updatedConfig = cfg;-- for (size_t i = 0; i < descInputNumbers(); i++) {- PortConfig& dataConfig = updatedConfig.inConfs[i];- dataConfig.inPlace(-1);- dataConfig.setMemDesc(dataConfig.getMemDesc());- }-- for (size_t i = 0; i < descOutputNumbers(); i++) {- PortConfig& dataConfig = updatedConfig.outConfs[i];- dataConfig.inPlace(-1);- dataConfig.setMemDesc(dataConfig.getMemDesc());- if (withSum) {- auto& eltwiseConfig = updatedConfig.inConfs.back();- eltwiseConfig.setMemDesc(eltwiseConfig.getMemDesc()->cloneWithNewPrecision(eltwisePrecision));- dataConfig.inPlace(getParentEdges().size() - 1);- }- }-- return updatedConfig;- };-- if (!canBeExecutedInInt8()) { // strided blobs are suppoted only for FP32 convolutions- descs.clear();- createDescriptor({config.inConfs[0].getMemDesc()}, {config.outConfs[0].getMemDesc()});-- for (auto& desc : descs) {- if (DnnlExtensionUtils::find_implementation(desc, selectedPD->getImplementationType())) {- selectedPD->setConfig(config);- return;- }- }- }-- auto currentConfig = selectedPD->getConfig();- const auto& updatedConfig = updateNodeConfig(currentConfig);-- selectedPD->setConfig(updatedConfig);-}--std::shared_ptr<MemoryDesc> Convolution::getSrcMemDesc(const dnnl::primitive_desc& prim_desc, size_t idx) const {- if (idx == 1) {- // report original plain layout for weight since it needs to be reordered dynamically at runtime- return std::make_shared<CpuBlockedMemoryDesc>(getOriginalInputPrecisionAtPort(idx),- Shape(getInputShapeAtPort(idx).getStaticDims()));- }- auto desc = idx > 0 ? prim_desc.weights_desc(idx - 1) : prim_desc.src_desc(idx);- if (getInputShapeAtPort(idx).isDynamic()) {- return DnnlExtensionUtils::makeUndefinedDesc(desc, getInputShapeAtPort(idx));- }- return DnnlExtensionUtils::makeDescriptor(desc);+template <typename T>+static MemoryPtr memoryViewToVector(const std::vector<T>& vec, const dnnl::engine& engine) {+ const auto type = ov::element::from<T>();+ DnnlBlockedMemoryDesc memoryDesc(type, {vec.size()});+ return std::make_shared<Memory>(engine, memoryDesc, vec.data());}bool Convolution::canFuse(const NodePtr& node) const {@@ -1269,14 +556,6 @@ bool Convolution::canFuse(const NodePtr& node) const {return canFuseSimpleOperation(node);}-dnnl::memory Convolution::getWeights() const {- return getParentEdgeAt(1)->getMemory().getPrimitive();-}--dnnl::memory Convolution::getBias() const {- return getParentEdgeAt(2)->getMemory().getPrimitive();-}-ov::element::Type Convolution::getRuntimePrecision() const {std::vector<ov::element::Type> inputPrecisions;// Don't take bias precision into account@@ -1292,466 +571,162 @@ ov::element::Type Convolution::getRuntimePrecision() const {return getMaxPrecision(inputPrecisions);}-bool Convolution::isNspcAvailable() const {- using impl::cpu::x64::mayiuse;-- // do not use in non-quantized networks until it is enforced externally- if (!context->isGraphQuantized()) {- auto predicate = [](memory::format_tag tag) {- return one_of(tag, memory::format_tag::nwc, memory::format_tag::nhwc, memory::format_tag::ndhwc);- };- if (std::none_of(inputMemoryFormatsFilter.begin(), inputMemoryFormatsFilter.end(), predicate)) {- return false;- }- }- // AVX2 heuristic- if (useJitPlanar) {- return false;- }- // A bunch of heuristics are designed to cut off not optimal nspc convolution applications- auto inpDims = getInputShapeAtPort(0).getDims();- auto outDims = getOutputShapeAtPort(0).getDims();- auto ndims = inpDims.size();- if (isDepthWise()) {- // 1d equivalent cases are painfully slow- if (inpDims.size() == 3 || 1 == inpDims[inpDims.size() - 2]) {- return false;- }- } else {- // it was empirically observed that the nspc convolutions perform much slower than the blocked ones if the- // channels number more than the specific value- size_t spatialRank = ndims - 2; // two means batch dim plus channels dim-- bool is1x1 = false;-- if (!isGrouped) {- auto weightDimsReversItr = weightDims.crbegin();- auto strideReversItr = stride.crbegin();- auto paddingLreversItr = paddingL.crbegin();- auto paddingRreversItr = paddingR.crbegin();-- for (size_t i = 0; i < spatialRank; ++i) {- is1x1 = true && *(weightDimsReversItr++) == 1 && *(strideReversItr++) == 1 &&- *(paddingLreversItr++) == 0 && *(paddingRreversItr++) == 0;- }- }-- // if the activation field size is 1x1 the avx512 1x1 nspc convolution pollutes caches so that the layer after- // the convolution performs slow- if (mayiuse(impl::cpu::x64::avx512_core) && is1x1) {- auto end = inpDims.rbegin();- std::advance(end, spatialRank);- if (std::all_of(inpDims.rbegin(), end, [](size_t x) {- return dimsEqualStrong(1, x);- })) {- return false;- }- }-- unsigned thresholdNumChannels = 128u; // for avx and below- if (is1x1) {- thresholdNumChannels = 2048u;- } else if (mayiuse(impl::cpu::x64::avx512_core)) {- thresholdNumChannels = 512u;- }-- size_t OC = outDims[1];- if (std::max(IC, OC) >= thresholdNumChannels) {- return false;- }- if (!mayiuse(impl::cpu::x64::avx)) {- // SSE41 nspc convolutions do not support ic and oc tails yet and the blocked implementation will be much- // better than gemm- if ((IC % 8) || (OC % 8)) {- return false;- }- }+int Convolution::registerToAllocationContext(int offset, AllocationContext& context) {+ if (subgraph) {+ return subgraph->RegisterToAllocationContext(offset, context);}- return true;+ return Node::registerToAllocationContext(offset, context);}-void Convolution::prepareParams() {- auto srcMemPtr = getSrcMemoryAtPort(0);- auto wghMemPtr = getSrcMemoryAtPort(1);- auto dstMemPtr = getOutputMemory();- if (!dstMemPtr || !dstMemPtr->isDefined()) {- THROW_CPU_NODE_ERR("Destination memory was undefined.");- }- if (!srcMemPtr || !srcMemPtr->isDefined()) {- THROW_CPU_NODE_ERR("Input memory was undefined.");- }- if (!wghMemPtr || !wghMemPtr->isDefined()) {- THROW_CPU_NODE_ERR("Weight memory was undefined.");- }- MemoryPtr biasMemPtr = nullptr;- if (withBiases) {- biasMemPtr = getSrcMemoryAtPort(2);- if (!biasMemPtr || !biasMemPtr->isDefined()) {- THROW_CPU_NODE_ERR("Input memory is undefined.");- }+void Convolution::createPrimitive() {+ for (const auto& entry : m_atoi) {+ const auto argumentId = entry.first;+ const auto inputId = entry.second;+ m_memory[argumentId] = getSrcMemoryAtPort(inputId);}- const NodeDesc* selected_pd = getSelectedPrimitiveDescriptor();- if (selected_pd == nullptr) {- THROW_CPU_NODE_ERR("Preferable primitive descriptor is not set.");+ if (!m_attrs.withBias) {+ m_memory[ARG_BIAS] = MemoryDescUtils::makeEmptyMemory(context);}- DnnlMemoryDescCPtr inMemoryDesc = srcMemPtr->getDescWithType<DnnlMemoryDesc>();- DnnlMemoryDescCPtr weightMemoryDesc = wghMemPtr->getDescWithType<DnnlMemoryDesc>();- DnnlMemoryDescCPtr outMemoryDesc = dstMemPtr->getDescWithType<DnnlMemoryDesc>();- DnnlMemoryDescCPtr biasDesc;- if (biasMemPtr) {- biasDesc = biasMemPtr->getDescWithType<DnnlMemoryDesc>();+ if (withDWConv) {+ m_memory[ARG_ATTR_POST_OP_DW | ARG_WEI] = getSrcMemoryAtPort(getOriginalInputsNumber() + 0);+ m_memory[ARG_ATTR_POST_OP_DW | ARG_BIAS] = getSrcMemoryAtPort(getOriginalInputsNumber() + 1);}- auto initPrimitiveAttr = [&]() {- dnnl::primitive_attr attr;- if (preferLegacyZeroPoint) {- addLegacyZeroPoints(attr);- } else {- addZeroPoints(attr);- }- setPostOps(attr, outMemoryDesc->getShape().getStaticDims(), preferLegacyPostOps, true);- attr.set_scratchpad_mode(dnnl::scratchpad_mode::user);+ if (!legacyInputZeroPoints.empty()) {+ m_memory[ARG_ATTR_ZERO_POINTS | ARG_SRC] = memoryViewToVector(legacyInputZeroPoints, getEngine());+ }- return std::make_shared<dnnl::primitive_attr>(std::move(attr));- };+ if (!legacyWeightsZeroPoints.empty()) {+ m_memory[ARG_ATTR_ZERO_POINTS | ARG_WEI] = memoryViewToVector(legacyWeightsZeroPoints, getEngine());+ }- AttrPtr pAttrLocal;+ if (!legacyOutputCompensation.empty()) {+ m_memory[ARG_ATTR_ZERO_POINTS | ARG_DST] = memoryViewToVector(legacyOutputCompensation, getEngine());+ }- if (isDynamicNode()) {- if (!pAttr || withSum) {- pAttr = initPrimitiveAttr();- }- pAttrLocal = pAttr;- } else {- pAttrLocal = initPrimitiveAttr();+ if (!inputZeroPoints.empty()) {+ // WA Pass different representation of zero points using different identifier ARG_SRC_3+ // which is normally not used by convolution+ m_memory[ARG_ATTR_ZERO_POINTS | ARG_SRC_3] = memoryViewToVector(inputZeroPoints, getEngine());}- updatePadding();- ConvKey key = {inMemoryDesc,- weightMemoryDesc,- biasDesc,- outMemoryDesc,- stride,- dilation,- paddingL,- paddingR,- *pAttrLocal,- selected_pd->getImplementationType(),- getParentEdgeAt(1)->getParent()->isConstant()};-- auto engine = getEngine();- auto convAlg = baseConvAlgorithm;- auto builder = [&engine, convAlg](const ConvKey& key) -> executorPtr {- // remove the requirement on weight memory layout to let primitive- // report the best layout for weight to be reordered dynamically at runtime- auto wghDescAny =- dnnl::memory::desc(DnnlExtensionUtils::convertToDnnlDims(key.inp1->getShape().getStaticDims()),- deriveWeightDataType(key.inp0->getDataType()),- memory::format_tag::any);- auto createDnnlConvDesc = [](const dnnl::engine& engine,- const dnnl::memory::desc& srcDesc,- const dnnl::memory::desc& wghDesc,- const dnnl::memory::desc& dstDesc,- const DnnlMemoryDescCPtr& biasDescPtr,- const std::vector<size_t>& stride,- const std::vector<ptrdiff_t>& dilation,- const std::vector<ptrdiff_t>& paddingL,- const std::vector<ptrdiff_t>& paddingR,- dnnl::algorithm alg,- const dnnl::primitive_attr& attr) -> dnnl::primitive_desc {- dnnl::memory::desc dnnlBiasDesc;- if (biasDescPtr) {- dnnlBiasDesc = biasDescPtr->getDnnlDesc();- }+ if (withSum) {+ m_memory[ARG_SUM] = getSrcMemoryAtPort(getParentEdges().size() - 1);+ }- return createDescriptorInternal(engine,- srcDesc,- wghDesc,- dnnlBiasDesc,- dstDesc,- (biasDescPtr != nullptr),- stride,- dilation,- paddingL,- paddingR,- alg,- attr);- };+ m_memory[ARG_DST] = getDstMemoryAtPort(0);- dnnl::primitive_desc prim_desc = createDnnlConvDesc(engine,- key.inp0->getDnnlDesc(),- wghDescAny,- key.out->getDnnlDesc(),- key.bias,- key.stride,- key.dilation,- key.paddingL,- key.paddingR,- convAlg,- key.attr);-- const bool found = DnnlExtensionUtils::find_implementation(prim_desc, key.implType);-- if (found) {- return std::make_shared<ConvolutionExecutor>(prim_desc,- key.inp0->getDnnlDesc(),- key.inp1->getDnnlDesc(),- key.out->getDnnlDesc(),- engine,- key.constWeight);- }+ m_executor = m_factory->make(m_memory);- // primitive desc with proper implementation type not found, use the first available- auto inDesc = dnnl::memory::desc(DnnlExtensionUtils::convertToDnnlDims(key.inp0->getShape().getStaticDims()),- key.inp0->getDataType(),- memory::format_tag::any);- auto outDesc = dnnl::memory::desc(DnnlExtensionUtils::convertToDnnlDims(key.out->getShape().getStaticDims()),- key.out->getDataType(),- memory::format_tag::any);-- auto reorderConvDesc = createDnnlConvDesc(engine,- inDesc,- wghDescAny,- outDesc,- key.bias,- key.stride,- key.dilation,- key.paddingL,- key.paddingR,- convAlg,- key.attr);-- // unable to create a primitive desc- if (!reorderConvDesc) {- return nullptr;- }+ getSelectedPrimitiveDescriptor()->setImplementationType(m_executor->implType());- if (key.attr.get()->post_ops_.count(dnnl::impl::primitive_kind::sum)) {- return std::make_shared<ConvolutionSumExecutor>(reorderConvDesc,- key.inp0->getDnnlDesc(),- key.inp1->getDnnlDesc(),- key.out->getDnnlDesc(),- engine,- key.constWeight);- }+ if (subgraph) {+ subgraph->Activate();+ }- return std::make_shared<ConvolutionExecutor>(reorderConvDesc,- key.inp0->getDnnlDesc(),- key.inp1->getDnnlDesc(),- key.out->getDnnlDesc(),- engine,- key.constWeight);- };+ Node::createPrimitive();+}- auto prevExecPtr = execPtr;- execPtr = nullptr;- auto cache = context->getParamsCache();- auto result = cache->getOrCreate(key, builder);+ExecutorPtr Convolution::createFallbackExecutor() {+ if (fallbackExecutor) {+ return fallbackExecutor;+ }- execPtr = result.first;+ PostOps fallbackPostOps = m_postOps;+ // remove sum post-op from fallback post-ops+ auto sumPostOp =+ std::find_if(fallbackPostOps.begin(), fallbackPostOps.end(), [](const std::shared_ptr<PostOp>& postOp) {+ return std::dynamic_pointer_cast<SumPostOp>(postOp);+ });- if (!execPtr) {- THROW_CPU_NODE_ERR("Primitive descriptor was not found");- }+ fallbackPostOps.erase(sumPostOp, fallbackPostOps.end());- primArgs[DNNL_ARG_SRC] = srcMemPtr->getPrimitive();- primArgs[DNNL_ARG_DST] = dstMemPtr->getPrimitive();-- if (key.constWeight) {- // const weight preparation/reordering needs to be done once at next execution- // when the input weight data is guaranteed to be ready (considering possible const-folding- // subgraphs inserted between constant weight node and conv)- auto it = primArgs.find(DNNL_ARG_WEIGHTS);- if (it == primArgs.end() || !prevExecPtr ||- !execPtr->getWeightDesc()->isCompatible(*(prevExecPtr->getWeightDesc()))) {- primArgs[DNNL_ARG_WEIGHTS] = prepareWeightMemory(execPtr->getWeightDesc())->getPrimitive();- }- } else {- // non-const weight will be reordered by executor on every exec- primArgs[DNNL_ARG_WEIGHTS] = wghMemPtr->getPrimitive();- }+ CPU_NODE_ASSERT(fallbackPostOps.size() < m_postOps.size(), "Unexpected post-ops size after sum post-op removal");- if (withBiases) {- primArgs[DNNL_ARG_BIAS] = biasMemPtr->getPrimitive();- }+ auto dstType = getOriginalInputPrecisionAtPort(0);- if (preferLegacyZeroPoint) {- appendLegacyZeroPointsArgs();- } else {- appendZeroPointsArgs();+ if (!fusedWith.empty()) {+ dstType = fusedWith.back()->getOriginalOutputPrecisionAtPort(0);}- Node::appendPostOpArgs(*pAttrLocal, primArgs, convPostOpsArgs[preferLegacyPostOps]);+ auto [srcDescs, dstDesc] = initMemoryDescriptors(dstType);- auto scratchpadMem = getScratchPadMem(execPtr->getScratchPadDesc());- primArgs[DNNL_ARG_SCRATCHPAD] = scratchpadMem->getPrimitive();+ MemoryDescArgs descs{+ {ARG_SRC, srcDescs[DATA]},+ {ARG_WEI, srcDescs[WEIGHTS]},+ {ARG_BIAS, m_attrs.withBias ? srcDescs[BIAS] : MemoryDescUtils::makeEmptyDesc()},+ {ARG_DST, dstDesc},+ };-#ifdef CPU_DEBUG_CAPS- auto pd = execPtr->getPrimitiveDesc();- DEBUG_LOG("verbose##", getName(), "##", DnnlExtensionUtils::query_pd_info(pd), "\n");-#endif+ auto fallbackFactory = createExecutorFactory(descs, m_attrs, fallbackPostOps);+ fallbackExecutor = fallbackFactory->make(m_memory);+ return fallbackExecutor;}-Convolution::ConvolutionExecutor::ConvolutionExecutor(const dnnl::primitive_desc& pd,- const dnnl::memory::desc& inMemDesc,- const dnnl::memory::desc& weightMemDesc,- const dnnl::memory::desc& outMemDesc,- const dnnl::engine& engine,- bool constWeight)- : DnnlExecutor(pd) {- if (inMemDesc != getDnnlSrcDesc()) {- inputReorders.insert({DNNL_ARG_SRC, IntermReorder(inMemDesc, getDnnlSrcDesc(), engine)});- }+void Convolution::prepareParams() {+ // In case of fallback dst memory is a subgraph input+ m_memory[ARG_DST] = withSumBroadcast ? subgraph->getInput(0)->getDstMemoryAtPort(0) : getDstMemoryAtPort(0);+ const auto& executor = withSumBroadcast ? createFallbackExecutor() : m_executor;+ assert(executor);+ executor->update(m_memory);+}- if (!constWeight && weightMemDesc != getDnnlWeightDesc()) {- // const weight will be reordered at first execution- inputReorders.insert({DNNL_ARG_WEIGHTS, IntermReorder(weightMemDesc, getDnnlWeightDesc(), engine)});+void Convolution::redefineOutputMemory(const std::vector<VectorDims>& newOutputShapes) {+ if (!withSum) { // fast path+ return Node::redefineOutputMemory(newOutputShapes);}- if (outMemDesc != getDnnlDstDesc()) {- outputReorders.insert({DNNL_ARG_DST, IntermReorder(getDnnlDstDesc(), outMemDesc, engine)});- }-}+ const size_t sumPortNum = getParentEdges().size() - 1;+ const auto& sumInpMem = getParentEdgeAt(sumPortNum)->getMemory();+ if (newOutputShapes.front() != sumInpMem.getStaticDims()) {+ withSumBroadcast = true;-Convolution::ConvolutionSumExecutor::ConvolutionSumExecutor(const dnnl::primitive_desc& pd,- const dnnl::memory::desc& inMemDesc,- const dnnl::memory::desc& weightMemDesc,- const dnnl::memory::desc& outMemDesc,- const dnnl::engine& engine,- bool constWeight)- : DnnlExecutor(pd) {- if (inMemDesc != getDnnlSrcDesc()) {- inputReorders.insert({DNNL_ARG_SRC, IntermReorder(inMemDesc, getDnnlSrcDesc(), engine)});- }+ auto inp0 = subgraph->getInput(0);+ inp0->redefineOutputMemory(newOutputShapes);- if (!constWeight && weightMemDesc != getDnnlWeightDesc()) {- // const weight will be reordered at first execution- inputReorders.insert({DNNL_ARG_WEIGHTS, IntermReorder(weightMemDesc, getDnnlWeightDesc(), engine)});+ auto inp1 = subgraph->getInput(1);+ inp1->redefineOutputMemory({sumInpMem.getStaticDims()});+ // postpone output memory reallocation since it is the same memory with the sum+ // second input+ return;}- if (outMemDesc != getDnnlDstDesc()) {- // In the case of fusing sum, we have to reorder the output data before executing the primitive,- // since the output data are used as an accumulator for the covolution computations.- inputReorders.insert({DNNL_ARG_DST, IntermReorder(outMemDesc, getDnnlDstDesc(), engine)});- outputReorders.insert({DNNL_ARG_DST, IntermReorder(getDnnlDstDesc(), outMemDesc, engine)});- }-}+ withSumBroadcast = false;-void Convolution::ConvolutionSumExecutor::reorder_exec(std::unordered_map<int, dnnl::memory> primArgs,- const dnnl::stream& strm) {- auto outputMem = primArgs.at(DNNL_ARG_DST);- for (auto& inReorder : inputReorders) {- if (primArgs.count(inReorder.first)) {- dnnl::memory memDst(inReorder.second.getDstDesc(), strm.get_engine());- inReorder.second.exec(primArgs[inReorder.first], memDst, strm);- primArgs[inReorder.first] = memDst;- } else {- OPENVINO_THROW("DnnlExecutor has reorder for input ", inReorder.first, ", but doesn't have source memory");- }- }- execPrim.execute(strm, primArgs);- if (!outputReorders.empty()) {- outputReorders.at(DNNL_ARG_DST).exec(primArgs.at(DNNL_ARG_DST), outputMem, strm);- }+ Node::redefineOutputMemory(newOutputShapes);}-void Convolution::execute(const dnnl::stream& strm) {- if (!execPtr) {- THROW_CPU_NODE_ERR("executor is not compiled");- }-- execPtr->exec(primArgs, strm);+void Convolution::execute([[maybe_unused]] const dnnl::stream& strm) {+ const auto& executor = withSumBroadcast ? fallbackExecutor : m_executor;+ assert(executor);+ executor->execute(m_memory);}void Convolution::executeDynamicImpl(const dnnl::stream& strm) {execute(strm);- if (withSumBroadcast) {- if (!subgraph) {- THROW_CPU_NODE_ERR("Fused ops subgraph has not been created");- }- const size_t sumPortNum = getParentEdges().size() - 1;- const auto& sumInpMem = getParentEdgeAt(sumPortNum)->getMemory();- auto inp1 = subgraph->getInput(1);- auto inp1Mem = inp1->getDstMemoryAtPort(0);- inp1Mem->getMemoryBlock()->setExtBuff(sumInpMem.getData(), sumInpMem.getSize());- subgraph->infer();-- auto out = subgraph->getOutput(0);- const auto& outMem = out->getParentEdgeAt(0)->getMemory();- auto convOutMem = getDstMemoryAtPort(0);- Node::redefineOutputMemory({outMem.getStaticDims()});- convOutMem->load(outMem, true, false);- }-}--void Convolution::updatePadding() {- // update padding.- if (isDynamicNode() && autoPadding) {- paddingL = shapeInference->get_pads_begin();- paddingR = shapeInference->get_pads_end();+ if (!withSumBroadcast) {+ return;}-}-void Convolution::redefineOutputMemory(const std::vector<VectorDims>& newOutputShapes) {- if (withSum) {- const size_t sumPortNum = getParentEdges().size() - 1;- const auto& sumInpMem = getParentEdgeAt(sumPortNum)->getMemory();- if (newOutputShapes.front() != sumInpMem.getStaticDims()) {- withSumBroadcast = true;-- auto inp0 = subgraph->getInput(0);- inp0->redefineOutputMemory(newOutputShapes);-- auto inp1 = subgraph->getInput(1);- inp1->redefineOutputMemory({sumInpMem.getStaticDims()});- // here we postpone output memory reallocation due to the fact that it is the same memory with the sum- // second input- return;- }- withSumBroadcast = false;- }- Node::redefineOutputMemory(newOutputShapes);-}+ CPU_NODE_ASSERT(subgraph, "Fused ops subgraph has not been created");-MemoryDescPtr Convolution::getSumMemDesc(const primitive_desc& primitive_desc_it) {- if (getOutputShapeAtPort(0).isDynamic()) {- // When we set input shape with ranged dims, sum node input shape maybe mismatch with output shape, we just- // change ranged min value to 1 to meet this case. For example: Output shape = {1, 160, {128, 256}, {128, 256}}- // Sum input shape = {1, 160, 1, 1}- // Update sum shape to {1, 160, {1, 256}, {1, 256}}- auto shape = getOutputShapeAtPort(0);- auto sumShape = getInputShapeAtPort(getParentEdges().size() - 1);- Shape finalShape = shape;- if (shape.getRank() == sumShape.getRank()) {- auto sumDims = sumShape.getDims();- auto minDims = shape.getMinDims();- auto maxDims = shape.getMaxDims();- for (size_t i = 0; i < maxDims.size(); i++) {- if ((maxDims[i] > minDims[i]) && sumDims[i] == 1) {- minDims[i] = 1;- }- }- finalShape = Shape(minDims, maxDims);- }+ const size_t sumPortNum = getParentEdges().size() - 1;+ const auto& sumInpMem = getParentEdgeAt(sumPortNum)->getMemory();+ auto inp1 = subgraph->getInput(1);+ auto inp1Mem = inp1->getDstMemoryAtPort(0);+ inp1Mem->getMemoryBlock()->setExtBuff(sumInpMem.getData(), sumInpMem.getSize());- return DnnlExtensionUtils::makeUndefinedDesc(primitive_desc_it.dst_desc(0), finalShape);- }- return DnnlExtensionUtils::makeDescriptor(primitive_desc_it.dst_desc(0));-}+ subgraph->infer();-MemoryPtr Convolution::getOutputMemory() const {- if (withSumBroadcast) {- if (!subgraph) {- THROW_CPU_NODE_ERR("Fused ops subgraph has not been created");- }- auto inp0 = subgraph->getInput(0);- return inp0->getDstMemoryAtPort(0);- }- return getDstMemoryAtPort(0);+ auto out = subgraph->getOutput(0);+ const auto& outMem = out->getParentEdgeAt(0)->getMemory();+ auto convOutMem = getDstMemoryAtPort(0);+ Node::redefineOutputMemory({outMem.getStaticDims()});+ convOutMem->load(outMem, true, false);}void Convolution::addFusedNode(const NodePtr& fusingNode) {@@ -1772,83 +747,77 @@ void Convolution::addFusedNode(const NodePtr& fusingNode) {}}}- Node::addFusedNode(fusingNode);-}-void Convolution::appendLegacyZeroPointsArgs() {- if (legacyInputZeroPointsMemPtr != nullptr) {- primArgs[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC] = legacyInputZeroPointsMemPtr->getPrimitive();- }- if (legacyWeightsZeroPointsMemPtr != nullptr) {- primArgs[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS] = legacyWeightsZeroPointsMemPtr->getPrimitive();- }- if (legacyOutputCompensationMemPtr != nullptr) {- primArgs[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_DST] = legacyOutputCompensationMemPtr->getPrimitive();- }-}+ if (fusingNode->getType() == Type::Convolution) {+ auto convolutionNode = std::dynamic_pointer_cast<Convolution>(fusingNode);+ CPU_NODE_ASSERT(convolutionNode, "Unexpected dynamic node type");+ withDWConv = true;+ auto& inActivationDims = convolutionNode->inputShapes[0].getStaticDims();+ dw_conv_ih = inActivationDims[convolutionNode->inputShapes[0].getRank() - 2];+ dw_conv_iw = inActivationDims[convolutionNode->inputShapes[0].getRank() - 1];++ auto& outDims = convolutionNode->outputShapes[0].getStaticDims();+ dw_conv_oc = outDims[1];-void Convolution::appendZeroPointsArgs() {- if (stockInputZeroPointsMemPtr != nullptr) {- primArgs[DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC] = stockInputZeroPointsMemPtr->getPrimitive();+ const auto& dwWeightsDims = convolutionNode->inputShapes[1].getStaticDims();+ dw_conv_kernel.push_back(dwWeightsDims[dwWeightsDims.size() - 1]);+ dw_conv_kernel.push_back(dwWeightsDims[dwWeightsDims.size() - 2]);+ dw_conv_strides = convolutionNode->getStride();++ if (canBeExecutedInInt8()) {+ if (fusedWith.empty()) {+ dw_conv_in_dt = DnnlExtensionUtils::ElementTypeToDataType(getOriginalOutputPrecisionAtPort(0));+ } else {+ dw_conv_in_dt =+ DnnlExtensionUtils::ElementTypeToDataType(fusedWith.back()->getOriginalOutputPrecisionAtPort(0));+ }+ } else {+ dw_conv_in_dt = memory::data_type::f32;+ }++ const auto& weightDims = getInputShapeAtPort(1).getStaticDims();+ // @todo padding should be updated by the graph optimizer / transformation+ for (size_t j = 0; j < m_attrs.paddingR.size(); j++) {+ int with_group = m_attrs.isGrouped ? 1 : 0;+ int krn = weightDims[with_group + 2 + j];+ int src = getInputShapeAtPort(0).getStaticDims()[2 + j];+ int dst = fusingNode->getOutputShapeAtPort(0).getStaticDims()[2 + j];++ krn = (krn - 1) * (m_attrs.dilation[j] + 1) + 1;+ int calc_dst = (src - krn + m_attrs.paddingL[j]) / m_attrs.stride[j] + 1;+ m_attrs.paddingR[j] = (dst - calc_dst) * m_attrs.stride[j];+ }}++ Node::addFusedNode(fusingNode);}void Convolution::initializeInputZeroPoints(const uint8_t* inputZpData, const size_t inputZpSize) {- if (!inputZeroPoints.empty() || !legacyInputZeroPoints.empty()) {- THROW_CPU_NODE_ERR("input zero point is not empty");- }+ const bool zeroPointsNotSet = inputZeroPoints.empty() && legacyInputZeroPoints.empty();+ CPU_NODE_ASSERT(zeroPointsNotSet, "input zero points are not empty");+if (inputZpSize) {- inputZeroPointType = zpType::PerTensor;+ m_attrs.inputZeroPointsType = ZeroPointsType::PerTensor;}+for (size_t j = 0; j < inputZpSize; j++) {legacyInputZeroPoints.push_back(inputZpData[j]);if (inputZpData[j] != inputZpData[0]) {- inputZeroPointType = zpType::PerChannel;+ m_attrs.inputZeroPointsType = ZeroPointsType::PerChannel;}}// Only enable per-tensor zero point on avx512-amx and avx512-core-vnni, avx2_vnni_2.// avx2_vnni is not enabled per-tensor z because of perf regression brgconv with per-tensor zpcompared with jit// per-channel zp If zero point is pertensor, both legacy zp and stock zp would be passed into conv node. The conv// node would determine how to create post-ops attribute and prioritize to choose final onednn kernel.- if (inputZeroPointType == zpType::PerTensor && (impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core_amx) ||- impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core_vnni) ||- impl::cpu::x64::mayiuse(impl::cpu::x64::avx2_vnni_2))) {+ if (m_attrs.inputZeroPointsType == ZeroPointsType::PerTensor &&+ (impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core_amx) ||+ impl::cpu::x64::mayiuse(impl::cpu::x64::avx512_core_vnni) ||+ impl::cpu::x64::mayiuse(impl::cpu::x64::avx2_vnni_2))) {inputZeroPoints.push_back(static_cast<int32_t>(inputZpData[0]));} else {- inputZeroPointType = zpType::PerChannel;- }-}--VectorDims Convolution::makeInputDummyShape(const Shape& inpShape) const {- // There are a bunch of heuristics mostly aimed to guess the most appropriate oneDNN implementation, to reduce the- // amount of the implementation mismatch and the internal reordering as a consequence.- constexpr Dim dummyInputDim = 64;-- const size_t spatialRank = stride.size();- const size_t filterStartIndx = weightDims.size() - spatialRank;-- VectorDims dummyInputShapeVals(inpShape.getRank(), dummyInputDim);- dummyInputShapeVals[1] = IC; // channels-- for (size_t i = 0; i < spatialRank; i++) {- if (weightDims[filterStartIndx + i] > dummyInputShapeVals[2 + i]) {- constexpr Dim dummyOutputDim = 16;- dummyInputShapeVals[2 + i] = (dummyOutputDim - 1) * stride[i] - (paddingL[i] + paddingR[i]) +- weightDims[filterStartIndx + i] +- (weightDims[filterStartIndx + i] - 1) * (dilation[i]);- }- }- return MemoryDescUtils::makeDummyShape(inpShape, dummyInputShapeVals).getStaticDims();-}--VectorDims Convolution::outputStaticShape() const {- auto& outputShape = getOutputShapeAtPort(0);- if (outputShape.isDynamic()) {- auto inpDummyShape = makeInputDummyShape(getInputShapeAtPort(0));- auto outputDims = shapeInferGeneric({Shape(inpDummyShape), Shape(weightDims)});- return Shape(outputDims.front()).getStaticDims();+ m_attrs.inputZeroPointsType = ZeroPointsType::PerChannel;}- return outputShape.getStaticDims();}} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes/conv.h b/src/plugins/intel_cpu/src/nodes/conv.hindex 222a1134c45..d4834d165ec 100644--- a/src/plugins/intel_cpu/src/nodes/conv.h+++ b/src/plugins/intel_cpu/src/nodes/conv.h@@ -5,23 +5,21 @@#include "common/dnnl_executor.h"#include "node.h"+#include "nodes/executors/convolution_config.hpp"+#include "nodes/executors/executor.hpp"+#include "nodes/executors/executor_factory.hpp"#include "oneapi/dnnl/dnnl.hpp"+#include "openvino/core/type/element_type.hpp"-namespace ov {-namespace intel_cpu {-namespace node {--class Eltwise;+namespace ov::intel_cpu::node {class Convolution : public Node {public:Convolution(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context);static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;- void getSupportedDescriptors() override;- void createDescriptor(const std::vector<MemoryDescPtr>& inputDesc,- const std::vector<MemoryDescPtr>& outputDesc) override;- void initDescriptor(const NodeConfig& config) override;++ void getSupportedDescriptors() override{};void selectOptimalPrimitiveDescriptor() override;void initSupportedPrimitiveDescriptors() override;int registerToAllocationContext(int offset, AllocationContext& context) override;@@ -31,10 +29,6 @@ public:return false;}ov::element::Type getRuntimePrecision() const override;- std::shared_ptr<MemoryDesc> getSrcMemDesc(const dnnl::primitive_desc& prim_desc, size_t idx) const override;-- dnnl::memory getWeights() const;- dnnl::memory getBias() const;size_t descInputNumbers() override {return getOriginalInputsNumber();@@ -56,102 +50,73 @@ public:void initializeInputZeroPoints(const uint8_t* inputZpData, const size_t inputZpSize);const VectorDims& getWeightDims() {- return weightDims;+ return getInputShapeAtPort(WEIGHTS).getDims();}const std::vector<size_t>& getStride() {- return stride;+ return m_attrs.stride;}- const std::vector<ptrdiff_t>& getDilation() {- return dilation;+ const std::vector<size_t>& getDilation() {+ return m_attrs.dilation;}const std::vector<ptrdiff_t>& getPaddingL() {- return paddingL;+ return m_attrs.paddingL;}const std::vector<ptrdiff_t>& getPaddingR() {- return paddingR;+ return m_attrs.paddingR;}bool canFuse(const NodePtr& node) const override;bool isDepthWise() const {- return isGrouped && 1 == groupOC && 1 == groupIC;+ return m_attrs.isGrouped && 1 == groupOC && 1 == groupIC;}protected:- ov::element::Type fusedEltwisePrecision(const NodePtr& fusingNode) const;- void redefineOutputMemory(const std::vector<VectorDims>& newOutputShapes) override;void addFusedNode(const NodePtr& fusingNode) override;+ void redefineOutputMemory(const std::vector<VectorDims>& newOutputShapes) override;const std::vector<impl_desc_type>& getDefaultImplPriority() override;private:- enum class zpType { None, PerTensor, PerChannel };-class FusedSubgraph;using FusedSubgraphPtr = std::shared_ptr<FusedSubgraph>;- using executorPtr = std::shared_ptr<DnnlExecutor>;- executorPtr execPtr = nullptr;-- class ConvolutionExecutor : public DnnlExecutor {- public:- ConvolutionExecutor(const dnnl::primitive_desc& pd,- const dnnl::memory::desc& inMemDesc,- const dnnl::memory::desc& weightMemDesc,- const dnnl::memory::desc& outMemDesc,- const dnnl::engine& engine,- bool constWeight);- };+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;- class ConvolutionSumExecutor : public DnnlExecutor {- public:- ConvolutionSumExecutor(const dnnl::primitive_desc& pd,- const dnnl::memory::desc& inMemDesc,- const dnnl::memory::desc& weightMemDesc,- const dnnl::memory::desc& outMemDesc,- const dnnl::engine& engine,- bool constWeight);-- private:- void reorder_exec(std::unordered_map<int, dnnl::memory> primArgs, const dnnl::stream& strm) override;- };+ std::tuple<ov::element::Type, ov::element::Type> getDstAndSumPrecision();+ std::tuple<VecMemoryDescs, MemoryDescPtr> initMemoryDescriptors(ov::element::Type dstType) const;+ ExecutorFactoryPtr<ConvAttrs> createExecutorFactory(const MemoryDescArgs& descs,+ const ConvAttrs& attrs,+ const PostOps& postOps);+ ExecutorPtr createFallbackExecutor();void prepareParams() override;void execute(const dnnl::stream& strm) override;void executeDynamicImpl(const dnnl::stream& strm) override;- void addLegacyZeroPoints(dnnl::primitive_attr& attr);- void addZeroPoints(dnnl::primitive_attr& attr);- void setPostOps(dnnl::primitive_attr& attr,- const VectorDims& dims,- bool useLegacyPostOps,- bool initWeights = false);- void SetPostOpsAndZeroPoints(std::vector<dnnl::primitive_attr>& attrs);void filterSupportedDescriptors();- bool isNspcAvailable() const;- void updatePadding();- MemoryDescPtr getSumMemDesc(const dnnl::primitive_desc& primitive_desc_it);- MemoryPtr getOutputMemory() const;VectorDims makeInputDummyShape(const Shape& inpShape) const;- VectorDims outputStaticShape() const;- void appendLegacyZeroPointsArgs();- void appendZeroPointsArgs();- bool withBiases;+ enum InputId : uint8_t {+ DATA = 0,+ WEIGHTS,+ BIAS,+ WEIGHT_SCALES,+ WEIGHT_ZERO_POINTS,+ INPUT_SCALES,+ INPUT_ZERO_POINTS,+ OUTPUT_SCALES,+ OUTPUT_ZERO_POINTS,+ };++ std::unordered_map<size_t, size_t> m_atoi; // memory argument id to input id+ ConvAttrs m_attrs;+ PostOps m_postOps;+ MemoryArgs m_memory;+ ExecutorFactoryPtr<ConvAttrs> m_factory;+ ExecutorPtr m_executor = nullptr;+ ExecutorPtr fallbackExecutor = nullptr;+bool withSum;bool withDWConv;- bool isGrouped;bool withSumBroadcast = false;- bool preferLegacyPostOps = false;- bool preferLegacyZeroPoint = false;- zpType inputZeroPointType = zpType::None;- // maps each supportedPrimitiveDescriptor to corresponding desc from descs- std::vector<size_t> descIdx;- VectorDims expectedBiasDims{};-- std::vector<size_t> stride;- std::vector<ptrdiff_t> dilation;- std::vector<ptrdiff_t> paddingL;- std::vector<ptrdiff_t> paddingR;- VectorDims weightDims;- std::unordered_map<int, MemoryPtr> convPostOpsArgs[2];size_t dw_conv_oc;size_t dw_conv_ih;@@ -165,33 +130,10 @@ private:size_t groupIC;size_t groupOC;- ov::element::Type eltwisePrecision;-- const size_t X_AXIS = 0;- const size_t Y_AXIS = 1;-- const bool isBrgConvAvailable();- std::vector<dnnl::primitive_attr> attrs;- AttrPtr pAttr;- bool autoPadding = false;FusedSubgraphPtr subgraph;std::unordered_map<NodePtr, std::vector<NodePtr>> fusedConstNodes;- MemoryPtr legacyInputZeroPointsMemPtr;- MemoryPtr legacyWeightsZeroPointsMemPtr;- MemoryPtr legacyOutputCompensationMemPtr;- MemoryPtr stockInputZeroPointsMemPtr;- dnnl::memory::data_type outputDataType = dnnl::memory::data_type::undef;- ov::element::Type sumPrc = ov::element::dynamic;bool useJitPlanar = false;- // TODO: migrate on convolution_auto algorithm for x64-#if defined(OPENVINO_ARCH_X86_64)- const dnnl::algorithm baseConvAlgorithm = dnnl::algorithm::convolution_direct;-#else- const dnnl::algorithm baseConvAlgorithm = dnnl::algorithm::convolution_auto;-#endif};-} // namespace node-} // namespace intel_cpu-} // namespace ov+} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/nodes/deconv.cpp b/src/plugins/intel_cpu/src/nodes/deconv.cppindex 0aa1098d780..46f0367e4ea 100644--- a/src/plugins/intel_cpu/src/nodes/deconv.cpp+++ b/src/plugins/intel_cpu/src/nodes/deconv.cpp@@ -1207,7 +1207,7 @@ Deconvolution::DeconvDNNLExecutor::DeconvDNNLExecutor(const dnnl::deconvolution_const dnnl::memory::desc& outMemDesc,const dnnl::engine& engine,bool constWeight)- : DnnlExecutor(pd) {+ : DnnlExecutorLegacy(pd) {if (inMemDesc != getDnnlSrcDesc()) {inputReorders.insert({DNNL_ARG_SRC, IntermReorder(inMemDesc, getDnnlSrcDesc(), engine)});}diff --git a/src/plugins/intel_cpu/src/nodes/deconv.h b/src/plugins/intel_cpu/src/nodes/deconv.hindex 4a045f86e6d..c64a2a27899 100644--- a/src/plugins/intel_cpu/src/nodes/deconv.h+++ b/src/plugins/intel_cpu/src/nodes/deconv.h@@ -62,9 +62,9 @@ protected:std::shared_ptr<DeconvExecutor> execPtrDeconvACL = nullptr;private:- using executorPtr = std::shared_ptr<DnnlExecutor>;+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;executorPtr execPtr = nullptr;- class DeconvDNNLExecutor : public DnnlExecutor {+ class DeconvDNNLExecutor : public DnnlExecutorLegacy {public:DeconvDNNLExecutor(const dnnl::deconvolution_forward::primitive_desc& pd,const dnnl::memory::desc& inMemDesc,diff --git a/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hppindex 96929992f77..ac617e420ca 100644--- a/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/convolution_config.hpp@@ -8,12 +8,28 @@namespace ov::intel_cpu {+enum class ZeroPointsType : uint8_t { None, PerTensor, PerChannel };+enum class AutoPaddingType : uint8_t { None, SAME_UPPER, SAME_LOWER };/*** @todo only attributes necessary for 1x1 convlution as fullyconnected fallback* are currently listed*/struct ConvAttrs {+ std::vector<size_t> stride;+ std::vector<size_t> dilation;+ std::vector<ptrdiff_t> paddingL;+ std::vector<ptrdiff_t> paddingR;+ AutoPaddingType autoPadding;+bool withBias;+ bool weightsNonTransposed;+ bool isGrouped;+ // @todo can we just check for port precisions instead?+ bool isGraphQuantized;+ bool fcSemantic;+ bool nonConstantWeights;+ ZeroPointsType inputZeroPointsType;+ std::vector<float> dqScales;};using ConvConfig = executor::Config<ConvAttrs>;diff --git a/src/plugins/intel_cpu/src/nodes/executors/convolution_implementations.cpp b/src/plugins/intel_cpu/src/nodes/executors/convolution_implementations.cppnew file mode 100644index 00000000000..e203a479eb9--- /dev/null+++ b/src/plugins/intel_cpu/src/nodes/executors/convolution_implementations.cpp@@ -0,0 +1,248 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include <vector>++#include "memory_desc/dnnl_blocked_memory_desc.h"+#include "memory_format_filter.hpp"+#include "nodes/executors/convolution_config.hpp"+#include "nodes/executors/dnnl/dnnl_convolution_primitive.hpp"+#include "nodes/executors/executor.hpp"+#include "nodes/executors/executor_implementation.hpp"+#include "nodes/executors/implementation_utils.hpp"+#include "nodes/executors/implementations.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"+#include "utils/general_utils.h"++namespace ov::intel_cpu {++using namespace ov::element;+using namespace TypeMaskAlias;+using namespace executor;++using LayoutConfig = std::vector<LayoutType>;++static const MappingNotation dnnlConvolutionMappingNotation{ARG_SRC, ARG_WEI, ARG_BIAS, ARG_DST};++// clang-format off+static const TypeMapping dnnlConvTypeMapping {+ // {src, wei, bia, dst} pt<src, wei, bias, dst>+ {{_bf16, _bf16 | _f16 | _f32, _any, _bf16 | _f32}, pt(bypass(), bypass(), use<3>(), bypass())},+ {{_f16, _bf16 | _f16 | _f32, _any, _f16 | _f32}, pt(bypass(), bypass(), use<3>(), bypass())},+ // integer precision outputs are not supported for float precision inputs+ {{_f32 | _bf16 | _f16, _any, _any, _i8 | _u8}, pt(bypass(), bypass(), use<0>(), use<0>())},+ // compresses float weights which do not match input data precision+ {{_f32, _half_float | _i8, _any, _any}, pt(bypass(), bypass(), use<0>(), use<0>())},+ {{_bf16, _f16, _any, _any}, pt(bypass(), bypass(), use<0>(), use<0>())},+ {{_f16, _bf16, _any, _any}, pt(bypass(), bypass(), use<0>(), use<0>())},+ // quantization configuration+ {{_u8 | _i8, _i8, _quant | _hw_float | _i32 | _dynamic, _quant | _hw_float | _i32 | _dynamic}, pt(bypass(), bypass(), bypass(), bypass())},+ // @todo should we fallback to FPXX instead of _f32?+ {{_any, _any, _any, _any}, pt(just<f32>(), just<f32>(), just<f32>(), just<f32>())},+ // @todo explicitly cover configuration limitations for oneDNN on ARM+};+// clang-format on+struct RequiresFallbackDefault {+ std::optional<ConvConfig> operator()(const ConvConfig& config) const {+ return requiresFallbackCommon(config, dnnlConvTypeMapping, layoutConfig, dnnlConvolutionMappingNotation);+ }++ LayoutConfig layoutConfig;+};++template <typename Attrs>+bool MatchesMemoryFormatFilter(const executor::Config<Attrs>& config,+ const LayoutConfig& layoutConfig,+ const MemoryFormatFilter& filter) {+ const auto& notation = dnnlConvolutionMappingNotation;++ for (size_t i = 0; i < filter.input.size(); i++) {+ const auto& desc = config.descs.at(notation[i]);++ if (desc->empty()) {+ continue;+ }++ const auto dnnlDesc = DnnlBlockedMemoryDesc(config.descs.at(notation[i])->getShape(),+ dnnl::memory::data_type::f32,+ filter.input[i]);+ if (!dnnlDesc.hasLayoutType(layoutConfig[i])) {+ return false;+ }+ }++ if (filter.output.empty()) {+ return true;+ }++ const auto desc = DnnlBlockedMemoryDesc(config.descs.at(ARG_DST)->getShape(),+ dnnl::memory::data_type::f32,+ filter.output.front());+ if (!desc.hasLayoutType(layoutConfig.back())) {+ return false;+ }++ return true;+}++// to keep OV_CPU_INSTANCE macros aligned+// clang-format off+template <>+const std::vector<ExecutorImplementation<ConvAttrs>>& getImplementations() {+ static const std::vector<ExecutorImplementation<ConvAttrs>> convolutionImplementations {+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_nspc_nspc", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc},+ memoryFormatFilter)) {+ return false;+ }+ // nspc shows better performance only with brgconv implementation+ return DnnlConvolutionPrimitive::isBrgConvAvailable(config);+ },+ RequiresFallbackDefault{{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_ncsp_ncsp", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp},+ memoryFormatFilter)) {+ return false;+ }++ const auto [groupNum, groupIC, IC, groupOC] = DnnlConvolutionPrimitive::getChannelParams(config);++ return IC == 1 && groupOC == 1;+ },+ RequiresFallbackDefault{{LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_ncsp_nCsp16c", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::ncsp, LayoutType::ncsp, LayoutType::nCsp16c, LayoutType::nCsp16c},+ memoryFormatFilter)) {+ return false;+ }++ const auto [groupNum, groupIC, IC, groupOC] = DnnlConvolutionPrimitive::getChannelParams(config);++ return IC < 4 && groupOC != 1;+ },+ RequiresFallbackDefault{{LayoutType::ncsp, LayoutType::ncsp, LayoutType::nCsp16c, LayoutType::nCsp16c}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_ncsp_nCsp8c", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::ncsp, LayoutType::ncsp, LayoutType::nCsp8c, LayoutType::nCsp8c},+ memoryFormatFilter)) {+ return false;+ }++ const auto [groupNum, groupIC, IC, groupOC] = DnnlConvolutionPrimitive::getChannelParams(config);++ return IC < 4 && groupOC != 1;+ },+ RequiresFallbackDefault{{LayoutType::ncsp, LayoutType::ncsp, LayoutType::nCsp8c, LayoutType::nCsp8c}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_nCsp16c_nCsp16c", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::nCsp16c, LayoutType::ncsp, LayoutType::nCsp16c, LayoutType::nCsp16c},+ memoryFormatFilter)) {+ return false;+ }++ const auto [groupNum, groupIC, IC, groupOC] = DnnlConvolutionPrimitive::getChannelParams(config);++ return IC > 4;+ },+ RequiresFallbackDefault{{LayoutType::nCsp16c, LayoutType::ncsp, LayoutType::nCsp16c, LayoutType::nCsp16c}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_nCsp8c_nCsp8c", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::nCsp8c, LayoutType::ncsp, LayoutType::nCsp8c, LayoutType::nCsp8c},+ memoryFormatFilter)) {+ return false;+ }++ const auto [groupNum, groupIC, IC, groupOC] = DnnlConvolutionPrimitive::getChannelParams(config);++ return IC > 4;+ },+ RequiresFallbackDefault{{LayoutType::nCsp8c, LayoutType::ncsp, LayoutType::nCsp8c, LayoutType::nCsp8c}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_ncsp_ncsp_unconditional", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp},+ memoryFormatFilter)) {+ return false;+ }++ return true;+ },+ RequiresFallbackDefault{{LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp, LayoutType::ncsp}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_DNNL_X64(+ "convolution_dnnl_nspc_nspc_backup", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc},+ memoryFormatFilter)) {+ return false;+ }++ return !one_of(srcType(config), ov::element::bf16, ov::element::f16) && DnnlConvolutionPrimitive::isNspcAvailable(config);+ },+ RequiresFallbackDefault{{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ OV_CPU_INSTANCE_ACL(+ "convolution_dnnl_nspc_nspc_unconditional_acl", ExecutorType::Dnnl, OperationType::Convolution, ShapeTolerance::Agnostic,+ // supports+ [](const ConvConfig& config, const MemoryFormatFilter& memoryFormatFilter) -> bool {+ if (!MatchesMemoryFormatFilter(config, LayoutConfig{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc},+ memoryFormatFilter)) {+ return false;+ }++ return true;+ },+ RequiresFallbackDefault{{LayoutType::nspc, LayoutType::ncsp, LayoutType::nspc, LayoutType::nspc}},+ AcceptsAnyShape<ConvAttrs>{},+ CreateDnnlDefault<DnnlConvolutionPrimitive, ConvAttrs>{}+ )+ };++ return convolutionImplementations;+}+// clang-format on++} // namespace ov::intel_cpudiff --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.cppindex e6302e19b16..091d96615c0 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@@ -4,12 +4,23 @@#include "nodes/executors/dnnl/dnnl_convolution_primitive.hpp"+#include <algorithm>+#include <cassert>+#include <common/c_types_map.hpp>#include <common/primitive_desc_iface.hpp>+#include <common/utils.hpp>+#include <cstddef>+#include <cstdint>#include <oneapi/dnnl/dnnl.hpp>+#include <oneapi/dnnl/dnnl_common.hpp>+#include <tuple>#include <vector>+#include "cpu/x64/cpu_isa_traits.hpp"+#include "cpu_types.h"#include "dnnl_extension_utils.h"#include "dnnl_postops_composer.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/convolution_config.hpp"@@ -18,14 +29,84 @@#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"#include "nodes/executors/executor.hpp"#include "nodes/executors/fullyconnected_config.hpp"+#include "nodes/executors/graph_emitter.hpp"#include "nodes/executors/memory_arguments.hpp"#include "onednn/iml_type_mapper.h"+#include "openvino/core/type/element_type.hpp"+#include "shape_inference/custom/convolution.hpp"namespace ov::intel_cpu {using namespace dnnl;using namespace executor;+DnnlConvolutionPrimitive::IntermediateReorders::IntermediateReorders(const Key& key,+ const dnnl::primitive_desc& primDesc,+ const dnnl::engine& engine) {+ if (key.fcSemantic) {+ return; // currently 'any' format is never used for src / dst memory for FullyConnected+ }++ enum class AllocateMemoryFor : uint8_t { Src, Dst };++ const auto& postOps = primDesc.get_primitive_attr().get_post_ops();++ const bool withSum = [&postOps] {+ for (int i = 0; i < postOps.len(); ++i) {+ if (postOps.kind(i) == dnnl::primitive::kind::sum) {+ return true;+ }+ }+ return false;+ }();++ auto createIfNotEqual = [](const dnnl::memory::desc& src,+ const dnnl::memory::desc& dst,+ AllocateMemoryFor allocate,+ const dnnl::engine& engine) -> IntermediateReorder {+ auto reorderDesc = dnnl::reorder::primitive_desc(engine, src, engine, dst);+ auto reorder = dnnl::reorder(reorderDesc);+ const auto& memDescToAllocate = allocate == AllocateMemoryFor::Dst ? dst : src;++ return {reorder, memDescToAllocate};+ };++ if (key.src->getDnnlDesc() != primDesc.src_desc()) {+ m_inputReorders[DNNL_ARG_SRC] =+ createIfNotEqual(key.src->getDnnlDesc(), primDesc.src_desc(), AllocateMemoryFor::Dst, engine);+ }++ // In the case of fusing sum, we have to reorder the output data before executing the primitive,+ // since the output data are used as an accumulator for the covolution computations.+ if (withSum && key.dst->getDnnlDesc() != primDesc.dst_desc()) {+ m_inputReorders[DNNL_ARG_DST] =+ createIfNotEqual(key.dst->getDnnlDesc(), primDesc.dst_desc(), AllocateMemoryFor::Dst, engine);+ }++ if (key.nonConstantWeights && key.wei->getDnnlDesc() != primDesc.weights_desc()) {+ m_inputReorders[DNNL_ARG_WEIGHTS] =+ createIfNotEqual(key.wei->getDnnlDesc(), primDesc.weights_desc(), AllocateMemoryFor::Dst, engine);+ }++ if (key.dst->getDnnlDesc() != primDesc.dst_desc()) {+ m_outputReorders[DNNL_ARG_DST] =+ createIfNotEqual(primDesc.dst_desc(), key.dst->getDnnlDesc(), AllocateMemoryFor::Src, engine);+ }+}++bool DnnlConvolutionPrimitive::IntermediateReorders::empty() const {+ return m_inputReorders.empty() && m_outputReorders.empty();+}++static const std::map<memory::data_type, memory::data_type> weightsTypeByInputType{+ // input data type weights data type+ {memory::data_type::f32, memory::data_type::f32},+ {memory::data_type::f16, memory::data_type::f16},+ {memory::data_type::bf16, memory::data_type::bf16},+ {memory::data_type::u8, memory::data_type::s8},+ {memory::data_type::s8, memory::data_type::s8},+};+// @todo rewrite using hash_buildersize_t DnnlConvolutionPrimitive::Key::hash() const {using namespace dnnl::impl;@@ -39,7 +120,14 @@ size_t DnnlConvolutionPrimitive::Key::hash() const {}}+ seed = get_vector_hash(seed, stride);+ seed = get_vector_hash(seed, dilation);+ seed = get_vector_hash(seed, paddingL);+ seed = get_vector_hash(seed, paddingR);+seed = hash_combine(seed, get_attr_hash(*attr.get()));+ seed = hash_combine(seed, fcSemantic);+ seed = hash_combine(seed, nonConstantWeights);return seed;}@@ -60,7 +148,12 @@ bool DnnlConvolutionPrimitive::Key::operator==(const Key& rhs) const {result = result && dst && rhs.dst && dst->getDnnlDesc() == rhs.dst->getDnnlDesc();}+ result = result && stride == rhs.stride;+ result = result && dilation == rhs.dilation;+result = result && *attr.get() == *rhs.attr.get();+ result = result && fcSemantic == rhs.fcSemantic;+ result = result && nonConstantWeights == rhs.nonConstantWeights;return result;}@@ -77,27 +170,21 @@ static std::vector<T> normalizeDims(const std::vector<T>& dims) {return {dnnl::memory::dim{1}, dims[1], dims[0]};}-static dnnl::convolution_forward::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) {+static dnnl::convolution_forward::primitive_desc createInnerProductDescriptor(const dnnl::memory::desc& inputDesc,+ const dnnl::memory::desc& weightDesc,+ const dnnl::memory::desc& biasDesc,+ const dnnl::memory::desc& outputDesc,+ const std::vector<size_t>& stride,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,+ const dnnl::primitive_attr& attr,+ const dnnl::engine& engine) {const auto normalizedInDims = normalizeDims(inputDesc.get_dims());const auto convInDesc = dnnl::memory::desc(normalizedInDims, inputDesc.get_data_type(), memory::format_tag::nwc);const auto normalizedOutDims = normalizeDims(outputDesc.get_dims());const auto convOutDesc = dnnl::memory::desc(normalizedOutDims, outputDesc.get_data_type(), memory::format_tag::nwc);- // @todo create general mapping from node configuration to backend configuration- static const std::map<memory::data_type, memory::data_type> weightsTypeByInputType{- // input data type weights data type- {memory::data_type::f32, memory::data_type::f32},- {memory::data_type::f16, memory::data_type::f16},- {memory::data_type::bf16, memory::data_type::bf16},- {memory::data_type::u8, memory::data_type::s8},- {memory::data_type::s8, memory::data_type::s8},- };-// make a fake shape: OC, IC, 1const auto& weightDims = weightDesc.get_dims();const dnnl::memory::dims normalizedWeightDims{static_cast<dnnl::memory::dim>(weightDims[0]),@@ -107,90 +194,656 @@ static dnnl::convolution_forward::primitive_desc createDescriptorInternal(constconst auto convWeightDescAny =dnnl::memory::desc(normalizedWeightDims, weightDataType, dnnl::memory::format_tag::any);- return dnnl::convolution_forward::primitive_desc(engine,- prop_kind::forward_inference,- dnnl::algorithm::convolution_direct,- convInDesc,- convWeightDescAny,- biasDesc,- convOutDesc,- dnnl::memory::dims{1}, // stride- dnnl::memory::dims{0}, // dilation- dnnl::memory::dims{0}, // paddingL- dnnl::memory::dims{0}, // paddingR- attr);-}--static primitive_desc createPrimitiveDesc(const dnnl::engine& engine,- const dnnl::memory::desc& inputDesc,+ // TODO: migrate on convolution_auto algorithm for x64+#if defined(OPENVINO_ARCH_X86_64)+ const dnnl::algorithm algorithm = dnnl::algorithm::convolution_direct;+#else+ const dnnl::algorithm algorithm = dnnl::algorithm::convolution_auto;+#endif++ return {engine,+ prop_kind::forward_inference,+ algorithm,+ convInDesc,+ convWeightDescAny,+ biasDesc,+ convOutDesc,+ dnnl::memory::dims(stride.begin(), stride.end()),+ dnnl::memory::dims(dilation.begin(), dilation.end()),+ dnnl::memory::dims(paddingL.begin(), paddingL.end()),+ dnnl::memory::dims(paddingR.begin(), paddingR.end()),+ attr};+}++static dnnl::convolution_forward::primitive_desc createConvolutionDescriptor(const dnnl::memory::desc& inputDesc,+ const dnnl::memory::desc& weightDesc,+ const dnnl::memory::desc& biasDesc,+ const dnnl::memory::desc& outputDesc,+ const std::vector<size_t>& stride,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,+ const dnnl::primitive_attr& attr,+ const dnnl::engine& engine) {+ const auto weightDataType = weightsTypeByInputType.at(inputDesc.get_data_type());+ const auto weightDescAny = dnnl::memory::desc(weightDesc.get_dims(), weightDataType, dnnl::memory::format_tag::any);+ // TODO: migrate on convolution_auto algorithm for x64+#if defined(OPENVINO_ARCH_X86_64)+ const dnnl::algorithm algorithm = dnnl::algorithm::convolution_direct;+#else+ const dnnl::algorithm algorithm = dnnl::algorithm::convolution_auto;+#endif+ return {engine,+ prop_kind::forward_inference,+ algorithm,+ inputDesc,+ weightDescAny,+ biasDesc,+ outputDesc,+ dnnl::memory::dims(stride.begin(), stride.end()),+ dnnl::memory::dims(dilation.begin(), dilation.end()),+ dnnl::memory::dims(paddingL.begin(), paddingL.end()),+ dnnl::memory::dims(paddingR.begin(), paddingR.end()),+ attr,+ true};+}++static std::tuple<primitive_desc, size_t> selectPrimitiveDescWithMultipleAttributes(+ const dnnl::engine& engine,+ const dnnl::memory::desc& inputDesc,+ const dnnl::memory::desc& weightDesc,+ const dnnl::memory::desc& biasDesc,+ const dnnl::memory::desc& outputDesc,+ const std::vector<size_t>& stride,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,+ const std::vector<dnnl::primitive_attr>& attrs,+ const std::vector<impl_desc_type>& implPriorities) {+ auto createPrimitiveDescriptor = [&](const dnnl::primitive_attr& attr) {+ return createConvolutionDescriptor(inputDesc,+ weightDesc,+ biasDesc,+ outputDesc,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine);+ };++ struct PrimitiveDescWithPriority {+ dnnl::primitive_desc prim_desc;+ size_t attrId;+ size_t priority;+ };++ PrimitiveDescWithPriority prim_desc_w_priority{dnnl::primitive_desc(), 0, implPriorities.size()};++ // try all the provided attributes and select the one which results in a primitive desc with the highest priority+ for (size_t attrId = 0; attrId < attrs.size(); attrId++) {+ const auto& attr = attrs[attrId];++ for (size_t priorityId = 0; priorityId < implPriorities.size(); priorityId++) {+ const auto preferredImplType = implPriorities[priorityId];+ // the only way to fully reset primitive_desc after iterating over the implementations is to re-create it+ auto cur_desc = createPrimitiveDescriptor(attr);+ const bool found = DnnlExtensionUtils::find_implementation(cur_desc, preferredImplType);++ const size_t highestPriority = prim_desc_w_priority.priority;+ if (found && priorityId < highestPriority) {+ prim_desc_w_priority = {cur_desc, attrId, priorityId};+ }+ }+ }++ auto prim_desc = prim_desc_w_priority.prim_desc;++ return {prim_desc, prim_desc_w_priority.attrId};+}++static primitive_desc createPrimitiveDesc(const dnnl::memory::desc& inputDesc,const dnnl::memory::desc& weightDesc,const dnnl::memory::desc& biasDesc,const dnnl::memory::desc& outputDesc,+ const std::vector<size_t>& stride,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,const dnnl::primitive_attr& attr,- const std::vector<impl_desc_type>& implPriorities) {- auto prim_desc = createDescriptorInternal(inputDesc, weightDesc, biasDesc, outputDesc, attr, engine);- auto first_desc = dnnl::convolution_forward::primitive_desc(prim_desc.get());+ const dnnl::engine& engine,+ bool fcSemantic,+ const std::vector<impl_desc_type>& implPriorities,+ const impl_desc_type defaultImplType) {+ auto createPrimitiveDescriptor = [&](const dnnl::primitive_attr& attr) {+ return fcSemantic ? createInnerProductDescriptor(inputDesc,+ weightDesc,+ biasDesc,+ outputDesc,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine)+ : createConvolutionDescriptor(inputDesc,+ weightDesc,+ biasDesc,+ outputDesc,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine);+ };- for (auto preferredImplType : implPriorities) {- const bool found = DnnlExtensionUtils::find_implementation(prim_desc, preferredImplType);+ auto createConvolutionDescriptorAny = [](const dnnl::memory::desc& inputDesc,+ const dnnl::memory::desc& weightDesc,+ const dnnl::memory::desc& biasDesc,+ const dnnl::memory::desc& outputDesc,+ const std::vector<size_t>& stride,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,+ const dnnl::primitive_attr& attr,+ const dnnl::engine& engine) {+ auto inputDescAny =+ dnnl::memory::desc(inputDesc.get_dims(), inputDesc.get_data_type(), memory::format_tag::any);+ auto outputDescAny =+ dnnl::memory::desc(outputDesc.get_dims(), outputDesc.get_data_type(), memory::format_tag::any);+ return createConvolutionDescriptor(inputDescAny,+ weightDesc,+ biasDesc,+ outputDescAny,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine);+ };- if (found) {+ auto prim_desc = createPrimitiveDescriptor(attr);+ // keep first implementation descriptor to fallback to it if no other implementation is found+ auto first_desc = prim_desc;+ // if default implementation type is not specified, try to find the best implementation+ if (defaultImplType == impl_desc_type::undef) {+ if (!prim_desc) {+ // fallback to 'any' implementation+ return createConvolutionDescriptorAny(inputDesc,+ weightDesc,+ biasDesc,+ outputDesc,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine);return std::move(prim_desc);}++ for (auto preferredImplType : implPriorities) {+ // the only way to fully reset primitive_desc after iterating over the implementations is to re-create it+ const bool found = DnnlExtensionUtils::find_implementation(prim_desc, preferredImplType);++ if (found) {+ return std::move(prim_desc);+ }++ prim_desc = createPrimitiveDescriptor(attr);+ }++ return std::move(first_desc);+ }+ // try to use a default implementations type (created using dummy shapes) if specified+ const bool found = DnnlExtensionUtils::find_implementation(prim_desc, defaultImplType);++ if (found) {+ return std::move(prim_desc);+ }++ if (fcSemantic) { // fallback to the first implementation if used as FC executor+ return std::move(first_desc);}- return std::move(first_desc);+ // fallback to 'any' implementation+ return createConvolutionDescriptorAny(inputDesc,+ weightDesc,+ biasDesc,+ outputDesc,+ stride,+ dilation,+ paddingL,+ paddingR,+ attr,+ engine);}-static DnnlPrimitiveAttrs createPrimitiveAttrs(const PostOps& postOps,- const MemoryArgs& memory,- const ExecutorContext::CPtr& context) {+static std::vector<DnnlPrimitiveAttrs> createPrimitiveAttrs(const ConvAttrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr& context) {const auto& srcDesc = memory.at(ARG_SRC)->getDescPtr();const auto& weiDesc = memory.at(ARG_WEI)->getDescPtr();const auto& dstDesc = memory.at(ARG_DST)->getDescPtr();- const auto& originalDims = dstDesc->getShape().getMinDims();- const auto& dims = normalizeDims(originalDims);+ const auto& originalOutputDims = dstDesc->getShape().getMinDims();+ const auto& outputDims = attrs.fcSemantic ? normalizeDims(originalOutputDims) : originalOutputDims;auto isINT8 =one_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, 1, isINT8, 1 << 0, memory, outputDataType);+ const auto weightScaleMask = attrs.isGrouped ? 3 : 1 << 0;+ constexpr int channelDimIdx = 1;++ if (attrs.fcSemantic) {+ // use original post ops and zero points in case if used as FC executor+ return {DnnlPostOpsComposer(postOps,+ context->getEngine(),+ outputDims,+ channelDimIdx,+ isINT8,+ weightScaleMask,+ memory,+ outputDataType,+ attrs.dqScales,+ false,+ false)+ .compose()};+ }++ DnnlPostOpsComposer legacyPostOpsLegacyZeroPoints(postOps,+ context->getEngine(),+ outputDims,+ channelDimIdx,+ isINT8,+ weightScaleMask,+ memory,+ outputDataType,+ attrs.dqScales,+ true,+ true);+ // first try to compose using legacy post ops+ auto legacyCompose = legacyPostOpsLegacyZeroPoints.compose();++ // check if legacy compose is enough+ auto attrContainsPostOp = [](const dnnl::primitive_attr& attr, const dnnl::impl::primitive_kind_t kind) -> bool {+ const auto ops = attr.get_post_ops();+ return ops.get()->find(kind) != -1;+ };++ // dw-conv would be fused into conv only on AVX2 platform.+ if (attrContainsPostOp(legacyCompose.attr, dnnl::impl::primitive_kind::convolution)) {+ DEBUG_LOG("Attribute contains conv post op. Use legacy post ops");+ return {legacyCompose};+ }++ if (attrs.inputZeroPointsType == ZeroPointsType::None &&+ !attrContainsPostOp(legacyCompose.attr, dnnl::impl::primitive_kind::depthwise) &&+ !attrContainsPostOp(legacyCompose.attr, dnnl::impl::primitive_kind::quantization)) {+ DEBUG_LOG("Attribute already contains no legacy post ops");+ return {legacyCompose};+ }++ if (attrs.inputZeroPointsType == ZeroPointsType::PerChannel) {+ DEBUG_LOG("Per channel zero point can only supported with legacy post ops");+ return {legacyCompose};+ }++ // @todo avoid extra step of creating config to get the brgconv availability+ auto config = GraphEmitter<ConvAttrs>::createConfig(memory, attrs, postOps);+ if (!DnnlConvolutionPrimitive::isBrgConvAvailable(config)) {+ DEBUG_LOG("Brgconv is not available. Skip extra attribute");+ return {legacyCompose};+ }++ if (!dstDesc->hasLayoutType(LayoutType::nspc)) {+ DEBUG_LOG("Brgemm convolution supports only nspc layout. Use legacy post ops");+ return {legacyCompose};+ }++ std::vector<DnnlPrimitiveAttrs> attributeVariants{legacyCompose};++ if (dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core_amx) &&+ attrs.inputZeroPointsType == ZeroPointsType::PerTensor) {+ DnnlPostOpsComposer legacyPostOpsOriginalZeroPoints(postOps,+ context->getEngine(),+ outputDims,+ channelDimIdx,+ isINT8,+ weightScaleMask,+ memory,+ outputDataType,+ attrs.dqScales,+ true,+ false);+ attributeVariants.emplace_back(legacyPostOpsOriginalZeroPoints.compose());++ return attributeVariants;+ }++ DnnlPostOpsComposer originalPostOpsOriginalZeroPoints(postOps,+ context->getEngine(),+ outputDims,+ channelDimIdx,+ isINT8,+ weightScaleMask,+ memory,+ outputDataType,+ attrs.dqScales,+ false,+ false);+ attributeVariants.emplace_back(originalPostOpsOriginalZeroPoints.compose());++ return attributeVariants;+}++constexpr auto dilated(const int64_t dim, const int64_t dilation) {+ constexpr int64_t inf_bound = -1; //!< Infinite bound value for dimension.+ return (dim < 1) ? inf_bound : (dilation + 1) * (dim - 1) + 1;+}++static std::pair<int64_t, int64_t> padding(const int64_t dim,+ const int64_t kernel_size,+ const int64_t dilation,+ const int64_t stride) {+ const auto dilated_kernel = dilated(kernel_size, dilation);+ const int64_t tmp = (dim + stride - 1) / stride;++ const auto padding = std::max<int64_t>(0, (tmp - 1) * stride + dilated_kernel - dim);+ const auto left_padding = padding / 2;++ return {left_padding, padding - left_padding};+}++static std::tuple<std::vector<ptrdiff_t>, std::vector<ptrdiff_t>> apply_auto_pad(const VectorDims& data_shape,+ const VectorDims& weights_shape,+ const std::vector<size_t>& strides,+ const std::vector<size_t>& dilations,+ AutoPaddingType type) {+ const auto num_spatial = strides.size();+ std::vector<ptrdiff_t> padB(num_spatial);+ std::vector<ptrdiff_t> padE(num_spatial);++ auto data_dim = data_shape.size() - num_spatial;+ auto kernel_dim = weights_shape.size() - num_spatial;++ const auto padding_swap = type == AutoPaddingType::SAME_UPPER;+ auto& pad_b = padding_swap ? padB : padE;+ auto& pad_e = padding_swap ? padE : padB;++ for (size_t i = 0; i < num_spatial; ++i, ++data_dim, ++kernel_dim) {+ std::tie(pad_b[i], pad_e[i]) =+ padding(data_shape[data_dim], weights_shape[kernel_dim], dilations[i], strides[i]);+ }++ return {padB, padE};+}++VectorDims static makeInputDummyShape(const Shape& inputShape,+ const Shape& weightShape,+ const std::vector<size_t>& strides,+ const std::vector<size_t>& dilation,+ const std::vector<ptrdiff_t>& paddingL,+ const std::vector<ptrdiff_t>& paddingR,+ bool isGrouped) {+ // There are a bunch of heuristics mostly aimed to guess the most appropriate oneDNN implementation, to reduce+ // thie amount of the implementation mismatch and the internal reordering as a consequence.+ constexpr Dim dummyInputDim = 64;++ const size_t spatialRank = strides.size();+ const auto& weightDims = weightShape.getStaticDims();+ const size_t filterStartIndx = weightDims.size() - spatialRank;++ VectorDims dummyInputShapeVals(inputShape.getRank(), dummyInputDim);++ const auto G = isGrouped ? weightDims[0] : 1;+ const auto IC = isGrouped ? weightDims[2] : weightDims[1];+ dummyInputShapeVals[1] = G * IC;++ for (size_t i = 0; i < spatialRank; i++) {+ if (weightDims[filterStartIndx + i] > dummyInputShapeVals[2 + i]) {+ constexpr Dim dummyOutputDim = 16;+ dummyInputShapeVals[2 + i] = (dummyOutputDim - 1) * strides[i] - (paddingL[i] + paddingR[i]) ++ weightDims[filterStartIndx + i] ++ (weightDims[filterStartIndx + i] - 1) * (dilation[i]);+ }+ }++ return MemoryDescUtils::makeDummyShape(inputShape, dummyInputShapeVals).getStaticDims();+}++static std::tuple<MemoryDescPtr, MemoryDescPtr> createDummySrcDstDescs(const ConvAttrs& attrs,+ const MemoryArgs& memory) {+ const auto& srcShape = memory.at(ARG_SRC)->getShape();+ const auto& weiShape = memory.at(ARG_WEI)->getShape();+ const auto& strides = attrs.stride;+ const auto& dilation = attrs.dilation;+ auto paddingL = attrs.paddingL;+ if (paddingL.size() < strides.size()) {+ paddingL.resize(strides.size(), 0);+ }++ auto paddingR = attrs.paddingR;+ if (paddingR.size() < strides.size()) {+ paddingR.resize(strides.size(), 0);+ }++ auto dummyInputDims =+ makeInputDummyShape(srcShape, weiShape, strides, dilation, paddingL, paddingR, attrs.isGrouped);++ auto ovDilation = dilation;+ std::transform(ovDilation.begin(), ovDilation.end(), ovDilation.begin(), [](size_t d) {+ return d + 1;+ });++ auto dummyOutputDims = node::convolution_shape_infer(dummyInputDims,+ weiShape.getStaticDims(),+ strides,+ ovDilation,+ paddingL,+ paddingR,+ attrs.autoPadding != AutoPaddingType::None,+ attrs.isGrouped);++ auto srcDesc = memory.at(ARG_SRC)->getDescPtr();+ const auto& weiDesc = memory.at(ARG_WEI)->getDescPtr();+ auto dstDesc = memory.at(ARG_DST)->getDescPtr();- return dnnlpoc.compose();+ srcDesc = srcDesc->cloneWithNewDims(dummyInputDims);+ dstDesc = dstDesc->cloneWithNewDims(dummyOutputDims);++ if (attrs.autoPadding != AutoPaddingType::None) {+ std::tie(paddingL, paddingR) = apply_auto_pad(srcDesc->getShape().getDims(),+ weiDesc->getShape().getDims(),+ attrs.stride,+ attrs.dilation,+ attrs.autoPadding);+ }++ return {srcDesc, dstDesc};}-DnnlShapeAgnosticDataPtr DnnlConvolutionPrimitive::createShapeAgnosticData([[maybe_unused]] const FCAttrs& attrs,+DnnlShapeAgnosticDataPtr DnnlConvolutionPrimitive::createShapeAgnosticData(const ConvAttrs& attrs,const PostOps& postOps,const MemoryArgs& memory,const ExecutorContext::CPtr& context,- [[maybe_unused]] const bool cacheWeights) {- DEBUG_LOG("Creating shape agnostic data");+ const bool cacheWeights) {+ // @todo we might want to enable weights prepacking for dynamic shapes as well+ const bool undefinedInputShapes = !memory.at(ARG_SRC)->isDefined();+ const bool cacheWeightsWithUndefData = undefinedInputShapes && cacheWeights;+ OPENVINO_ASSERT(!cacheWeightsWithUndefData,+ "dnnl convolution weights caching for dynamic shapes is not implemented");++ auto [srcDesc, dstDesc] = undefinedInputShapes+ ? createDummySrcDstDescs(attrs, memory)+ : std::tuple{memory.at(ARG_SRC)->getDescPtr(), memory.at(ARG_DST)->getDescPtr()};++ const auto& weiDesc = memory.at(ARG_WEI)->getDescPtr();+ const auto& biasDesc = memory.at(ARG_BIAS)->getDescPtr();++ const bool autoPadding = attrs.autoPadding != AutoPaddingType::None;+ const bool calculatePadding = undefinedInputShapes && autoPadding;+ auto [paddingL, paddingR] = calculatePadding ? apply_auto_pad(srcDesc->getShape().getDims(),+ weiDesc->getShape().getDims(),+ attrs.stride,+ attrs.dilation,+ attrs.autoPadding)+ : std::tuple(attrs.paddingL, attrs.paddingR);++ const dnnl::memory::desc srcDnnlDesc = MemoryDescUtils::convertToDnnlMemoryDesc(srcDesc)->getDnnlDesc();+ const dnnl::memory::desc weiDnnlDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weiDesc)->getDnnlDesc();+ const dnnl::memory::desc dstDnnlDesc = MemoryDescUtils::convertToDnnlMemoryDesc(dstDesc)->getDnnlDesc();+ const dnnl::memory::desc biaDnnlDesc = MemoryDescUtils::convertToDnnlMemoryDesc(biasDesc)->getDnnlDesc();- const auto postOpData = createPrimitiveAttrs(postOps, memory, context);+ const auto primitiveAttributes = createPrimitiveAttrs(attrs, postOps, memory, context);- return std::make_shared<DnnlShapeAgnosticData>(postOpData);+ std::vector<dnnl::primitive_attr> dnnlAttrVariants;+ dnnlAttrVariants.reserve(primitiveAttributes.size());++ for (const auto& postOp : primitiveAttributes) {+ dnnlAttrVariants.push_back(postOp.attr);+ }++ auto [primitiveDesc, attrId] = selectPrimitiveDescWithMultipleAttributes(context->getEngine(),+ srcDnnlDesc,+ weiDnnlDesc,+ biaDnnlDesc,+ dstDnnlDesc,+ attrs.stride,+ attrs.dilation,+ paddingL,+ paddingR,+ dnnlAttrVariants,+ context->getImplPriorities());++ // with all the current hacks it is not guaranteed that a primitive descriptor will be created+ if (cacheWeights && primitiveDesc) {+ auto originalWeightsDesc = MemoryDescUtils::convertToDnnlMemoryDesc(weiDesc);+ const auto weightsDesc = DnnlExtensionUtils::makeDescriptor(primitiveDesc.weights_desc());+ (void)utils::prepareWeightsMemory(originalWeightsDesc, weightsDesc, memory.at(ARG_WEI), context);+ }++ const auto defaultImpType = primitiveDesc ? parse_impl_name(primitiveDesc.impl_info_str()) : impl_desc_type::undef;++ return std::make_shared<DnnlShapeAgnosticData>(primitiveAttributes.at(attrId), defaultImpType);+}++DnnlShapeAgnosticDataPtr DnnlConvolutionPrimitive::createShapeAgnosticData(const FCAttrs& fcAttrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr& context,+ const bool cacheWeights) {+ const bool cacheWeightsWithUndefData = !memory.at(ARG_SRC)->isDefined() && cacheWeights;+ OPENVINO_ASSERT(!cacheWeightsWithUndefData,+ "dnnl convolution weights caching for dynamic shapes is not implemented");++ ConvAttrs attrs{{1},+ {0},+ {0},+ {0},+ AutoPaddingType::None,+ fcAttrs.withBias,+ fcAttrs.weightsNonTransposed,+ false,+ false,+ true};++ const auto postOpData = createPrimitiveAttrs(attrs, postOps, memory, context);+ OPENVINO_ASSERT(postOpData.size() == 1, "Single attribute variant is expected when used as FC executor");++ return std::make_shared<DnnlShapeAgnosticData>(postOpData.front());}-void DnnlConvolutionPrimitive::execute(const dnnl_primitive_args& primArgs) const {+void DnnlConvolutionPrimitive::execute(dnnl_primitive_args& primArgs) {+ if (m_intermediateReorders.empty()) { // fast path+ return m_prim.execute(m_stream, primArgs);+ }++ // keep original memory to restore it after the execution+ std::unordered_map<int, dnnl::memory> originalMemory;+ // execute intermediate src reorders+ for (auto& [id, reorder] : m_intermediateReorders.m_inputReorders) {+ auto& [primitive, dstMemoryDesc] = reorder;+ if (auto primArg = primArgs.find(id); primArg != primArgs.end()) {+ auto& [id, srcMemory] = *primArg;+ dnnl::memory dstMemory(dstMemoryDesc, m_stream.get_engine());+ primitive.execute(m_stream, srcMemory, dstMemory);+ originalMemory[id] = primArgs[id];+ primArgs[id] = dstMemory;+ }+ }+ // prepare intermediate dst memory+ auto& outputReorders = m_intermediateReorders.m_outputReorders;+ if (auto outputReorder = outputReorders.find(DNNL_ARG_DST); outputReorder != outputReorders.end()) {+ auto& [id, reorder] = *outputReorder;+ auto& [primitive, srcMemoryDesc] = reorder;+ dnnl::memory srcMemory(srcMemoryDesc, m_stream.get_engine());+ originalMemory[id] = primArgs[id];+ primArgs[id] = srcMemory;+ }+m_prim.execute(m_stream, primArgs);+ // execute intermediate dst reorders+ if (const auto& outputReorder = outputReorders.find(DNNL_ARG_DST); outputReorder != outputReorders.end()) {+ const auto& [id, reorder] = *outputReorder;+ const auto& primitive = reorder.m_reorder;+ primitive.execute(m_stream, primArgs[id], originalMemory[id]);+ }+ // restore original memory+ for (const auto& [id, mem] : originalMemory) {+ primArgs[id] = mem;+ }}std::shared_ptr<DnnlConvolutionPrimitive> DnnlConvolutionPrimitive::create(const MemoryArgs& memory,- [[maybe_unused]] const ConvAttrs& attrs,- const ExecutorContext::CPtr context,+ const ConvAttrs& attrs,+ const ExecutorContext::CPtr& context,const DnnlShapeAgnosticDataPtr& shapeAgnosticData) {const auto& srcDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_SRC)->getDescPtr());const auto& weiDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_WEI)->getDescPtr());const auto& biaDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_BIAS)->getDescPtr());const auto& dstDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_DST)->getDescPtr());- const Key dnnlConvKey{srcDesc, weiDesc, biaDesc, dstDesc, shapeAgnosticData->primAttrs.attr};+ auto getPaddings = [&attrs](const VectorDims& dataShape, const VectorDims& weightsShape) {+ const bool zeroPaddingR = std::all_of(attrs.paddingR.begin(), attrs.paddingR.end(), [](const auto& p) {+ return p == 0;+ });++ if (attrs.autoPadding == AutoPaddingType::None || // auto padding disabled+ !zeroPaddingR) { // auto padding enabled, but paddingR is calculated manually for fused convolution+ return std::make_tuple(attrs.paddingL, attrs.paddingR);+ }++ return apply_auto_pad(dataShape, weightsShape, attrs.stride, attrs.dilation, attrs.autoPadding);+ };- auto builder = [&context](const Key& dnnlKey) {- return std::make_shared<DnnlConvolutionPrimitive>(dnnlKey, context->getEngine(), context->getImplPriorities());+ auto [paddingL, paddingR] = getPaddings(srcDesc->getShape().getDims(), weiDesc->getShape().getDims());++ const Key dnnlConvKey{srcDesc,+ weiDesc,+ biaDesc,+ dstDesc,+ attrs.stride,+ attrs.dilation,+ paddingL,+ paddingR,+ shapeAgnosticData->m_primAttrs.attr,+ attrs.fcSemantic,+ attrs.nonConstantWeights};++ const auto defaultImplType = shapeAgnosticData->m_implType;++ auto builder = [&context, defaultImplType](const Key& dnnlKey) {+ return std::make_shared<DnnlConvolutionPrimitive>(dnnlKey,+ context->getEngine(),+ context->getImplPriorities(),+ defaultImplType);};auto runtimeCache = context->getRuntimeCache();@@ -207,22 +860,158 @@ DnnlMemoryDescPtr DnnlConvolutionPrimitive::makeTransposedWeightDescriptor(constreturn DnnlFCPrimitive::makeTransposedWeightDescriptor(srcDesc, dstDesc, weightsNonTransposed);}+std::tuple<size_t, size_t, size_t, size_t> DnnlConvolutionPrimitive::getChannelParams(const ConvConfig& config) {+ const auto& attrs = config.attrs;+ const auto& weightDesc = config.descs.at(ARG_WEI);+ const auto& weightDims = weightDesc->getShape().getStaticDims();++ const auto groupNum = attrs.isGrouped ? weightDims[0] : 1;+ const auto groupIC = attrs.isGrouped ? weightDims[2] : weightDims[1];+ const auto IC = attrs.isGrouped ? groupNum * groupIC : groupIC;+ const auto groupOC = attrs.isGrouped ? weightDims[1] : weightDims[0];++ return std::make_tuple(groupNum, groupIC, IC, groupOC);+}++bool DnnlConvolutionPrimitive::isJitPlanarAvailable(const ConvConfig& config) {+ // Only apply this heuristic logic on FP32 IR. IC=1, OC=1 would disable brgconv on avx2.+ const bool isAvx2FP32 = !dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx512_core) &&+ dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2) && !config.attrs.isGraphQuantized;++ const auto [groupNum, groupIC, groupOC, IC] = getChannelParams(config);++ return (IC == 1 && groupOC * groupNum == 1) && isAvx2FP32;+}++bool DnnlConvolutionPrimitive::isBrgConvAvailable(const ConvConfig& config) {+ // When avx2 brgconv heuristic case, disable brgconv to WA the regression.+ const bool isBrgConvAvailable =+ dnnl::impl::cpu::x64::mayiuse(dnnl::impl::cpu::x64::avx2) && !isJitPlanarAvailable(config);++ return isBrgConvAvailable;+}++bool DnnlConvolutionPrimitive::isNspcAvailable(const ConvConfig& config) {+ using impl::cpu::x64::mayiuse;++ // do not use in non-quantized networks until it is enforced externally+ if (!config.attrs.isGraphQuantized) {+ return false;+ // @todo master implementation had the following logic as well:+ // auto predicate = [](memory::format_tag tag) {+ // return one_of(tag, memory::format_tag::nwc, memory::format_tag::nhwc, memory::format_tag::ndhwc);+ // };+ // if (std::none_of(inputMemoryFormatsFilter.begin(), inputMemoryFormatsFilter.end(), predicate)) {+ // return false;+ // }+ // }+ }+ // AVX2 heuristic+ if (isJitPlanarAvailable(config)) {+ return false;+ }++ // A bunch of heuristics are designed to cut off not optimal nspc convolution applications+ auto inpDims = config.descs.at(ARG_SRC)->getShape().getDims();+ auto outDims = config.descs.at(ARG_DST)->getShape().getDims();+ auto ndims = inpDims.size();++ size_t groupNum;+ size_t groupIC;+ size_t groupOC;+ size_t IC;++ std::tie(groupNum, groupIC, groupOC, IC) = getChannelParams(config);++ bool isDepthWise = config.attrs.isGrouped && 1 == groupOC && 1 == groupIC;++ if (isDepthWise) {+ // 1d equivalent cases are painfully slow+ if (inpDims.size() == 3 || 1 == inpDims[inpDims.size() - 2]) {+ return false;+ }++ return true;+ }++ // it was empirically observed that the nspc convolutions perform much slower than the blocked ones if the+ // channels number more than the specific value+ size_t spatialRank = ndims - 2; // two means batch dim plus channels dim++ bool is1x1 = false;++ if (!config.attrs.isGrouped) {+ const auto& weightDims = config.descs.at(ARG_WEI)->getShape().getDims();+ auto weightDimsReversItr = weightDims.crbegin();+ auto strideReversItr = config.attrs.stride.crbegin();+ auto paddingLreversItr = config.attrs.paddingL.crbegin();+ auto paddingRreversItr = config.attrs.paddingR.crbegin();++ for (size_t i = 0; i < spatialRank; ++i) {+ is1x1 = true && *(weightDimsReversItr++) == 1 && *(strideReversItr++) == 1 && *(paddingLreversItr++) == 0 &&+ *(paddingRreversItr++) == 0;+ }+ }++ // if the activation field size is 1x1 the avx512 1x1 nspc convolution pollutes caches so that the layer after+ // the convolution performs slow+ if (mayiuse(impl::cpu::x64::avx512_core) && is1x1) {+ auto end = inpDims.rbegin();+ std::advance(end, spatialRank);+ if (std::all_of(inpDims.rbegin(), end, [](size_t x) {+ return dimsEqualStrong(1, x);+ })) {+ return false;+ }+ }++ unsigned thresholdNumChannels = 128u; // for avx and below+ if (is1x1) {+ thresholdNumChannels = 2048u;+ } else if (mayiuse(impl::cpu::x64::avx512_core)) {+ thresholdNumChannels = 512u;+ }++ size_t OC = outDims[1];+ if (std::max(IC, OC) >= thresholdNumChannels) {+ return false;+ }++ if (!mayiuse(impl::cpu::x64::avx)) {+ // SSE41 nspc convolutions do not support ic and oc tails yet+ // the blocked implementation is faster than gemm+ if ((IC % 8) || (OC % 8)) {+ return false;+ }+ }++ return true;+}+DnnlConvolutionPrimitive::DnnlConvolutionPrimitive(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(engine,- key.src->getDnnlDesc(),+ m_primDesc(createPrimitiveDesc(key.src->getDnnlDesc(),key.wei->getDnnlDesc(),key.bias->getDnnlDesc(),key.dst->getDnnlDesc(),- key.attr,- implPriorities)),+ key.stride,+ key.dilation,+ key.paddingL,+ key.paddingR,+ {key.attr},+ engine,+ key.fcSemantic,+ implPriorities,+ defaultImplType)),m_implType(parse_impl_name(m_primDesc.impl_info_str())),m_srcDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.src_desc())),m_weiDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.weights_desc())),m_dstDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.dst_desc())),m_scratchPadDesc(DnnlExtensionUtils::makeDescriptor(m_primDesc.scratchpad_desc())),- m_prim(primitive(m_primDesc)) {}+ m_prim(primitive(m_primDesc)),+ m_intermediateReorders(key, m_primDesc, engine) {}} // namespace ov::intel_cpudiff --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.hppindex 27e5f599914..744e6d19ccb 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@@ -4,6 +4,8 @@#pragma once+#include <oneapi/dnnl/dnnl_types.h>+#include <memory>#include <oneapi/dnnl/dnnl.hpp>@@ -22,23 +24,47 @@ class DnnlConvolutionPrimitive {// @todo generalize caching for dnnl backendstruct Key {// @todo shouldn't we have a key representing onednn specific data types only?- const DnnlMemoryDescCPtr src;- const DnnlMemoryDescCPtr wei;- const DnnlMemoryDescCPtr bias;- const DnnlMemoryDescCPtr dst;+ DnnlMemoryDescCPtr src;+ DnnlMemoryDescCPtr wei;+ DnnlMemoryDescCPtr bias;+ DnnlMemoryDescCPtr dst;++ std::vector<size_t> stride;+ std::vector<size_t> dilation;+ std::vector<ptrdiff_t> paddingL;+ std::vector<ptrdiff_t> paddingR;++ dnnl::primitive_attr attr;- const dnnl::primitive_attr attr;+ bool fcSemantic;+ bool nonConstantWeights;[[nodiscard]] size_t hash() const;bool operator==(const Key& rhs) const;};+ struct IntermediateReorder {+ dnnl::reorder m_reorder;+ dnnl::memory::desc m_memory_desc;+ };++ class IntermediateReorders {+ public:+ IntermediateReorders(const Key& key, const dnnl::primitive_desc& primDesc, const dnnl::engine& engine);++ bool empty() const;++ std::unordered_map<int, IntermediateReorder> m_inputReorders;+ std::unordered_map<int, IntermediateReorder> m_outputReorders;+ };+public:DnnlConvolutionPrimitive(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);- void execute(const dnnl_primitive_args& primArgs) const;+ void execute(dnnl_primitive_args& primArgs);[[nodiscard]] const DnnlMemoryDescPtr srcDesc() const {return m_srcDesc;@@ -64,8 +90,14 @@ public:const DnnlMemoryDescPtr& dstDesc,bool weightsNonTransposed);+ static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const ConvAttrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr& context,+ const bool cacheWeights);+// create shape agnostic data using FC attributes (1x1 Convolution as FC executor)- static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const FCAttrs& attrs,+ static DnnlShapeAgnosticDataPtr createShapeAgnosticData(const FCAttrs& fcAttrs,const PostOps& postOps,const MemoryArgs& memory,const ExecutorContext::CPtr& context,@@ -73,9 +105,17 @@ public:static std::shared_ptr<DnnlConvolutionPrimitive> create(const MemoryArgs& memory,const ConvAttrs& attrs,- const ExecutorContext::CPtr context,+ const ExecutorContext::CPtr& context,const DnnlShapeAgnosticDataPtr& shapeAgnosticData);+ static bool isJitPlanarAvailable(const ConvConfig& config);++ static bool isBrgConvAvailable(const ConvConfig& config);++ static bool isNspcAvailable(const ConvConfig& config);++ static std::tuple<size_t, size_t, size_t, size_t> getChannelParams(const ConvConfig& config);+private:dnnl::stream m_stream;dnnl::primitive_desc m_primDesc;@@ -85,6 +125,7 @@ private:DnnlMemoryDescPtr m_dstDesc;DnnlMemoryDescPtr m_scratchPadDesc;dnnl::primitive m_prim;+ IntermediateReorders m_intermediateReorders;};using DnnlConvExecutorPtr = std::shared_ptr<DnnlConvolutionPrimitive>;diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hppindex 5fe9c50d4b1..ca728edb47e 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_fullyconnected.hpp@@ -4,6 +4,8 @@#pragma once+#include <oneapi/dnnl/dnnl_types.h>+#include <memory>#include <oneapi/dnnl/dnnl.hpp>#include <utility>@@ -33,20 +35,22 @@ template <typename Primitive,typename Attrs,typename ShapeAgnosticData,typename Instantiator = DefaultInstantiator<Primitive, Attrs, ShapeAgnosticData>>-class DnnlFCExecutor : public Executor {+class DnnlExecutor : public Executor {public:using PrimitivePtr = std::shared_ptr<Primitive>;- DnnlFCExecutor(const Attrs& attrs,- const PostOps& postOps,- const MemoryArgs& memory,- ExecutorContext::CPtr context,- const bool cacheWeights)+ DnnlExecutor(const Attrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ ExecutorContext::CPtr context,+ const bool cacheWeights,+ const bool fc3Das2D = false): m_attrs(attrs),m_context(std::move(context)),m_shapeAgnosticData(Primitive::createShapeAgnosticData(m_attrs, postOps, memory, m_context, cacheWeights)),- m_primArgs(m_shapeAgnosticData->primAttrs.dnnlArgs) {}+ m_primArgs(m_shapeAgnosticData->m_primAttrs.dnnlArgs),+ m_fc3Das2D(fc3Das2D) {}bool update(const MemoryArgs& memory) override {- const auto primitive = createPrimitive(memory);+ const auto primitive = createPrimitive(memory, m_attrs);if (!primitive) {return false;}@@ -66,8 +70,21 @@ public:m_primitive->execute(m_primArgs);}+ void execute() override {+ m_primitive->execute(m_primArgs);+ }++ void execute() const override {+ m_primitive->execute(m_primArgs);+ }+[[nodiscard]] impl_desc_type implType() const override {- return m_primitive ? m_primitive->implType() : undef;+ // to satisfy functional tests logic, implementation type should be shape agnostic+ if (m_shapeAgnosticData->m_implType != impl_desc_type::undef) {+ return m_shapeAgnosticData->m_implType;+ }++ return m_primitive ? m_primitive->implType() : impl_desc_type::undef;}void moveMemToNumaNode(int numaNodeID) override {@@ -121,7 +138,13 @@ private:const PrimitivePtr currentPrimitive,const PrimitivePtr newPrimitive,const MemoryPtr& memory) {+ if (m_attrs.nonConstantWeights) { // non constant weights are handled by the primitive+ m_primArgs[DNNL_ARG_WEIGHTS] = memory->getPrimitive();+ return;+ }+const auto newPrimMemDesc = newPrimitive->weightsDesc();+if (currentPrimitive && currentPrimitive->weightsDesc()->isCompatible(*newPrimMemDesc)) {return;}@@ -137,6 +160,26 @@ private:m_primArgs[DNNL_ARG_BIAS] = memory->getPrimitive();}+ void updatePostOpsMemory(const MemoryArgs& memory) {+ auto update = [&memory, this](int cpuMemoryArg, int dnnlMemoryArg) {+ if (const auto arg = memory.find(cpuMemoryArg); arg != memory.end()) {+ const auto& memory = arg->second;+ m_primArgs[dnnlMemoryArg] = memory->getPrimitive();+ }+ };++ update(ARG_ATTR_POST_OP_DW | ARG_WEI, DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_WEIGHTS);+ update(ARG_ATTR_POST_OP_DW | ARG_BIAS, DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_BIAS);++ if (m_shapeAgnosticData->m_primAttrs.legacyZeroPoints) {+ update(ARG_ATTR_ZERO_POINTS | ARG_SRC, DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC);+ update(ARG_ATTR_ZERO_POINTS | ARG_WEI, DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_WEIGHTS);+ update(ARG_ATTR_ZERO_POINTS | ARG_DST, DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_DST);+ } else {+ update(ARG_ATTR_ZERO_POINTS | ARG_SRC_3, DNNL_ARG_ATTR_ZERO_POINTS | DNNL_ARG_SRC);+ }+ }+void updateScratchPadMem(const PrimitivePtr currentPrimitive, const PrimitivePtr newPrimitive) {const auto newPrimMemDesc = newPrimitive->scratchPadDesc();// @todo should we compare dnnl::memory::desc directly to avoid any overhead?@@ -153,26 +196,34 @@ private:const auto& weiDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_WEI)->getDescPtr());const auto& dstDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_DST)->getDescPtr());- updateSrcMemory(srcDesc, newPrimitive, memory.at(ARG_SRC));- updateDstMemory(dstDesc, newPrimitive, memory.at(ARG_DST));+ if (m_fc3Das2D) {+ updateSrcMemory(srcDesc, newPrimitive, memory.at(ARG_SRC));+ updateDstMemory(dstDesc, newPrimitive, memory.at(ARG_DST));+ } else {+ m_primArgs[DNNL_ARG_SRC] = memory.at(ARG_SRC)->getPrimitive();+ m_primArgs[DNNL_ARG_DST] = memory.at(ARG_DST)->getPrimitive();+ }+updateWeightsMemory(weiDesc, currentPrimitive, newPrimitive, memory.at(ARG_WEI));updateBiasMemory(memory.at(ARG_BIAS));+ updatePostOpsMemory(memory);updateScratchPadMem(currentPrimitive, newPrimitive);}- PrimitivePtr createPrimitive(const MemoryArgs& memory) {- return Instantiator{}(memory, m_attrs, m_context, m_shapeAgnosticData);+ PrimitivePtr createPrimitive(const MemoryArgs& memory, const Attrs& attrs) {+ return Instantiator{}(memory, attrs, m_context, m_shapeAgnosticData);}-- const Attrs& m_attrs;+ // @todo there is no real reason to store attrs. Better to just pass as api argument+ Attrs m_attrs;const ExecutorContext::CPtr m_context;- const std::shared_ptr<ShapeAgnosticData> m_shapeAgnosticData;+ std::shared_ptr<ShapeAgnosticData> m_shapeAgnosticData;dnnl_primitive_args& m_primArgs;bool resetSrcMemoryDataHandle = false;bool resetDstMemoryDataHandle = false;MemoryPtr m_scratchPadMemory;PrimitivePtr m_primitive;int curNumaNode = -1;+ bool m_fc3Das2D = false;};} // namespace ov::intel_cpudiff --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.cppindex e9686e5f612..b8bf4d0a7a1 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@@ -81,7 +81,7 @@ bool DnnlFCPrimitive::Key::operator==(const Key& rhs) const {std::shared_ptr<DnnlFCPrimitive> DnnlFCPrimitive::create(const MemoryArgs& memory,const FCAttrs& attrs,- const ExecutorContext::CPtr context,+ const ExecutorContext::CPtr& context,const DnnlShapeAgnosticDataPtr& shapeAgnosticData) {const auto& srcDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_SRC)->getDescPtr());const auto& weiDesc = MemoryDescUtils::convertToDnnlMemoryDesc(memory.at(ARG_WEI)->getDescPtr());@@ -92,7 +92,7 @@ std::shared_ptr<DnnlFCPrimitive> DnnlFCPrimitive::create(const MemoryArgs& memorweiDesc,biaDesc,dstDesc,- shapeAgnosticData->primAttrs.attr,+ shapeAgnosticData->m_primAttrs.attr,attrs.sparseWeights,attrs.modelType};@@ -218,8 +218,17 @@ static DnnlPrimitiveAttrs createPrimitiveAttrs(const FCAttrs& attrs,one_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(postOps,+ context->getEngine(),+ dims,+ dims.size() - 1,+ isINT8,+ 1 << 0,+ memory,+ outputDataType,+ {},+ false,+ false);if (memory.count(ARG_WEI | ARG_ATTR_SCALES)) {auto dstPrc = memory.at(ARG_WEI | ARG_ATTR_SCALES)->getPrecision();@@ -437,7 +446,9 @@ DnnlShapeAgnosticDataPtr DnnlFCPrimitive::createShapeAgnosticData(const FCAttrs&context,useDynamicQuantization);- return std::make_shared<DnnlShapeAgnosticData>(postOpData);+ const auto defaultImpType = parse_impl_name(primDesc.impl_info_str());++ return std::make_shared<DnnlShapeAgnosticData>(postOpData, defaultImpType);}static impl_desc_type implTypeFromPrimDesc(const dnnl::primitive_desc& primDesc) {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.hppindex 04181a2bbc1..5b289099884 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@@ -70,7 +70,7 @@ public:static std::shared_ptr<DnnlFCPrimitive> create(const MemoryArgs& memory,const FCAttrs& attrs,- const ExecutorContext::CPtr context,+ const ExecutorContext::CPtr& context,const DnnlShapeAgnosticDataPtr& shapeAgnosticData);private: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.cppindex 4b65b1e807a..521e92f13d8 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@@ -103,7 +103,7 @@ std::shared_ptr<DnnlMatMulPrimitive> DnnlMatMulPrimitive::create(const MemoryArgconst 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->primAttrs.attr};+ 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());diff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_post_op_data.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_post_op_data.hppindex ccfc1fd735c..a1b09141dc6 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_post_op_data.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_post_op_data.hpp@@ -13,6 +13,7 @@ struct DnnlPrimitiveAttrs {dnnl::primitive_attr attr;dnnl_primitive_args dnnlArgs;MemoryArgs cpuArgs;+ bool legacyZeroPoints;};} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_shape_agnostic_data.hppindex 4265743bef6..7c3446b12ee 100644--- a/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp@@ -7,13 +7,21 @@#include <oneapi/dnnl/dnnl.hpp>#include "nodes/executors/dnnl/dnnl_post_op_data.hpp"+#include "onednn/iml_type_mapper.h"namespace ov::intel_cpu {struct DnnlShapeAgnosticData {- DnnlShapeAgnosticData(DnnlPrimitiveAttrs primAttrs) : primAttrs(std::move(primAttrs)) {}-- DnnlPrimitiveAttrs primAttrs;+ DnnlShapeAgnosticData(DnnlPrimitiveAttrs primAttrs, impl_desc_type implType = impl_desc_type::undef)+ : m_primAttrs(std::move(primAttrs)),+ m_implType(implType) {}++ DnnlPrimitiveAttrs m_primAttrs;+ // implementation type is a part of shape agnostic data to allow using+ // the same implementation for different shapes to avoid dealing with+ // multiple packed weights based on different implementations even it+ // may be not optimal from a performance perspective+ impl_desc_type m_implType;};using DnnlShapeAgnosticDataPtr = std::shared_ptr<DnnlShapeAgnosticData>;diff --git a/src/plugins/intel_cpu/src/nodes/executors/executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor.hppindex a564fc8d2a6..79c6a7af7d7 100644--- a/src/plugins/intel_cpu/src/nodes/executors/executor.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/executor.hpp@@ -57,6 +57,18 @@ namespace ov::intel_cpu {# define OV_CPU_INSTANCE_KLEIDIAI(...)#endif+#if defined(OV_CPU_WITH_DNNL) && defined(OPENVINO_ARCH_X86_64)+# define OV_CPU_INSTANCE_DNNL_X64(...) {__VA_ARGS__},+#else+# define OV_CPU_INSTANCE_DNNL_X64(...)+#endif++#if defined(OV_CPU_WITH_DNNL) && defined(OPENVINO_ARCH_ARM64)+# define OV_CPU_INSTANCE_DNNL_ARM64(...) {__VA_ARGS__},+#else+# define OV_CPU_INSTANCE_DNNL_ARM64(...)+#endif+#if defined(OPENVINO_ARCH_X86_64)# define OV_CPU_INSTANCE_X64(...) {__VA_ARGS__},#else@@ -164,7 +176,14 @@ public:OPENVINO_THROW_NOT_IMPLEMENTED("This version of the 'update' method is not implemented by executor");return false;}- virtual void execute() const {}++ virtual void execute() const {+ OPENVINO_THROW_NOT_IMPLEMENTED("This version of the 'execute' method is not implemented by executor");+ }++ virtual void execute() {+ OPENVINO_THROW_NOT_IMPLEMENTED("This version of the 'execute' method is not implemented by executor");+ }// dnnl_fullyconnected 3D workaround versionvirtual void execute([[maybe_unused]] const MemoryArgs& memory) {OPENVINO_THROW_NOT_IMPLEMENTED("This version of the 'execute' method is not implemented by executor");@@ -180,6 +199,7 @@ public:}virtual ~Executor() = default;};+using ExecutorPtr = std::shared_ptr<Executor>;} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hppindex 38be6e02072..da597021549 100644--- a/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/executor_factory.hpp@@ -9,6 +9,7 @@#include <utility>#include "executor.hpp"+#include "memory_format_filter.hpp"#include "nodes/executors/executor_config.hpp"#include "nodes/executors/executor_implementation.hpp"#include "nodes/executors/graph_emitter.hpp"@@ -16,6 +17,7 @@#include "nodes/executors/memory_arguments.hpp"#include "nodes/executors/printers.hpp"#include "nodes/executors/variable_executor.hpp"+#include "openvino/core/except.hpp"#include "post_ops.hpp"namespace ov::intel_cpu {@@ -25,15 +27,19 @@ class ExecutorFactory {public:using ExecutorImplementationRef = std::reference_wrapper<const ExecutorImplementation<Attrs>>;- ExecutorFactory(const Attrs& attrs,- const PostOps& postOps,+ ExecutorFactory(Attrs attrs,+ PostOps postOps,ExecutorContext::CPtr context,const MemoryDescArgs& descriptors,+ const MemoryFormatFilter& memoryFormatFilter = {},const std::string& implementationPriority = {}): m_attrs(attrs),- m_postOps(postOps),+ m_postOps(std::move(postOps)),m_context(std::move(context)),- m_suitableImplementations(filter(m_attrs, m_postOps, descriptors, implementationPriority)) {}+ m_suitableImplementations(+ filter(m_attrs, m_postOps, descriptors, memoryFormatFilter, implementationPriority)) {+ OPENVINO_ASSERT(!m_suitableImplementations.empty(), "No suitable implementations found");+ }/*** @brief Retrieves the proper memory descriptors based on the provided memory descriptors.@@ -43,24 +49,33 @@ public:* returns the corresponding memory descriptors.** @param descriptors memory descriptors.- * @return MemoryDescArgs The proper memory descriptors based on the configuration.+ * @return MemoryDescArgs The list of proper memory descriptors based on the configuration.* @todo Create proper memory descriptors for all the implementations* to fully enable graph's layout propagation functionality** @note The main use case is to avoid a fallback during the creation of an executor* by passing proper memory descriptors to the make() method*/- [[nodiscard]] MemoryDescArgs getProperMemoryDescriptors(const MemoryDescArgs& descriptors) const {+ [[nodiscard]] std::vector<MemoryDescArgs> getProperMemoryDescriptors(const MemoryDescArgs& descriptors) const {DEBUG_LOG("Preconfiguring memory descriptors");- const auto& impl = m_suitableImplementations.front();executor::Config<Attrs> config{descriptors, m_attrs, m_postOps};- if (auto fallbackConfig = impl.get().requiresFallback(config)) {- return fallbackConfig->descs;+ auto getProperMemoryDescArgs = [](const ExecutorImplementationRef& impl,+ const executor::Config<Attrs>& config) {+ if (auto fallbackConfig = impl.get().requiresFallback(config)) {+ return fallbackConfig->descs;+ }++ return config.descs;+ };++ std::vector<MemoryDescArgs> memoryDescArgs;+ for (const auto& impl : m_suitableImplementations) {+ memoryDescArgs.emplace_back(getProperMemoryDescArgs(impl, config));}- return config.descs;+ return memoryDescArgs;}/**@@ -115,6 +130,7 @@ private:static std::vector<ExecutorImplementationRef> filter(const Attrs& attrs,const PostOps& postOps,const MemoryDescArgs& descs,+ const MemoryFormatFilter& memoryFormatFilter = {},const std::string& implementationPriority = {}) {const auto& implementations = getImplementations<Attrs>();std::vector<ExecutorImplementationRef> suitableImplementations;@@ -130,7 +146,7 @@ private:continue;}- if (!implementation.supports(config)) {+ if (!implementation.supports(config, memoryFormatFilter)) {DEBUG_LOG("Implementation is not supported: ", implementation.name());continue;}@@ -150,9 +166,9 @@ private:return suitableImplementations;}- const Attrs& m_attrs;- const PostOps& m_postOps;- const ExecutorContext::CPtr m_context;+ Attrs m_attrs;+ PostOps m_postOps;+ ExecutorContext::CPtr m_context;std::vector<ExecutorImplementationRef> m_suitableImplementations;};diff --git a/src/plugins/intel_cpu/src/nodes/executors/executor_implementation.hpp b/src/plugins/intel_cpu/src/nodes/executors/executor_implementation.hppindex 80ec7b436e5..dca24cdd650 100644--- a/src/plugins/intel_cpu/src/nodes/executors/executor_implementation.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/executor_implementation.hpp@@ -8,6 +8,7 @@#include <memory>#include <optional>+#include "memory_format_filter.hpp"#include "nodes/executors/executor.hpp"#include "nodes/executors/executor_config.hpp"@@ -17,10 +18,13 @@ namespace ov::intel_cpu {template <typename Attrs>class ExecutorImplementation {public:- using SupportsPredicate = std::function<bool(const executor::Config<Attrs>&)>;+ using SupportsExtendedPredicate = std::function<bool(const executor::Config<Attrs>&, const MemoryFormatFilter&)>;+ using SupportsSimplePredicate = std::function<bool(const executor::Config<Attrs>&)>;+using RequiresFallbackPredicate =std::function<std::optional<executor::Config<Attrs>>(const executor::Config<Attrs>&)>;- using AcceptsShapePredicate = std::function<bool(const MemoryArgs& memory)>;+ using AcceptsShapePredicate =+ std::function<bool(const Attrs& attrs, const PostOps& postOps, const MemoryArgs& memory)>;using CreateFunction = std::function<ExecutorPtr(const Attrs& attrs,const PostOps& postOps,const MemoryArgs& memory,@@ -30,7 +34,7 @@ public:const ExecutorType type,const OperationType operationType,const ShapeTolerance shapeRelation,- SupportsPredicate supports,+ SupportsExtendedPredicate supports,RequiresFallbackPredicate requiresFallback,AcceptsShapePredicate acceptsShape,CreateFunction create)@@ -43,9 +47,28 @@ public:m_acceptsShape(std::move(acceptsShape)),m_create(std::move(create)) {}- bool supports(const executor::Config<Attrs>& config) const {+ ExecutorImplementation(const char* name,+ const ExecutorType type,+ const OperationType operationType,+ const ShapeTolerance shapeRelation,+ SupportsSimplePredicate supports,+ RequiresFallbackPredicate requiresFallback,+ AcceptsShapePredicate acceptsShape,+ CreateFunction create)+ : m_name(name),+ m_type(type),+ m_operationType(operationType),+ m_shapeRelation(shapeRelation),+ m_supports([supports](const executor::Config<Attrs>& config, const MemoryFormatFilter&) {+ return supports(config);+ }),+ m_requiresFallback(std::move(requiresFallback)),+ m_acceptsShape(std::move(acceptsShape)),+ m_create(std::move(create)) {}++ bool supports(const executor::Config<Attrs>& config, const MemoryFormatFilter& memoryFormatFilter) const {if (m_supports) {- return m_supports(config);+ return m_supports(config, memoryFormatFilter);}return false;@@ -59,9 +82,9 @@ public:return {};}- [[nodiscard]] bool acceptsShapes(const MemoryArgs& memory) const {+ [[nodiscard]] bool acceptsShapes(const Attrs& attrs, const PostOps& postOps, const MemoryArgs& memory) const {if (m_acceptsShape) {- return m_acceptsShape(memory);+ return m_acceptsShape(attrs, postOps, memory);}return false;@@ -100,7 +123,7 @@ private:ExecutorType m_type;OperationType m_operationType;ShapeTolerance m_shapeRelation;- SupportsPredicate m_supports;+ SupportsExtendedPredicate m_supports;RequiresFallbackPredicate m_requiresFallback;AcceptsShapePredicate m_acceptsShape;CreateFunction m_create;diff --git a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hppindex bd3340796cd..02fffcee84f 100644--- a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_config.hpp@@ -19,6 +19,7 @@ struct FCAttrs {bool weightsNonTransposed = false;bool sparseWeights = false;uint64_t dynamicQuantizationGroupSize;+ bool nonConstantWeights = false;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.cppindex a4c7e7e57ae..b9ee7b8f3c6 100644--- a/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp+++ b/src/plugins/intel_cpu/src/nodes/executors/fullyconnected_implementations.cpp@@ -143,73 +143,6 @@ static const TypeMapping dnnlMatMulTypeMapping {};// clang-format on-static bool fullyMatchConfiguration(const MemoryDescArgs& currentDescriptors,- const InOutTypes& typeConfig,- const LayoutConfig& layoutConfig,- const MappingNotation& notation) {- for (size_t i = 0; i < typeConfig.size(); i++) {- const auto& type = typeConfig[i];- const auto& desc = currentDescriptors.at(notation[i]);-- if (desc->empty()) {- continue;- }-- if (desc->getPrecision() != type) {- return false; // type mismatch- }-- if (!desc->hasLayoutType(layoutConfig[i])) {- return false; // layout mismatch- }- }-- return true;-}--static MemoryDescArgs createOptimalDescriptors(const MemoryDescArgs& currentDescriptors,- const InOutTypes& typeConfig,- const LayoutConfig& layoutConfig,- const MappingNotation& notation) {- MemoryDescArgs descs = currentDescriptors;-- const auto& creatorsMap = BlockedDescCreator::getCommonCreators();- for (size_t i = 0; i < typeConfig.size(); i++) {- const auto& desc = currentDescriptors.at(notation[i]);- const auto& descType = desc->getPrecision();- const auto& type = typeConfig[i];- const auto& layout = layoutConfig[i];-- if (desc->empty()) {- continue;- }-- if (descType == type && desc->hasLayoutType(layout)) {- continue;- }-- descs[notation[i]] = creatorsMap.at(layout)->createSharedDesc(type, desc->getShape());- }-- return descs;-}--template <typename Attrs>-std::optional<executor::Config<Attrs>> requiresFallbackCommon(const executor::Config<Attrs>& config,- const TypeMapping& typeMapping,- const LayoutConfig& layoutConfig,- const MappingNotation& notation) {- const auto typeConfig = getTypeConfiguration(config.descs, typeMapping, notation);-- if (fullyMatchConfiguration(config.descs, typeConfig, layoutConfig, notation)) {- return {};- }-- const auto optimalDescriptors = createOptimalDescriptors(config.descs, typeConfig, layoutConfig, notation);-- return std::optional<executor::Config<Attrs>>(FCConfig{optimalDescriptors, config.attrs, config.postOps});-}-[[maybe_unused]] static inline bool noWeightsDecompression(const FCConfig& config) {return !DnnlFCPrimitive::useWeightsDecompressionImpl(srcType(config), weiType(config), config.attrs.modelType);}@@ -222,6 +155,15 @@ std::optional<executor::Config<Attrs>> requiresFallbackCommon(const executor::Coreturn config.postOps.empty();}+struct RequiresFallbackDefault {+ std::optional<ConvConfig> operator()(const ConvConfig& config) const {+ return requiresFallbackCommon(config,+ dnnlMatMulTypeMapping,+ dnnlFCLayoutConfig,+ dnnlConvolutionMappingNotation);+ }+};+// to keep OV_CPU_INSTANCE macros aligned// clang-format offtemplate <>@@ -243,26 +185,10 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {return MlasGemmExecutor::supports(config);},- // requiresFallback- []([[maybe_unused]] const FCConfig& config) -> std::optional<executor::Config<FCAttrs>> {- // @todo Implement proper handling for the cases when fallback is not expected- // throwing exception is not an option, since requiresFallback is used in two contexts:- // 1) getting proper memory descriptors configuration- // 2) actual fallback to subgraph- return {};- },- // acceptsShapes- []([[maybe_unused]] const MemoryArgs& memory) -> bool {- // @todo create syntactic sugar (functor) for shape agnostic lambda- return true;- },- // create- [](const FCAttrs& attrs,- const PostOps& postOps,- const MemoryArgs& memory,- const ExecutorContext::CPtr& context) {- return std::make_shared<MlasGemmExecutor>(attrs, postOps, memory, context);- })+ RequiredNoFallback<FCAttrs>{},+ AcceptsAnyShape<FCAttrs>{},+ CreateDefault<MlasGemmExecutor, FCAttrs>{}+ )OV_CPU_INSTANCE_X64("convolution_1x1_dnnl",ExecutorType::Dnnl,@@ -301,7 +227,9 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {dnnlFCMappingNotation);},// acceptsShapes- [](const MemoryArgs& memory) -> bool {+ []([[maybe_unused]] const FCAttrs& attrs,+ [[maybe_unused]] const PostOps& postOps,+ const MemoryArgs& memory) -> bool {const auto inRank = memory.at(ARG_SRC)->getShape().getRank();const auto& inDims = memory.at(ARG_SRC)->getShape().getDims();const auto& weightDims = memory.at(ARG_WEI)->getShape().getDims();@@ -328,14 +256,19 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {[](const FCAttrs& attrs,const PostOps& postOps,const MemoryArgs& memory,- const ExecutorContext::CPtr& context) -> std::shared_ptr<Executor> {+ const ExecutorContext::CPtr& context) -> ExecutorPtr {struct ConvolutionInstantiator {std::shared_ptr<DnnlConvolutionPrimitive> operator()(const MemoryArgs& memory,const FCAttrs& attrs,const ExecutorContext::CPtr& context,const std::shared_ptr<DnnlShapeAgnosticData>& shareAgnosticData) const {- ConvAttrs convAttrs{attrs.withBias};++ const bool fcSemantic = true;+ ConvAttrs convAttrs{{1}, {0}, {0}, {0},+ AutoPaddingType::None, attrs.withBias, attrs.weightsNonTransposed,+ false, false, fcSemantic, false, ZeroPointsType::None, {}};+auto primitive =DefaultInstantiator<DnnlConvolutionPrimitive, ConvAttrs, DnnlShapeAgnosticData>{}(memory,@@ -352,7 +285,7 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {};return std::make_shared<- DnnlFCExecutor<DnnlConvolutionPrimitive, FCAttrs, DnnlShapeAgnosticData, ConvolutionInstantiator>>(+ DnnlExecutor<DnnlConvolutionPrimitive, FCAttrs, DnnlShapeAgnosticData, ConvolutionInstantiator>>(attrs,postOps,memory,@@ -377,18 +310,9 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {aclFCLayoutConfig,aclFullyConnectedMappingNotation);},- // acceptsShapes- [](const MemoryArgs& memory) -> bool {- // @todo create syntactic sugar (functor) for shape agnostic lambda- return true;- },- // create- [](const FCAttrs& attrs,- const PostOps& postOps,- const MemoryArgs& memory,- const ExecutorContext::CPtr& context) {- return std::make_shared<ACLFullyConnectedExecutor>(attrs, postOps, memory, context);- })+ AcceptsAnyShape<FCAttrs>{},+ CreateDefault<ACLFullyConnectedExecutor, FCAttrs>{}+ )OV_CPU_INSTANCE_ACL("fullyconnected_acl_lowp",ExecutorType::Acl,@@ -408,19 +332,16 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {aclFullyConnectedMappingNotation);},// acceptsShapes- [](const MemoryArgs& memory) -> bool {+ [](const FCAttrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory) -> bool {const auto dequantizationScales = getDeQuantizedScales(memory);bool isPerChannelQuantization = dequantizationScales.size() > 1;// per-channel quantization is not unsupported by ACLreturn !isPerChannelQuantization;},- // create- [](const FCAttrs& attrs,- const PostOps& postOps,- const MemoryArgs& memory,- const ExecutorContext::CPtr& context) {- return std::make_shared<ACLLowpFullyConnectedExecutor>(attrs, postOps, memory, context);- })+ CreateDefault<ACLLowpFullyConnectedExecutor, FCAttrs>{}+ )OV_CPU_INSTANCE_KLEIDIAI("fullyconnected_kleidiai",ExecutorType::Kleidiai,@@ -439,18 +360,10 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {VERIFY(weiRank(config) == 2U, UNSUPPORTED_WEI_RANK);return MatMulKleidiAIExecutor::supports(config);},- // requiresFallback- [](const FCConfig& config) -> std::optional<executor::Config<FCAttrs>> {- return {};- },- // acceptsShapes- [](const MemoryArgs& memory) -> bool {- return true;- },- // create- [](const FCAttrs& attrs, const PostOps& postOps, const MemoryArgs& memory, ExecutorContext::CPtr context) {- return std::make_shared<MatMulKleidiAIExecutor>(attrs, postOps, memory, context);- })+ RequiredNoFallback<FCAttrs>{},+ AcceptsAnyShape<FCAttrs>{},+ CreateDefault<MatMulKleidiAIExecutor, FCAttrs>{}+ )OV_CPU_INSTANCE_SHL("fullyconnected_shl",ExecutorType::Shl,@@ -465,22 +378,10 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {return ShlFCExecutor::supports(config);},- // requiresFallback- [](const FCConfig& config) -> std::optional<executor::Config<FCAttrs>> {- return {};- },- // acceptsShapes- [](const MemoryArgs& memory) -> bool {- return true;- },- // create- [](const FCAttrs& attrs,- const PostOps& postOps,- const MemoryArgs& memory,- const ExecutorContext::CPtr& context) {- return std::make_shared<ShlFCExecutor>(attrs, postOps, memory, context);- }- )+ RequiredNoFallback<FCAttrs>{},+ AcceptsAnyShape<FCAttrs>{},+ CreateDefault<ShlFCExecutor, FCAttrs>{}+ )OV_CPU_INSTANCE_DNNL("matmul_dnnl",ExecutorType::Dnnl,@@ -503,15 +404,12 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {dnnlFCLayoutConfig,dnnlFCMappingNotation);},- // acceptsShapes- []([[maybe_unused]] const MemoryArgs& memory) -> bool {- return true;- },+ AcceptsAnyShape<FCAttrs>{},// create[](const FCAttrs& attrs,const PostOps& postOps,const MemoryArgs& memory,- const ExecutorContext::CPtr& context) -> std::shared_ptr<Executor> {+ const ExecutorContext::CPtr& context) -> ExecutorPtr {struct MatMulInstantiator {std::shared_ptr<DnnlMatMulPrimitive> operator()(const MemoryArgs& memory,@@ -531,7 +429,7 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {};return std::make_shared<- DnnlFCExecutor<DnnlMatMulPrimitive, FCAttrs, DnnlShapeAgnosticData, MatMulInstantiator>>(+ DnnlExecutor<DnnlMatMulPrimitive, FCAttrs, DnnlShapeAgnosticData, MatMulInstantiator>>(attrs,postOps,memory,@@ -543,10 +441,7 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {ExecutorType::Dnnl,OperationType::FullyConnected,ShapeTolerance::Dependant,- // supports- []([[maybe_unused]] const FCConfig& config) -> bool {- return true;- },+ SupportsAnyConfig<FCAttrs>{},// requiresFallback[](const FCConfig& config) -> std::optional<executor::Config<FCAttrs>> {return requiresFallbackCommon(config,@@ -554,20 +449,18 @@ const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations() {dnnlFCLayoutConfig,dnnlConvolutionMappingNotation);},- // acceptsShapes- []([[maybe_unused]] const MemoryArgs& memory) -> bool {- return true;- },+ AcceptsAnyShape<FCAttrs>{},// create[](const FCAttrs& attrs,const PostOps& postOps,const MemoryArgs& memory,const ExecutorContext::CPtr& context) {- return std::make_shared<DnnlFCExecutor<DnnlFCPrimitive, FCAttrs, DnnlShapeAgnosticData>>(attrs,+ return std::make_shared<DnnlExecutor<DnnlFCPrimitive, FCAttrs, DnnlShapeAgnosticData>>(attrs,postOps,memory,context,- false);+ false,+ true);})};diff --git a/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp b/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hppindex 8d8a10e594e..32b069d37b0 100644--- a/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/implementation_utils.hpp@@ -5,10 +5,15 @@#pragma once#include <cstdlib>+#include <oneapi/dnnl/dnnl.hpp>#include "cpu_types.h"#include "memory_desc/cpu_memory_desc.h"+#include "nodes/executors/dnnl/dnnl_fullyconnected.hpp"+#include "nodes/executors/dnnl/dnnl_shape_agnostic_data.hpp"+#include "nodes/executors/executor_config.hpp"#include "nodes/executors/memory_arguments.hpp"+#include "nodes/executors/precision_translation.hpp"#include "openvino/core/type/element_type.hpp"namespace ov::intel_cpu {@@ -88,4 +93,128 @@ size_t postOpsNumbers(const Config& config) {return config.postOps.size();}+template <typename Attrs>+struct RequiredNoFallback {+ std::optional<executor::Config<Attrs>> operator()([[maybe_unused]] const executor::Config<Attrs>& attrs) const {+ return {};+ }+};++template <typename Attrs>+struct SupportsAnyConfig {+ bool operator()([[maybe_unused]] const executor::Config<Attrs>& attrs) const {+ return true;+ }+};++template <typename Attrs>+struct AcceptsAnyShape {+ bool operator()([[maybe_unused]] const Attrs& attrs,+ [[maybe_unused]] const PostOps& postOps,+ [[maybe_unused]] const MemoryArgs& memory) const {+ return true;+ }+};++template <typename Primitive, typename Attrs>+struct CreateDefault {+ ExecutorPtr operator()(const Attrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr& context) const {+ return std::make_shared<Primitive>(attrs, postOps, memory, context);+ }+};++template <typename Primitive,+ typename Attrs,+ typename ShapeAgnosticData = DnnlShapeAgnosticData,+ typename Instantiator = DefaultInstantiator<Primitive, Attrs, ShapeAgnosticData>>+struct CreateDnnlDefault {+ ExecutorPtr operator()(const Attrs& attrs,+ const PostOps& postOps,+ const MemoryArgs& memory,+ const ExecutorContext::CPtr& context) const {+ return std::make_shared<DnnlExecutor<Primitive, Attrs, DnnlShapeAgnosticData, Instantiator>>(attrs,+ postOps,+ memory,+ context,+ false);+ }+};++template <typename Attrs>+std::optional<executor::Config<Attrs>> requiresFallbackCommon(const executor::Config<Attrs>& config,+ const TypeMapping& typeMapping,+ const std::vector<LayoutType>& layoutConfig,+ const MappingNotation& notation) {+ // @todo lambdas inside a template function can potentially increase binary size+ auto fullyMatchConfiguration = [](const MemoryDescArgs& currentDescriptors,+ const InOutTypes& typeConfig,+ const std::vector<LayoutType>& layoutConfig,+ const MappingNotation& notation) {+ for (size_t i = 0; i < typeConfig.size(); i++) {+ const auto& type = typeConfig[i];+ const auto& desc = currentDescriptors.at(notation[i]);++ if (desc->empty()) {+ continue;+ }++ if (desc->getPrecision() != type) {+ return false; // type mismatch+ }++ if (desc->getShape().getRank() > 2 && !desc->hasLayoutType(layoutConfig[i])) {+ return false; // layout mismatch+ }+ }++ return true;+ };++ auto createOptimalDescriptors = [](const MemoryDescArgs& currentDescriptors,+ const InOutTypes& typeConfig,+ const std::vector<LayoutType>& layoutConfig,+ const MappingNotation& notation) {+ MemoryDescArgs descs = currentDescriptors;++ const auto& creatorsMap = BlockedDescCreator::getCommonCreators();+ for (size_t i = 0; i < typeConfig.size(); i++) {+ const auto& desc = currentDescriptors.at(notation[i]);+ const auto& descType = desc->getPrecision();+ const auto& type = typeConfig[i];+ const auto& layout = layoutConfig[i];++ if (desc->empty()) {+ continue;+ }++ if (descType == type && desc->hasLayoutType(layout)) {+ continue;+ }++ if (desc->getShape().getRank() < 2) {+ descs[notation[i]] = creatorsMap.at(LayoutType::ncsp)->createSharedDesc(type, desc->getShape());+ continue;+ }++ descs[notation[i]] = creatorsMap.at(layout)->createSharedDesc(type, desc->getShape());+ }++ return descs;+ };++ const auto typeConfig = getTypeConfiguration(config.descs, typeMapping, notation);++ if (fullyMatchConfiguration(config.descs, typeConfig, layoutConfig, notation)) {+ return {};+ }++ const auto optimalDescriptors = createOptimalDescriptors(config.descs, typeConfig, layoutConfig, notation);++ return std::optional<executor::Config<Attrs>>(+ executor::Config<Attrs>{optimalDescriptors, config.attrs, config.postOps});+}+} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp b/src/plugins/intel_cpu/src/nodes/executors/implementations.hppindex c91bec045a2..e6fa3079a9c 100644--- a/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/implementations.hpp@@ -6,6 +6,7 @@#include <vector>+#include "nodes/executors/convolution_config.hpp"#include "nodes/executors/executor_implementation.hpp"#include "nodes/executors/fullyconnected_config.hpp"@@ -24,7 +25,8 @@ const std::vector<ExecutorImplementation<Attrs>>& getImplementations() {// FullyConnectedtemplate <>const std::vector<ExecutorImplementation<FCAttrs>>& getImplementations();--// ...+// Convolution+template <>+const std::vector<ExecutorImplementation<ConvAttrs>>& getImplementations();} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/executors/memory_arguments.hpp b/src/plugins/intel_cpu/src/nodes/executors/memory_arguments.hppindex 2e1ba9e6b23..1230cb39801 100644--- a/src/plugins/intel_cpu/src/nodes/executors/memory_arguments.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/memory_arguments.hpp@@ -18,6 +18,8 @@ using MemoryArgs = std::unordered_map<int, MemoryPtr>;#define ARG_SRC ARG_SRC_0#define ARG_SRC_1 2#define ARG_SRC_2 3+#define ARG_SRC_3 4+#define ARG_SUM ARG_SRC_2#define ARG_DST_0 17#define ARG_DST ARG_DST_0#define ARG_WEI_0 33@@ -29,5 +31,7 @@ using MemoryArgs = std::unordered_map<int, MemoryPtr>;#define ARG_ATTR_SCALES 4096// zero points provided at execution time#define ARG_ATTR_ZERO_POINTS 8192+/// fused depthwise convolution.+#define ARG_ATTR_POST_OP_DW 16384} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/nodes/executors/mlas/mlas_gemm.hpp b/src/plugins/intel_cpu/src/nodes/executors/mlas/mlas_gemm.hppindex b9113850e7a..6c4c93730a6 100644--- a/src/plugins/intel_cpu/src/nodes/executors/mlas/mlas_gemm.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/mlas/mlas_gemm.hpp@@ -7,6 +7,7 @@#include <oneapi/dnnl/dnnl.hpp>#include "cpu_memory.h"+#include "nodes/executors/executor.hpp"#include "nodes/executors/fullyconnected_config.hpp"#include "onednn/iml_type_mapper.h"diff --git a/src/plugins/intel_cpu/src/nodes/executors/printers.cpp b/src/plugins/intel_cpu/src/nodes/executors/printers.cppindex 6bce0cc1f3f..a18a0a98407 100644--- a/src/plugins/intel_cpu/src/nodes/executors/printers.cpp+++ b/src/plugins/intel_cpu/src/nodes/executors/printers.cpp@@ -9,6 +9,7 @@# include <ostream># include "fullyconnected_config.hpp"+# include "nodes/executors/convolution_config.hpp"# include "post_ops.hpp"namespace ov::intel_cpu {@@ -18,6 +19,11 @@ std::ostream& operator<<(std::ostream& os, [[maybe_unused]] const FCAttrs& attrsreturn os;}+std::ostream& operator<<(std::ostream& os, [[maybe_unused]] const ConvAttrs& attrs) {+ // @todo print Attrs+ return os;+}+std::ostream& operator<<(std::ostream& os, [[maybe_unused]] const PostOps& postOps) {// @todo print PostOpsreturn os;diff --git a/src/plugins/intel_cpu/src/nodes/executors/printers.hpp b/src/plugins/intel_cpu/src/nodes/executors/printers.hppindex 40db1ec2e1d..7bf365a52ef 100644--- a/src/plugins/intel_cpu/src/nodes/executors/printers.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/printers.hpp@@ -2,6 +2,7 @@// SPDX-License-Identifier: Apache-2.0//+#include "nodes/executors/convolution_config.hpp"#ifdef CPU_DEBUG_CAPS# pragma once@@ -17,8 +18,10 @@ struct Config;}struct FCAttrs;+struct ConvAttrs;std::ostream& operator<<(std::ostream& os, const FCAttrs& attrs);+std::ostream& operator<<(std::ostream& os, const ConvAttrs& attrs);std::ostream& operator<<(std::ostream& os, const PostOps& postOps);template <typename Attrs>diff --git a/src/plugins/intel_cpu/src/nodes/executors/type_mask.hpp b/src/plugins/intel_cpu/src/nodes/executors/type_mask.hppindex 06c7641c174..00a4b1155d2 100644--- a/src/plugins/intel_cpu/src/nodes/executors/type_mask.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/type_mask.hpp@@ -116,6 +116,7 @@ DEFINE_TYPE_ALIAS(_string);DEFINE_TYPE_ALIAS(_f4e2m1);DEFINE_TYPE_ALIAS(_f8e8m0);constexpr auto _any_float = _f64 | _f32 | _f16 | _bf16;+constexpr auto _hw_float = _f32 | _f16 | _bf16;constexpr auto _half_float = _f16 | _bf16;constexpr auto _quant = _u8 | _i8;constexpr auto _any = std::numeric_limits<uint64_t>::max();diff --git a/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hppindex 27229f3106a..ad97ec85dfc 100644--- a/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp+++ b/src/plugins/intel_cpu/src/nodes/executors/variable_executor.hpp@@ -24,12 +24,12 @@ public:using ExecutorImplementationRef = std::reference_wrapper<const ExecutorImplementation<Attrs>>;VariableExecutor(const MemoryArgs& memory,- const Attrs& attrs,- const PostOps& postOps,+ Attrs attrs,+ PostOps postOps,ExecutorContext::CPtr context,std::vector<ExecutorImplementationRef> suitableImplementations)- : m_attrs(attrs),- m_postOps(postOps),+ : m_attrs(std::move(attrs)),+ m_postOps(std::move(postOps)),m_context(std::move(context)),m_suitableImplementations(std::move(suitableImplementations)),m_implementationRequiresFallback(@@ -43,7 +43,7 @@ public:bool update(const MemoryArgs& memory) override {for (auto implId = select(memory, 0); implId < m_suitableImplementations.size();- implId = select(memory, implId)) {+ implId = select(memory, ++implId)) {if (!m_executors[implId]) {m_executors[implId] = create(implId, memory);}@@ -98,8 +98,9 @@ private:const auto selectedImplementation =std::find_if(startIt,m_suitableImplementations.end(),- [&memory](const ExecutorImplementationRef& implementation) {- return implementation.get().shapeAgnostic() || implementation.get().acceptsShapes(memory);+ [&memory, this](const ExecutorImplementationRef& implementation) {+ return implementation.get().shapeAgnostic() ||+ implementation.get().acceptsShapes(m_attrs, m_postOps, memory);});OPENVINO_ASSERT(selectedImplementation != m_suitableImplementations.end(), "Failed to select an implemetation");@@ -126,8 +127,8 @@ private:return createWithFallback(implId, memory);}- const Attrs& m_attrs;- const PostOps& m_postOps;+ Attrs m_attrs;+ PostOps m_postOps;const ExecutorContext::CPtr m_context;std::vector<ExecutorImplementationRef> m_suitableImplementations;// stores fallback status to avoid performing the check for every make() calldiff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp b/src/plugins/intel_cpu/src/nodes/fullyconnected.cppindex d308d0f63a7..979e146fbcb 100644--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.cpp@@ -245,7 +245,10 @@ void FullyConnected::prepareParams() {needPrepareParamsForTensorParallel();executor->update(memory);- // @todo avoid updating implementation type in scope of every prepareParams call+ // @todo avoid updating implementation type in scope of every prepareParams call.+ // Currently the tests are implemented in such way that the actual used implementation type is changed+ // based on a shape and the expected implementation type is determined by the last shape.+ // I.e. for convolution it is different. The dymmy shape determines the expected implementation type.getSelectedPrimitiveDescriptor()->setImplementationType(executor->implType());}@@ -416,6 +419,7 @@ const std::vector<impl_desc_type>& FullyConnected::getDefaultImplPriority() {impl_desc_type::shl,impl_desc_type::brgemm_sparse_avx512_amx,impl_desc_type::brgemm_avx512_amx,+ impl_desc_type::brgconv_avx512_1x1,impl_desc_type::brgemm_avx512,impl_desc_type::brgemm_avx2,impl_desc_type::gemm_blas,@@ -551,7 +555,8 @@ void FullyConnected::initSupportedPrimitiveDescriptors() {auto executionContext = std::make_shared<ExecutorContext>(context, getImplPriority(), privateWeightCache);factory = std::make_shared<ExecutorFactory<FCAttrs>>(attrs, postOps, executionContext, descs);- const auto nodeDescriptors = factory->getProperMemoryDescriptors(descs);+ const std::vector<MemoryDescArgs> nodeDescriptorsList = factory->getProperMemoryDescriptors(descs);+ const MemoryDescArgs& nodeDescriptors = nodeDescriptorsList.front();NodeConfig nodeConfig;nodeConfig.inConfs.resize(srcDescs.size());diff --git a/src/plugins/intel_cpu/src/nodes/fullyconnected.h b/src/plugins/intel_cpu/src/nodes/fullyconnected.hindex 40391043d0c..811eed08812 100644--- a/src/plugins/intel_cpu/src/nodes/fullyconnected.h+++ b/src/plugins/intel_cpu/src/nodes/fullyconnected.h@@ -14,6 +14,7 @@#include <vector>#include "cpu_memory.h"+#include "nodes/executors/executor.hpp"#include "nodes/executors/executor_factory.hpp"#include "nodes/executors/fullyconnected_config.hpp"#include "nodes/executors/memory_arguments.hpp"@@ -93,7 +94,7 @@ protected:void toNumaNodeImpl(int numaID) override;private:- enum InputId : size_t {+ enum InputId : uint8_t {DATA = 0,WEIGHTS,BIAS,diff --git a/src/plugins/intel_cpu/src/nodes/input.cpp b/src/plugins/intel_cpu/src/nodes/input.cppindex 25fa72e1df3..2768a12bd9c 100644--- a/src/plugins/intel_cpu/src/nodes/input.cpp+++ b/src/plugins/intel_cpu/src/nodes/input.cpp@@ -599,6 +599,13 @@ Input::Input(const MemoryDescPtr& memDesc,extMemDesc = memDesc;}+Input::Input(const MemoryPtr& mem, const std::string& name, const std::string& type, const GraphContext::CPtr& context)+ : Input(mem->getDesc().getShape(), mem->getDesc().getPrecision(), name, type, context) {+ extMemDesc = mem->getDescPtr(); // NOLINT(cppcoreguidelines-prefer-member-initializer) fixed in clang-tidy-18+ memoryPtr = mem; // NOLINT(cppcoreguidelines-prefer-member-initializer) fixed in clang-tidy-18+ constant = Node::ConstantType::Const;+}+Input::Input(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context, const InputConfig& config): Input(op, context) {extMemDesc = config.desc;diff --git a/src/plugins/intel_cpu/src/nodes/input.h b/src/plugins/intel_cpu/src/nodes/input.hindex b21e4ae080f..de49f955ad7 100644--- a/src/plugins/intel_cpu/src/nodes/input.h+++ b/src/plugins/intel_cpu/src/nodes/input.h@@ -46,6 +46,8 @@ public:const std::string& type,const GraphContext::CPtr& context);+ Input(const MemoryPtr& mem, const std::string& name, const std::string& type, const GraphContext::CPtr& context);+Input(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context, const InputConfig& config);Input(const std::shared_ptr<ov::Node>& op, const GraphContext::CPtr& context, const OutputConfig& config);diff --git a/src/plugins/intel_cpu/src/nodes/lrn.cpp b/src/plugins/intel_cpu/src/nodes/lrn.cppindex 787bb6aa12c..11d959ed366 100644--- a/src/plugins/intel_cpu/src/nodes/lrn.cpp+++ b/src/plugins/intel_cpu/src/nodes/lrn.cpp@@ -202,7 +202,7 @@ void Lrn::prepareParams() {return nullptr;}- return std::make_shared<DnnlExecutor>(prim_desc);+ return std::make_shared<DnnlExecutorLegacy>(prim_desc);};auto cache = context->getParamsCache();diff --git a/src/plugins/intel_cpu/src/nodes/lrn.h b/src/plugins/intel_cpu/src/nodes/lrn.hindex b74a63745b5..3258fa45744 100644--- a/src/plugins/intel_cpu/src/nodes/lrn.h+++ b/src/plugins/intel_cpu/src/nodes/lrn.h@@ -34,7 +34,7 @@ public:static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;private:- using executorPtr = std::shared_ptr<DnnlExecutor>;+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;executorPtr execPtr = nullptr;dnnl::algorithm alg;size_t size = 1;diff --git a/src/plugins/intel_cpu/src/nodes/matmul.cpp b/src/plugins/intel_cpu/src/nodes/matmul.cppindex 1d06382f5a1..96ab17a6471 100644--- a/src/plugins/intel_cpu/src/nodes/matmul.cpp+++ b/src/plugins/intel_cpu/src/nodes/matmul.cpp@@ -662,14 +662,14 @@ void MatMul::prepareParams() {const bool found = DnnlExtensionUtils::find_implementation(prim_desc, key.implType);if (found) {- return std::make_shared<DnnlExecutor>(prim_desc);+ return std::make_shared<DnnlExecutorLegacy>(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<DnnlExecutor>(first_desc);+ return std::make_shared<DnnlExecutorLegacy>(first_desc);};auto cache = context->getParamsCache();diff --git a/src/plugins/intel_cpu/src/nodes/matmul.h b/src/plugins/intel_cpu/src/nodes/matmul.hindex 1ffd35807f0..603097440a1 100644--- a/src/plugins/intel_cpu/src/nodes/matmul.h+++ b/src/plugins/intel_cpu/src/nodes/matmul.h@@ -51,7 +51,7 @@ protected:AttrPtr initPrimitiveAttr(const VectorDims& dims);private:- using executorPtr = std::shared_ptr<DnnlExecutor>;+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;executorPtr execPtr = nullptr;dnnl::memory::desc getBiasDescFrom(const DnnlMemoryDescCPtr& outMemDesc);std::pair<Shape, Shape> makeDummyInputShapes(const Shape& in0, const Shape& in1, const Shape& out) const;diff --git a/src/plugins/intel_cpu/src/nodes/pooling.cpp b/src/plugins/intel_cpu/src/nodes/pooling.cppindex 9459b1c9d8c..e36f57d8843 100644--- a/src/plugins/intel_cpu/src/nodes/pooling.cpp+++ b/src/plugins/intel_cpu/src/nodes/pooling.cpp@@ -493,11 +493,11 @@ void Pooling::prepareParams() {const bool found = DnnlExtensionUtils::find_implementation(prim_desc, key.implType);if (found) {- return std::make_shared<DnnlExecutor>(prim_desc);+ return std::make_shared<DnnlExecutorLegacy>(prim_desc);}// use the first available- return std::make_shared<DnnlExecutor>(first_desc);+ return std::make_shared<DnnlExecutorLegacy>(first_desc);};auto cache = context->getParamsCache();diff --git a/src/plugins/intel_cpu/src/nodes/pooling.h b/src/plugins/intel_cpu/src/nodes/pooling.hindex 269a155ff9b..077876ad77e 100644--- a/src/plugins/intel_cpu/src/nodes/pooling.h+++ b/src/plugins/intel_cpu/src/nodes/pooling.h@@ -38,7 +38,7 @@ protected:AttrPtr initPrimitiveAttr() override;private:- using executorPtr = std::shared_ptr<DnnlExecutor>;+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;executorPtr dnnlExecPtr = nullptr;void setPostOps(dnnl::primitive_attr& attr);diff --git a/src/plugins/intel_cpu/src/nodes/reorder.cpp b/src/plugins/intel_cpu/src/nodes/reorder.cppindex a6f26088f1c..a787634b505 100644--- a/src/plugins/intel_cpu/src/nodes/reorder.cpp+++ b/src/plugins/intel_cpu/src/nodes/reorder.cpp@@ -323,6 +323,7 @@ void Reorder::createReorderPrimitive(const DnnlMemoryDescPtr& srcDesc, const DnnDEBUG_LOG("CreateReorderPrimitive is called for node", getName(), " src desc: ", src_desc, " dst_desc: ", dst_desc);CPU_NODE_ASSERT(src_desc.get_ndims() == dst_desc.get_ndims(),"OneDNN doesn't support reorder with different ranks.");+prim = getReorderPrim(context->getParamsCache(), getEngine(), src_desc, dst_desc);CPU_NODE_ASSERT(prim, "could not create reorder primitive: unsupported reorder case.");diff --git a/src/plugins/intel_cpu/src/nodes/rnn.cpp b/src/plugins/intel_cpu/src/nodes/rnn.cppindex 3c4a89af5af..8bce758bddb 100644--- a/src/plugins/intel_cpu/src/nodes/rnn.cpp+++ b/src/plugins/intel_cpu/src/nodes/rnn.cpp@@ -1478,7 +1478,7 @@ void RNN::cleanup() {}}-RNN::RnnDnnlExecutor::RnnDnnlExecutor(const dnnl::primitive_desc& pd) : DnnlExecutor(pd) {+RNN::RnnDnnlExecutor::RnnDnnlExecutor(const dnnl::primitive_desc& pd) : DnnlExecutorLegacy(pd) {wghts_iter_md = DnnlExtensionUtils::makeDescriptor(pd.weights_desc(1));bias_md = DnnlExtensionUtils::makeDescriptor(pd.weights_desc(2));}diff --git a/src/plugins/intel_cpu/src/nodes/rnn.h b/src/plugins/intel_cpu/src/nodes/rnn.hindex a2b4c5227bc..0a0dd0eea22 100644--- a/src/plugins/intel_cpu/src/nodes/rnn.h+++ b/src/plugins/intel_cpu/src/nodes/rnn.h@@ -58,7 +58,7 @@ private:void copyWeightsData();void prepareMemory(const DnnlMemoryDescPtr& intDesc, size_t indx) override;- class RnnDnnlExecutor : public DnnlExecutor {+ class RnnDnnlExecutor : public DnnlExecutorLegacy {public:RnnDnnlExecutor(const dnnl::primitive_desc& pd);diff --git a/src/plugins/intel_cpu/src/nodes/softmax.cpp b/src/plugins/intel_cpu/src/nodes/softmax.cppindex 1ad3aaaa342..da82f5ef21d 100644--- a/src/plugins/intel_cpu/src/nodes/softmax.cpp+++ b/src/plugins/intel_cpu/src/nodes/softmax.cpp@@ -208,7 +208,7 @@ void SoftMax::prepareParams() {break;}}- return std::make_shared<DnnlExecutor>(prim_desc);+ return std::make_shared<DnnlExecutorLegacy>(prim_desc);};auto cache = context->getParamsCache();diff --git a/src/plugins/intel_cpu/src/nodes/softmax.h b/src/plugins/intel_cpu/src/nodes/softmax.hindex 0ce000d38dd..0576c1cc97d 100644--- a/src/plugins/intel_cpu/src/nodes/softmax.h+++ b/src/plugins/intel_cpu/src/nodes/softmax.h@@ -28,7 +28,7 @@ public:static bool isSupportedOperation(const std::shared_ptr<const ov::Node>& op, std::string& errorMessage) noexcept;private:- using executorPtr = std::shared_ptr<DnnlExecutor>;+ using executorPtr = std::shared_ptr<DnnlExecutorLegacy>;executorPtr execPtr = nullptr;size_t axis = 0;};diff --git a/src/plugins/intel_cpu/src/post_ops.cpp b/src/plugins/intel_cpu/src/post_ops.cppindex e5361896e3a..0f0db301a92 100644--- a/src/plugins/intel_cpu/src/post_ops.cpp+++ b/src/plugins/intel_cpu/src/post_ops.cpp@@ -4,9 +4,14 @@#include "post_ops.hpp"+#include <cstddef>++#include "cpu_types.h"#include "node.h"+#include "nodes/conv.h"#include "nodes/eltwise.h"#include "nodes/fake_quantize.h"+#include "openvino/core/type/element_type.hpp"namespace ov::intel_cpu {@@ -29,13 +34,13 @@ EltwiseKind getEltwiseKind(const Algorithm alg) {case Algorithm::EltwiseHsigmoid:case Algorithm::EltwiseRoundHalfToEven:case Algorithm::EltwiseRoundHalfAwayFromZero:+ case Algorithm::EltwisePowerStatic:return EltwiseKind::Activation;case Algorithm::EltwiseAdd:case Algorithm::EltwiseSubtract:case Algorithm::EltwiseDivide:case Algorithm::EltwiseMultiply:case Algorithm::EltwiseMulAdd:- case Algorithm::EltwisePowerStatic:case Algorithm::EltwisePrelu:return EltwiseKind::ScaleShift;default:@@ -46,19 +51,17 @@ EltwiseKind getEltwiseKind(const Algorithm alg) {ScaleShiftPostOp::Type convertToScaleShiftOpt(const Algorithm alg) {switch (alg) {case Algorithm::EltwiseAdd:- return ScaleShiftPostOp::add;+ return ScaleShiftPostOp::Type::add;case Algorithm::EltwiseSubtract:- return ScaleShiftPostOp::subtract;+ return ScaleShiftPostOp::Type::subtract;case Algorithm::EltwiseDivide:- return ScaleShiftPostOp::divide;+ return ScaleShiftPostOp::Type::divide;case Algorithm::EltwiseMultiply:- return ScaleShiftPostOp::multiply;+ return ScaleShiftPostOp::Type::multiply;case Algorithm::EltwiseMulAdd:- return ScaleShiftPostOp::muladd;- case Algorithm::EltwisePowerStatic:- return ScaleShiftPostOp::powerstatic;+ return ScaleShiftPostOp::Type::muladd;case Algorithm::EltwisePrelu:- return ScaleShiftPostOp::prelu;+ return ScaleShiftPostOp::Type::prelu;default:OPENVINO_THROW("Unexpected eltwise algorithm: ", algToString(alg));}@@ -100,6 +103,21 @@ ActivationPostOp::Type convertToActivationPostOpt(const Algorithm alg) {return ActivationPostOp::Type::round_half_to_even;case Algorithm::EltwiseRoundHalfAwayFromZero:return ActivationPostOp::Type::round_half_away_from_zero;+ case Algorithm::EltwisePowerStatic:+ return ActivationPostOp::Type::powerstatic;+ default:+ OPENVINO_THROW("Unexpected eltwise algorithm: ", algToString(alg));+ }+}++FakeQuantizePostOp::Type convertToFqPostOp(const Algorithm alg) {+ switch (alg) {+ case ov::intel_cpu::Algorithm::FQBinarization:+ return FakeQuantizePostOp::Type::binarization;+ case ov::intel_cpu::Algorithm::FQQuantization:+ return FakeQuantizePostOp::Type::quantization_only;+ case ov::intel_cpu::Algorithm::FQCommon:+ return FakeQuantizePostOp::Type::quantization_dequantization;default:OPENVINO_THROW("Unexpected eltwise algorithm: ", algToString(alg));}@@ -141,6 +159,8 @@ Algorithm convertToEltwiseAlgorithm(const ActivationPostOp::Type type) {return Algorithm::EltwiseRoundHalfToEven;case ActivationPostOp::Type::round_half_away_from_zero:return Algorithm::EltwiseRoundHalfAwayFromZero;+ case ActivationPostOp::Type::powerstatic:+ return Algorithm::EltwisePowerStatic;case ActivationPostOp::Type::square:OPENVINO_THROW("square is not supported");case ActivationPostOp::Type::linear:@@ -150,7 +170,7 @@ Algorithm convertToEltwiseAlgorithm(const ActivationPostOp::Type type) {OPENVINO_THROW("Unsupported algorithm");}-PostOps getPostOps(const std::vector<NodePtr>& fused) {+PostOps getPostOps(const std::vector<NodePtr>& fused, ov::element::Type_t sumDataType) {PostOps ops;auto makeActivationPostOp = [](const std::shared_ptr<node::Eltwise>& eltwise) {@@ -166,6 +186,11 @@ PostOps getPostOps(const std::vector<NodePtr>& fused) {eltwise->getShifts());};+ auto makeSumPostOp = [&](const std::shared_ptr<node::Eltwise>& eltwise) {+ OPENVINO_ASSERT(sumDataType != ov::element::dynamic, "Sum data type is not defined ", eltwise->getName());+ return std::make_shared<SumPostOp>(1.0, 0, sumDataType);+ };+for (const auto& node : fused) {if (const auto eltwise = std::dynamic_pointer_cast<node::Eltwise>(node)) {const auto eltwiseKind = getEltwiseKind(eltwise->getAlgorithm());@@ -174,19 +199,41 @@ PostOps getPostOps(const std::vector<NodePtr>& fused) {ops.push_back(makeActivationPostOp(eltwise));break;case EltwiseKind::ScaleShift:- ops.push_back(makeScaleShiftPostOp(eltwise));+ if (eltwise->isSpecialConvolutionAddFusing()) {+ ops.push_back(makeSumPostOp(eltwise));+ } else {+ ops.push_back(makeScaleShiftPostOp(eltwise));+ }break;}}if (const auto fq = std::dynamic_pointer_cast<node::FakeQuantize>(node)) {- ops.push_back(std::make_shared<FakeQuantizePostOp>(fq->getCropLow(),+ ops.push_back(std::make_shared<FakeQuantizePostOp>(convertToFqPostOp(fq->getAlgorithm()),+ fq->getCropLow(),fq->getCropHigh(),fq->getInputScale(),fq->getInputShift(),fq->getOutputScale(),fq->getOutputShift(),- fq->getLevels()));+ fq->getLevels(),+ fq->isInputLowBroadcast(),+ fq->isOutputHighBroadcast()));+ }++ if (const auto conv = std::dynamic_pointer_cast<node::Convolution>(node)) {+ const auto& inputShape = conv->getInputShapeAtPort(0);+ const auto& inActivationDims = inputShape.getStaticDims();+ const size_t ih = inActivationDims[inputShape.getRank() - 2];+ const size_t iw = inActivationDims[inputShape.getRank() - 1];++ const auto& wieghtsShape = conv->getInputShapeAtPort(1);+ const auto& dwWeightsDims = wieghtsShape.getStaticDims();+ const std::vector<size_t> kernel{dwWeightsDims[dwWeightsDims.size() - 1],+ dwWeightsDims[dwWeightsDims.size() - 2]};+ const auto& strides = conv->getStride();++ ops.push_back(std::make_shared<DepthwiseConvolutionPostOp>(ih, iw, kernel, strides));}}diff --git a/src/plugins/intel_cpu/src/post_ops.hpp b/src/plugins/intel_cpu/src/post_ops.hppindex 81715ff2375..d6532d348a6 100644--- a/src/plugins/intel_cpu/src/post_ops.hpp+++ b/src/plugins/intel_cpu/src/post_ops.hpp@@ -5,12 +5,14 @@#pragma once#include <cstddef>+#include <cstdint>#include <memory>#include <vector>#include "cpu_types.h"#include "node.h"#include "nodes/executors/executor.hpp"+#include "openvino/core/type/element_type.hpp"namespace ov::intel_cpu {@@ -29,7 +31,7 @@ using eltwiseExecutorCreatingStrategy = std::function<ExecutorPtr(const Activaticonst PostOps&)>;struct ActivationPostOp : PostOp {- enum class Type : size_t {+ enum class Type : uint8_t {relu,tanh,elu,@@ -49,6 +51,7 @@ struct ActivationPostOp : PostOp {round_half_to_even,round_half_away_from_zero,linear,+ powerstatic};ActivationPostOp(const Type type,@@ -85,13 +88,12 @@ private:};struct ScaleShiftPostOp : PostOp {- enum Type {+ enum class Type : uint8_t {add,subtract,divide,multiply,muladd,- powerstatic,prelu,};@@ -119,20 +121,28 @@ private:};struct FakeQuantizePostOp : PostOp {- FakeQuantizePostOp(std::vector<float> cropLow,+ enum class Type : uint8_t { binarization, quantization_only, quantization_dequantization };++ FakeQuantizePostOp(const Type type,+ std::vector<float> cropLow,std::vector<float> cropHigh,std::vector<float> inputScale,std::vector<float> inputShift,std::vector<float> outputScale,std::vector<float> outputShift,- const size_t levels)- : m_cropLow(std::move(cropLow)),+ const size_t levels,+ bool isInputLowBroadcasted,+ bool isOutputHighBroadcasted)+ : m_type(type),+ m_cropLow(std::move(cropLow)),m_cropHigh(std::move(cropHigh)),m_inputScale(std::move(inputScale)),m_inputShift(std::move(inputShift)),m_outputScale(std::move(outputScale)),m_outputShift(std::move(outputShift)),- m_levels(levels) {}+ m_levels(levels),+ m_isInputLowBroadcasted(isInputLowBroadcasted),+ m_isOutputHighBroadcasted(isOutputHighBroadcasted) {}[[nodiscard]] const std::vector<float>& cropLow() const {return m_cropLow;@@ -162,7 +172,20 @@ struct FakeQuantizePostOp : PostOp {return m_levels;}+ Type type() const {+ return m_type;+ }++ bool isInputLowBroadcast() const {+ return m_isInputLowBroadcasted;+ }++ bool isOutputHighBroadcast() const {+ return m_isOutputHighBroadcasted;+ }+private:+ const Type m_type;const std::vector<float> m_cropLow;const std::vector<float> m_cropHigh;const std::vector<float> m_inputScale;@@ -170,9 +193,66 @@ private:const std::vector<float> m_outputScale;const std::vector<float> m_outputShift;const size_t m_levels;+ // necessary only for legacy post ops+ bool m_isInputLowBroadcasted;+ bool m_isOutputHighBroadcasted;};-enum class EltwiseKind {+struct DepthwiseConvolutionPostOp : PostOp {+ DepthwiseConvolutionPostOp(size_t ih, size_t iw, std::vector<size_t> kernel, std::vector<size_t> strides)+ : m_ih(ih),+ m_iw(iw),+ m_kernel(std::move(kernel)),+ m_strides(std::move(strides)) {}++ size_t ih() const {+ return m_ih;+ }++ size_t iw() const {+ return m_iw;+ }++ const std::vector<size_t>& kernel() const {+ return m_kernel;+ }++ const std::vector<size_t>& strides() const {+ return m_strides;+ }++private:+ size_t m_ih;+ size_t m_iw;+ std::vector<size_t> m_kernel;+ std::vector<size_t> m_strides;+};++struct SumPostOp : PostOp {+ SumPostOp(float scale, int32_t zero_point, ov::element::Type_t dataType)+ : m_scale(scale),+ m_zero_point(zero_point),+ m_dataType(dataType) {}++ float scale() const {+ return m_scale;+ }++ int32_t zeroPoint() const {+ return m_zero_point;+ }++ ov::element::Type_t dataType() const {+ return m_dataType;+ }++private:+ float m_scale;+ int32_t m_zero_point;+ ov::element::Type_t m_dataType;+};++enum class EltwiseKind : uint8_t {Activation,ScaleShift,// @todo Binary?@@ -188,5 +268,7 @@ ActivationPostOp::Type convertToActivationPostOpt(const Algorithm alg);Algorithm convertToEltwiseAlgorithm(const ActivationPostOp::Type m_type);-PostOps getPostOps(const std::vector<NodePtr>& fused);+FakeQuantizePostOp::Type convertToFqPostOp(const Algorithm alg);++PostOps getPostOps(const std::vector<NodePtr>& fused, ov::element::Type_t sumDataType = ov::element::dynamic);} // namespace ov::intel_cpudiff --git a/src/plugins/intel_cpu/src/shape_inference/custom/convolution.cpp b/src/plugins/intel_cpu/src/shape_inference/custom/convolution.cppnew file mode 100644index 00000000000..c6e437c30f0--- /dev/null+++ b/src/plugins/intel_cpu/src/shape_inference/custom/convolution.cpp@@ -0,0 +1,108 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "convolution.hpp"++#include "openvino/core/type.hpp"+#include "openvino/op/group_conv.hpp"+#include "openvino/op/util/attr_types.hpp"++namespace ov::intel_cpu::node {++constexpr auto dilated(const size_t dim, const size_t dilation) -> size_t {+ return (dim - 1) * dilation + 1;+}++VectorDims convolution_shape_infer(const VectorDims& data_shape,+ const VectorDims& filters_shape,+ const std::vector<size_t>& strides,+ const std::vector<size_t>& dilations,+ const std::vector<ptrdiff_t>& pads_begin,+ const std::vector<ptrdiff_t>& pads_end,+ bool auto_padding,+ bool isGrouped) {+ OPENVINO_ASSERT(data_shape.size() >= 3, "At least 3D data shape is expected");+ OPENVINO_ASSERT(filters_shape.size() >= 3, "At least 3D filters shape is expected");+ const auto G = isGrouped ? filters_shape[0] : 1;+ const auto data_shape_IC = data_shape[1] / G;+ const auto filter_shape_IC = isGrouped ? filters_shape[2] : filters_shape[1];+ OPENVINO_ASSERT(data_shape_IC == filter_shape_IC, "Input and filter channels must match");++ const auto data_rank = data_shape.size();+ constexpr int spatial_offset = 2;+ const auto num_spatial = data_rank - spatial_offset;++ // {N, C_OUT, Spatial(1 / 2 / 3)}+ VectorDims output_shape;+ output_shape.reserve(spatial_offset + num_spatial);+ // {N, C_OUT, ...}+ const auto N = data_shape[0];+ output_shape.emplace_back(N);+ const auto CO = isGrouped ? filters_shape[0] * filters_shape[1] : filters_shape[0];+ output_shape.emplace_back(CO);++ const auto spatial_num = strides.size();++ auto data_dim_it = data_shape.cend() - spatial_num;++ const auto ceil_div = [](const auto& x, const auto& y) {+ assert(y > 0);+ return (x == 0 ? 0 : (1 + (x - 1) / y));+ };++ if (auto_padding) {+ std::transform(data_dim_it, data_shape.cend(), strides.cbegin(), std::back_inserter(output_shape), ceil_div);+ } else {+ auto filters_dim = filters_shape.cend() - spatial_num;++ for (size_t i = 0; i < spatial_num; ++i, ++data_dim_it, ++filters_dim) {+ auto dim = *data_dim_it + pads_begin[i] + pads_end[i];++ const auto f_dim = *filters_dim;+ const auto filter_dilated = (f_dim - 1) * dilations[i] + 1;++ dim = (dim - filter_dilated) / strides[i];+ dim += 1;++ output_shape.push_back(dim);+ }+ }++ return output_shape;+}++Result ConvolutionShapeInfer::infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,+ const std::unordered_map<size_t, MemoryPtr>&) {+ assert(input_shapes.size() >= 2);+ const auto& data_shape = input_shapes[0].get();+ const auto& filters_shape = input_shapes[1].get();++ auto output_shape = convolution_shape_infer(data_shape,+ filters_shape,+ m_strides,+ m_dilations,+ m_pads_begin,+ m_pads_end,+ m_auto_padding,+ m_isGrouped);++ return {{output_shape}, ShapeInferStatus::success};+}++ShapeInferPtr ConvolutionShapeInferFactory::makeShapeInfer() const {+ if (const auto convolution = ov::as_type_ptr<const ov::op::util::ConvolutionFwdPropBase>(m_op)) {+ const auto is_grouped = ov::is_type<const ov::op::v1::GroupConvolution>(convolution);+ return std::make_shared<ConvolutionShapeInfer>(+ convolution->get_strides(),+ convolution->get_dilations(),+ convolution->get_pads_begin(),+ convolution->get_pads_end(),+ one_of(convolution->get_auto_pad(), ov::op::PadType::SAME_LOWER, ov::op::PadType::SAME_UPPER),+ is_grouped);+ }++ OPENVINO_THROW("Unexpected operation type in the Convolution shape inference factory");+}++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/shape_inference/custom/convolution.hpp b/src/plugins/intel_cpu/src/shape_inference/custom/convolution.hppnew file mode 100644index 00000000000..e982098b8ac--- /dev/null+++ b/src/plugins/intel_cpu/src/shape_inference/custom/convolution.hpp@@ -0,0 +1,66 @@+// Copyright (C) 2018-2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#pragma once++#include <node.h>++#include <cstddef>+#include <utility>++#include "cpu_types.h"+#include "shape_inference/shape_inference_cpu.hpp"++namespace ov::intel_cpu::node {++VectorDims convolution_shape_infer(const VectorDims& data_shape,+ const VectorDims& filters_shape,+ const std::vector<size_t>& strides,+ const std::vector<size_t>& dilations,+ const std::vector<ptrdiff_t>& pads_begin,+ const std::vector<ptrdiff_t>& pads_end,+ bool auto_padding,+ bool isGrouped);++using Result = IShapeInfer::Result;+class ConvolutionShapeInfer : public ShapeInferEmptyPads {+public:+ ConvolutionShapeInfer(std::vector<size_t> strides,+ std::vector<size_t> dilations,+ std::vector<ptrdiff_t> pads_begin,+ std::vector<ptrdiff_t> pads_end,+ bool auto_padding,+ bool isGrouped = false)+ : m_strides(std::move(strides)),+ m_dilations(std::move(dilations)),+ m_pads_begin(std::move(pads_begin)),+ m_pads_end(std::move(pads_end)),+ m_auto_padding(auto_padding),+ m_isGrouped(isGrouped) {}+ Result infer(const std::vector<std::reference_wrapper<const VectorDims>>& input_shapes,+ const std::unordered_map<size_t, MemoryPtr>& data_dependency) override;++ [[nodiscard]] port_mask_t get_port_mask() const override {+ return EMPTY_PORT_MASK;+ }++private:+ std::vector<size_t> m_strides;+ std::vector<size_t> m_dilations;+ std::vector<ptrdiff_t> m_pads_begin;+ std::vector<ptrdiff_t> m_pads_end;+ bool m_auto_padding;+ bool m_isGrouped;+};++class ConvolutionShapeInferFactory : public ShapeInferFactory {+public:+ ConvolutionShapeInferFactory(std::shared_ptr<ov::Node> op) : m_op(std::move(op)) {}+ [[nodiscard]] ShapeInferPtr makeShapeInfer() const override;++private:+ std::shared_ptr<ov::Node> m_op;+};++} // namespace ov::intel_cpu::nodediff --git a/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp b/src/plugins/intel_cpu/src/shape_inference/shape_inference.cppindex 27a0d2e2cac..ecbc796f535 100644--- a/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp+++ b/src/plugins/intel_cpu/src/shape_inference/shape_inference.cpp@@ -36,6 +36,7 @@#include "ctc_greedy_decoder_seq_len_shape_inference.hpp"#include "ctc_greedy_decoder_shape_inference.hpp"#include "ctc_loss_shape_inference.hpp"+#include "custom/convolution.hpp"#include "deformable_convolution_shape_inference.hpp"#include "deformable_psroi_pooling_shape_inference.hpp"#include "depth_to_space_shape_inference.hpp"@@ -79,6 +80,9 @@#include "nms_shape_inference.hpp"#include "nv12_shape_inference.hpp"#include "one_hot_shape_inference.hpp"+#include "openvino/op/binary_convolution.hpp"+#include "openvino/op/convolution.hpp"+#include "openvino/op/group_conv.hpp"#include "openvino/opsets/opset1.hpp"#include "openvino/opsets/opset11.hpp"#include "openvino/opsets/opset3.hpp"@@ -140,7 +144,7 @@ class ShapeInferBase : public IStaticShapeInfer {public:using iface_type = IStaticShapeInfer;- ShapeInferBase(std::shared_ptr<Node> node) : m_input_ranks{}, m_node{std::move(node)} {+ ShapeInferBase(std::shared_ptr<ov::Node> node) : m_input_ranks{}, m_node{std::move(node)} {static_assert(std::is_same_v<int64_t, Dimension::value_type>, "Rank type not match to input_ranks type.");for (size_t i = 0; i < m_node->get_input_size(); ++i) {const auto& shape = m_node->get_input_partial_shape(i);@@ -310,7 +314,10 @@ public:/** @brief Base shape inference object implementing the IStaticShapeInfer with padding support. */class ShapeInferPaddingBase : public ShapeInferBase {public:- ShapeInferPaddingBase(std::shared_ptr<Node> node) : ShapeInferBase(std::move(node)), m_pads_begin{}, m_pads_end{} {}+ ShapeInferPaddingBase(std::shared_ptr<ov::Node> node)+ : ShapeInferBase(std::move(node)),+ m_pads_begin{},+ m_pads_end{} {}const ov::CoordinateDiff& get_pads_begin() override {return m_pads_begin;@@ -346,7 +353,7 @@ public:};/**- * @brief Shape inference using tensor accessor to get constant data and padding+ * @brief Shape inference without using tensor accessor to get constant data and padding** @tparam TOp Type of operator.* @tparam MASK The bit mask where each bit corresponds to an input port number.@@ -552,7 +559,6 @@ const IStaticShapeInferFactory::TRegistry IStaticShapeInferFactory::registry{OV_OP_SHAPE_INFER_MASK_REG(opset1::BinaryConvolution, ShapeInferPaddingTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(opset1::Broadcast, ShapeInferTA, util::bit::mask(1, 2)),OV_OP_SHAPE_INFER_MASK_REG(opset1::Concat, ShapeInferTA, util::bit::mask()),- OV_OP_SHAPE_INFER_MASK_REG(opset1::Convolution, ShapeInferPaddingTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(opset1::ConvolutionBackpropData, ShapeInferPaddingTA, util::bit::mask(2)),OV_OP_SHAPE_INFER_MASK_REG(opset1::CTCGreedyDecoder, ShapeInferTA, util::bit::mask()),OV_OP_SHAPE_INFER_MASK_REG(opset1::DeformableConvolution, ShapeInferPaddingTA, util::bit::mask()),diff --git a/src/plugins/intel_cpu/src/utils/cpp/to_underlying.hpp b/src/plugins/intel_cpu/src/utils/cpp/to_underlying.hppnew file mode 100644index 00000000000..613aede4925--- /dev/null+++ b/src/plugins/intel_cpu/src/utils/cpp/to_underlying.hpp@@ -0,0 +1,19 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//+#pragma once++#include <type_traits>++namespace ov::intel_cpu {++#ifdef OPENVINO_CPP_23_VER+using to_underlying = std::to_underlying;+#else+// implementation of C++23 std::to_underlying+template <typename E>+constexpr auto to_underlying(E e) noexcept {+ return static_cast<std::underlying_type_t<E>>(e);+}+} // namespace ov::intel_cpu+#endifdiff --git a/src/plugins/intel_cpu/tests/functional/cmake/target_per_test.cmake b/src/plugins/intel_cpu/tests/functional/cmake/target_per_test.cmakeindex 52ccb94c7fa..797602d9db7 100644--- a/src/plugins/intel_cpu/tests/functional/cmake/target_per_test.cmake+++ b/src/plugins/intel_cpu/tests/functional/cmake/target_per_test.cmake@@ -96,7 +96,8 @@ endif()endfunction()if(ENABLE_CPU_SPECIFIC_TARGET_PER_TEST)- create_target_per_test_for_directory(${CMAKE_CURRENT_SOURCE_DIR}/custom/subgraph_tests/src/common ov_cpu_func_subgraph)+ create_target_per_test_for_directory(${CMAKE_CURRENT_SOURCE_DIR}/custom/subgraph_tests/src ov_cpu_func_subgraph)+ create_target_per_test_for_directory(${CMAKE_CURRENT_SOURCE_DIR}/custom/subgraph_tests/src/common ov_cpu_func_subgraph_common)create_target_per_test_for_directory(${CMAKE_CURRENT_SOURCE_DIR}/custom/single_layer_tests ov_cpu_func_slt)endif()diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/group_convolution.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/group_convolution.cppindex 09c20dc658b..2804f5a89e9 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/group_convolution.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/group_convolution.cpp@@ -1403,7 +1403,8 @@ const auto groupConvParams_ExplicitPadding_DW_3D = ::testing::Combine(::testing:::testing::ValuesIn(dilations3d),::testing::ValuesIn(numOutChannels_DW),::testing::ValuesIn(numGroups_DW),- ::testing::Values(ov::op::PadType::EXPLICIT));+ ::testing::Values(ov::op::PadType::EXPLICIT,+ ov::op::PadType::AUTO));const std::vector<CPUSpecificParams> CPUParams_DW_3D = {conv_avx2_dw_3D,conv_avx512_dw_3D,diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/matmul.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/matmul.cppindex 3405f12e0c3..aecb5b7bdb3 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/matmul.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/instances/x64/matmul.cpp@@ -238,8 +238,10 @@ std::vector<fusingSpecificParams> fusingParamsSet2D_Brgemm_smoke {// The following three patterns are covered by MLAS test#ifndef OV_CPU_WITH_MLASemptyFusingSpec,- fusingBias,fusingMultiplyPerChannel,+ fusingBias,+#else+ fusingBiasGelu, // bias + gelu to ensure mlas is not selected#endiffusingFakeQuantizePerTensorRelu,fusingReluScaleShiftdiff --git a/src/plugins/intel_cpu/tests/functional/utils/cpu_test_utils.cpp b/src/plugins/intel_cpu/tests/functional/utils/cpu_test_utils.cppindex 90f4c2acb42..817938e6fed 100644--- a/src/plugins/intel_cpu/tests/functional/utils/cpu_test_utils.cpp+++ b/src/plugins/intel_cpu/tests/functional/utils/cpu_test_utils.cpp@@ -245,7 +245,7 @@ void CPUTestsBase::CheckPluginRelatedResultsImpl(const std::shared_ptr<const ov:bool CPUTestsBase::primTypeCheck(std::string primType) const {#ifndef NDEBUG- std::cout << "selectedType: " << selectedType << std::endl;+ std::cout << "selectedType: " << selectedType << "primType: " << primType << std::endl;#endifif (selectedType.find("FP") != std::string::npos)return selectedType.find(CPUTestsBase::any_type) != std::string::npos ||diff --git a/src/plugins/intel_cpu/tests/functional/utils/fusing_test_utils.hpp b/src/plugins/intel_cpu/tests/functional/utils/fusing_test_utils.hppindex 2641d8b00d8..83946ac8b9f 100644--- a/src/plugins/intel_cpu/tests/functional/utils/fusing_test_utils.hpp+++ b/src/plugins/intel_cpu/tests/functional/utils/fusing_test_utils.hpp@@ -515,4 +515,14 @@ const auto fusingBias = fusingSpecificParams{std::make_shared<postNodesMgr>(std:return std::make_shared<ov::op::v1::Add>(cfg.input, bias);}, "fusingBias"}}), {"Add"}};+const auto fusingBiasGelu = fusingSpecificParams{std::make_shared<postNodesMgr>(std::vector<postNodeBuilder>{+ {[](postNodeConfig& cfg) {+ size_t last_dim = cfg.input->get_output_partial_shape(0).rbegin()->get_length();+ auto bias = ov::test::utils::make_constant(cfg.type, ov::Shape{last_dim});+ return std::make_shared<ov::op::v1::Add>(cfg.input, bias);+ }, "fusingBias"},+ {[](postNodeConfig& cfg){+ return utils::make_activation(cfg.input, cfg.type, utils::Gelu);+ }, "Gelu"}}), {"Gelu"} };+} // namespace CPUTestUtilsdiff --git a/src/plugins/intel_cpu/tests/unit/shape_inference_test/convolution_shape_inference_test.cpp b/src/plugins/intel_cpu/tests/unit/shape_inference_test/convolution_shape_inference_test.cppdeleted file mode 100644index 839cc5e2dd0..00000000000--- a/src/plugins/intel_cpu/tests/unit/shape_inference_test/convolution_shape_inference_test.cpp+++ /dev/null@@ -1,135 +0,0 @@-// Copyright (C) 2018-2025 Intel Corporation-// SPDX-License-Identifier: Apache-2.0-//--#include <gmock/gmock.h>--#include "common_test_utils/test_assertions.hpp"-#include "openvino/opsets/opset11.hpp"-#include "utils.hpp"--using namespace ov;-using namespace ov::intel_cpu;-using namespace testing;--class ConvolutionV1StaticShapeInferenceTest : public OpStaticShapeInferenceTest<op::v1::Convolution> {-protected:- void SetUp() override {- output_shapes.resize(1);- }-};--TEST_F(ConvolutionV1StaticShapeInferenceTest, default_ctor) {- op = make_op();- op->set_strides({1, 1});- op->set_dilations({1, 1});- op->set_pads_begin({2, 2});- op->set_pads_end({2, 1});- op->set_auto_pad(op::PadType::VALID);-- input_shapes = StaticShapeVector{{1, 3, 10, 12}, {2, 3, 5, 5}};- auto shape_infer = make_shape_inference(op);- const auto input_shape_refs = make_static_shape_refs(input_shapes);- output_shapes = *shape_infer->infer(input_shape_refs, make_tensor_accessor());-- EXPECT_EQ(output_shapes.size(), 1);- EXPECT_EQ(output_shapes.front(), StaticShape({1, 2, 6, 8}));- EXPECT_EQ(shape_infer->get_pads_begin(), CoordinateDiff({0, 0}));- EXPECT_EQ(shape_infer->get_pads_end(), CoordinateDiff({0, 0}));-}--TEST_F(ConvolutionV1StaticShapeInferenceTest, default_ctor_three_input_shapes) {- op = make_op();- op->set_strides({1, 1});- op->set_dilations({1, 1});- op->set_pads_begin({2, 2});- op->set_pads_end({2, 1});- op->set_auto_pad(op::PadType::VALID);-- // Third input shape (bias) can be provided, but is not used- input_shapes = StaticShapeVector{{1, 3, 10, 12}, {2, 3, 5, 5}, {2}};- auto shape_infer = make_shape_inference(op);- const auto input_shape_refs = make_static_shape_refs(input_shapes);- output_shapes = *shape_infer->infer(input_shape_refs, make_tensor_accessor());-- EXPECT_EQ(output_shapes.size(), 1);- EXPECT_EQ(output_shapes.front(), StaticShape({1, 2, 6, 8}));- EXPECT_EQ(shape_infer->get_pads_begin(), CoordinateDiff({0, 0}));- EXPECT_EQ(shape_infer->get_pads_end(), CoordinateDiff({0, 0}));-}--TEST_F(ConvolutionV1StaticShapeInferenceTest, 2d_auto_pads_same_lower_inputs_dynamic_rank) {- const auto strides = Strides{1, 1};- const auto dilations = Strides{1, 1};- const auto pads_begin = CoordinateDiff{0, 0};- const auto pads_end = CoordinateDiff{0, 0};- const auto auto_pad = op::PadType::SAME_LOWER;-- const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic());- const auto filters = std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic());-- op = make_op(data, filters, strides, pads_begin, pads_end, dilations, auto_pad);-- input_shapes = StaticShapeVector{{3, 6, 5, 5}, {7, 6, 3, 3}};- output_shapes = shape_inference(op.get(), input_shapes);-- EXPECT_EQ(output_shapes.size(), 1);- EXPECT_EQ(output_shapes[0], StaticShape({3, 7, 5, 5}));-}--TEST_F(ConvolutionV1StaticShapeInferenceTest, 3d_auto_pad_same_lower_inputs_static_ranks) {- const auto strides = Strides{1, 1, 1};- const auto dilations = Strides{1, 1, 1};- const auto pads_begin = CoordinateDiff{0, 0, 0};- const auto pads_end = CoordinateDiff{0, 0, 0};- const auto auto_pad = op::PadType::SAME_UPPER;-- const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});- const auto filters = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});-- op = make_op(data, filters, strides, pads_begin, pads_end, dilations, auto_pad);-- input_shapes = StaticShapeVector{{3, 6, 5, 5, 5}, {7, 6, 3, 3, 3}};- output_shapes = shape_inference(op.get(), input_shapes);-- EXPECT_EQ(output_shapes.size(), 1);- EXPECT_EQ(output_shapes[0], StaticShape({3, 7, 5, 5, 5}));-}--TEST_F(ConvolutionV1StaticShapeInferenceTest, data_and_filters_num_channels_not_same) {- const auto strides = Strides{1, 1, 1};- const auto dilations = Strides{1, 1, 1};- const auto pads_begin = CoordinateDiff{0, 0, 0};- const auto pads_end = CoordinateDiff{0, 0, 0};- const auto auto_pad = op::PadType::SAME_UPPER;-- const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});- const auto filters = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});-- op = make_op(data, filters, strides, pads_begin, pads_end, dilations, auto_pad);-- input_shapes = StaticShapeVector{{3, 5, 5, 5, 5}, {7, 6, 3, 3, 3}};-- OV_EXPECT_THROW(shape_inference(op.get(), input_shapes),- NodeValidationFailure,- HasSubstr("Data batch channel count (5) does not match filter"));-}--TEST_F(ConvolutionV1StaticShapeInferenceTest, data_rank_not_compatible_with_filters_rank) {- const auto strides = Strides{1, 1};- const auto dilations = Strides{1, 1};- const auto pads_begin = CoordinateDiff{0, 0};- const auto pads_end = CoordinateDiff{0, 0};- const auto auto_pad = op::PadType::SAME_LOWER;-- const auto data = std::make_shared<op::v0::Parameter>(element::f32, PartialShape::dynamic());- const auto filters = std::make_shared<op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});-- op = make_op(data, filters, strides, pads_begin, pads_end, dilations, auto_pad);-- input_shapes = StaticShapeVector{{3, 6, 5, 5, 5}, {7, 6, 3, 3}};-- OV_EXPECT_THROW(shape_inference(op.get(), input_shapes),- NodeValidationFailure,- HasSubstr("Data batch and filters rank do not match"));-}diff --git a/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/convolution.cpp b/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/convolution.cppnew file mode 100644index 00000000000..2288c5eb642--- /dev/null+++ b/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/convolution.cpp@@ -0,0 +1,102 @@+// Copyright (C) 2025 Intel Corporation+// SPDX-License-Identifier: Apache-2.0+//++#include "openvino/op/convolution.hpp"++#include <gtest/gtest.h>++#include "common_test_utils/test_assertions.hpp"+#include "custom_shape_infer.hpp"+#include "openvino/op/parameter.hpp"++namespace ov {+namespace intel_cpu {+namespace unit_test {+namespace cpu_shape_infer {++using namespace ov;+using namespace ov::intel_cpu;++TEST(CpuShapeInfer, Conv2D_DefaultCtor) {+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto op = std::make_shared<ov::op::v1::Convolution>(data,+ filters,+ Strides{1, 1},+ CoordinateDiff{2, 2},+ CoordinateDiff{2, 1},+ Strides{1, 1},+ op::PadType::VALID);+ std::vector<StaticShape> static_input_shapes = {StaticShape{1, 3, 10, 12}, {2, 3, 5, 5}};+ std::vector<StaticShape> static_output_shapes = {StaticShape{1, 2, 6, 8}};+ unit_test::cpu_test_shape_infer(op.get(), static_input_shapes, static_output_shapes);+}++TEST(CpuShapeInfer, Conv2D_ThreeInputShapes) {+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto op = std::make_shared<ov::op::v1::Convolution>(data,+ filters,+ Strides{1, 1},+ CoordinateDiff{2, 2},+ CoordinateDiff{2, 1},+ Strides{1, 1},+ op::PadType::VALID);+ std::vector<StaticShape> static_input_shapes = {StaticShape{1, 3, 10, 12}, {2, 3, 5, 5}, {2}};+ std::vector<StaticShape> static_output_shapes = {StaticShape{1, 2, 6, 8}};+ unit_test::cpu_test_shape_infer(op.get(), static_input_shapes, static_output_shapes);+}++TEST(CpuShapeInfer, Conv2D_AutoPadsSameLower) {+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1});+ auto op = std::make_shared<ov::op::v1::Convolution>(data,+ filters,+ Strides{1, 1},+ CoordinateDiff{0, 0},+ CoordinateDiff{0, 0},+ Strides{1, 1},+ op::PadType::SAME_LOWER);+ std::vector<StaticShape> static_input_shapes = {StaticShape{3, 6, 5, 5}, {7, 6, 3, 3}};+ std::vector<StaticShape> static_output_shapes = {StaticShape{3, 7, 5, 5}};+ unit_test::cpu_test_shape_infer(op.get(), static_input_shapes, static_output_shapes);+}++TEST(CpuShapeInfer, Conv3D_AutoPadsSameUpper) {+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});+ auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});+ auto op = std::make_shared<ov::op::v1::Convolution>(data,+ filters,+ Strides{1, 1, 1},+ CoordinateDiff{0, 0, 0},+ CoordinateDiff{0, 0, 0},+ Strides{1, 1, 1},+ op::PadType::SAME_UPPER);+ std::vector<StaticShape> static_input_shapes = {StaticShape{3, 6, 5, 5, 5}, {7, 6, 3, 3, 3}};+ std::vector<StaticShape> static_output_shapes = {StaticShape{3, 7, 5, 5, 5}};+ unit_test::cpu_test_shape_infer(op.get(), static_input_shapes, static_output_shapes);+}++TEST(CpuShapeInfer, Conv3D_DataAndFiltersNumChannelsMismatch) {+ auto data = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});+ auto filters = std::make_shared<ov::op::v0::Parameter>(element::f32, PartialShape{-1, -1, -1, -1, -1});+ auto op = std::make_shared<ov::op::v1::Convolution>(data,+ filters,+ Strides{1, 1, 1},+ CoordinateDiff{0, 0, 0},+ CoordinateDiff{0, 0, 0},+ Strides{1, 1, 1},+ op::PadType::SAME_UPPER);+ std::vector<StaticShape> static_input_shapes = {StaticShape{3, 5, 5, 5, 5}, {7, 6, 3, 3, 3}};+ std::vector<StaticShape> static_output_shapes = {};++ OV_EXPECT_THROW(unit_test::cpu_test_shape_infer(op.get(), static_input_shapes, static_output_shapes),+ ov::Exception,+ testing::HasSubstr("Input and filter channels must match"));+}++} // namespace cpu_shape_infer+} // namespace unit_test+} // namespace intel_cpu+} // namespace ovdiff --git a/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/custom_shape_infer.cpp b/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/custom_shape_infer.cppindex f96e4b6f752..b117a8024ed 100644--- a/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/custom_shape_infer.cpp+++ b/src/plugins/intel_cpu/tests/unit/shape_inference_test/custom_shape_infer/custom_shape_infer.cpp@@ -12,6 +12,7 @@#include "openvino/op/parameter.hpp"#include "shape_inference/custom/adaptive_pooling.hpp"#include "shape_inference/custom/color_convert.hpp"+#include "shape_inference/custom/convolution.hpp"#include "shape_inference/custom/eltwise.hpp"#include "shape_inference/custom/fullyconnected.hpp"#include "shape_inference/custom/gather.hpp"@@ -62,6 +63,7 @@ public:INTEL_CPU_CUSTOM_SHAPE_INFER(node::NgramShapeInferFactory, Type::Ngram);INTEL_CPU_CUSTOM_SHAPE_INFER(node::GatherShapeInferFactory, Type::Gather);INTEL_CPU_CUSTOM_SHAPE_INFER(node::SDPAShapeInferFactory, Type::ScaledDotProductAttention);+ INTEL_CPU_CUSTOM_SHAPE_INFER(node::ConvolutionShapeInferFactory, Type::Convolution);#undef INTEL_CPU_CUSTOM_SHAPE_INFER}