1 /*M///////////////////////////////////////////////////////////////////////////////////////
3 // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
5 // By downloading, copying, installing or using the software you agree to this license.
6 // If you do not agree to this license, do not download, install,
7 // copy or use the software.
11 // For Open Source Computer Vision Library
13 // Copyright (C) 2013, OpenCV Foundation, all rights reserved.
14 // Copyright (C) 2017, Intel Corporation, all rights reserved.
15 // Third party copyrights are property of their respective owners.
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
20 // * Redistribution's of source code must retain the above copyright notice,
21 // this list of conditions and the following disclaimer.
23 // * Redistribution's in binary form must reproduce the above copyright notice,
24 // this list of conditions and the following disclaimer in the documentation
25 // and/or other materials provided with the distribution.
27 // * The name of the copyright holders may not be used to endorse or promote products
28 // derived from this software without specific prior written permission.
30 // This software is provided by the copyright holders and contributors "as is" and
31 // any express or implied warranties, including, but not limited to, the implied
32 // warranties of merchantability and fitness for a particular purpose are disclaimed.
33 // In no event shall the Intel Corporation or contributors be liable for any direct,
34 // indirect, incidental, special, exemplary, or consequential damages
35 // (including, but not limited to, procurement of substitute goods or services;
36 // loss of use, data, or profits; or business interruption) however caused
37 // and on any theory of liability, whether in contract, strict liability,
38 // or tort (including negligence or otherwise) arising in any way out of
39 // the use of this software, even if advised of the possibility of such damage.
43 #include "../precomp.hpp"
44 #include "layers_common.hpp"
45 #include "../op_halide.hpp"
46 #include "../op_inf_engine.hpp"
47 #include "../op_vkcom.hpp"
48 #include "opencv2/core/hal/hal.hpp"
49 #include "opencv2/core/hal/intrin.hpp"
54 #include "opencl_kernels_dnn.hpp"
55 using namespace cv::dnn::ocl4dnn;
63 class BaseConvolutionLayerImpl : public ConvolutionLayer
66 bool fusedWeights, fusedBias;
67 std::vector<double> weightsMultipliers;
68 BaseConvolutionLayerImpl(const LayerParams ¶ms)
70 setParamsFrom(params);
71 getConvolutionKernelParams(params, kernel_size, pads_begin, pads_end, strides, dilations, padMode, adjust_pads);
73 numOutput = params.get<int>("num_output");
74 int ngroups = params.get<int>("group", 1);
75 CV_Assert(numOutput % ngroups == 0);
77 if (kernel_size.size() == 2) {
78 kernel = Size(kernel_size[1], kernel_size[0]);
79 stride = Size(strides[1], strides[0]);
80 for (int i = 0; i < pads_begin.size(); i++) {
81 if (pads_begin[i] != pads_end[i])
82 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
84 pad = Size(pads_begin[1], pads_begin[0]);
85 dilation = Size(dilations[1], dilations[0]);
87 adjustPad.height = adjust_pads[0];
88 adjustPad.width = adjust_pads[1];
91 for (int i = 0; i < adjust_pads.size(); i++) {
92 CV_Assert(adjust_pads[i] < strides[i]);
99 virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
101 std::vector<Mat> inputs, outputs;
102 inputs_arr.getMatVector(inputs);
103 outputs_arr.getMatVector(outputs);
105 CV_Assert(inputs.size() > 0);
107 CV_Assert(blobs.size() == 1 || blobs.size() == 2);
108 CV_Assert(inputs[0].dims == outputs[0].dims);
109 CV_Assert(blobs[0].dims == kernel_size.size() + 2);
110 for (int i = 0; i < kernel_size.size(); i++) {
111 CV_Assert(blobs[0].size[i + 2] == kernel_size[i]);
114 const Mat &input = inputs[0];
115 CV_Assert((input.dims == 4 || input.dims == 5) && (input.type() == CV_32F || input.type() == CV_16S));
116 for (size_t i = 0; i < inputs.size(); i++)
118 CV_Assert(inputs[i].type() == input.type());
119 CV_Assert((inputs[i].dims == 4 || inputs[i].dims == 5) && inputs[i].size[1] == input.size[1]);
120 for (int j = 0; j < inputs[i].dims; j++) {
121 CV_Assert(inputs[i].size[j] == input.size[j]);
125 std::vector<int> inpShape;
126 std::vector<int> outShape;
127 for (int i = 2; i < inputs[0].dims; i++) {
128 inpShape.push_back(inputs[0].size[i]);
129 outShape.push_back(outputs[0].size[i]);
131 getConvPoolPaddings(inpShape, kernel_size, strides, padMode, pads_begin, pads_end);
132 if (pads_begin.size() == 2) {
133 for (int i = 0; i < pads_begin.size(); i++) {
134 if (pads_begin[i] != pads_end[i])
135 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
137 pad = Size(pads_begin[1], pads_begin[0]);
139 fusedWeights = false;
145 return blobs.size() >= 2;
148 virtual MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const = 0;
151 return (kernel.height == 1 && kernel.width == 1) &&
152 (stride.height == 1 && stride.width == 1) &&
153 (dilation.height == 1 && dilation.width == 1);
156 virtual bool tryFuse(Ptr<Layer>& top) CV_OVERRIDE
159 top->getScaleShift(w, b);
160 if (!w.empty() || !b.empty())
163 fusedWeights = fusedWeights || !w.empty();
164 fusedBias = fusedBias || (hasBias() && !w.empty()) || !b.empty();
170 virtual void fuseWeights(const Mat& w_, const Mat& b_) = 0;
172 virtual void applyHalideScheduler(Ptr<BackendNode>& node,
173 const std::vector<Mat*> &inputs,
174 const std::vector<Mat> &outputs,
175 int targetId) const CV_OVERRIDE
178 if (targetId != DNN_TARGET_CPU)
180 Layer::applyHalideScheduler(node, inputs, outputs, targetId);
183 Halide::Var x("x"), y("y"), c("c"), n("n"), tile("tile"), yi("yi"), yo("yo"), co("co"), ci("ci");
184 Halide::Func& top = node.dynamicCast<HalideBackendNode>()->funcs[1];
185 Halide::Func& padded_input = node.dynamicCast<HalideBackendNode>()->funcs[0];
187 int outW, outH, outC, outN;
188 getCanonicalSize(outputs[0].size, &outW, &outH, &outC, &outN);
190 if (outW == 1 || outH <= 2)
193 if (is1x1() || outC <= 16)
199 .vectorize(x, outW >= 16 ? 16 : outW);
203 .split(c, co, ci, 16)
204 .fuse(yo, co, tile).fuse(n, tile, tile)
207 .vectorize(x, outW >= 16 ? 16 : outW);
208 padded_input.compute_at(top, yi);
209 #endif // HAVE_HALIDE
214 #define IS_POWER_LAYER(layer) \
215 (!layer.empty() && !layer->type.compare("Power"))
216 //TODO: simultaneously convolution and bias addition for cache optimization
217 class ConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
220 enum { VEC_ALIGN = 8, DFT_TYPE = CV_32F };
222 std::vector<float> biasvec;
223 std::vector<float> reluslope;
224 Ptr<ActivationLayer> activ;
227 Ptr<OCL4DNNConvSpatial<float> > convolutionOp;
228 std::vector<UMat> umat_blobs;
230 ocl4dnnFusedActiv_t activType;
233 ConvolutionLayerImpl(const LayerParams ¶ms) : BaseConvolutionLayerImpl(params)
237 activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
242 MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
244 int dims = inpShape.size();
245 int inpD = dims == 5 ? inpShape[2] : 1;
246 int inpH = inpShape[dims - 2];
247 int inpW = inpShape.back();
248 int inpGroupCn = blobs[0].size[1];
249 int ksize = inpGroupCn * std::accumulate(kernel_size.begin(), kernel_size.end(),
250 1, std::multiplies<size_t>());
251 return shape(inpD * inpH * inpW, ksize);
254 virtual bool supportBackend(int backendId) CV_OVERRIDE
256 #ifdef HAVE_INF_ENGINE
257 if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
259 if (kernel_size.size() == 3)
260 return preferableTarget == DNN_TARGET_CPU;
261 return (preferableTarget != DNN_TARGET_MYRIAD || dilation.width == dilation.height);
266 if (kernel_size.size() == 3)
267 return (preferableTarget == DNN_TARGET_CPU && backendId == DNN_BACKEND_OPENCV);
268 else if (kernel_size.size() == 2)
269 return backendId == DNN_BACKEND_OPENCV ||
270 backendId == DNN_BACKEND_HALIDE ||
271 (backendId == DNN_BACKEND_VKCOM && haveVulkan());
277 bool getMemoryShapes(const std::vector<MatShape> &inputs,
278 const int requiredOutputs,
279 std::vector<MatShape> &outputs,
280 std::vector<MatShape> &internals) const CV_OVERRIDE
282 CV_Assert(blobs.size() != 0);
283 CV_Assert(!hasBias() || blobs[1].total() == (size_t)blobs[0].size[0]);
284 CV_Assert(inputs.size() == (size_t)1);
288 CV_Assert(inputs.size() != 0);
289 std::vector<int> inpShape(inputs[0].begin() + 2, inputs[0].end());
291 int outCn = blobs[0].size[0];
292 std::vector<int> outShape;
293 outShape.push_back(inputs[0][0]);
294 outShape.push_back(outCn);
296 int inpCn = inputs[0][1];
299 for (int i = 0; i < inpShape.size(); i++)
300 outShape.push_back((inpShape[i] + pads_begin[i] + pads_end[i] - dilations[i] * (kernel_size[i] - 1) - 1) / strides[i] + 1);
304 getConvPoolOutParams(inpShape, kernel_size, strides, padMode, dilations, outShape);
307 int ngroups = inpCn / blobs[0].size[1];
308 if (ngroups == 0 || ngroups * blobs[0].size[1] != inpCn)
309 CV_Error(Error::StsError, format("Number of input channels should "
310 "be multiple of %d but got %d", blobs[0].size[1], inpCn));
311 CV_Assert(ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0);
313 outputs.resize(1, outShape);
318 virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
320 BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
322 CV_Assert(!blobs.empty());
323 const int outCn = blobs[0].size[0];
324 // prepare weightsMat where each row is aligned and has enough zero padding on the right to
325 // use vectorized (i.e. with intrinsics) loops without tail processing
326 Mat wm = blobs[0].reshape(1, outCn);
327 if( wm.step1() % VEC_ALIGN != 0 )
329 int newcols = (int)alignSize(wm.step1(), VEC_ALIGN);
330 Mat wm_buffer = Mat(outCn, newcols, wm.type());
331 Mat wm_padding = wm_buffer.colRange(wm.cols, newcols);
332 wm_padding.setTo(Scalar::all(0.));
333 Mat wm_aligned = wm_buffer.colRange(0, wm.cols);
334 wm.copyTo(wm_aligned);
338 weightsMultipliers.assign(outCn, 1.0);
340 Mat biasMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat();
341 biasvec.resize(outCn+2);
342 if( biasMat.empty() )
344 for(int i = 0; i < outCn; i++ )
349 for(int i = 0; i < outCn; i++ )
350 biasvec[i] = biasMat.at<float>(i);
353 convolutionOp.release();
357 bool setActivation(const Ptr<ActivationLayer>& layer) CV_OVERRIDE
359 if (!activ.empty() && !layer.empty())
367 activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
369 if (IS_DNN_OPENCL_TARGET(preferableTarget))
371 Ptr<PowerLayer> activ_power = activ.dynamicCast<PowerLayer>();
372 if (!activ_power.empty())
374 if (activ_power->scale != 1.f || activ_power->shift != 0.f)
376 const int outCh = blobs[0].size[0];
377 fuseWeights(Mat(1, outCh, CV_32F, Scalar(activ_power->scale)),
378 Mat(1, outCh, CV_32F, Scalar(activ_power->shift)));
381 power = activ_power->power;
382 activType = OCL4DNN_CONV_FUSED_ACTIV_POWER;
384 Ptr<TanHLayer> activ_tanh = activ.dynamicCast<TanHLayer>();
385 if (!activ_tanh.empty())
387 activType = OCL4DNN_CONV_FUSED_ACTIV_TANH;
391 return !activ.empty();
394 void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
396 // Convolution weights have OIHW data layout. Parameters fusion in case of
397 // (conv(I) + b1 ) * w + b2
398 // means to replace convolution's weights to [w*conv(I)] and bias to [b1 * w + b2]
399 const int outCn = weightsMat.size[0];
400 Mat w = w_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(w_.at<float>(0))) : w_;
401 Mat b = b_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(b_.at<float>(0))) : b_;
402 CV_Assert_N(!weightsMat.empty(), biasvec.size() == outCn + 2,
403 w.empty() || outCn == w.total(), b.empty() || outCn == b.total());
407 // Keep origin weights unchanged.
408 if (weightsMat.data == blobs[0].data)
409 weightsMat = weightsMat.clone();
411 Mat originWeights = blobs[0].reshape(1, outCn);
412 for (int i = 0; i < outCn; ++i)
414 double wi = w.at<float>(i);
415 weightsMultipliers[i] *= wi;
416 cv::multiply(originWeights.row(i), weightsMultipliers[i], weightsMat.row(i));
423 for (int i = 0; i < outCn; ++i)
424 biasvec[i] += b.at<float>(i);
426 biasvec[outCn] = biasvec[outCn+1] = biasvec[outCn-1];
429 virtual Ptr<BackendNode> initVkCom(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
432 int out_channel = blobs[0].size[0];
433 bool has_bias = hasBias() || fusedBias;
434 int filter_size[2] = {kernel.height, kernel.width};
435 int pad_size[2] = {pad.height, pad.width};
436 int stride_size[2] = {stride.height, stride.width};
437 int dilation_size[2] = {dilation.height, dilation.width};
439 vkcom::Tensor input_tensor = VkComTensor(inputs[0]);
440 int in_channel = input_tensor.dimSize(1);
441 int group = in_channel / blobs[0].size[1];
443 // TODO: support group > 1
445 return Ptr<BackendNode>();
450 padding_mode = vkcom::kPaddingModeCaffe;
452 else if (padMode == "VALID")
454 padding_mode = vkcom::kPaddingModeValid;
456 else if (padMode == "SAME")
458 padding_mode = vkcom::kPaddingModeSame;
461 CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
463 std::shared_ptr<vkcom::OpBase> op(new vkcom::OpConv(out_channel, has_bias,
464 filter_size, pad_size,
465 stride_size, dilation_size,
469 std::vector<Ptr<BackendWrapper> > blobsWrapper;
474 weightsMat.copyTo(wm); // to handle the case of isContinuous() == false
475 wm = wm.reshape(1, blobs[0].dims, blobs[0].size);
476 blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(wm)));
480 blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(blobs[0])));
485 Mat biasesMat({out_channel}, CV_32F, &biasvec[0]);
486 blobsWrapper.push_back(Ptr<BackendWrapper>(new VkComBackendWrapper(biasesMat)));
489 return Ptr<BackendNode>(new VkComBackendNode(inputs, op, blobsWrapper));
490 #endif // HAVE_VULKAN
491 return Ptr<BackendNode>();
496 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
499 Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
501 const int inpCn = inputBuffer.channels();
502 const int outCn = blobs[0].size[0];
503 const int inpGroupCn = blobs[0].size[1];
504 const int group = inpCn / inpGroupCn;
505 const int outGroupCn = outCn / group;
507 Halide::Buffer<float> weights = wrapToHalideBuffer(blobs[0]);
509 Halide::Var x("x"), y("y"), c("c"), n("n");
510 Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
511 Halide::Func padded_input(name + "_constant_exterior");
512 if (pad.width || pad.height)
514 Halide::Func bounded =
515 Halide::BoundaryConditions::constant_exterior(inputBuffer, 0);
516 padded_input(x, y, c, n) = bounded(x, y, c, n);
520 padded_input(x, y, c, n) = inputBuffer(x, y, c, n);
523 Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
524 Halide::Expr kx = x * stride.width - pad.width + r.x * dilation.width;
525 Halide::Expr ky = y * stride.height - pad.height + r.y * dilation.height;
526 Halide::Expr kc = r.z;
527 for (int i = 1; i < group; ++i)
529 kc = select(c < outGroupCn * i, kc, inpGroupCn * i + r.z);
531 Halide::Expr topExpr = sum(padded_input(kx, ky, kc, n) *
532 weights(r.x, r.y, r.z, c));
535 Halide::Buffer<float> bias = wrapToHalideBuffer(blobs[1], {outCn});
538 top(x, y, c, n) = topExpr;
539 return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
540 #endif // HAVE_HALIDE
541 return Ptr<BackendNode>();
544 #ifdef HAVE_INF_ENGINE
545 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
547 InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);
548 std::vector<size_t> dims = input->getDims();
549 CV_Assert(dims.size() == 4 || dims.size() == 5);
550 const int inpCn = dims[1];
551 const int outCn = blobs[0].size[0];
552 const int inpGroupCn = blobs[0].size[1];
553 const int group = inpCn / inpGroupCn;
554 InferenceEngine::Layout layout = (dims.size() == 4) ? InferenceEngine::Layout::OIHW :
555 InferenceEngine::Layout::NCDHW;
557 auto ieWeights = wrapToInfEngineBlob(blobs[0], layout);
560 if (weightsMat.isContinuous())
562 Mat cvWeights = weightsMat.reshape(1, blobs[0].dims, blobs[0].size);
563 ieWeights = wrapToInfEngineBlob(cvWeights, layout);
567 ieWeights = InferenceEngine::make_shared_blob<float>({
568 InferenceEngine::Precision::FP32,
569 ieWeights->getTensorDesc().getDims(), layout
571 ieWeights->allocate();
573 Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, outCn);
574 Mat cvWeights = weightsMat.colRange(0, newWeights.cols);
575 cvWeights.copyTo(newWeights);
578 InferenceEngine::Blob::Ptr ieBiases;
579 if (hasBias() || fusedBias)
581 Mat biasesMat({outCn}, CV_32F, &biasvec[0]);
582 ieBiases = wrapToInfEngineBlob(biasesMat, {(size_t)outCn}, InferenceEngine::Layout::C);
585 InferenceEngine::Builder::ConvolutionLayer ieLayer(name);
587 ieLayer.setKernel(kernel_size);
588 ieLayer.setStrides(strides);
589 ieLayer.setDilation(dilations);
590 ieLayer.setPaddingsBegin(pads_begin);
591 ieLayer.setPaddingsEnd(pads_end);
592 ieLayer.setGroup((size_t)group);
593 ieLayer.setOutDepth((size_t)outCn);
595 InferenceEngine::Builder::Layer l = ieLayer;
596 addConstantData("weights", ieWeights, l);
598 addConstantData("biases", ieBiases, l);
600 if (!padMode.empty())
601 l.getParameters()["auto_pad"] = padMode == "VALID" ? std::string("valid") : std::string("same_upper");
603 return Ptr<BackendNode>(new InfEngineBackendNode(l));
605 #endif // HAVE_INF_ENGINE
607 class ParallelConv : public cv::ParallelLoopBody
610 enum { BLK_SIZE = 32, BLK_SIZE_CN = 64 };
615 int outShape[4]; // used only for conv2d
616 std::vector<size_t> kernel_size, pads_begin, pads_end, strides, dilations;
617 int ngroups_, nstripes_;
618 std::vector<int> ofstab_;
619 const std::vector<float>* biasvec_;
620 const std::vector<float>* reluslope_;
621 const ActivationLayer* activ_;
628 : input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0),
629 biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX(false), useAVX2(false), useAVX512(false)
632 static void run( const Mat& input, Mat& output, const Mat& weights,
633 const std::vector<float>& biasvec,
634 const std::vector<float>& reluslope,
635 const std::vector<size_t>& kernel_size, const std::vector<size_t>& strides,
636 const std::vector<size_t>& pads_begin, const std::vector<size_t>& pads_end,
637 const std::vector<size_t>& dilations,
638 const ActivationLayer* activ, int ngroups, int nstripes )
640 size_t karea = std::accumulate(kernel_size.begin(), kernel_size.end(),
641 1, std::multiplies<size_t>());
643 (input.dims == 4 || input.dims == 5) && (input.dims == output.dims),
644 input.size[0] == output.size[0],
645 weights.rows == output.size[1],
646 weights.cols == (input.size[1]/ngroups)*karea,
647 input.type() == output.type(),
648 input.type() == weights.type(),
649 input.type() == CV_32FC1,
650 input.isContinuous(),
651 output.isContinuous(),
652 biasvec.size() == (size_t)output.size[1]+2);
656 p.weights_ = &weights;
658 for( int i = 0; i < 4; i++ ) p.outShape[i] = output.size[i];
659 p.outShape[1] /= ngroups;
661 p.kernel_size = kernel_size; p.strides = strides; p.dilations = dilations;
662 p.pads_begin = pads_begin; p.pads_end = pads_end;
664 p.ngroups_ = ngroups;
665 p.nstripes_ = nstripes;
667 int inpCnAll = input.size[1];
668 int depth = (input.dims == 5) ? input.size[2] : 1;
669 int width = input.size[input.dims - 1];
670 int height = input.size[input.dims - 2];
671 int inpCn = inpCnAll / ngroups;
673 bool isConv2D = kernel_size.size() == 2;
675 p.is1x1_ = isConv2D && kernel_size[0] == 1 && kernel_size[1] == 1 &&
676 pads_begin[0] == 0 && pads_begin[1] == 0;
678 p.useAVX = checkHardwareSupport(CPU_AVX) && isConv2D;
679 p.useAVX2 = checkHardwareSupport(CPU_AVX2) && isConv2D;
680 p.useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX && isConv2D;
682 int ncn = std::min(inpCn, (int)BLK_SIZE_CN);
684 int kernel_d = !isConv2D? kernel_size[0] : 1;
685 int kernel_h = kernel_size[kernel_size.size() - 2];
686 int kernel_w = kernel_size.back();
688 int dil_d = !isConv2D? dilations[0] : 1;
689 int dil_h = dilations[dilations.size() - 2];
690 int dil_w = dilations.back();
692 p.ofstab_.resize(karea * ncn);
693 int* ofstab = &p.ofstab_[0];
697 for( int k = 0; k < ncn; k++ )
698 for( int k_r = 0; k_r < kernel_h; k_r++ )
699 for( int k_c = 0; k_c < kernel_w; k_c++ )
700 ofstab[(k*kernel_h + k_r)*kernel_w + k_c] =
701 (k*height + k_r*dil_h)*width + k_c*dil_w;
705 for( int k = 0; k < ncn; k++ )
706 for (int k_d = 0; k_d < kernel_d; k_d++)
707 for( int k_r = 0; k_r < kernel_h; k_r++ )
708 for( int k_c = 0; k_c < kernel_w; k_c++ )
709 ofstab[(k*kernel_d*kernel_h + k_d*kernel_h + k_r)*kernel_w + k_c] =
710 (k*depth*height + k_d*dil_d*height + k_r*dil_h)*width + k_c*dil_w;
713 p.biasvec_ = &biasvec;
714 p.reluslope_ = &reluslope;
715 p.activ_ = p.reluslope_->empty() ? activ : 0;
717 parallel_for_(Range(0, nstripes), p, nstripes);
720 virtual void operator ()(const Range &r0) const CV_OVERRIDE
722 const int valign = ConvolutionLayerImpl::VEC_ALIGN;
723 int ngroups = ngroups_, batchSize = input_->size[0]*ngroups;
724 bool isConv2D = input_->dims == 4;
726 int outW = output_->size[output_->dims - 1];
727 int outH = output_->size[output_->dims - 2];
728 int outCn = output_->size[1]/ngroups;
730 int depth = !isConv2D? input_->size[2] : 1;
731 int height = input_->size[input_->dims - 2];
732 int width = input_->size[input_->dims - 1];
733 int inpCn = input_->size[1]/ngroups;
735 const int nstripes = nstripes_;
737 int kernel_d = !isConv2D? kernel_size[0] : 1;
738 int kernel_h = kernel_size[kernel_size.size() - 2];
739 int kernel_w = kernel_size.back();
740 int karea = kernel_w*kernel_h*kernel_d;
742 int pad_d = !isConv2D? pads_begin[0] : 0;
743 int pad_t = pads_begin[pads_begin.size() - 2];
744 int pad_l = pads_begin.back();
746 int stride_d = !isConv2D? strides[0] : 0;
747 int stride_h = strides[strides.size() - 2];
748 int stride_w = strides.back();
750 int dilation_d = !isConv2D? dilations[0] : 1;
751 int dilation_h = dilations[dilations.size() - 2];
752 int dilation_w = dilations.back();
755 size_t inpPlaneSize = input_->total(2);
756 size_t outPlaneSize = output_->total(2);
759 int stripesPerSample;
763 if( nstripes >= batchSize*2 )
765 stripesPerSample = nstripes/batchSize;
766 stripeSize = alignSize((outPlaneSize + stripesPerSample - 1)/stripesPerSample, valign);
767 stripeSize = std::min(stripeSize, outPlaneSize);
771 stripesPerSample = 1;
772 int samplesPerStripe = std::max((batchSize + nstripes - 1)/nstripes, 1);
773 r.start *= samplesPerStripe;
774 r.end *= samplesPerStripe;
775 stripeSize = outPlaneSize;
778 const float* data_inp0_ = input_->ptr<float>();
779 const int* ofstab = &ofstab_[0];
780 const float* wptr_orig_ = weights_->ptr<float>();
781 size_t wstep = weights_->step1();
782 const float* biasptr_ = &biasvec_->at(0);
783 const float* reluptr_ = reluslope_->empty() ? 0 : &reluslope_->at(0);
784 float* data_out0_ = output_->ptr<float>();
785 size_t rowbufsz = (size_t)karea*BLK_SIZE_CN*BLK_SIZE;
786 AutoBuffer<float> rowbuf0_(rowbufsz + valign);
787 float* rowbuf0 = alignPtr(rowbuf0_.data(), (int)(valign*sizeof(float)));
789 // we clear the buffer once; ultimately, it lets us to avoid
790 // tail processing after running the unrolled/vectorized loop.
791 // the main idea is to make sure that the tail (a.k.a. padding) of each row
792 // (i.e. the elements with indices between vsz=karea*ncn and vsz_a)
793 // does not contain NaNs or Infs. Because the padding in the weights
794 // matrix is explicitly initialized with 0's, we handle all other
795 // cases nicely, i.e. we can skip expliciting re-initialization
796 // of the padding - we just retain elements from the previous iteration
797 // of the loop over channels (cn0).
798 memset(rowbuf0, 0, rowbufsz*sizeof(rowbuf0[0]) );
800 for( int stripe = r.start; stripe < r.end; stripe++ )
802 int subsampleIdx = stripe/stripesPerSample;
803 if( subsampleIdx >= batchSize )
805 int stripeStart = (int)((stripe - subsampleIdx*stripesPerSample)*stripeSize);
806 int stripeEnd = (int)std::min(stripeStart + stripeSize, outPlaneSize);
807 const float* data_inp0 = data_inp0_ + subsampleIdx*inpPlaneSize*inpCn;
808 float* data_out0 = data_out0_ + subsampleIdx*outPlaneSize*outCn;
809 int startOutCn = (subsampleIdx % ngroups)*outCn;
810 const float* wptr_orig = wptr_orig_ + wstep*startOutCn;
811 const float* biasptr = biasptr_ + startOutCn;
813 for( int cn0 = 0; cn0 < inpCn; cn0 += BLK_SIZE_CN )
815 int cn1 = std::min(cn0 + BLK_SIZE_CN, inpCn);
816 int ncn = cn1 - cn0, vsz = karea*ncn;
817 int vsz_a = (int)alignSize(vsz, valign);
818 const float* wptr = wptr_orig + cn0*karea;
819 // we apply [Channels][P]ReLU (if any) during the final pass only.
820 const float* relu = cn1 == inpCn && reluptr_ ? reluptr_ + startOutCn : 0;
822 for( int ofs0 = stripeStart; ofs0 < stripeEnd; ofs0 += BLK_SIZE )
824 int ofs, ofs1 = std::min(ofs0 + BLK_SIZE, stripeEnd);
826 int out_d = ofs0 / (outH * outW);
827 int out_i = (ofs0 - out_d * outH * outW) / outW;
828 int out_j = ofs0 % outW;
830 // do im2row for a part of input tensor
831 float* rowbuf = rowbuf0;
835 for( ofs = ofs0; ofs < ofs1; out_j = 0, ++out_i )
837 int delta = std::min(ofs1 - ofs, outW - out_j);
838 int out_j1 = out_j + delta;
840 int in_i = out_i * stride_h - pad_t;
841 int in_j = out_j * stride_w - pad_l;
842 const float* imgptr = data_inp0 + (cn0*height + in_i)*width + in_j;
845 // do im2row for a part of input tensor
848 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w )
850 for( k = 0; k < vsz; k++ )
851 rowbuf[k] = imgptr[k*inpPlaneSize];
856 bool ok_i = 0 <= in_i && in_i < height - (kernel_h-1)*dilation_h;
857 int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);
858 int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);
860 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )
862 // this condition should be true for most of the tensor elements, i.e.
863 // most of the time the kernel aperture is inside the tensor X-Y plane.
864 if( ok_i && out_j + 2 <= out_j1 && 0 <= in_j && in_j + stride_w*2 <= width - (kernel_w-1)*dilation_w )
866 for( k = 0; k < vsz; k++ )
869 float v0 = imgptr[k1];
870 float v1 = imgptr[k1 + stride_w];
872 rowbuf[k+vsz_a] = v1;
881 int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);
882 int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);
884 // here some non-continuous sub-row of the row will not be
885 // filled from the tensor; we need to make sure that the uncovered
886 // elements are explicitly set to 0's. the easiest way is to
887 // set all the elements to 0's before the loop.
888 memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));
889 for( k = 0; k < ncn; k++ )
891 for( i = i0; i < i1; i++ )
893 for( j = j0; j < j1; j++ )
895 int imgofs = k*(width*height) + i*(dilation_h*width) + j*dilation_w;
896 rowbuf[(k*kernel_h + i)*kernel_w + j] = imgptr[imgofs];
907 for( ofs = ofs0; ofs < ofs1; out_d += (out_i + 1) / outH, out_i = (out_i + 1) % outH, out_j = 0 )
909 int delta = std::min(ofs1 - ofs, outW - out_j);
910 int out_j1 = out_j + delta;
912 int in_d = out_d * stride_d - pad_d;
913 int in_i = out_i * stride_h - pad_t;
914 int in_j = out_j * stride_w - pad_l;
915 const float* imgptr = data_inp0 + (cn0*depth*height + in_d*height + in_i)*width + in_j;
918 int d0 = std::max(0, (-in_d + dilation_d - 1) / dilation_d);
919 int d1 = std::min(kernel_d, (depth - in_d + dilation_d - 1) / dilation_d);
921 int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);
922 int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);
924 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )
926 int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);
927 int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);
929 // here some non-continuous sub-row of the row will not be
930 // filled from the tensor; we need to make sure that the uncovered
931 // elements are explicitly set to 0's. the easiest way is to
932 // set all the elements to 0's before the loop.
933 memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));
934 for( k = 0; k < ncn; k++ )
936 for ( d = d0; d < d1; d++)
938 for( i = i0; i < i1; i++ )
940 for( j = j0; j < j1; j++ )
942 int imgofs = k*(depth*width*height) + d*dilation_d*width*height + i*(dilation_h*width) + j*dilation_w;
943 rowbuf[(k*kernel_d*kernel_h + d*kernel_h + i)*kernel_w + j] = imgptr[imgofs];
952 // now compute dot product of the weights
953 // and im2row-transformed part of the tensor
954 int bsz = ofs1 - ofs0;
955 #if CV_TRY_AVX512_SKX
956 /* AVX512 convolution requires an alignment of 16, and ROI is only there for larger vector sizes */
958 opt_AVX512_SKX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
959 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
964 opt_AVX2::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
965 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
970 opt_AVX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
971 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
974 for( int i = 0; i < outCn; i += 2 )
976 const float* wptr0 = wptr + i*wstep;
977 const float* wptr1 = wptr0 + wstep;
978 float* outptr0 = data_out0 + ofs0 + i*outPlaneSize;
979 float* outptr1 = outptr0 + outPlaneSize;
980 float bias0 = biasptr[i], bias1 = biasptr[i+1];
981 float r0 = 1.f, r1 = 1.f;
992 r0 = relu[i]; r1 = relu[i+1];
999 v_float32x4 vr0 = v_setall_f32(r0), vr1 = v_setall_f32(r1), z = v_setzero_f32();
1001 for( ; j <= bsz - 4; j += 4 )
1003 const float* rptr = rowbuf0 + j*vsz_a;
1008 s0 = v_setall_f32(bias0);
1009 s1 = v_setall_f32(bias1);
1013 s0 = v_load(outptr0 + j);
1014 s1 = v_load(outptr1 + j);
1017 v_float32x4 vs00 = v_setzero_f32(), vs01 = v_setzero_f32(),
1018 vs02 = v_setzero_f32(), vs03 = v_setzero_f32(),
1019 vs10 = v_setzero_f32(), vs11 = v_setzero_f32(),
1020 vs12 = v_setzero_f32(), vs13 = v_setzero_f32();
1021 for( k = 0; k < vsz; k += 4, rptr += 4 )
1023 v_float32x4 w0 = v_load_aligned(wptr0 + k), w1 = v_load_aligned(wptr1 + k);
1024 v_float32x4 r0 = v_load_aligned(rptr), r1 = v_load_aligned(rptr + vsz_a),
1025 r2 = v_load_aligned(rptr + vsz_a*2), r3 = v_load_aligned(rptr + vsz_a*3);
1037 s0 += v_reduce_sum4(vs00, vs01, vs02, vs03);
1038 s1 += v_reduce_sum4(vs10, vs11, vs12, vs13);
1041 s0 = v_select(s0 > z, s0, s0*vr0);
1042 s1 = v_select(s1 > z, s1, s1*vr1);
1045 v_store(outptr0 + j, s0);
1046 v_store(outptr1 + j, s1);
1049 for( ; j < bsz; j++ )
1051 const float* rptr = rowbuf0 + j*vsz_a;
1065 for( k = 0; k < vsz; k++ )
1073 s00 = s00 > 0.f ? s00 : s00*r0;
1074 s10 = s10 > 0.f ? s10 : s10*r1;
1085 activ_->forwardSlice(data_out0 + stripeStart, data_out0 + stripeStart,
1086 (int)(stripeEnd - stripeStart),
1087 outPlaneSize, startOutCn, startOutCn + outCn);
1093 bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
1095 std::vector<UMat> inputs;
1096 std::vector<UMat> outputs;
1098 bool use_half = (inps.depth() == CV_16S);
1099 inps.getUMatVector(inputs);
1100 outs.getUMatVector(outputs);
1102 CV_Assert(outputs.size() == 1);
1103 for (int i = 0; i < inputs.size(); ++i)
1104 CV_Assert(inputs[i].u != outputs[0].u);
1106 if (umat_blobs.empty())
1108 size_t n = blobs.size();
1109 umat_blobs.resize(n);
1110 for (size_t i = 0; i < n; i++)
1112 blobs[i].copyTo(umat_blobs[i]);
1116 if (convolutionOp.empty())
1118 OCL4DNNConvConfig config;
1119 config.in_shape = shape(inputs[0]);
1120 config.out_shape = shape(outputs[0]);
1121 config.kernel = kernel;
1123 config.stride = stride;
1124 config.dilation = dilation;
1125 config.group = inputs[0].size[1] / umat_blobs[0].size[1];
1126 config.bias_term = (hasBias()) ? true : false;
1127 config.use_half = use_half;
1129 convolutionOp = Ptr<OCL4DNNConvSpatial<float> >(new OCL4DNNConvSpatial<float>(config));
1132 int outCn = umat_blobs[0].size[0];
1137 Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
1138 if( !activ_relu.empty() )
1140 reluslope.assign(outCn+2, activ_relu->negativeSlope);
1141 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU;
1144 Ptr<ReLU6Layer> activ_relu6 = activ.dynamicCast<ReLU6Layer>();
1145 if( !activ_relu6.empty() )
1147 reluslope.resize(2);
1148 reluslope[0] = activ_relu6->minValue;
1149 reluslope[1] = activ_relu6->maxValue;
1150 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU6;
1153 Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1154 if( !activ_chprelu.empty() )
1156 const Mat& m = activ_chprelu->blobs[0];
1157 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1158 const float* mdata = m.ptr<float>();
1159 reluslope.resize(outCn+2);
1160 std::copy(mdata, mdata + outCn, reluslope.begin());
1161 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1162 activType = OCL4DNN_CONV_FUSED_ACTIV_PRELU;
1168 weightsMat.copyTo(umat_blobs[0]);
1169 fusedWeights = false;
1173 if ( umat_blobs.size() < 2 )
1174 umat_blobs.resize(2);
1175 umat_blobs[1] = UMat(biasvec, true);
1176 convolutionOp->setBias(true);
1182 if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU )
1184 CV_Assert(!reluslope.empty());
1185 convolutionOp->setActivReLU(true, reluslope[0]);
1187 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_PRELU)
1189 CV_Assert(!reluslope.empty());
1190 convolutionOp->setActivPReLU(true, reluslope);
1192 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_POWER)
1194 convolutionOp->setActivPower(true, power);
1196 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_TANH)
1198 convolutionOp->setActivTanh(true);
1200 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU6)
1202 convolutionOp->setActivReLU6(true, reluslope[0], reluslope[1]);
1206 convolutionOp->setActivReLU(false, 0);
1207 convolutionOp->setActivPReLU(false, reluslope);
1208 convolutionOp->setActivPower(false, 1.f);
1209 convolutionOp->setActivTanh(false);
1210 convolutionOp->setActivReLU6(false, 0, 0);
1215 UMat& inpMat = inputs[0];
1216 UMat& outMat = outputs[0];
1217 int batch_size = inpMat.size[0];
1219 return convolutionOp->Forward(inpMat,
1220 inputs.size() == 2 ? inputs[1] : UMat(),
1222 umat_blobs.size() > 1 ? umat_blobs[1] : UMat(),
1228 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1230 CV_TRACE_FUNCTION();
1231 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1233 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1234 forward_ocl(inputs_arr, outputs_arr, internals_arr))
1236 if (inputs_arr.depth() == CV_16S)
1238 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1242 std::vector<Mat> inputs, outputs;
1243 inputs_arr.getMatVector(inputs);
1244 outputs_arr.getMatVector(outputs);
1246 /*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",
1247 name.c_str(), inputs[0].size[0], inputs[0].size[1], inputs[0].size[2], inputs[0].size[3],
1248 kernel.width, kernel.height, pad.width, pad.height,
1249 stride.width, stride.height, dilation.width, dilation.height);*/
1250 CV_Assert_N(inputs.size() == (size_t)1, inputs[0].size[1] % blobs[0].size[1] == 0,
1251 outputs.size() == 1, inputs[0].data != outputs[0].data);
1253 int ngroups = inputs[0].size[1]/blobs[0].size[1];
1254 CV_Assert(outputs[0].size[1] % ngroups == 0);
1255 int outCn = blobs[0].size[0];
1260 Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
1261 if( !activ_relu.empty() )
1263 reluslope.assign(outCn+2, activ_relu->negativeSlope);
1266 Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1267 if( !activ_chprelu.empty() )
1269 const Mat& m = activ_chprelu->blobs[0];
1270 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1271 const float* mdata = m.ptr<float>();
1272 reluslope.resize(outCn+2);
1273 std::copy(mdata, mdata + outCn, reluslope.begin());
1274 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1278 int nstripes = std::max(getNumThreads(), 1);
1280 ParallelConv::run(inputs[0], outputs[0], weightsMat, biasvec, reluslope,
1281 kernel_size, strides, pads_begin, pads_end, dilations, activ.get(), ngroups, nstripes);
1284 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
1285 const std::vector<MatShape> &outputs) const CV_OVERRIDE
1287 CV_Assert(inputs.size() == outputs.size());
1290 int karea = std::accumulate(kernel_size.begin(), kernel_size.end(), 1, std::multiplies<size_t>());
1291 for (int i = 0; i < inputs.size(); i++)
1293 flops += total(outputs[i])*(CV_BIG_INT(2)*karea*inputs[i][1] + 1);
1300 class DeConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
1303 Mat weightsMat, biasesMat;
1307 DeConvolutionLayerImpl(const LayerParams& params) : BaseConvolutionLayerImpl(params) {}
1309 MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
1311 int dims = inpShape.size();
1312 int inpCn = inpShape[1];
1313 int inpD = dims == 5 ? inpShape[2] : 1;
1314 int inpH = inpShape[dims - 2];
1315 int inpW = inpShape.back();
1316 int outCn = outShape[1];
1317 int ngroups = inpCn / blobs[0].size[0];
1318 int outGroupCn = outCn / ngroups;
1319 int ksize = outGroupCn * std::accumulate(kernel_size.begin(), kernel_size.end(),
1320 1, std::multiplies<size_t>());
1321 return shape(ksize, inpD * inpH * inpW);
1324 virtual bool supportBackend(int backendId) CV_OVERRIDE
1326 #ifdef HAVE_INF_ENGINE
1327 const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW or IODHW layout
1328 const int group = numOutput / outGroupCn;
1330 if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
1332 if (kernel_size.size() == 3 && preferableTarget != DNN_TARGET_CPU) {
1336 if (std::accumulate(adjust_pads.begin(), adjust_pads.end(), 0, std::plus<size_t>()) > 0)
1338 if (padMode.empty())
1340 if (preferableTarget != DNN_TARGET_CPU && group != 1)
1342 for (int i = 0; i < adjust_pads.size(); i++) {
1343 if (adjust_pads[i] && pads_begin[i])
1347 for (int i = 0; i < adjust_pads.size(); i++) {
1348 if (pads_end[i] < adjust_pads[i])
1353 else if (padMode == "SAME")
1355 for (int i = 0; i < adjust_pads.size(); i++) {
1356 if (kernel_size[i] < pads_begin[i] + 1 + adjust_pads[i])
1361 else if (padMode == "VALID")
1367 return preferableTarget == DNN_TARGET_CPU;
1369 if (preferableTarget == DNN_TARGET_OPENCL || preferableTarget == DNN_TARGET_OPENCL_FP16)
1370 return std::accumulate(dilations.begin(), dilations.end(), 1, std::multiplies<size_t>()) == 1;
1374 #endif // HAVE_INF_ENGINE
1375 return kernel_size.size() == 2 && (backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE);
1378 bool getMemoryShapes(const std::vector<MatShape> &inputs,
1379 const int requiredOutputs,
1380 std::vector<MatShape> &outputs,
1381 std::vector<MatShape> &internals) const CV_OVERRIDE
1383 CV_Assert(!hasBias() || blobs[1].total() == (size_t)numOutput);
1384 CV_Assert(inputs.size() != 0);
1386 int outCn = numOutput;
1387 std::vector<int> outShape;
1388 outShape.push_back(inputs[0][0]); // batch
1389 outShape.push_back(outCn);
1390 if (padMode.empty())
1392 for (int i = 0; i < kernel_size.size(); i++)
1393 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] - pads_begin[i] - pads_end[i] + adjust_pads[i]);
1395 else if (padMode == "VALID")
1397 for (int i = 0; i < kernel_size.size(); i++)
1398 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] + adjust_pads[i]);
1400 else if (padMode == "SAME")
1402 for (int i = 0; i < kernel_size.size(); i++)
1403 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + 1 + adjust_pads[i]);
1406 CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
1408 CV_Assert(outCn % blobs[0].size[1] == 0);
1409 int ngroups = outCn / blobs[0].size[1];
1411 int inpCn = inputs[0][1];
1412 CV_Assert(inpCn % ngroups == 0 && outCn % ngroups == 0);
1413 CV_Assert(blobs[0].size[0] == inpCn);
1415 outputs.resize(1, outShape);
1418 internals.push_back(computeColRowShape(inputs[0], outputs[0]));
1423 void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1425 BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
1427 std::vector<Mat> inputs, outputs;
1428 inputs_arr.getMatVector(inputs);
1429 outputs_arr.getMatVector(outputs);
1431 std::vector<int> inpShape;
1432 std::vector<int> outShape;
1433 for (int i = 2; i < inputs[0].dims; i++) {
1434 inpShape.push_back(inputs[0].size[i]);
1435 outShape.push_back(outputs[0].size[i]);
1437 getConvPoolPaddings(outShape, kernel_size, strides, padMode, pads_begin, pads_end);
1438 if (pads_begin.size() == 2) {
1439 for (int i = 0; i < pads_begin.size(); i++) {
1440 if (pads_begin[i] != pads_end[i])
1441 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in deconvolution layer");
1443 pad = Size(pads_begin[1], pads_begin[0]);
1446 weightsMultipliers.assign(numOutput, 1.0);
1447 if (weightsMat.empty())
1449 transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1450 biasesMat = hasBias() ? blobs[1].reshape(1, numOutput)
1451 : Mat::zeros(numOutput, 1, CV_32F);
1455 void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
1457 Mat w = w_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(w_.at<float>(0))) : w_;
1458 Mat b = b_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(b_.at<float>(0))) : b_;
1460 CV_Assert_N(!weightsMat.empty(),
1461 w.empty() || numOutput == w.total(),
1462 b.empty() || numOutput == b.total());
1466 transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1467 weightsMat = weightsMat.reshape(1, numOutput);
1468 for (int i = 0; i < numOutput; ++i)
1470 double wi = w.at<float>(i);
1471 weightsMultipliers[i] *= wi;
1472 cv::multiply(weightsMat.row(i), weightsMultipliers[i], weightsMat.row(i));
1473 biasesMat.at<float>(i) *= wi;
1475 weightsMat = weightsMat.reshape(1, weightsMat.total() / blobs[0].size[0]);
1480 cv::add(biasesMat, b.reshape(1, numOutput), biasesMat);
1484 class MatMulInvoker : public ParallelLoopBody
1487 MatMulInvoker(const Mat& a, const Mat& b, Mat& c, int nstripes)
1492 nstripes_ = nstripes;
1493 useAVX = checkHardwareSupport(CPU_AVX);
1494 useAVX2 = checkHardwareSupport(CPU_AVX2);
1495 useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;
1498 void operator()(const Range& range_) const CV_OVERRIDE
1500 int stripeSize = (int)alignSize((b_->cols + nstripes_ - 1)/nstripes_, 16);
1501 Range range(range_.start*stripeSize, std::min(range_.end*stripeSize, b_->cols));
1502 int mmax = a_->rows;
1503 int nmax = range.end - range.start;
1504 int kmax = a_->cols;
1506 const float* aptr = a_->ptr<float>();
1507 const float* bptr = b_->ptr<float>() + range.start;
1508 float* cptr = c_->ptr<float>() + range.start;
1509 size_t astep = a_->step1();
1510 size_t bstep = b_->step1();
1511 size_t cstep = c_->step1();
1513 #if CV_TRY_AVX512_SKX
1515 opt_AVX512_SKX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1520 opt_AVX2::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1525 opt_AVX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1528 for( m = 0; m < mmax; m += 2 )
1530 float* dst0 = cptr + cstep*m;
1531 float* dst1 = cptr + cstep*std::min(m+1, mmax-1);
1532 const float* aptr0 = aptr + astep*m;
1533 const float* aptr1 = aptr + astep*std::min(m+1, mmax-1);
1535 for( n = 0; n < nmax; n++ )
1541 for( k = 0; k < kmax; k += 4 )
1543 float alpha00 = aptr0[k];
1544 float alpha01 = aptr1[k];
1545 float alpha10 = 0.f, alpha11 = 0.f;
1546 float alpha20 = 0.f, alpha21 = 0.f;
1547 float alpha30 = 0.f, alpha31 = 0.f;
1548 const float* bptr0 = bptr + k*bstep;
1549 const float* bptr1 = bptr0;
1550 const float* bptr2 = bptr0;
1551 const float* bptr3 = bptr0;
1555 alpha10 = aptr0[k+1];
1556 alpha11 = aptr1[k+1];
1557 bptr1 = bptr0 + bstep;
1560 alpha20 = aptr0[k+2];
1561 alpha21 = aptr1[k+2];
1562 bptr2 = bptr1 + bstep;
1565 alpha30 = aptr0[k+3];
1566 alpha31 = aptr1[k+3];
1567 bptr3 = bptr2 + bstep;
1574 v_float32x4 a00 = v_setall_f32(alpha00);
1575 v_float32x4 a01 = v_setall_f32(alpha01);
1576 v_float32x4 a10 = v_setall_f32(alpha10);
1577 v_float32x4 a11 = v_setall_f32(alpha11);
1578 v_float32x4 a20 = v_setall_f32(alpha20);
1579 v_float32x4 a21 = v_setall_f32(alpha21);
1580 v_float32x4 a30 = v_setall_f32(alpha30);
1581 v_float32x4 a31 = v_setall_f32(alpha31);
1583 for( ; n <= nmax - 4; n += 4 )
1585 v_float32x4 b0 = v_load(bptr0 + n);
1586 v_float32x4 b1 = v_load(bptr1 + n);
1587 v_float32x4 b2 = v_load(bptr2 + n);
1588 v_float32x4 b3 = v_load(bptr3 + n);
1589 v_float32x4 d0 = v_load(dst0 + n);
1590 v_float32x4 d1 = v_load(dst1 + n);
1599 v_store(dst0 + n, d0);
1600 v_store(dst1 + n, d1);
1604 for( ; n < nmax; n++ )
1606 float b0 = bptr0[n], b1 = bptr1[n];
1607 float b2 = bptr2[n], b3 = bptr3[n];
1608 float d0 = dst0[n] + alpha00*b0 + alpha10*b1 + alpha20*b2 + alpha30*b3;
1609 float d1 = dst1[n] + alpha01*b0 + alpha11*b1 + alpha21*b2 + alpha31*b3;
1625 class Col2ImInvoker : public cv::ParallelLoopBody
1628 const float* data_col;
1629 const float* biasvec;
1630 int channels, height, width;
1631 int kernel_h, kernel_w;
1633 int stride_h, stride_w;
1635 int height_col, width_col;
1640 : data_col(0), biasvec(0), channels(0), height(0), width(0),
1641 kernel_h(0), kernel_w(0), pad_h(0), pad_w(0), stride_h(0), stride_w(0), data_im(0),
1642 height_col(0), width_col(0), nstripes(0), is1x1(0)
1645 static void run(const float* data_col,
1646 int channels, int height, int width,
1647 int kernel_h, int kernel_w,
1648 int pad_h, int pad_w,
1649 int stride_h, int stride_w,
1650 int height_col, int width_col,
1652 const float* biasvec,
1655 const int nstripes = getNumThreads();
1658 t.data_col = data_col;
1659 t.data_im = data_im;
1660 t.channels = channels; t.height = height; t.width = width;
1661 t.kernel_h = kernel_h; t.kernel_w = kernel_w;
1662 t.pad_h = pad_h; t.pad_w = pad_w;
1663 t.stride_h = stride_h; t.stride_w = stride_w;
1664 t.height_col = height_col;
1665 t.width_col = width_col;
1666 t.nstripes = nstripes;
1668 t.biasvec = biasvec;
1670 parallel_for_(Range(0, nstripes), t, nstripes);
1673 virtual void operator ()(const Range &r) const CV_OVERRIDE
1675 const float* data_col_ = data_col;
1676 float* data_im_ = data_im;
1677 int coeff_h = (1 - stride_h * kernel_w * height_col) * width_col;
1678 int coeff_w = (1 - stride_w * height_col * width_col);
1679 size_t total = (size_t)channels * height * width;
1680 size_t stripeSize = (total + nstripes - 1)/nstripes;
1681 size_t startIndex = r.start*stripeSize;
1682 size_t endIndex = std::min(r.end*stripeSize, total);
1683 int w = (int)(startIndex % width + pad_w);
1684 int h = (int)((startIndex / width) % height + pad_h);
1685 int c = (int)(startIndex / (width * height));
1686 int h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1687 int h_col_end = std::min(h / stride_h + 1, height_col);
1688 int plane_size_col = height_col * width_col;
1689 int offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1690 bool is1x1_ = is1x1;
1691 const float* biasvec_ = biasvec;
1693 for (size_t index = startIndex; index < endIndex; index++)
1695 // compute the start and end of the output
1696 int w_col_start = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1;
1697 int w_col_end = std::min(w / stride_w + 1, width_col);
1701 val = data_im_[index];
1705 for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {
1706 for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {
1707 val += data_col_[offset + h_col * coeff_h + w_col * coeff_w];
1711 data_im_[index] = val + biasvec_[c];
1713 offset += plane_size_col;
1714 if( ++w >= width + pad_w )
1716 w = (int)((index + 1)% width + pad_w);
1717 h = (int)(((index + 1) / width) % height + pad_h);
1718 c = (int)((index + 1) / (width * height));
1719 h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1720 h_col_end = std::min(h / stride_h + 1, height_col);
1721 offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1728 bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
1730 std::vector<UMat> inputs;
1731 std::vector<UMat> outputs;
1732 std::vector<UMat> internals;
1734 if (inputs_.depth() == CV_16S)
1737 inputs_.getUMatVector(inputs);
1738 outputs_.getUMatVector(outputs);
1739 internals_.getUMatVector(internals);
1741 int outCn = numOutput;
1742 int inpCn = inputs[0].size[1];
1747 if (umat_weights.empty())
1750 weightsMat.copyTo(umat_weights);
1752 transpose(blobs[0].reshape(1, inpCn), umat_weights);
1755 biasesMat.copyTo(umat_biases);
1759 blobs[1].reshape(1, outCn).copyTo(umat_biases);
1761 umat_biases = UMat::zeros(outCn, 1, CV_32F);
1765 String buildopt = format("-DT=%s ", ocl::typeToStr(inputs[0].type()));
1766 buildopt += format("-DPAD_H=%d -DPAD_W=%d -DKERNEL_H=%d -DKERNEL_W=%d -DSTRIDE_H=%d -DSTRIDE_W=%d ",
1767 pad.height, pad.width, kernel.height, kernel.width, stride.height, stride.width);
1769 for (size_t ii = 0; ii < outputs.size(); ii++)
1771 int ngroups = outCn / blobs[0].size[1];
1772 int inpGroupCn = inpCn / ngroups;
1773 int outGroupCn = blobs[0].size[1];
1774 const UMat& inp = inputs[ii];
1775 UMat& out = outputs[ii];
1776 int numImg = inp.size[0];
1777 int inpH = inp.size[2], inpW = inp.size[3];
1778 int outH = out.size[2], outW = out.size[3];
1780 MatShape inpshape = shape(numImg*inpCn, inpH*inpW);
1781 MatShape outshape = shape(numImg*outCn, outH*outW);
1782 UMat convBlob = inputs[ii].reshape(1, inpshape.size(), &inpshape[0]);
1783 UMat decnBlob = out.reshape(1, outshape.size(), &outshape[0]);
1784 int rows = internals[0].rows / ngroups;
1786 for (int n = 0; n < numImg; n++)
1788 for (int g = 0; g < ngroups; g++)
1790 UMat colMat = internals[0].rowRange(_Range(g * rows, rows));
1791 UMat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1792 UMat wghtMat = umat_weights.colRange(_Range(g * inpGroupCn, inpGroupCn));
1793 gemm(wghtMat, convMat, 1, noArray(), 0, colMat, 0);
1796 for (int g = 0; g < ngroups; g++)
1798 int total = outGroupCn * decnBlob.cols;
1800 int height_col = inpH;
1801 int width_col = inpW;
1802 int coeff_h = (1 - stride.height * kernel.width * height_col) * width_col;
1803 int coeff_w = (1 - stride.width * height_col * width_col);
1805 ocl::Kernel k("col2im", ocl::dnn::col2im_oclsrc, buildopt);
1806 k.set(index++, total);
1807 k.set(index++, ocl::KernelArg::PtrReadOnly(internals[0]));
1808 k.set(index++, (int)(g * rows * internals[0].cols));
1809 k.set(index++, outGroupCn);
1810 k.set(index++, outH);
1811 k.set(index++, outW);
1812 k.set(index++, height_col);
1813 k.set(index++, width_col);
1814 k.set(index++, coeff_h);
1815 k.set(index++, coeff_w);
1816 k.set(index++, ocl::KernelArg::PtrReadOnly(umat_biases));
1817 k.set(index++, (int)(g * outGroupCn * umat_biases.cols));
1818 k.set(index++, ocl::KernelArg::PtrWriteOnly(decnBlob));
1819 k.set(index++, (int)((g + n * ngroups) * outGroupCn * decnBlob.cols));
1821 size_t global[] = { (size_t)total };
1822 bool ret = k.run(1, global, NULL, false);
1833 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1835 CV_TRACE_FUNCTION();
1836 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1838 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1839 forward_ocl(inputs_arr, outputs_arr, internals_arr));
1841 if (inputs_arr.depth() == CV_16S)
1843 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1847 std::vector<Mat> inputs, outputs, internals;
1848 inputs_arr.getMatVector(inputs);
1849 outputs_arr.getMatVector(outputs);
1850 internals_arr.getMatVector(internals);
1852 int outCn = numOutput;
1853 int inpCn = inputs[0].size[1];
1854 bool is1x1flag = is1x1();
1855 int nstripes = getNumThreads();
1857 if( weightsMat.empty() )
1859 transpose(blobs[0].reshape(1, inpCn), weightsMat);
1860 biasesMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);
1863 for (size_t ii = 0; ii < outputs.size(); ii++)
1865 int ngroups = outCn / blobs[0].size[1];
1866 int inpGroupCn = inpCn / ngroups;
1867 int outGroupCn = blobs[0].size[1];
1868 const Mat& inp = inputs[ii];
1869 Mat& out = outputs[ii];
1870 int numImg = inp.size[0];
1871 int inpH = inp.size[2], inpW = inp.size[3];
1872 int outH = out.size[2], outW = out.size[3];
1874 Mat convBlob = inputs[ii].reshape(1, numImg*inpCn);
1875 Mat decnBlob = out.reshape(1, numImg*outCn);
1877 for (int n = 0; n < numImg; n++)
1879 for (int g = 0; g < ngroups; g++)
1881 Mat dstMat = decnBlob.rowRange(_Range((g + n * ngroups) * outGroupCn, outGroupCn));
1882 Mat &colMat = is1x1flag ? dstMat : internals[0];
1884 Mat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1885 Mat wghtMat = weightsMat.colRange(_Range(g * inpGroupCn, inpGroupCn));
1886 Mat curBiasMat = biasesMat.rowRange(_Range(g * outGroupCn, outGroupCn));
1888 //gemm(wghtMat, convMat, 1, colMat, 0, colMat, 0);
1889 MatMulInvoker mminvoker(wghtMat, convMat, colMat, nstripes);
1890 parallel_for_(Range(0, nstripes), mminvoker, nstripes);
1892 Col2ImInvoker::run(colMat.ptr<float>(), outGroupCn, outH, outW,
1893 kernel.height, kernel.width, pad.height, pad.width,
1894 stride.height, stride.width, inpH, inpW, dstMat.ptr<float>(),
1895 curBiasMat.ptr<float>(), is1x1flag);
1901 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
1904 Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
1906 int inW, inH, inC, inN;
1907 getCanonicalSize(inputBuffer, &inW, &inH, &inC, &inN);
1908 const int outGroupCn = blobs[0].size[1];
1909 const int group = numOutput / outGroupCn;
1910 const int inpGroupCn = blobs[0].size[0] / group;
1912 Halide::Var x("x"), y("y"), c("c"), n("n");
1913 Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
1914 Halide::Func padded_input(name + "_constant_exterior");
1915 auto weights = wrapToHalideBuffer(blobs[0]);
1917 Halide::Func dilated_input("dilated_input");
1918 dilated_input(x, y, c, n) = 0.0f;
1919 Halide::RDom r1(0, inW, 0, inH);
1920 dilated_input(r1.x * stride.width, r1.y * stride.height, c, n) =
1921 inputBuffer(r1.x, r1.y, c, n);
1922 dilated_input.compute_root();
1924 Halide::Func bounded =
1925 Halide::BoundaryConditions::constant_exterior(dilated_input, 0,
1926 0, (inW - 1) * stride.width + 1,
1927 0, (inH - 1) * stride.height + 1,
1929 padded_input(x, y, c, n) = bounded(x, y, c, n);
1931 Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
1932 Halide::Expr kx = x + pad.width - r.x;
1933 Halide::Expr ky = y + pad.height - r.y;
1934 Halide::Expr kInC = r.z;
1935 Halide::Expr kOutC = c;
1936 for (int i = 1; i < group; ++i)
1938 kInC = select(c < outGroupCn * i, kInC, inpGroupCn * i + r.z);
1939 kOutC = select(c < outGroupCn * i, kOutC, c - outGroupCn * i);
1941 Halide::Expr topExpr = sum(padded_input(kx, ky, kInC, n) *
1942 weights(r.x, r.y, kOutC, kInC));
1945 auto bias = wrapToHalideBuffer(blobs[1], {numOutput});
1948 top(x, y, c, n) = topExpr;
1949 return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
1950 #endif // HAVE_HALIDE
1951 return Ptr<BackendNode>();
1954 #ifdef HAVE_INF_ENGINE
1955 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &) CV_OVERRIDE
1957 InferenceEngine::Layout layout = blobs[0].dims == 5? InferenceEngine::Layout::NCDHW :
1958 InferenceEngine::Layout::OIHW;
1960 auto ieWeights = wrapToInfEngineBlob(blobs[0], layout);
1963 ieWeights = InferenceEngine::make_shared_blob<float>({
1964 InferenceEngine::Precision::FP32,
1965 ieWeights->getTensorDesc().getDims(), layout
1967 ieWeights->allocate();
1969 int inpCn = blobs[0].size[0];
1970 Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, inpCn);
1971 transpose(weightsMat, newWeights);
1974 const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW or OIDHW layout
1975 const int group = numOutput / outGroupCn;
1977 InferenceEngine::Builder::DeconvolutionLayer ieLayer(name);
1979 ieLayer.setKernel(kernel_size);
1980 ieLayer.setStrides(strides);
1981 ieLayer.setDilation(dilations);
1982 ieLayer.setPaddingsBegin(pads_begin);
1984 if (padMode.empty())
1986 std::vector<size_t> paddings_end;
1987 for (int i = 0; i < pads_end.size(); i++) {
1988 paddings_end.push_back(pads_end[i] - adjust_pads[i]);
1990 ieLayer.setPaddingsEnd(paddings_end);
1992 else if (padMode == "SAME")
1994 std::vector<size_t> paddings_end;
1995 for (int i = 0; i < pads_begin.size(); i++) {
1996 paddings_end.push_back(kernel_size[i] - pads_begin[i] - 1 - adjust_pads[i]);
1998 ieLayer.setPaddingsEnd(paddings_end);
2000 ieLayer.setGroup((size_t)group);
2001 ieLayer.setOutDepth((size_t)numOutput);
2003 InferenceEngine::Builder::Layer l = ieLayer;
2004 addConstantData("weights", ieWeights, l);
2006 addConstantData("biases", wrapToInfEngineBlob(biasesMat, {(size_t)numOutput}, InferenceEngine::Layout::C), l);
2007 return Ptr<BackendNode>(new InfEngineBackendNode(l));
2009 #endif // HAVE_INF_ENGINE
2011 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
2012 const std::vector<MatShape> &outputs) const CV_OVERRIDE
2014 CV_Assert(inputs.size() == outputs.size());
2017 int outChannels = blobs[0].size[0];
2018 size_t karea = std::accumulate(kernel_size.begin(), kernel_size.end(),
2019 1, std::multiplies<size_t>());
2021 for (int i = 0; i < inputs.size(); i++)
2023 flops += CV_BIG_INT(2)*outChannels*karea*total(inputs[i]);
2030 Ptr<BaseConvolutionLayer> ConvolutionLayer::create(const LayerParams ¶ms)
2032 Ptr<ConvolutionLayerImpl> l(new ConvolutionLayerImpl(params));
2036 Ptr<BaseConvolutionLayer> DeconvolutionLayer::create(const LayerParams ¶ms)
2038 return Ptr<BaseConvolutionLayer>(new DeConvolutionLayerImpl(params));