Path: blob/master/modules/dnn/src/layers/convolution_layer.cpp
16337 views
/*M///////////////////////////////////////////////////////////////////////////////////////1//2// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.3//4// By downloading, copying, installing or using the software you agree to this license.5// If you do not agree to this license, do not download, install,6// copy or use the software.7//8//9// License Agreement10// For Open Source Computer Vision Library11//12// Copyright (C) 2013, OpenCV Foundation, all rights reserved.13// Copyright (C) 2017, Intel Corporation, all rights reserved.14// Third party copyrights are property of their respective owners.15//16// Redistribution and use in source and binary forms, with or without modification,17// are permitted provided that the following conditions are met:18//19// * Redistribution's of source code must retain the above copyright notice,20// this list of conditions and the following disclaimer.21//22// * Redistribution's in binary form must reproduce the above copyright notice,23// this list of conditions and the following disclaimer in the documentation24// and/or other materials provided with the distribution.25//26// * The name of the copyright holders may not be used to endorse or promote products27// derived from this software without specific prior written permission.28//29// This software is provided by the copyright holders and contributors "as is" and30// any express or implied warranties, including, but not limited to, the implied31// warranties of merchantability and fitness for a particular purpose are disclaimed.32// In no event shall the Intel Corporation or contributors be liable for any direct,33// indirect, incidental, special, exemplary, or consequential damages34// (including, but not limited to, procurement of substitute goods or services;35// loss of use, data, or profits; or business interruption) however caused36// and on any theory of liability, whether in contract, strict liability,37// or tort (including negligence or otherwise) arising in any way out of38// the use of this software, even if advised of the possibility of such damage.39//40//M*/4142#include "../precomp.hpp"43#include "layers_common.hpp"44#include "../op_halide.hpp"45#include "../op_inf_engine.hpp"46#include "../op_vkcom.hpp"47#include "opencv2/core/hal/hal.hpp"48#include "opencv2/core/hal/intrin.hpp"49#include <iostream>5051#ifdef HAVE_OPENCL52#include "opencl_kernels_dnn.hpp"53using namespace cv::dnn::ocl4dnn;54#endif5556namespace cv57{58namespace dnn59{6061class BaseConvolutionLayerImpl : public ConvolutionLayer62{63public:64BaseConvolutionLayerImpl(const LayerParams ¶ms)65{66setParamsFrom(params);67int pad_t = 0, pad_l = 0, pad_r = 0, pad_b = 0;68getConvolutionKernelParams(params, kernel.height, kernel.width, pad_t,69pad_l, pad_b, pad_r, stride.height, stride.width, dilation.height,70dilation.width, padMode);7172if (pad_t != pad_b || pad_l != pad_r)73CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");7475pad.width = pad_l;76pad.height = pad_t;7778numOutput = params.get<int>("num_output");79int ngroups = params.get<int>("group", 1);8081adjustPad.height = params.get<int>("adj_h", 0);82adjustPad.width = params.get<int>("adj_w", 0);8384CV_Assert(numOutput % ngroups == 0);85CV_Assert(adjustPad.width < stride.width &&86adjustPad.height < stride.height);87}8889void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE90{91std::vector<Mat> inputs, outputs;92inputs_arr.getMatVector(inputs);93outputs_arr.getMatVector(outputs);9495CV_Assert(inputs.size() > 0);9697CV_Assert(blobs.size() >= 1 && blobs.size() <= 2);98CV_Assert(blobs[0].dims == 4 && blobs[0].size[3] == kernel.width && blobs[0].size[2] == kernel.height);99100const Mat &input = inputs[0];101CV_Assert(input.dims == 4 && (input.type() == CV_32F || input.type() == CV_64F || input.type() == CV_16S));102for (size_t i = 0; i < inputs.size(); i++)103{104CV_Assert(inputs[i].type() == input.type());105CV_Assert(inputs[i].dims == 4 && inputs[i].size[1] == input.size[1]);106CV_Assert(inputs[i].size[2] == input.size[2] && inputs[i].size[3] == input.size[3]);107}108109Size outSize = Size(outputs[0].size[3], outputs[0].size[2]);110111int pad_t = pad.height, pad_l = pad.width, pad_b = pad.height, pad_r = pad.width;112113getConvPoolPaddings(Size(input.size[3], input.size[2]), outSize,114kernel, stride, padMode, dilation, pad_t, pad_l, pad_b, pad_r);115116117if (pad_t != pad_b || pad_l != pad_r)118CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");119120pad.width = pad_l;121pad.height = pad_t;122}123124bool hasBias() const125{126return blobs.size() >= 2;127}128129virtual MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const = 0;130bool is1x1() const131{132return (kernel.height == 1 && kernel.width == 1) &&133(stride.height == 1 && stride.width == 1) &&134(dilation.height == 1 && dilation.width == 1);135}136137virtual void applyHalideScheduler(Ptr<BackendNode>& node,138const std::vector<Mat*> &inputs,139const std::vector<Mat> &outputs,140int targetId) const CV_OVERRIDE141{142#ifdef HAVE_HALIDE143if (targetId != DNN_TARGET_CPU)144{145Layer::applyHalideScheduler(node, inputs, outputs, targetId);146return;147}148Halide::Var x("x"), y("y"), c("c"), n("n"), tile("tile"), yi("yi"), yo("yo"), co("co"), ci("ci");149Halide::Func& top = node.dynamicCast<HalideBackendNode>()->funcs[1];150Halide::Func& padded_input = node.dynamicCast<HalideBackendNode>()->funcs[0];151152int outW, outH, outC, outN;153getCanonicalSize(outputs[0].size, &outW, &outH, &outC, &outN);154155if (outW == 1 || outH <= 2)156return;157158if (is1x1() || outC <= 16)159top.reorder(x, c, y)160.split(y, yo, yi, 2)161.fuse(yo, n, tile)162.parallel(tile)163.unroll(yi)164.vectorize(x, outW >= 16 ? 16 : outW);165else166top.reorder(x, c, y)167.split(y, yo, yi, 2)168.split(c, co, ci, 16)169.fuse(yo, co, tile).fuse(n, tile, tile)170.parallel(tile)171.unroll(yi)172.vectorize(x, outW >= 16 ? 16 : outW);173padded_input.compute_at(top, yi);174#endif // HAVE_HALIDE175}176};177178179#define IS_POWER_LAYER(layer) \180(!layer.empty() && !layer->type.compare("Power"))181//TODO: simultaneously convolution and bias addition for cache optimization182class ConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl183{184public:185enum { VEC_ALIGN = 8, DFT_TYPE = CV_32F };186Mat weightsMat;187std::vector<double> weightsMultipliers;188std::vector<float> biasvec;189std::vector<float> reluslope;190Ptr<ActivationLayer> activ;191bool newWeightAndBias;192bool fusedBias;193194#ifdef HAVE_OPENCL195Ptr<OCL4DNNConvSpatial<float> > convolutionOp;196std::vector<UMat> umat_blobs;197bool newActiv;198ocl4dnnFusedActiv_t activType;199float power;200#endif201ConvolutionLayerImpl(const LayerParams ¶ms) : BaseConvolutionLayerImpl(params)202{203newWeightAndBias = false;204fusedBias = false;205#ifdef HAVE_OPENCL206newActiv = false;207activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;208power = 0.f;209#endif210}211212MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE213{214Size out(outShape[3], outShape[2]);215int inpGroupCn = blobs[0].size[1];216int ksize = inpGroupCn * kernel.height * kernel.width;217return shape(out.area(), ksize);218}219220virtual bool supportBackend(int backendId) CV_OVERRIDE221{222if (backendId == DNN_BACKEND_INFERENCE_ENGINE)223return preferableTarget != DNN_TARGET_MYRIAD || dilation.width == dilation.height;224else225return backendId == DNN_BACKEND_OPENCV ||226backendId == DNN_BACKEND_HALIDE ||227backendId == DNN_BACKEND_VKCOM && haveVulkan();228}229230bool getMemoryShapes(const std::vector<MatShape> &inputs,231const int requiredOutputs,232std::vector<MatShape> &outputs,233std::vector<MatShape> &internals) const CV_OVERRIDE234{235CV_Assert(blobs.size() != 0);236CV_Assert(!hasBias() || blobs[1].total() == (size_t)blobs[0].size[0]);237CV_Assert(inputs.size() == (size_t)1);238239internals.clear();240241int inpCn = inputs[0][1];242int inpH = inputs[0][2];243int inpW = inputs[0][3];244245int outCn = blobs[0].size[0];246Size out;247248if (padMode.empty())249{250out.height = (inpH + 2 * pad.height - (dilation.height * (kernel.height - 1) + 1)) / stride.height + 1;251out.width = (inpW + 2 * pad.width - (dilation.width * (kernel.width - 1) + 1)) / stride.width + 1;252}253else254{255getConvPoolOutParams(Size(inpW, inpH), kernel, stride, padMode, dilation, out);256}257258int ngroups = inpCn / blobs[0].size[1];259CV_Assert(ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0);260261int dims[] = {inputs[0][0], outCn, out.height, out.width};262outputs.resize(inputs.size(), shape(dims, 4));263264return false;265}266267virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE268{269BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);270271CV_Assert(!blobs.empty());272const int outCn = blobs[0].size[0];273// prepare weightsMat where each row is aligned and has enough zero padding on the right to274// use vectorized (i.e. with intrinsics) loops without tail processing275Mat wm = blobs[0].reshape(1, outCn).clone();276if( wm.step1() % VEC_ALIGN != 0 )277{278int newcols = (int)alignSize(wm.step1(), VEC_ALIGN);279Mat wm_buffer = Mat(outCn, newcols, wm.type());280Mat wm_padding = wm_buffer.colRange(wm.cols, newcols);281wm_padding.setTo(Scalar::all(0.));282Mat wm_aligned = wm_buffer.colRange(0, wm.cols);283wm.copyTo(wm_aligned);284wm = wm_aligned;285}286weightsMat = wm;287weightsMultipliers.assign(outCn, 1.0);288289Mat biasMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat();290biasvec.resize(outCn+2);291if( biasMat.empty() )292{293for(int i = 0; i < outCn; i++ )294biasvec[i] = 0.f;295}296else297{298for(int i = 0; i < outCn; i++ )299biasvec[i] = biasMat.at<float>(i);300}301#ifdef HAVE_OPENCL302convolutionOp.release();303#endif304}305306bool setActivation(const Ptr<ActivationLayer>& layer) CV_OVERRIDE307{308if (!activ.empty() && !layer.empty())309return false;310311activ = layer;312if (activ.empty())313reluslope.clear();314#ifdef HAVE_OPENCL315newActiv = true;316activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;317318if (IS_DNN_OPENCL_TARGET(preferableTarget))319{320Ptr<PowerLayer> activ_power = activ.dynamicCast<PowerLayer>();321if (!activ_power.empty())322{323if (activ_power->scale != 1.f || activ_power->shift != 0.f)324{325const int outCh = blobs[0].size[0];326fuseWeights(Mat(1, outCh, CV_32F, Scalar(activ_power->scale)),327Mat(1, outCh, CV_32F, Scalar(activ_power->shift)));328}329330power = activ_power->power;331activType = OCL4DNN_CONV_FUSED_ACTIV_POWER;332}333Ptr<TanHLayer> activ_tanh = activ.dynamicCast<TanHLayer>();334if (!activ_tanh.empty())335{336activType = OCL4DNN_CONV_FUSED_ACTIV_TANH;337}338}339#endif340return !activ.empty();341}342343virtual bool tryFuse(Ptr<Layer>& top) CV_OVERRIDE344{345Mat w, b;346top->getScaleShift(w, b);347if (!w.empty() || !b.empty())348{349fuseWeights(w, b);350return true;351}352return false;353}354355void fuseWeights(const Mat& w_, const Mat& b_)356{357// Convolution weights have OIHW data layout. Parameters fusion in case of358// (conv(I) + b1 ) * w + b2359// means to replace convolution's weights to [w*conv(I)] and bias to [b1 * w + b2]360const int outCn = weightsMat.size[0];361Mat w = w_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(w_.at<float>(0))) : w_;362Mat b = b_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(b_.at<float>(0))) : b_;363CV_Assert_N(!weightsMat.empty(), biasvec.size() == outCn + 2,364w.empty() || outCn == w.total(), b.empty() || outCn == b.total());365366if (!w.empty())367{368Mat originWeights = blobs[0].reshape(1, outCn);369for (int i = 0; i < outCn; ++i)370{371double wi = w.at<float>(i);372weightsMultipliers[i] *= wi;373cv::multiply(originWeights.row(i), weightsMultipliers[i], weightsMat.row(i));374biasvec[i] *= wi;375}376}377378if (!b.empty())379{380for (int i = 0; i < outCn; ++i)381biasvec[i] += b.at<float>(i);382}383384newWeightAndBias = !w.empty() || !b.empty();385fusedBias = hasBias() || !b.empty();386biasvec[outCn] = biasvec[outCn+1] = biasvec[outCn-1];387}388389virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE390{391#ifdef HAVE_VULKAN392int out_channel = blobs[0].size[0];393bool has_bias = hasBias() || fusedBias;394int filter_size[2] = {kernel.height, kernel.width};395int pad_size[2] = {pad.height, pad.width};396int stride_size[2] = {stride.height, stride.width};397int dilation_size[2] = {dilation.height, dilation.width};398int activation = 0;399vkcom::Tensor input_tensor = VkComTensor(inputs[0]);400int in_channel = input_tensor.dimSize(1);401int group = in_channel / blobs[0].size[1];402403// TODO: support group > 1404if (group != 1)405return Ptr<BackendNode>();406407int padding_mode;408if (padMode.empty())409{410padding_mode = vkcom::kPaddingModeCaffe;411}412else if (padMode == "VALID")413{414padding_mode = vkcom::kPaddingModeValid;415}416else if (padMode == "SAME")417{418padding_mode = vkcom::kPaddingModeSame;419}420else421CV_Error(Error::StsError, "Unsupported padding mode " + padMode);422423std::shared_ptr<vkcom::OpBase> op(new vkcom::OpConv(out_channel, has_bias,424filter_size, pad_size,425stride_size, dilation_size,426activation, group,427padding_mode));428429std::vector<Ptr<BackendWrapper> > blobsWrapper;430431if (newWeightAndBias)432{433Mat wm;434weightsMat.copyTo(wm); // to handle the case of isContinuous() == false435wm.reshape(1, blobs[0].dims, blobs[0].size);436blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(wm)));437}438else439{440blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(blobs[0])));441}442443if (has_bias)444{445Mat biasesMat({out_channel}, CV_32F, &biasvec[0]);446blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(biasesMat)));447}448449return Ptr<BackendNode>(new VkComBackendNode(inputs, op, blobsWrapper));450#endif // HAVE_VULKAN451return Ptr<BackendNode>();452}453454455456virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE457{458#ifdef HAVE_HALIDE459Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);460461const int inpCn = inputBuffer.channels();462const int outCn = blobs[0].size[0];463const int inpGroupCn = blobs[0].size[1];464const int group = inpCn / inpGroupCn;465const int outGroupCn = outCn / group;466467Halide::Buffer<float> weights = wrapToHalideBuffer(blobs[0]);468469Halide::Var x("x"), y("y"), c("c"), n("n");470Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));471Halide::Func padded_input(name + "_constant_exterior");472if (pad.width || pad.height)473{474Halide::Func bounded =475Halide::BoundaryConditions::constant_exterior(inputBuffer, 0);476padded_input(x, y, c, n) = bounded(x, y, c, n);477}478else479{480padded_input(x, y, c, n) = inputBuffer(x, y, c, n);481}482483Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);484Halide::Expr kx = x * stride.width - pad.width + r.x * dilation.width;485Halide::Expr ky = y * stride.height - pad.height + r.y * dilation.height;486Halide::Expr kc = r.z;487for (int i = 1; i < group; ++i)488{489kc = select(c < outGroupCn * i, kc, inpGroupCn * i + r.z);490}491Halide::Expr topExpr = sum(padded_input(kx, ky, kc, n) *492weights(r.x, r.y, r.z, c));493if (hasBias())494{495Halide::Buffer<float> bias = wrapToHalideBuffer(blobs[1], {outCn});496topExpr += bias(c);497}498top(x, y, c, n) = topExpr;499return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));500#endif // HAVE_HALIDE501return Ptr<BackendNode>();502}503504virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE505{506#ifdef HAVE_INF_ENGINE507InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);508CV_Assert(input->dims.size() == 4);509510const int inpCn = input->dims[2]; // NOTE: input->dims are reversed (whcn)511const int outCn = blobs[0].size[0];512const int inpGroupCn = blobs[0].size[1];513const int group = inpCn / inpGroupCn;514515InferenceEngine::LayerParams lp;516lp.name = name;517lp.type = "Convolution";518lp.precision = InferenceEngine::Precision::FP32;519std::shared_ptr<InferenceEngine::ConvolutionLayer> ieLayer(new InferenceEngine::ConvolutionLayer(lp));520521#if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2018R3)522ieLayer->_kernel.insert(InferenceEngine::X_AXIS, kernel.width);523ieLayer->_kernel.insert(InferenceEngine::Y_AXIS, kernel.height);524ieLayer->_stride.insert(InferenceEngine::X_AXIS, stride.width);525ieLayer->_stride.insert(InferenceEngine::Y_AXIS, stride.height);526ieLayer->_padding.insert(InferenceEngine::X_AXIS, pad.width);527ieLayer->_padding.insert(InferenceEngine::Y_AXIS, pad.height);528ieLayer->_pads_end.insert(InferenceEngine::X_AXIS, pad.width);529ieLayer->_pads_end.insert(InferenceEngine::Y_AXIS, pad.height);530ieLayer->_dilation.insert(InferenceEngine::X_AXIS, dilation.width);531ieLayer->_dilation.insert(InferenceEngine::Y_AXIS, dilation.height);532#else533ieLayer->_kernel_x = kernel.width;534ieLayer->_kernel_y = kernel.height;535ieLayer->_stride_x = stride.width;536ieLayer->_stride_y = stride.height;537ieLayer->_padding_x = pad.width;538ieLayer->_padding_y = pad.height;539ieLayer->_dilation_x = dilation.width;540ieLayer->_dilation_y = dilation.height;541#endif542ieLayer->_out_depth = outCn;543ieLayer->_group = group;544545ieLayer->_weights = wrapToInfEngineBlob(blobs[0], InferenceEngine::Layout::OIHW);546if (newWeightAndBias)547{548if (weightsMat.isContinuous())549{550Mat fusedWeights = weightsMat.reshape(1, blobs[0].dims, blobs[0].size);551ieLayer->_weights = wrapToInfEngineBlob(fusedWeights, InferenceEngine::Layout::OIHW);552}553else554{555ieLayer->_weights = InferenceEngine::make_shared_blob<float>(556InferenceEngine::Precision::FP32, InferenceEngine::Layout::OIHW,557ieLayer->_weights->dims());558ieLayer->_weights->allocate();559560Mat newWeights = infEngineBlobToMat(ieLayer->_weights).reshape(1, outCn);561Mat fusedWeights = weightsMat.colRange(0, newWeights.cols);562fusedWeights.copyTo(newWeights);563}564}565if (hasBias() || fusedBias)566{567Mat biasesMat({outCn}, CV_32F, &biasvec[0]);568ieLayer->_biases = wrapToInfEngineBlob(biasesMat, {(size_t)outCn}, InferenceEngine::Layout::C);569}570return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));571#endif // HAVE_INF_ENGINE572return Ptr<BackendNode>();573}574575class ParallelConv : public cv::ParallelLoopBody576{577public:578enum { BLK_SIZE = 32, BLK_SIZE_CN = 64 };579580const Mat* input_;581const Mat* weights_;582Mat* output_;583int outShape[4];584Size kernel_, pad_, stride_, dilation_;585int ngroups_, nstripes_;586std::vector<int> ofstab_;587const std::vector<float>* biasvec_;588const std::vector<float>* reluslope_;589const ActivationLayer* activ_;590bool is1x1_;591bool useAVX;592bool useAVX2;593bool useAVX512;594595ParallelConv()596: input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0),597biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX(false), useAVX2(false), useAVX512(false)598{}599600static void run( const Mat& input, Mat& output, const Mat& weights,601const std::vector<float>& biasvec,602const std::vector<float>& reluslope,603Size kernel, Size pad, Size stride, Size dilation,604const ActivationLayer* activ, int ngroups, int nstripes )605{606CV_Assert_N(607input.dims == 4 && output.dims == 4,608input.size[0] == output.size[0],609weights.rows == output.size[1],610weights.cols == (input.size[1]/ngroups)*kernel.width*kernel.height,611input.type() == output.type(),612input.type() == weights.type(),613input.type() == CV_32FC1,614input.isContinuous(),615output.isContinuous(),616biasvec.size() == (size_t)output.size[1]+2);617ParallelConv p;618619p.input_ = &input;620p.weights_ = &weights;621p.output_ = &output;622for( int i = 0; i < 4; i++ ) p.outShape[i] = output.size[i];623p.outShape[1] /= ngroups;624p.kernel_ = kernel; p.pad_ = pad; p.stride_ = stride; p.dilation_ = dilation;625p.ngroups_ = ngroups;626p.nstripes_ = nstripes;627628int inpCnAll = input.size[1], width = input.size[3], height = input.size[2];629int inpCn = inpCnAll / ngroups;630p.is1x1_ = kernel == Size(0,0) && pad == Size(0, 0);631p.useAVX = checkHardwareSupport(CPU_AVX);632p.useAVX2 = checkHardwareSupport(CPU_AVX2);633p.useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;634635int ncn = std::min(inpCn, (int)BLK_SIZE_CN);636p.ofstab_.resize(kernel.width*kernel.height*ncn);637int* ofstab = &p.ofstab_[0];638639for( int k = 0; k < ncn; k++ )640for( int k_r = 0; k_r < kernel.height; k_r++ )641for( int k_c = 0; k_c < kernel.width; k_c++ )642ofstab[(k*kernel.height + k_r)*kernel.width + k_c] =643(k*height + k_r*dilation.height)*width + k_c*dilation.width;644645p.biasvec_ = &biasvec;646p.reluslope_ = &reluslope;647p.activ_ = p.reluslope_->empty() ? activ : 0;648649parallel_for_(Range(0, nstripes), p, nstripes);650}651652virtual void operator ()(const Range &r0) const CV_OVERRIDE653{654const int valign = ConvolutionLayerImpl::VEC_ALIGN;655int ngroups = ngroups_, batchSize = input_->size[0]*ngroups;656int outW = output_->size[3], outH = output_->size[2], outCn = output_->size[1]/ngroups;657int width = input_->size[3], height = input_->size[2], inpCn = input_->size[1]/ngroups;658const int nstripes = nstripes_;659int kernel_w = kernel_.width, kernel_h = kernel_.height;660int pad_w = pad_.width, pad_h = pad_.height;661int stride_w = stride_.width, stride_h = stride_.height;662int dilation_w = dilation_.width, dilation_h = dilation_.height;663int karea = kernel_w*kernel_h;664int i, j, k;665size_t inpPlaneSize = width*height;666size_t outPlaneSize = outW*outH;667bool is1x1 = is1x1_;668669int stripesPerSample;670size_t stripeSize;671Range r = r0;672673if( nstripes >= batchSize*2 )674{675stripesPerSample = nstripes/batchSize;676stripeSize = alignSize((outPlaneSize + stripesPerSample - 1)/stripesPerSample, valign);677stripeSize = std::min(stripeSize, outPlaneSize);678}679else680{681stripesPerSample = 1;682int samplesPerStripe = std::max((batchSize + nstripes - 1)/nstripes, 1);683r.start *= samplesPerStripe;684r.end *= samplesPerStripe;685stripeSize = outPlaneSize;686}687688const float* data_inp0_ = input_->ptr<float>();689const int* ofstab = &ofstab_[0];690const float* wptr_orig_ = weights_->ptr<float>();691size_t wstep = weights_->step1();692const float* biasptr_ = &biasvec_->at(0);693const float* reluptr_ = reluslope_->empty() ? 0 : &reluslope_->at(0);694float* data_out0_ = output_->ptr<float>();695size_t rowbufsz = (size_t)karea*BLK_SIZE_CN*BLK_SIZE;696AutoBuffer<float> rowbuf0_(rowbufsz + valign);697float* rowbuf0 = alignPtr(rowbuf0_.data(), (int)(valign*sizeof(float)));698699// we clear the buffer once; ultimately, it lets us to avoid700// tail processing after running the unrolled/vectorized loop.701// the main idea is to make sure that the tail (a.k.a. padding) of each row702// (i.e. the elements with indices between vsz=karea*ncn and vsz_a)703// does not contain NaNs or Infs. Because the padding in the weights704// matrix is explicitly initialized with 0's, we handle all other705// cases nicely, i.e. we can skip expliciting re-initialization706// of the padding - we just retain elements from the previous iteration707// of the loop over channels (cn0).708memset(rowbuf0, 0, rowbufsz*sizeof(rowbuf0[0]) );709710for( int stripe = r.start; stripe < r.end; stripe++ )711{712int subsampleIdx = stripe/stripesPerSample;713if( subsampleIdx >= batchSize )714break;715int stripeStart = (int)((stripe - subsampleIdx*stripesPerSample)*stripeSize);716int stripeEnd = (int)std::min(stripeStart + stripeSize, outPlaneSize);717const float* data_inp0 = data_inp0_ + subsampleIdx*inpPlaneSize*inpCn;718float* data_out0 = data_out0_ + subsampleIdx*outPlaneSize*outCn;719int startOutCn = (subsampleIdx % ngroups)*outCn;720const float* wptr_orig = wptr_orig_ + wstep*startOutCn;721const float* biasptr = biasptr_ + startOutCn;722723for( int cn0 = 0; cn0 < inpCn; cn0 += BLK_SIZE_CN )724{725int cn1 = std::min(cn0 + BLK_SIZE_CN, inpCn);726int ncn = cn1 - cn0, vsz = karea*ncn;727int vsz_a = (int)alignSize(vsz, valign);728const float* wptr = wptr_orig + cn0*karea;729// we apply [Channels][P]ReLU (if any) during the final pass only.730const float* relu = cn1 == inpCn && reluptr_ ? reluptr_ + startOutCn : 0;731732for( int ofs0 = stripeStart; ofs0 < stripeEnd; ofs0 += BLK_SIZE )733{734int ofs, ofs1 = std::min(ofs0 + BLK_SIZE, stripeEnd);735int out_i = ofs0 / outW;736int out_j = ofs0 - out_i * outW;737738// do im2row for a part of input tensor739float* rowbuf = rowbuf0;740for( ofs = ofs0; ofs < ofs1; out_j = 0, ++out_i )741{742int delta = std::min(ofs1 - ofs, outW - out_j);743int out_j1 = out_j + delta;744int in_i = out_i * stride_h - pad_h;745int in_j = out_j * stride_w - pad_w;746const float* imgptr = data_inp0 + (cn0*height + in_i)*width + in_j;747ofs += delta;748749// do im2row for a part of input tensor750if( is1x1 )751{752for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w )753{754for( k = 0; k < vsz; k++ )755rowbuf[k] = imgptr[k*inpPlaneSize];756}757}758else759{760bool ok_i = 0 <= in_i && in_i < height - (kernel_h-1)*dilation_h;761int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);762int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);763764for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )765{766// this condition should be true for most of the tensor elements, i.e.767// most of the time the kernel aperture is inside the tensor X-Y plane.768if( ok_i && out_j + 2 <= out_j1 && 0 <= in_j && in_j + stride_w*2 <= width - (kernel_w-1)*dilation_w )769{770for( k = 0; k < vsz; k++ )771{772int k1 = ofstab[k];773float v0 = imgptr[k1];774float v1 = imgptr[k1 + stride_w];775rowbuf[k] = v0;776rowbuf[k+vsz_a] = v1;777}778out_j++;779rowbuf += vsz_a;780imgptr += stride_w;781in_j += stride_w;782}783else784{785int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);786int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);787788// here some non-continuous sub-row of the row will not be789// filled from the tensor; we need to make sure that the uncovered790// elements are explicitly set to 0's. the easiest way is to791// set all the elements to 0's before the loop.792memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));793for( k = 0; k < ncn; k++ )794{795for( i = i0; i < i1; i++ )796{797for( j = j0; j < j1; j++ )798{799int imgofs = k*(width*height) + i*(dilation_h*width) + j*dilation_w;800rowbuf[(k*kernel_h + i)*kernel_w + j] = imgptr[imgofs];801}802}803}804}805}806}807}808809// now compute dot product of the weights810// and im2row-transformed part of the tensor811int bsz = ofs1 - ofs0;812#if CV_TRY_AVX512_SKX813/* AVX512 convolution requires an alignment of 16, and ROI is only there for larger vector sizes */814if(useAVX512)815opt_AVX512_SKX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,816outShape, bsz, vsz, vsz_a, relu, cn0 == 0);817else818#endif819#if CV_TRY_AVX2820if(useAVX2)821opt_AVX2::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,822outShape, bsz, vsz, vsz_a, relu, cn0 == 0);823else824#endif825#if CV_TRY_AVX826if(useAVX)827opt_AVX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,828outShape, bsz, vsz, vsz_a, relu, cn0 == 0);829else830#endif831for( int i = 0; i < outCn; i += 2 )832{833const float* wptr0 = wptr + i*wstep;834const float* wptr1 = wptr0 + wstep;835float* outptr0 = data_out0 + ofs0 + i*outPlaneSize;836float* outptr1 = outptr0 + outPlaneSize;837float bias0 = biasptr[i], bias1 = biasptr[i+1];838float r0 = 1.f, r1 = 1.f;839840if( i+1 >= outCn )841{842wptr1 = wptr0;843outptr1 = outptr0;844bias1 = bias0;845}846847if( relu )848{849r0 = relu[i]; r1 = relu[i+1];850if( i+1 >= outCn )851r1 = r0;852}853854int j = 0;855#if CV_SIMD128856v_float32x4 vr0 = v_setall_f32(r0), vr1 = v_setall_f32(r1), z = v_setzero_f32();857858for( ; j <= bsz - 4; j += 4 )859{860const float* rptr = rowbuf0 + j*vsz_a;861v_float32x4 s0, s1;862863if( cn0 == 0 )864{865s0 = v_setall_f32(bias0);866s1 = v_setall_f32(bias1);867}868else869{870s0 = v_load(outptr0 + j);871s1 = v_load(outptr1 + j);872}873874v_float32x4 vs00 = v_setzero_f32(), vs01 = v_setzero_f32(),875vs02 = v_setzero_f32(), vs03 = v_setzero_f32(),876vs10 = v_setzero_f32(), vs11 = v_setzero_f32(),877vs12 = v_setzero_f32(), vs13 = v_setzero_f32();878for( k = 0; k < vsz; k += 4, rptr += 4 )879{880v_float32x4 w0 = v_load_aligned(wptr0 + k), w1 = v_load_aligned(wptr1 + k);881v_float32x4 r0 = v_load_aligned(rptr), r1 = v_load_aligned(rptr + vsz_a),882r2 = v_load_aligned(rptr + vsz_a*2), r3 = v_load_aligned(rptr + vsz_a*3);883884vs00 += w0*r0;885vs01 += w0*r1;886vs02 += w0*r2;887vs03 += w0*r3;888889vs10 += w1*r0;890vs11 += w1*r1;891vs12 += w1*r2;892vs13 += w1*r3;893}894s0 += v_reduce_sum4(vs00, vs01, vs02, vs03);895s1 += v_reduce_sum4(vs10, vs11, vs12, vs13);896if( relu )897{898s0 = v_select(s0 > z, s0, s0*vr0);899s1 = v_select(s1 > z, s1, s1*vr1);900}901902v_store(outptr0 + j, s0);903v_store(outptr1 + j, s1);904}905#endif906for( ; j < bsz; j++ )907{908const float* rptr = rowbuf0 + j*vsz_a;909float s00, s10;910911if( cn0 == 0 )912{913s00 = bias0;914s10 = bias1;915}916else917{918s00 = outptr0[j];919s10 = outptr1[j];920}921922for( k = 0; k < vsz; k++ )923{924float r0 = rptr[k];925s00 += wptr0[k]*r0;926s10 += wptr1[k]*r0;927}928if( relu )929{930s00 = s00 > 0.f ? s00 : s00*r0;931s10 = s10 > 0.f ? s10 : s10*r1;932}933934outptr0[j] = s00;935outptr1[j] = s10;936}937}938}939}940941if( activ_ )942activ_->forwardSlice(data_out0 + stripeStart, data_out0 + stripeStart,943(int)(stripeEnd - stripeStart),944outPlaneSize, startOutCn, startOutCn + outCn);945}946}947};948949#ifdef HAVE_OPENCL950bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)951{952std::vector<UMat> inputs;953std::vector<UMat> outputs;954955bool use_half = (inps.depth() == CV_16S);956inps.getUMatVector(inputs);957outs.getUMatVector(outputs);958959CV_Assert(outputs.size() == 1);960for (int i = 0; i < inputs.size(); ++i)961CV_Assert(inputs[i].u != outputs[0].u);962963if (umat_blobs.empty())964{965size_t n = blobs.size();966umat_blobs.resize(n);967for (size_t i = 0; i < n; i++)968{969blobs[i].copyTo(umat_blobs[i]);970}971}972973if (convolutionOp.empty())974{975OCL4DNNConvConfig config;976config.in_shape = shape(inputs[0]);977config.out_shape = shape(outputs[0]);978config.kernel = kernel;979config.pad = pad;980config.stride = stride;981config.dilation = dilation;982config.group = inputs[0].size[1] / umat_blobs[0].size[1];983config.bias_term = (hasBias()) ? true : false;984config.use_half = use_half;985986convolutionOp = Ptr<OCL4DNNConvSpatial<float> >(new OCL4DNNConvSpatial<float>(config));987}988989int outCn = umat_blobs[0].size[0];990991reluslope.clear();992if( activ )993{994Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();995if( !activ_relu.empty() )996{997reluslope.assign(outCn+2, activ_relu->negativeSlope);998activType = OCL4DNN_CONV_FUSED_ACTIV_RELU;999}10001001Ptr<ReLU6Layer> activ_relu6 = activ.dynamicCast<ReLU6Layer>();1002if( !activ_relu6.empty() )1003{1004reluslope.resize(2);1005reluslope[0] = activ_relu6->minValue;1006reluslope[1] = activ_relu6->maxValue;1007activType = OCL4DNN_CONV_FUSED_ACTIV_RELU6;1008}10091010Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();1011if( !activ_chprelu.empty() )1012{1013const Mat& m = activ_chprelu->blobs[0];1014CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);1015const float* mdata = m.ptr<float>();1016reluslope.resize(outCn+2);1017std::copy(mdata, mdata + outCn, reluslope.begin());1018reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];1019activType = OCL4DNN_CONV_FUSED_ACTIV_PRELU;1020}1021}10221023if ( newWeightAndBias )1024{1025weightsMat.copyTo(umat_blobs[0]);1026if ( fusedBias )1027{1028if ( umat_blobs.size() < 2 )1029umat_blobs.resize(2);1030umat_blobs[1] = UMat(biasvec, true);1031}1032convolutionOp->setBias(fusedBias || hasBias());1033newWeightAndBias = false;1034}10351036if ( newActiv )1037{1038if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU )1039{1040CV_Assert(!reluslope.empty());1041convolutionOp->setActivReLU(true, reluslope[0]);1042}1043else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_PRELU)1044{1045CV_Assert(!reluslope.empty());1046convolutionOp->setActivPReLU(true, reluslope);1047}1048else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_POWER)1049{1050convolutionOp->setActivPower(true, power);1051}1052else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_TANH)1053{1054convolutionOp->setActivTanh(true);1055}1056else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU6)1057{1058convolutionOp->setActivReLU6(true, reluslope[0], reluslope[1]);1059}1060else1061{1062convolutionOp->setActivReLU(false, 0);1063convolutionOp->setActivPReLU(false, reluslope);1064convolutionOp->setActivPower(false, 1.f);1065convolutionOp->setActivTanh(false);1066convolutionOp->setActivReLU6(false, 0, 0);1067}1068newActiv = false;1069}10701071UMat& inpMat = inputs[0];1072UMat& outMat = outputs[0];1073int batch_size = inpMat.size[0];10741075return convolutionOp->Forward(inpMat,1076inputs.size() == 2 ? inputs[1] : UMat(),1077umat_blobs[0],1078(hasBias() || fusedBias) ? umat_blobs[1] : UMat(),1079outMat,1080batch_size);1081}1082#endif10831084void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE1085{1086CV_TRACE_FUNCTION();1087CV_TRACE_ARG_VALUE(name, "name", name.c_str());10881089CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),1090forward_ocl(inputs_arr, outputs_arr, internals_arr))10911092if (inputs_arr.depth() == CV_16S)1093{1094forward_fallback(inputs_arr, outputs_arr, internals_arr);1095return;1096}10971098std::vector<Mat> inputs, outputs;1099inputs_arr.getMatVector(inputs);1100outputs_arr.getMatVector(outputs);11011102/*printf("conv %s: input (%d x %d x %d x %d), kernel (%d x %d), pad (%d x %d), stride (%d x %d), dilation (%d x %d)\n",1103name.c_str(), inputs[0].size[0], inputs[0].size[1], inputs[0].size[2], inputs[0].size[3],1104kernel.width, kernel.height, pad.width, pad.height,1105stride.width, stride.height, dilation.width, dilation.height);*/1106CV_Assert_N(inputs.size() == (size_t)1, inputs[0].size[1] % blobs[0].size[1] == 0,1107outputs.size() == 1, inputs[0].data != outputs[0].data);11081109int ngroups = inputs[0].size[1]/blobs[0].size[1];1110CV_Assert(outputs[0].size[1] % ngroups == 0);1111int outCn = blobs[0].size[0];11121113reluslope.clear();1114if( activ )1115{1116Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();1117if( !activ_relu.empty() )1118{1119reluslope.assign(outCn+2, activ_relu->negativeSlope);1120}11211122Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();1123if( !activ_chprelu.empty() )1124{1125const Mat& m = activ_chprelu->blobs[0];1126CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);1127const float* mdata = m.ptr<float>();1128reluslope.resize(outCn+2);1129std::copy(mdata, mdata + outCn, reluslope.begin());1130reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];1131}1132}11331134int nstripes = std::max(getNumThreads(), 1);11351136ParallelConv::run(inputs[0], outputs[0], weightsMat, biasvec, reluslope,1137kernel, pad, stride, dilation, activ.get(), ngroups, nstripes);1138}11391140virtual int64 getFLOPS(const std::vector<MatShape> &inputs,1141const std::vector<MatShape> &outputs) const CV_OVERRIDE1142{1143CV_Assert(inputs.size() == outputs.size());11441145int64 flops = 0;1146for (int i = 0; i < inputs.size(); i++)1147{1148flops += total(outputs[i])*(CV_BIG_INT(2)*kernel.area()*inputs[i][1] + 1);1149}11501151return flops;1152}1153};11541155class DeConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl1156{1157public:1158Mat weightsMat, biasesMat;1159UMat umat_weights;1160UMat umat_biases;11611162DeConvolutionLayerImpl(const LayerParams& params) : BaseConvolutionLayerImpl(params) {}11631164MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE1165{1166int inpCn = inpShape[1];1167int inpH = inpShape[2];1168int inpW = inpShape[3];1169int outCn = outShape[1];1170int ngroups = inpCn / blobs[0].size[0];1171int outGroupCn = outCn / ngroups;1172int ksize = outGroupCn * kernel.height * kernel.width;1173return shape(ksize, inpH * inpW);1174}11751176virtual bool supportBackend(int backendId) CV_OVERRIDE1177{1178#ifdef HAVE_INF_ENGINE1179if (backendId == DNN_BACKEND_INFERENCE_ENGINE)1180{1181const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW layout1182const int group = numOutput / outGroupCn;1183if (group != 1)1184{1185#if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2018R3)1186return preferableTarget == DNN_TARGET_CPU;1187#endif1188return false;1189}1190if (preferableTarget == DNN_TARGET_OPENCL || preferableTarget == DNN_TARGET_OPENCL_FP16)1191return dilation.width == 1 && dilation.height == 1;1192return true;1193}1194else1195#endif // HAVE_INF_ENGINE1196return backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE;1197}11981199bool getMemoryShapes(const std::vector<MatShape> &inputs,1200const int requiredOutputs,1201std::vector<MatShape> &outputs,1202std::vector<MatShape> &internals) const CV_OVERRIDE1203{1204CV_Assert(!hasBias() || blobs[1].total() == (size_t)numOutput);1205CV_Assert(inputs.size() != 0);12061207int inpCn = inputs[0][1];1208int inpH = inputs[0][2];1209int inpW = inputs[0][3];12101211int outH = -1, outW = -1;1212if (padMode.empty())1213{1214outH = stride.height * (inpH - 1) + kernel.height - 2 * pad.height + adjustPad.height;1215outW = stride.width * (inpW - 1) + kernel.width - 2 * pad.width + adjustPad.width;1216}1217else if (padMode == "VALID")1218{1219outH = stride.height * (inpH - 1) + kernel.height + adjustPad.height;1220outW = stride.width * (inpW - 1) + kernel.width + adjustPad.width;1221}1222else if (padMode == "SAME")1223{1224outH = stride.height * (inpH - 1) + 1 + adjustPad.height;1225outW = stride.width * (inpW - 1) + 1 + adjustPad.width;1226}1227else1228CV_Error(Error::StsError, "Unsupported padding mode " + padMode);12291230int outCn = numOutput;12311232CV_Assert(outCn % blobs[0].size[1] == 0);1233int ngroups = outCn / blobs[0].size[1];12341235CV_Assert(inpCn % ngroups == 0 && outCn % ngroups == 0);1236CV_Assert(blobs[0].size[0] == inpCn);12371238int dims[] = {inputs[0][0], outCn, outH, outW};1239outputs.resize(inputs.size(), shape(dims, 4));12401241internals.push_back(MatShape());1242if (!is1x1())1243internals[0] = computeColRowShape(inputs[0], outputs[0]);12441245if (hasBias())1246internals.push_back(shape(1, outH*outW));12471248return false;1249}12501251void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE1252{1253BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);12541255std::vector<Mat> inputs, outputs;1256inputs_arr.getMatVector(inputs);1257outputs_arr.getMatVector(outputs);12581259int pad_t = pad.height, pad_l = pad.width, pad_b = pad.height, pad_r = pad.width;1260getConvPoolPaddings(Size(outputs[0].size[3], outputs[0].size[2]),1261Size(inputs[0].size[3], inputs[0].size[2]),1262kernel, stride, padMode, dilation, pad_t, pad_l, pad_b, pad_r);12631264if (pad_t != pad_b || pad_l != pad_r)1265CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");12661267pad.width = pad_l;1268pad.height = pad_t;1269}12701271class MatMulInvoker : public ParallelLoopBody1272{1273public:1274MatMulInvoker(const Mat& a, const Mat& b, Mat& c, int nstripes)1275{1276a_ = &a;1277b_ = &b;1278c_ = &c;1279nstripes_ = nstripes;1280useAVX = checkHardwareSupport(CPU_AVX);1281useAVX2 = checkHardwareSupport(CPU_AVX2);1282useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;1283}12841285void operator()(const Range& range_) const CV_OVERRIDE1286{1287int stripeSize = (int)alignSize((b_->cols + nstripes_ - 1)/nstripes_, 16);1288Range range(range_.start*stripeSize, std::min(range_.end*stripeSize, b_->cols));1289int mmax = a_->rows;1290int nmax = range.end - range.start;1291int kmax = a_->cols;1292int m, n, k;1293const float* aptr = a_->ptr<float>();1294const float* bptr = b_->ptr<float>() + range.start;1295float* cptr = c_->ptr<float>() + range.start;1296size_t astep = a_->step1();1297size_t bstep = b_->step1();1298size_t cstep = c_->step1();12991300#if CV_TRY_AVX512_SKX1301if( useAVX512 )1302opt_AVX512_SKX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );1303else1304#endif1305#if CV_TRY_AVX21306if( useAVX2 )1307opt_AVX2::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );1308else1309#endif1310#if CV_TRY_AVX1311if( useAVX )1312opt_AVX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );1313else1314#endif1315for( m = 0; m < mmax; m += 2 )1316{1317float* dst0 = cptr + cstep*m;1318float* dst1 = cptr + cstep*std::min(m+1, mmax-1);1319const float* aptr0 = aptr + astep*m;1320const float* aptr1 = aptr + astep*std::min(m+1, mmax-1);13211322for( n = 0; n < nmax; n++ )1323{1324dst0[n] = 0.f;1325dst1[n] = 0.f;1326}13271328for( k = 0; k < kmax; k += 4 )1329{1330float alpha00 = aptr0[k];1331float alpha01 = aptr1[k];1332float alpha10 = 0.f, alpha11 = 0.f;1333float alpha20 = 0.f, alpha21 = 0.f;1334float alpha30 = 0.f, alpha31 = 0.f;1335const float* bptr0 = bptr + k*bstep;1336const float* bptr1 = bptr0;1337const float* bptr2 = bptr0;1338const float* bptr3 = bptr0;13391340if( k+1 < kmax )1341{1342alpha10 = aptr0[k+1];1343alpha11 = aptr1[k+1];1344bptr1 = bptr0 + bstep;1345if( k+2 < kmax )1346{1347alpha20 = aptr0[k+2];1348alpha21 = aptr1[k+2];1349bptr2 = bptr1 + bstep;1350if( k+3 < kmax )1351{1352alpha30 = aptr0[k+3];1353alpha31 = aptr1[k+3];1354bptr3 = bptr2 + bstep;1355}1356}1357}1358n = 0;13591360#if CV_SIMD1281361v_float32x4 a00 = v_setall_f32(alpha00);1362v_float32x4 a01 = v_setall_f32(alpha01);1363v_float32x4 a10 = v_setall_f32(alpha10);1364v_float32x4 a11 = v_setall_f32(alpha11);1365v_float32x4 a20 = v_setall_f32(alpha20);1366v_float32x4 a21 = v_setall_f32(alpha21);1367v_float32x4 a30 = v_setall_f32(alpha30);1368v_float32x4 a31 = v_setall_f32(alpha31);13691370for( ; n <= nmax - 4; n += 4 )1371{1372v_float32x4 b0 = v_load(bptr0 + n);1373v_float32x4 b1 = v_load(bptr1 + n);1374v_float32x4 b2 = v_load(bptr2 + n);1375v_float32x4 b3 = v_load(bptr3 + n);1376v_float32x4 d0 = v_load(dst0 + n);1377v_float32x4 d1 = v_load(dst1 + n);1378d0 += b0*a00;1379d1 += b0*a01;1380d0 += b1*a10;1381d1 += b1*a11;1382d0 += b2*a20;1383d1 += b2*a21;1384d0 += b3*a30;1385d1 += b3*a31;1386v_store(dst0 + n, d0);1387v_store(dst1 + n, d1);1388}1389#endif13901391for( ; n < nmax; n++ )1392{1393float b0 = bptr0[n], b1 = bptr1[n];1394float b2 = bptr2[n], b3 = bptr3[n];1395float d0 = dst0[n] + alpha00*b0 + alpha10*b1 + alpha20*b2 + alpha30*b3;1396float d1 = dst1[n] + alpha01*b0 + alpha11*b1 + alpha21*b2 + alpha31*b3;1397dst0[n] = d0;1398dst1[n] = d1;1399}1400}1401}1402}14031404const Mat *a_, *b_;1405Mat* c_;1406int nstripes_;1407bool useAVX;1408bool useAVX2;1409bool useAVX512;1410};14111412class Col2ImInvoker : public cv::ParallelLoopBody1413{1414public:1415const float* data_col;1416const float* biasvec;1417int channels, height, width;1418int kernel_h, kernel_w;1419int pad_h, pad_w;1420int stride_h, stride_w;1421float* data_im;1422int height_col, width_col;1423int nstripes;1424bool is1x1;14251426Col2ImInvoker()1427: data_col(0), biasvec(0), channels(0), height(0), width(0),1428kernel_h(0), kernel_w(0), pad_h(0), pad_w(0), stride_h(0), stride_w(0), data_im(0),1429height_col(0), width_col(0), nstripes(0), is1x1(0)1430{}14311432static void run(const float* data_col,1433int channels, int height, int width,1434int kernel_h, int kernel_w,1435int pad_h, int pad_w,1436int stride_h, int stride_w,1437int height_col, int width_col,1438float* data_im,1439const float* biasvec,1440bool is1x1)1441{1442const int nstripes = getNumThreads();14431444Col2ImInvoker t;1445t.data_col = data_col;1446t.data_im = data_im;1447t.channels = channels; t.height = height; t.width = width;1448t.kernel_h = kernel_h; t.kernel_w = kernel_w;1449t.pad_h = pad_h; t.pad_w = pad_w;1450t.stride_h = stride_h; t.stride_w = stride_w;1451t.height_col = height_col;1452t.width_col = width_col;1453t.nstripes = nstripes;1454t.is1x1 = is1x1;1455t.biasvec = biasvec;14561457parallel_for_(Range(0, nstripes), t, nstripes);1458}14591460virtual void operator ()(const Range &r) const CV_OVERRIDE1461{1462const float* data_col_ = data_col;1463float* data_im_ = data_im;1464int coeff_h = (1 - stride_h * kernel_w * height_col) * width_col;1465int coeff_w = (1 - stride_w * height_col * width_col);1466size_t total = (size_t)channels * height * width;1467size_t stripeSize = (total + nstripes - 1)/nstripes;1468size_t startIndex = r.start*stripeSize;1469size_t endIndex = std::min(r.end*stripeSize, total);1470int w = (int)(startIndex % width + pad_w);1471int h = (int)((startIndex / width) % height + pad_h);1472int c = (int)(startIndex / (width * height));1473int h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;1474int h_col_end = std::min(h / stride_h + 1, height_col);1475int plane_size_col = height_col * width_col;1476int offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;1477bool is1x1_ = is1x1;1478const float* biasvec_ = biasvec;14791480for (size_t index = startIndex; index < endIndex; index++)1481{1482// compute the start and end of the output1483int w_col_start = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1;1484int w_col_end = std::min(w / stride_w + 1, width_col);1485float val;14861487if( is1x1_ )1488val = data_im_[index];1489else1490{1491val = 0.f;1492for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {1493for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {1494val += data_col_[offset + h_col * coeff_h + w_col * coeff_w];1495}1496}1497}1498data_im_[index] = val + biasvec_[c];14991500offset += plane_size_col;1501if( ++w >= width + pad_w )1502{1503w = (int)((index + 1)% width + pad_w);1504h = (int)(((index + 1) / width) % height + pad_h);1505c = (int)((index + 1) / (width * height));1506h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;1507h_col_end = std::min(h / stride_h + 1, height_col);1508offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;1509}1510}1511}1512};15131514#ifdef HAVE_OPENCL1515bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)1516{1517std::vector<UMat> inputs;1518std::vector<UMat> outputs;1519std::vector<UMat> internals;15201521if (inputs_.depth() == CV_16S)1522return false;15231524inputs_.getUMatVector(inputs);1525outputs_.getUMatVector(outputs);1526internals_.getUMatVector(internals);15271528int outCn = numOutput;1529int inpCn = inputs[0].size[1];15301531if (is1x1())1532return false;15331534if (umat_weights.empty())1535{1536transpose(blobs[0].reshape(1, inpCn), umat_weights);1537if (hasBias())1538blobs[1].reshape(1, outCn).copyTo(umat_biases);1539else1540umat_biases = UMat::zeros(outCn, 1, CV_32F);1541}15421543String buildopt = format("-DT=%s ", ocl::typeToStr(inputs[0].type()));1544buildopt += format("-DPAD_H=%d -DPAD_W=%d -DKERNEL_H=%d -DKERNEL_W=%d -DSTRIDE_H=%d -DSTRIDE_W=%d ",1545pad.height, pad.width, kernel.height, kernel.width, stride.height, stride.width);15461547for (size_t ii = 0; ii < outputs.size(); ii++)1548{1549int ngroups = outCn / blobs[0].size[1];1550int inpGroupCn = inpCn / ngroups;1551int outGroupCn = blobs[0].size[1];1552const UMat& inp = inputs[ii];1553UMat& out = outputs[ii];1554int numImg = inp.size[0];1555int inpH = inp.size[2], inpW = inp.size[3];1556int outH = out.size[2], outW = out.size[3];15571558MatShape inpshape = shape(numImg*inpCn, inpH*inpW);1559MatShape outshape = shape(numImg*outCn, outH*outW);1560UMat convBlob = inputs[ii].reshape(1, inpshape.size(), &inpshape[0]);1561UMat decnBlob = out.reshape(1, outshape.size(), &outshape[0]);1562int rows = internals[0].rows / ngroups;15631564for (int n = 0; n < numImg; n++)1565{1566for (int g = 0; g < ngroups; g++)1567{1568UMat colMat = internals[0].rowRange(_Range(g * rows, rows));1569UMat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));1570UMat wghtMat = umat_weights.colRange(_Range(g * inpGroupCn, inpGroupCn));1571gemm(wghtMat, convMat, 1, noArray(), 0, colMat, 0);1572}15731574for (int g = 0; g < ngroups; g++)1575{1576int total = outGroupCn * decnBlob.cols;1577int index = 0;1578int height_col = inpH;1579int width_col = inpW;1580int coeff_h = (1 - stride.height * kernel.width * height_col) * width_col;1581int coeff_w = (1 - stride.width * height_col * width_col);15821583ocl::Kernel k("col2im", ocl::dnn::col2im_oclsrc, buildopt);1584k.set(index++, total);1585k.set(index++, ocl::KernelArg::PtrReadOnly(internals[0]));1586k.set(index++, (int)(g * rows * internals[0].cols));1587k.set(index++, outGroupCn);1588k.set(index++, outH);1589k.set(index++, outW);1590k.set(index++, height_col);1591k.set(index++, width_col);1592k.set(index++, coeff_h);1593k.set(index++, coeff_w);1594k.set(index++, ocl::KernelArg::PtrReadOnly(umat_biases));1595k.set(index++, (int)(g * outGroupCn * umat_biases.cols));1596k.set(index++, ocl::KernelArg::PtrWriteOnly(decnBlob));1597k.set(index++, (int)((g + n * ngroups) * outGroupCn * decnBlob.cols));15981599size_t global[] = { (size_t)total };1600bool ret = k.run(1, global, NULL, false);1601if (!ret)1602return false;1603}1604}1605}16061607return true;1608}1609#endif16101611void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE1612{1613CV_TRACE_FUNCTION();1614CV_TRACE_ARG_VALUE(name, "name", name.c_str());16151616CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),1617forward_ocl(inputs_arr, outputs_arr, internals_arr));16181619if (inputs_arr.depth() == CV_16S)1620{1621forward_fallback(inputs_arr, outputs_arr, internals_arr);1622return;1623}16241625std::vector<Mat> inputs, outputs, internals;1626inputs_arr.getMatVector(inputs);1627outputs_arr.getMatVector(outputs);1628internals_arr.getMatVector(internals);16291630int outCn = numOutput;1631int inpCn = inputs[0].size[1];1632bool is1x1flag = is1x1();1633int nstripes = getNumThreads();16341635if( weightsMat.empty() )1636{1637transpose(blobs[0].reshape(1, inpCn), weightsMat);1638biasesMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);1639}16401641for (size_t ii = 0; ii < outputs.size(); ii++)1642{1643int ngroups = outCn / blobs[0].size[1];1644int inpGroupCn = inpCn / ngroups;1645int outGroupCn = blobs[0].size[1];1646const Mat& inp = inputs[ii];1647Mat& out = outputs[ii];1648int numImg = inp.size[0];1649int inpH = inp.size[2], inpW = inp.size[3];1650int outH = out.size[2], outW = out.size[3];16511652Mat convBlob = inputs[ii].reshape(1, numImg*inpCn);1653Mat decnBlob = out.reshape(1, numImg*outCn);16541655for (int n = 0; n < numImg; n++)1656{1657for (int g = 0; g < ngroups; g++)1658{1659Mat dstMat = decnBlob.rowRange(_Range((g + n * ngroups) * outGroupCn, outGroupCn));1660Mat &colMat = is1x1flag ? dstMat : internals[0];16611662Mat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));1663Mat wghtMat = weightsMat.colRange(_Range(g * inpGroupCn, inpGroupCn));1664Mat curBiasMat = biasesMat.rowRange(_Range(g * outGroupCn, outGroupCn));16651666//gemm(wghtMat, convMat, 1, colMat, 0, colMat, 0);1667MatMulInvoker mminvoker(wghtMat, convMat, colMat, nstripes);1668parallel_for_(Range(0, nstripes), mminvoker, nstripes);16691670Col2ImInvoker::run(colMat.ptr<float>(), outGroupCn, outH, outW,1671kernel.height, kernel.width, pad.height, pad.width,1672stride.height, stride.width, inpH, inpW, dstMat.ptr<float>(),1673curBiasMat.ptr<float>(), is1x1flag);1674}1675}1676}1677}16781679virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE1680{1681#ifdef HAVE_HALIDE1682Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);16831684int inW, inH, inC, inN;1685getCanonicalSize(inputBuffer, &inW, &inH, &inC, &inN);1686const int outGroupCn = blobs[0].size[1];1687const int group = numOutput / outGroupCn;1688const int inpGroupCn = blobs[0].size[0] / group;16891690Halide::Var x("x"), y("y"), c("c"), n("n");1691Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));1692Halide::Func padded_input(name + "_constant_exterior");1693auto weights = wrapToHalideBuffer(blobs[0]);16941695Halide::Func dilated_input("dilated_input");1696dilated_input(x, y, c, n) = 0.0f;1697Halide::RDom r1(0, inW, 0, inH);1698dilated_input(r1.x * stride.width, r1.y * stride.height, c, n) =1699inputBuffer(r1.x, r1.y, c, n);1700dilated_input.compute_root();17011702Halide::Func bounded =1703Halide::BoundaryConditions::constant_exterior(dilated_input, 0,17040, (inW - 1) * stride.width + 1,17050, (inH - 1) * stride.height + 1,17060, inC, 0, inN);1707padded_input(x, y, c, n) = bounded(x, y, c, n);17081709Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);1710Halide::Expr kx = x + pad.width - r.x;1711Halide::Expr ky = y + pad.height - r.y;1712Halide::Expr kInC = r.z;1713Halide::Expr kOutC = c;1714for (int i = 1; i < group; ++i)1715{1716kInC = select(c < outGroupCn * i, kInC, inpGroupCn * i + r.z);1717kOutC = select(c < outGroupCn * i, kOutC, c - outGroupCn * i);1718}1719Halide::Expr topExpr = sum(padded_input(kx, ky, kInC, n) *1720weights(r.x, r.y, kOutC, kInC));1721if (hasBias())1722{1723auto bias = wrapToHalideBuffer(blobs[1], {numOutput});1724topExpr += bias(c);1725}1726top(x, y, c, n) = topExpr;1727return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));1728#endif // HAVE_HALIDE1729return Ptr<BackendNode>();1730}17311732virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &) CV_OVERRIDE1733{1734#ifdef HAVE_INF_ENGINE1735const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW layout1736const int group = numOutput / outGroupCn;17371738InferenceEngine::LayerParams lp;1739lp.name = name;1740lp.type = "Deconvolution";1741lp.precision = InferenceEngine::Precision::FP32;1742std::shared_ptr<InferenceEngine::DeconvolutionLayer> ieLayer(new InferenceEngine::DeconvolutionLayer(lp));17431744#if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2018R3)1745ieLayer->_kernel.insert(InferenceEngine::X_AXIS, kernel.width);1746ieLayer->_kernel.insert(InferenceEngine::Y_AXIS, kernel.height);1747ieLayer->_stride.insert(InferenceEngine::X_AXIS, stride.width);1748ieLayer->_stride.insert(InferenceEngine::Y_AXIS, stride.height);1749ieLayer->_padding.insert(InferenceEngine::X_AXIS, pad.width);1750ieLayer->_padding.insert(InferenceEngine::Y_AXIS, pad.height);1751ieLayer->_pads_end.insert(InferenceEngine::X_AXIS, pad.width);1752ieLayer->_pads_end.insert(InferenceEngine::Y_AXIS, pad.height);1753ieLayer->_dilation.insert(InferenceEngine::X_AXIS, dilation.width);1754ieLayer->_dilation.insert(InferenceEngine::Y_AXIS, dilation.height);1755#else1756ieLayer->_kernel_x = kernel.width;1757ieLayer->_kernel_y = kernel.height;1758ieLayer->_stride_x = stride.width;1759ieLayer->_stride_y = stride.height;1760ieLayer->_padding_x = pad.width;1761ieLayer->_padding_y = pad.height;1762ieLayer->_dilation_x = dilation.width;1763ieLayer->_dilation_y = dilation.height;1764#endif1765ieLayer->_out_depth = numOutput;1766ieLayer->_group = group;17671768ieLayer->_weights = wrapToInfEngineBlob(blobs[0], InferenceEngine::Layout::OIHW);1769if (hasBias())1770{1771ieLayer->_biases = wrapToInfEngineBlob(blobs[1], {(size_t)numOutput}, InferenceEngine::Layout::C);1772}1773return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));1774#endif // HAVE_INF_ENGINE1775return Ptr<BackendNode>();1776}17771778virtual int64 getFLOPS(const std::vector<MatShape> &inputs,1779const std::vector<MatShape> &outputs) const CV_OVERRIDE1780{1781CV_Assert(inputs.size() == outputs.size());17821783float flops = 0;1784int outChannels = blobs[0].size[0];17851786for (int i = 0; i < inputs.size(); i++)1787{1788flops += CV_BIG_INT(2)*outChannels*kernel.area()*total(inputs[i]);1789}17901791return flops;1792}1793};17941795Ptr<BaseConvolutionLayer> ConvolutionLayer::create(const LayerParams ¶ms)1796{1797Ptr<ConvolutionLayerImpl> l(new ConvolutionLayerImpl(params));1798return l;1799}18001801Ptr<BaseConvolutionLayer> DeconvolutionLayer::create(const LayerParams ¶ms)1802{1803return Ptr<BaseConvolutionLayer>(new DeConvolutionLayerImpl(params));1804}18051806}1807}180818091810