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 "opencv2/core/hal/hal.hpp"
48 #include "opencv2/core/hal/intrin.hpp"
53 #include "opencl_kernels_dnn.hpp"
54 using namespace cv::dnn::ocl4dnn;
62 class BaseConvolutionLayerImpl : public ConvolutionLayer
65 bool fusedWeights, fusedBias;
66 std::vector<double> weightsMultipliers;
67 BaseConvolutionLayerImpl(const LayerParams ¶ms)
69 setParamsFrom(params);
70 getConvolutionKernelParams(params, kernel_size, pads_begin, pads_end, strides, dilations, padMode, adjust_pads);
72 numOutput = params.get<int>("num_output");
73 int ngroups = params.get<int>("group", 1);
74 CV_Assert(numOutput % ngroups == 0);
76 if (kernel_size.size() == 2) {
77 kernel = Size(kernel_size[1], kernel_size[0]);
78 stride = Size(strides[1], strides[0]);
79 for (int i = 0; i < pads_begin.size(); i++) {
80 if (pads_begin[i] != pads_end[i])
81 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
83 pad = Size(pads_begin[1], pads_begin[0]);
84 dilation = Size(dilations[1], dilations[0]);
86 adjustPad.height = adjust_pads[0];
87 adjustPad.width = adjust_pads[1];
90 for (int i = 0; i < adjust_pads.size(); i++) {
91 CV_Assert(adjust_pads[i] < strides[i]);
98 virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
100 std::vector<Mat> inputs, outputs;
101 inputs_arr.getMatVector(inputs);
102 outputs_arr.getMatVector(outputs);
104 CV_Assert(inputs.size() > 0);
106 CV_Assert(blobs.size() == 1 || blobs.size() == 2);
107 CV_Assert(inputs[0].dims == outputs[0].dims);
108 CV_Assert(blobs[0].dims == kernel_size.size() + 2);
109 for (int i = 0; i < kernel_size.size(); i++) {
110 CV_Assert(blobs[0].size[i + 2] == kernel_size[i]);
113 const Mat &input = inputs[0];
114 CV_Assert((input.dims == 4 || input.dims == 5) && (input.type() == CV_32F || input.type() == CV_16S));
115 for (size_t i = 0; i < inputs.size(); i++)
117 CV_Assert(inputs[i].type() == input.type());
118 CV_Assert((inputs[i].dims == 4 || inputs[i].dims == 5) && inputs[i].size[1] == input.size[1]);
119 for (int j = 0; j < inputs[i].dims; j++) {
120 CV_Assert(inputs[i].size[j] == input.size[j]);
124 std::vector<int> inpShape;
125 std::vector<int> outShape;
126 for (int i = 2; i < inputs[0].dims; i++) {
127 inpShape.push_back(inputs[0].size[i]);
128 outShape.push_back(outputs[0].size[i]);
130 getConvPoolPaddings(inpShape, kernel_size, strides, padMode, pads_begin, pads_end);
131 if (pads_begin.size() == 2) {
132 for (int i = 0; i < pads_begin.size(); i++) {
133 if (pads_begin[i] != pads_end[i])
134 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
136 pad = Size(pads_begin[1], pads_begin[0]);
138 fusedWeights = false;
144 return blobs.size() >= 2;
147 virtual MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const = 0;
150 return (kernel.height == 1 && kernel.width == 1) &&
151 (stride.height == 1 && stride.width == 1) &&
152 (dilation.height == 1 && dilation.width == 1);
155 virtual bool tryFuse(Ptr<Layer>& top) CV_OVERRIDE
158 top->getScaleShift(w, b);
159 if (!w.empty() || !b.empty())
162 fusedWeights = fusedWeights || !w.empty();
163 fusedBias = fusedBias || (hasBias() && !w.empty()) || !b.empty();
169 virtual void fuseWeights(const Mat& w_, const Mat& b_) = 0;
171 virtual void applyHalideScheduler(Ptr<BackendNode>& node,
172 const std::vector<Mat*> &inputs,
173 const std::vector<Mat> &outputs,
174 int targetId) const CV_OVERRIDE
177 if (targetId != DNN_TARGET_CPU)
179 Layer::applyHalideScheduler(node, inputs, outputs, targetId);
182 Halide::Var x("x"), y("y"), c("c"), n("n"), tile("tile"), yi("yi"), yo("yo"), co("co"), ci("ci");
183 Halide::Func& top = node.dynamicCast<HalideBackendNode>()->funcs[1];
184 Halide::Func& padded_input = node.dynamicCast<HalideBackendNode>()->funcs[0];
186 int outW, outH, outC, outN;
187 getCanonicalSize(outputs[0].size, &outW, &outH, &outC, &outN);
189 if (outW == 1 || outH <= 2)
192 if (is1x1() || outC <= 16)
198 .vectorize(x, outW >= 16 ? 16 : outW);
202 .split(c, co, ci, 16)
203 .fuse(yo, co, tile).fuse(n, tile, tile)
206 .vectorize(x, outW >= 16 ? 16 : outW);
207 padded_input.compute_at(top, yi);
208 #endif // HAVE_HALIDE
213 #define IS_POWER_LAYER(layer) \
214 (!layer.empty() && !layer->type.compare("Power"))
215 //TODO: simultaneously convolution and bias addition for cache optimization
216 class ConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
219 enum { VEC_ALIGN = 8, DFT_TYPE = CV_32F };
221 std::vector<float> biasvec;
222 std::vector<float> reluslope;
223 Ptr<ActivationLayer> activ;
226 Ptr<OCL4DNNConvSpatial<float> > convolutionOp;
227 std::vector<UMat> umat_blobs;
229 ocl4dnnFusedActiv_t activType;
232 ConvolutionLayerImpl(const LayerParams ¶ms) : BaseConvolutionLayerImpl(params)
236 activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
241 MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
243 int dims = inpShape.size();
244 int inpD = dims == 5 ? inpShape[2] : 1;
245 int inpH = inpShape[dims - 2];
246 int inpW = inpShape.back();
247 int inpGroupCn = blobs[0].size[1];
248 int ksize = inpGroupCn * std::accumulate(kernel_size.begin(), kernel_size.end(),
249 1, std::multiplies<size_t>());
250 return shape(inpD * inpH * inpW, ksize);
253 virtual bool supportBackend(int backendId) CV_OVERRIDE
255 #ifdef HAVE_INF_ENGINE
256 if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
258 if (kernel_size.size() == 3)
259 return preferableTarget == DNN_TARGET_CPU;
260 return (preferableTarget != DNN_TARGET_MYRIAD || dilation.width == dilation.height);
264 return (kernel_size.size() == 3 && preferableTarget == DNN_TARGET_CPU && backendId == DNN_BACKEND_OPENCV) ||
265 (kernel_size.size() == 2 && (backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE));
268 bool getMemoryShapes(const std::vector<MatShape> &inputs,
269 const int requiredOutputs,
270 std::vector<MatShape> &outputs,
271 std::vector<MatShape> &internals) const CV_OVERRIDE
273 CV_Assert(blobs.size() != 0);
274 CV_Assert(!hasBias() || blobs[1].total() == (size_t)blobs[0].size[0]);
275 CV_Assert(inputs.size() == (size_t)1);
279 CV_Assert(inputs.size() != 0);
280 std::vector<int> inpShape(inputs[0].begin() + 2, inputs[0].end());
282 int outCn = blobs[0].size[0];
283 std::vector<int> outShape;
284 outShape.push_back(inputs[0][0]);
285 outShape.push_back(outCn);
287 int inpCn = inputs[0][1];
290 for (int i = 0; i < inpShape.size(); i++)
291 outShape.push_back((inpShape[i] + pads_begin[i] + pads_end[i] - dilations[i] * (kernel_size[i] - 1) - 1) / strides[i] + 1);
295 getConvPoolOutParams(inpShape, kernel_size, strides, padMode, dilations, outShape);
298 int ngroups = inpCn / blobs[0].size[1];
299 if (ngroups == 0 || ngroups * blobs[0].size[1] != inpCn)
300 CV_Error(Error::StsError, format("Number of input channels should "
301 "be multiple of %d but got %d", blobs[0].size[1], inpCn));
302 CV_Assert(ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0);
304 outputs.resize(1, outShape);
309 virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
311 BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
313 CV_Assert(!blobs.empty());
314 const int outCn = blobs[0].size[0];
315 // prepare weightsMat where each row is aligned and has enough zero padding on the right to
316 // use vectorized (i.e. with intrinsics) loops without tail processing
317 Mat wm = blobs[0].reshape(1, outCn);
318 if( wm.step1() % VEC_ALIGN != 0 )
320 int newcols = (int)alignSize(wm.step1(), VEC_ALIGN);
321 Mat wm_buffer = Mat(outCn, newcols, wm.type());
322 Mat wm_padding = wm_buffer.colRange(wm.cols, newcols);
323 wm_padding.setTo(Scalar::all(0.));
324 Mat wm_aligned = wm_buffer.colRange(0, wm.cols);
325 wm.copyTo(wm_aligned);
329 weightsMultipliers.assign(outCn, 1.0);
331 Mat biasMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat();
332 biasvec.resize(outCn+2);
333 if( biasMat.empty() )
335 for(int i = 0; i < outCn; i++ )
340 for(int i = 0; i < outCn; i++ )
341 biasvec[i] = biasMat.at<float>(i);
344 convolutionOp.release();
348 bool setActivation(const Ptr<ActivationLayer>& layer) CV_OVERRIDE
350 if (!activ.empty() && !layer.empty())
358 activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
360 if (IS_DNN_OPENCL_TARGET(preferableTarget))
362 Ptr<PowerLayer> activ_power = activ.dynamicCast<PowerLayer>();
363 if (!activ_power.empty())
365 if (activ_power->scale != 1.f || activ_power->shift != 0.f)
367 const int outCh = blobs[0].size[0];
368 fuseWeights(Mat(1, outCh, CV_32F, Scalar(activ_power->scale)),
369 Mat(1, outCh, CV_32F, Scalar(activ_power->shift)));
372 power = activ_power->power;
373 activType = OCL4DNN_CONV_FUSED_ACTIV_POWER;
375 Ptr<TanHLayer> activ_tanh = activ.dynamicCast<TanHLayer>();
376 if (!activ_tanh.empty())
378 activType = OCL4DNN_CONV_FUSED_ACTIV_TANH;
382 return !activ.empty();
385 void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
387 // Convolution weights have OIHW data layout. Parameters fusion in case of
388 // (conv(I) + b1 ) * w + b2
389 // means to replace convolution's weights to [w*conv(I)] and bias to [b1 * w + b2]
390 const int outCn = weightsMat.size[0];
391 Mat w = w_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(w_.at<float>(0))) : w_;
392 Mat b = b_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(b_.at<float>(0))) : b_;
393 CV_Assert_N(!weightsMat.empty(), biasvec.size() == outCn + 2,
394 w.empty() || outCn == w.total(), b.empty() || outCn == b.total());
398 // Keep origin weights unchanged.
399 if (weightsMat.data == blobs[0].data)
400 weightsMat = weightsMat.clone();
402 Mat originWeights = blobs[0].reshape(1, outCn);
403 for (int i = 0; i < outCn; ++i)
405 double wi = w.at<float>(i);
406 weightsMultipliers[i] *= wi;
407 cv::multiply(originWeights.row(i), weightsMultipliers[i], weightsMat.row(i));
414 for (int i = 0; i < outCn; ++i)
415 biasvec[i] += b.at<float>(i);
417 biasvec[outCn] = biasvec[outCn+1] = biasvec[outCn-1];
420 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
423 Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
425 const int inpCn = inputBuffer.channels();
426 const int outCn = blobs[0].size[0];
427 const int inpGroupCn = blobs[0].size[1];
428 const int group = inpCn / inpGroupCn;
429 const int outGroupCn = outCn / group;
431 Halide::Buffer<float> weights = wrapToHalideBuffer(blobs[0]);
433 Halide::Var x("x"), y("y"), c("c"), n("n");
434 Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
435 Halide::Func padded_input(name + "_constant_exterior");
436 if (pad.width || pad.height)
438 Halide::Func bounded =
439 Halide::BoundaryConditions::constant_exterior(inputBuffer, 0);
440 padded_input(x, y, c, n) = bounded(x, y, c, n);
444 padded_input(x, y, c, n) = inputBuffer(x, y, c, n);
447 Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
448 Halide::Expr kx = x * stride.width - pad.width + r.x * dilation.width;
449 Halide::Expr ky = y * stride.height - pad.height + r.y * dilation.height;
450 Halide::Expr kc = r.z;
451 for (int i = 1; i < group; ++i)
453 kc = select(c < outGroupCn * i, kc, inpGroupCn * i + r.z);
455 Halide::Expr topExpr = sum(padded_input(kx, ky, kc, n) *
456 weights(r.x, r.y, r.z, c));
459 Halide::Buffer<float> bias = wrapToHalideBuffer(blobs[1], {outCn});
462 top(x, y, c, n) = topExpr;
463 return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
464 #endif // HAVE_HALIDE
465 return Ptr<BackendNode>();
468 #ifdef HAVE_INF_ENGINE
469 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
471 InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);
472 std::vector<size_t> dims = input->getDims();
473 CV_Assert(dims.size() == 4 || dims.size() == 5);
474 const int inpCn = dims[1];
475 const int outCn = blobs[0].size[0];
476 const int inpGroupCn = blobs[0].size[1];
477 const int group = inpCn / inpGroupCn;
478 InferenceEngine::Layout layout = (dims.size() == 4) ? InferenceEngine::Layout::OIHW :
479 InferenceEngine::Layout::NCDHW;
481 auto ieWeights = wrapToInfEngineBlob(blobs[0], layout);
484 if (weightsMat.isContinuous())
486 Mat cvWeights = weightsMat.reshape(1, blobs[0].dims, blobs[0].size);
487 ieWeights = wrapToInfEngineBlob(cvWeights, layout);
491 ieWeights = InferenceEngine::make_shared_blob<float>({
492 InferenceEngine::Precision::FP32,
493 ieWeights->getTensorDesc().getDims(), layout
495 ieWeights->allocate();
497 Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, outCn);
498 Mat cvWeights = weightsMat.colRange(0, newWeights.cols);
499 cvWeights.copyTo(newWeights);
502 InferenceEngine::Blob::Ptr ieBiases;
503 if (hasBias() || fusedBias)
505 Mat biasesMat({outCn}, CV_32F, &biasvec[0]);
506 ieBiases = wrapToInfEngineBlob(biasesMat, {(size_t)outCn}, InferenceEngine::Layout::C);
509 InferenceEngine::Builder::ConvolutionLayer ieLayer(name);
511 ieLayer.setKernel(kernel_size);
512 ieLayer.setStrides(strides);
513 ieLayer.setDilation(dilations);
514 ieLayer.setPaddingsBegin(pads_begin);
515 ieLayer.setPaddingsEnd(pads_end);
516 ieLayer.setGroup((size_t)group);
517 ieLayer.setOutDepth((size_t)outCn);
519 InferenceEngine::Builder::Layer l = ieLayer;
520 addConstantData("weights", ieWeights, l);
522 addConstantData("biases", ieBiases, l);
524 if (!padMode.empty())
525 l.getParameters()["auto_pad"] = padMode == "VALID" ? std::string("valid") : std::string("same_upper");
527 return Ptr<BackendNode>(new InfEngineBackendNode(l));
529 #endif // HAVE_INF_ENGINE
531 class ParallelConv : public cv::ParallelLoopBody
534 enum { BLK_SIZE = 32, BLK_SIZE_CN = 64 };
539 int outShape[4]; // used only for conv2d
540 std::vector<size_t> kernel_size, pads_begin, pads_end, strides, dilations;
541 int ngroups_, nstripes_;
542 std::vector<int> ofstab_;
543 const std::vector<float>* biasvec_;
544 const std::vector<float>* reluslope_;
545 const ActivationLayer* activ_;
552 : input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0),
553 biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX(false), useAVX2(false), useAVX512(false)
556 static void run( const Mat& input, Mat& output, const Mat& weights,
557 const std::vector<float>& biasvec,
558 const std::vector<float>& reluslope,
559 const std::vector<size_t>& kernel_size, const std::vector<size_t>& strides,
560 const std::vector<size_t>& pads_begin, const std::vector<size_t>& pads_end,
561 const std::vector<size_t>& dilations,
562 const ActivationLayer* activ, int ngroups, int nstripes )
564 size_t karea = std::accumulate(kernel_size.begin(), kernel_size.end(),
565 1, std::multiplies<size_t>());
567 (input.dims == 4 || input.dims == 5) && (input.dims == output.dims),
568 input.size[0] == output.size[0],
569 weights.rows == output.size[1],
570 weights.cols == (input.size[1]/ngroups)*karea,
571 input.type() == output.type(),
572 input.type() == weights.type(),
573 input.type() == CV_32FC1,
574 input.isContinuous(),
575 output.isContinuous(),
576 biasvec.size() == (size_t)output.size[1]+2);
580 p.weights_ = &weights;
582 for( int i = 0; i < 4; i++ ) p.outShape[i] = output.size[i];
583 p.outShape[1] /= ngroups;
585 p.kernel_size = kernel_size; p.strides = strides; p.dilations = dilations;
586 p.pads_begin = pads_begin; p.pads_end = pads_end;
588 p.ngroups_ = ngroups;
589 p.nstripes_ = nstripes;
591 int inpCnAll = input.size[1];
592 int depth = (input.dims == 5) ? input.size[2] : 1;
593 int width = input.size[input.dims - 1];
594 int height = input.size[input.dims - 2];
595 int inpCn = inpCnAll / ngroups;
597 bool isConv2D = kernel_size.size() == 2;
599 p.is1x1_ = isConv2D && kernel_size[0] == 1 && kernel_size[1] == 1 &&
600 pads_begin[0] == 0 && pads_begin[1] == 0;
602 p.useAVX = checkHardwareSupport(CPU_AVX) && isConv2D;
603 p.useAVX2 = checkHardwareSupport(CPU_AVX2) && isConv2D;
604 p.useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX && isConv2D;
606 int ncn = std::min(inpCn, (int)BLK_SIZE_CN);
608 int kernel_d = !isConv2D? kernel_size[0] : 1;
609 int kernel_h = kernel_size[kernel_size.size() - 2];
610 int kernel_w = kernel_size.back();
612 int dil_d = !isConv2D? dilations[0] : 1;
613 int dil_h = dilations[dilations.size() - 2];
614 int dil_w = dilations.back();
616 p.ofstab_.resize(karea * ncn);
617 int* ofstab = &p.ofstab_[0];
621 for( int k = 0; k < ncn; k++ )
622 for( int k_r = 0; k_r < kernel_h; k_r++ )
623 for( int k_c = 0; k_c < kernel_w; k_c++ )
624 ofstab[(k*kernel_h + k_r)*kernel_w + k_c] =
625 (k*height + k_r*dil_h)*width + k_c*dil_w;
629 for( int k = 0; k < ncn; k++ )
630 for (int k_d = 0; k_d < kernel_d; k_d++)
631 for( int k_r = 0; k_r < kernel_h; k_r++ )
632 for( int k_c = 0; k_c < kernel_w; k_c++ )
633 ofstab[(k*kernel_d*kernel_h + k_d*kernel_h + k_r)*kernel_w + k_c] =
634 (k*depth*height + k_d*dil_d*height + k_r*dil_h)*width + k_c*dil_w;
637 p.biasvec_ = &biasvec;
638 p.reluslope_ = &reluslope;
639 p.activ_ = p.reluslope_->empty() ? activ : 0;
641 parallel_for_(Range(0, nstripes), p, nstripes);
644 virtual void operator ()(const Range &r0) const CV_OVERRIDE
646 const int valign = ConvolutionLayerImpl::VEC_ALIGN;
647 int ngroups = ngroups_, batchSize = input_->size[0]*ngroups;
648 bool isConv2D = input_->dims == 4;
650 int outW = output_->size[output_->dims - 1];
651 int outH = output_->size[output_->dims - 2];
652 int outCn = output_->size[1]/ngroups;
654 int depth = !isConv2D? input_->size[2] : 1;
655 int height = input_->size[input_->dims - 2];
656 int width = input_->size[input_->dims - 1];
657 int inpCn = input_->size[1]/ngroups;
659 const int nstripes = nstripes_;
661 int kernel_d = !isConv2D? kernel_size[0] : 1;
662 int kernel_h = kernel_size[kernel_size.size() - 2];
663 int kernel_w = kernel_size.back();
664 int karea = kernel_w*kernel_h*kernel_d;
666 int pad_d = !isConv2D? pads_begin[0] : 0;
667 int pad_t = pads_begin[pads_begin.size() - 2];
668 int pad_l = pads_begin.back();
670 int stride_d = !isConv2D? strides[0] : 0;
671 int stride_h = strides[strides.size() - 2];
672 int stride_w = strides.back();
674 int dilation_d = !isConv2D? dilations[0] : 1;
675 int dilation_h = dilations[dilations.size() - 2];
676 int dilation_w = dilations.back();
679 size_t inpPlaneSize = input_->total(2);
680 size_t outPlaneSize = output_->total(2);
683 int stripesPerSample;
687 if( nstripes >= batchSize*2 )
689 stripesPerSample = nstripes/batchSize;
690 stripeSize = alignSize((outPlaneSize + stripesPerSample - 1)/stripesPerSample, valign);
691 stripeSize = std::min(stripeSize, outPlaneSize);
695 stripesPerSample = 1;
696 int samplesPerStripe = std::max((batchSize + nstripes - 1)/nstripes, 1);
697 r.start *= samplesPerStripe;
698 r.end *= samplesPerStripe;
699 stripeSize = outPlaneSize;
702 const float* data_inp0_ = input_->ptr<float>();
703 const int* ofstab = &ofstab_[0];
704 const float* wptr_orig_ = weights_->ptr<float>();
705 size_t wstep = weights_->step1();
706 const float* biasptr_ = &biasvec_->at(0);
707 const float* reluptr_ = reluslope_->empty() ? 0 : &reluslope_->at(0);
708 float* data_out0_ = output_->ptr<float>();
709 size_t rowbufsz = (size_t)karea*BLK_SIZE_CN*BLK_SIZE;
710 AutoBuffer<float> rowbuf0_(rowbufsz + valign);
711 float* rowbuf0 = alignPtr(rowbuf0_.data(), (int)(valign*sizeof(float)));
713 // we clear the buffer once; ultimately, it lets us to avoid
714 // tail processing after running the unrolled/vectorized loop.
715 // the main idea is to make sure that the tail (a.k.a. padding) of each row
716 // (i.e. the elements with indices between vsz=karea*ncn and vsz_a)
717 // does not contain NaNs or Infs. Because the padding in the weights
718 // matrix is explicitly initialized with 0's, we handle all other
719 // cases nicely, i.e. we can skip expliciting re-initialization
720 // of the padding - we just retain elements from the previous iteration
721 // of the loop over channels (cn0).
722 memset(rowbuf0, 0, rowbufsz*sizeof(rowbuf0[0]) );
724 for( int stripe = r.start; stripe < r.end; stripe++ )
726 int subsampleIdx = stripe/stripesPerSample;
727 if( subsampleIdx >= batchSize )
729 int stripeStart = (int)((stripe - subsampleIdx*stripesPerSample)*stripeSize);
730 int stripeEnd = (int)std::min(stripeStart + stripeSize, outPlaneSize);
731 const float* data_inp0 = data_inp0_ + subsampleIdx*inpPlaneSize*inpCn;
732 float* data_out0 = data_out0_ + subsampleIdx*outPlaneSize*outCn;
733 int startOutCn = (subsampleIdx % ngroups)*outCn;
734 const float* wptr_orig = wptr_orig_ + wstep*startOutCn;
735 const float* biasptr = biasptr_ + startOutCn;
737 for( int cn0 = 0; cn0 < inpCn; cn0 += BLK_SIZE_CN )
739 int cn1 = std::min(cn0 + BLK_SIZE_CN, inpCn);
740 int ncn = cn1 - cn0, vsz = karea*ncn;
741 int vsz_a = (int)alignSize(vsz, valign);
742 const float* wptr = wptr_orig + cn0*karea;
743 // we apply [Channels][P]ReLU (if any) during the final pass only.
744 const float* relu = cn1 == inpCn && reluptr_ ? reluptr_ + startOutCn : 0;
746 for( int ofs0 = stripeStart; ofs0 < stripeEnd; ofs0 += BLK_SIZE )
748 int ofs, ofs1 = std::min(ofs0 + BLK_SIZE, stripeEnd);
750 int out_d = ofs0 / (outH * outW);
751 int out_i = (ofs0 - out_d * outH * outW) / outW;
752 int out_j = ofs0 % outW;
754 // do im2row for a part of input tensor
755 float* rowbuf = rowbuf0;
759 for( ofs = ofs0; ofs < ofs1; out_j = 0, ++out_i )
761 int delta = std::min(ofs1 - ofs, outW - out_j);
762 int out_j1 = out_j + delta;
764 int in_i = out_i * stride_h - pad_t;
765 int in_j = out_j * stride_w - pad_l;
766 const float* imgptr = data_inp0 + (cn0*height + in_i)*width + in_j;
769 // do im2row for a part of input tensor
772 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w )
774 for( k = 0; k < vsz; k++ )
775 rowbuf[k] = imgptr[k*inpPlaneSize];
780 bool ok_i = 0 <= in_i && in_i < height - (kernel_h-1)*dilation_h;
781 int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);
782 int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);
784 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )
786 // this condition should be true for most of the tensor elements, i.e.
787 // most of the time the kernel aperture is inside the tensor X-Y plane.
788 if( ok_i && out_j + 2 <= out_j1 && 0 <= in_j && in_j + stride_w*2 <= width - (kernel_w-1)*dilation_w )
790 for( k = 0; k < vsz; k++ )
793 float v0 = imgptr[k1];
794 float v1 = imgptr[k1 + stride_w];
796 rowbuf[k+vsz_a] = v1;
805 int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);
806 int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);
808 // here some non-continuous sub-row of the row will not be
809 // filled from the tensor; we need to make sure that the uncovered
810 // elements are explicitly set to 0's. the easiest way is to
811 // set all the elements to 0's before the loop.
812 memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));
813 for( k = 0; k < ncn; k++ )
815 for( i = i0; i < i1; i++ )
817 for( j = j0; j < j1; j++ )
819 int imgofs = k*(width*height) + i*(dilation_h*width) + j*dilation_w;
820 rowbuf[(k*kernel_h + i)*kernel_w + j] = imgptr[imgofs];
831 for( ofs = ofs0; ofs < ofs1; out_d += (out_i + 1) / outH, out_i = (out_i + 1) % outH, out_j = 0 )
833 int delta = std::min(ofs1 - ofs, outW - out_j);
834 int out_j1 = out_j + delta;
836 int in_d = out_d * stride_d - pad_d;
837 int in_i = out_i * stride_h - pad_t;
838 int in_j = out_j * stride_w - pad_l;
839 const float* imgptr = data_inp0 + (cn0*depth*height + in_d*height + in_i)*width + in_j;
842 int d0 = std::max(0, (-in_d + dilation_d - 1) / dilation_d);
843 int d1 = std::min(kernel_d, (depth - in_d + dilation_d - 1) / dilation_d);
845 int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);
846 int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);
848 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )
850 int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);
851 int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);
853 // here some non-continuous sub-row of the row will not be
854 // filled from the tensor; we need to make sure that the uncovered
855 // elements are explicitly set to 0's. the easiest way is to
856 // set all the elements to 0's before the loop.
857 memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));
858 for( k = 0; k < ncn; k++ )
860 for ( d = d0; d < d1; d++)
862 for( i = i0; i < i1; i++ )
864 for( j = j0; j < j1; j++ )
866 int imgofs = k*(depth*width*height) + d*dilation_d*width*height + i*(dilation_h*width) + j*dilation_w;
867 rowbuf[(k*kernel_d*kernel_h + d*kernel_h + i)*kernel_w + j] = imgptr[imgofs];
876 // now compute dot product of the weights
877 // and im2row-transformed part of the tensor
878 int bsz = ofs1 - ofs0;
879 #if CV_TRY_AVX512_SKX
880 /* AVX512 convolution requires an alignment of 16, and ROI is only there for larger vector sizes */
882 opt_AVX512_SKX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
883 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
888 opt_AVX2::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
889 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
894 opt_AVX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
895 outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
898 for( int i = 0; i < outCn; i += 2 )
900 const float* wptr0 = wptr + i*wstep;
901 const float* wptr1 = wptr0 + wstep;
902 float* outptr0 = data_out0 + ofs0 + i*outPlaneSize;
903 float* outptr1 = outptr0 + outPlaneSize;
904 float bias0 = biasptr[i], bias1 = biasptr[i+1];
905 float r0 = 1.f, r1 = 1.f;
916 r0 = relu[i]; r1 = relu[i+1];
923 v_float32x4 vr0 = v_setall_f32(r0), vr1 = v_setall_f32(r1), z = v_setzero_f32();
925 for( ; j <= bsz - 4; j += 4 )
927 const float* rptr = rowbuf0 + j*vsz_a;
932 s0 = v_setall_f32(bias0);
933 s1 = v_setall_f32(bias1);
937 s0 = v_load(outptr0 + j);
938 s1 = v_load(outptr1 + j);
941 v_float32x4 vs00 = v_setzero_f32(), vs01 = v_setzero_f32(),
942 vs02 = v_setzero_f32(), vs03 = v_setzero_f32(),
943 vs10 = v_setzero_f32(), vs11 = v_setzero_f32(),
944 vs12 = v_setzero_f32(), vs13 = v_setzero_f32();
945 for( k = 0; k < vsz; k += 4, rptr += 4 )
947 v_float32x4 w0 = v_load_aligned(wptr0 + k), w1 = v_load_aligned(wptr1 + k);
948 v_float32x4 r0 = v_load_aligned(rptr), r1 = v_load_aligned(rptr + vsz_a),
949 r2 = v_load_aligned(rptr + vsz_a*2), r3 = v_load_aligned(rptr + vsz_a*3);
961 s0 += v_reduce_sum4(vs00, vs01, vs02, vs03);
962 s1 += v_reduce_sum4(vs10, vs11, vs12, vs13);
965 s0 = v_select(s0 > z, s0, s0*vr0);
966 s1 = v_select(s1 > z, s1, s1*vr1);
969 v_store(outptr0 + j, s0);
970 v_store(outptr1 + j, s1);
973 for( ; j < bsz; j++ )
975 const float* rptr = rowbuf0 + j*vsz_a;
989 for( k = 0; k < vsz; k++ )
997 s00 = s00 > 0.f ? s00 : s00*r0;
998 s10 = s10 > 0.f ? s10 : s10*r1;
1009 activ_->forwardSlice(data_out0 + stripeStart, data_out0 + stripeStart,
1010 (int)(stripeEnd - stripeStart),
1011 outPlaneSize, startOutCn, startOutCn + outCn);
1017 bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
1019 std::vector<UMat> inputs;
1020 std::vector<UMat> outputs;
1022 bool use_half = (inps.depth() == CV_16S);
1023 inps.getUMatVector(inputs);
1024 outs.getUMatVector(outputs);
1026 CV_Assert(outputs.size() == 1);
1027 for (int i = 0; i < inputs.size(); ++i)
1028 CV_Assert(inputs[i].u != outputs[0].u);
1030 if (umat_blobs.empty())
1032 size_t n = blobs.size();
1033 umat_blobs.resize(n);
1034 for (size_t i = 0; i < n; i++)
1036 blobs[i].copyTo(umat_blobs[i]);
1040 if (convolutionOp.empty())
1042 OCL4DNNConvConfig config;
1043 config.in_shape = shape(inputs[0]);
1044 config.out_shape = shape(outputs[0]);
1045 config.kernel = kernel;
1047 config.stride = stride;
1048 config.dilation = dilation;
1049 config.group = inputs[0].size[1] / umat_blobs[0].size[1];
1050 config.bias_term = (hasBias()) ? true : false;
1051 config.use_half = use_half;
1053 convolutionOp = Ptr<OCL4DNNConvSpatial<float> >(new OCL4DNNConvSpatial<float>(config));
1056 int outCn = umat_blobs[0].size[0];
1061 Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
1062 if( !activ_relu.empty() )
1064 reluslope.assign(outCn+2, activ_relu->negativeSlope);
1065 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU;
1068 Ptr<ReLU6Layer> activ_relu6 = activ.dynamicCast<ReLU6Layer>();
1069 if( !activ_relu6.empty() )
1071 reluslope.resize(2);
1072 reluslope[0] = activ_relu6->minValue;
1073 reluslope[1] = activ_relu6->maxValue;
1074 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU6;
1077 Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1078 if( !activ_chprelu.empty() )
1080 const Mat& m = activ_chprelu->blobs[0];
1081 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1082 const float* mdata = m.ptr<float>();
1083 reluslope.resize(outCn+2);
1084 std::copy(mdata, mdata + outCn, reluslope.begin());
1085 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1086 activType = OCL4DNN_CONV_FUSED_ACTIV_PRELU;
1092 weightsMat.copyTo(umat_blobs[0]);
1093 fusedWeights = false;
1097 if ( umat_blobs.size() < 2 )
1098 umat_blobs.resize(2);
1099 umat_blobs[1] = UMat(biasvec, true);
1100 convolutionOp->setBias(true);
1106 if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU )
1108 CV_Assert(!reluslope.empty());
1109 convolutionOp->setActivReLU(true, reluslope[0]);
1111 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_PRELU)
1113 CV_Assert(!reluslope.empty());
1114 convolutionOp->setActivPReLU(true, reluslope);
1116 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_POWER)
1118 convolutionOp->setActivPower(true, power);
1120 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_TANH)
1122 convolutionOp->setActivTanh(true);
1124 else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU6)
1126 convolutionOp->setActivReLU6(true, reluslope[0], reluslope[1]);
1130 convolutionOp->setActivReLU(false, 0);
1131 convolutionOp->setActivPReLU(false, reluslope);
1132 convolutionOp->setActivPower(false, 1.f);
1133 convolutionOp->setActivTanh(false);
1134 convolutionOp->setActivReLU6(false, 0, 0);
1139 UMat& inpMat = inputs[0];
1140 UMat& outMat = outputs[0];
1141 int batch_size = inpMat.size[0];
1143 return convolutionOp->Forward(inpMat,
1144 inputs.size() == 2 ? inputs[1] : UMat(),
1146 umat_blobs.size() > 1 ? umat_blobs[1] : UMat(),
1152 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1154 CV_TRACE_FUNCTION();
1155 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1157 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1158 forward_ocl(inputs_arr, outputs_arr, internals_arr))
1160 if (inputs_arr.depth() == CV_16S)
1162 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1166 std::vector<Mat> inputs, outputs;
1167 inputs_arr.getMatVector(inputs);
1168 outputs_arr.getMatVector(outputs);
1170 /*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",
1171 name.c_str(), inputs[0].size[0], inputs[0].size[1], inputs[0].size[2], inputs[0].size[3],
1172 kernel.width, kernel.height, pad.width, pad.height,
1173 stride.width, stride.height, dilation.width, dilation.height);*/
1174 CV_Assert_N(inputs.size() == (size_t)1, inputs[0].size[1] % blobs[0].size[1] == 0,
1175 outputs.size() == 1, inputs[0].data != outputs[0].data);
1177 int ngroups = inputs[0].size[1]/blobs[0].size[1];
1178 CV_Assert(outputs[0].size[1] % ngroups == 0);
1179 int outCn = blobs[0].size[0];
1184 Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
1185 if( !activ_relu.empty() )
1187 reluslope.assign(outCn+2, activ_relu->negativeSlope);
1190 Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1191 if( !activ_chprelu.empty() )
1193 const Mat& m = activ_chprelu->blobs[0];
1194 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1195 const float* mdata = m.ptr<float>();
1196 reluslope.resize(outCn+2);
1197 std::copy(mdata, mdata + outCn, reluslope.begin());
1198 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1202 int nstripes = std::max(getNumThreads(), 1);
1204 ParallelConv::run(inputs[0], outputs[0], weightsMat, biasvec, reluslope,
1205 kernel_size, strides, pads_begin, pads_end, dilations, activ.get(), ngroups, nstripes);
1208 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
1209 const std::vector<MatShape> &outputs) const CV_OVERRIDE
1211 CV_Assert(inputs.size() == outputs.size());
1214 int karea = std::accumulate(kernel_size.begin(), kernel_size.end(), 1, std::multiplies<size_t>());
1215 for (int i = 0; i < inputs.size(); i++)
1217 flops += total(outputs[i])*(CV_BIG_INT(2)*karea*inputs[i][1] + 1);
1224 class DeConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
1227 Mat weightsMat, biasesMat;
1231 DeConvolutionLayerImpl(const LayerParams& params) : BaseConvolutionLayerImpl(params) {}
1233 MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
1235 int dims = inpShape.size();
1236 int inpCn = inpShape[1];
1237 int inpD = dims == 5 ? inpShape[2] : 1;
1238 int inpH = inpShape[dims - 2];
1239 int inpW = inpShape.back();
1240 int outCn = outShape[1];
1241 int ngroups = inpCn / blobs[0].size[0];
1242 int outGroupCn = outCn / ngroups;
1243 int ksize = outGroupCn * std::accumulate(kernel_size.begin(), kernel_size.end(),
1244 1, std::multiplies<size_t>());
1245 return shape(ksize, inpD * inpH * inpW);
1248 virtual bool supportBackend(int backendId) CV_OVERRIDE
1250 #ifdef HAVE_INF_ENGINE
1251 const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW or IODHW layout
1252 const int group = numOutput / outGroupCn;
1254 if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
1256 if (kernel_size.size() == 3 && preferableTarget != DNN_TARGET_CPU) {
1260 if (std::accumulate(adjust_pads.begin(), adjust_pads.end(), 0, std::plus<size_t>()) > 0)
1262 if (padMode.empty())
1264 if (preferableTarget != DNN_TARGET_CPU && group != 1)
1266 for (int i = 0; i < adjust_pads.size(); i++) {
1267 if (adjust_pads[i] && pads_begin[i])
1271 for (int i = 0; i < adjust_pads.size(); i++) {
1272 if (pads_end[i] < adjust_pads[i])
1277 else if (padMode == "SAME")
1279 for (int i = 0; i < adjust_pads.size(); i++) {
1280 if (kernel_size[i] < pads_begin[i] + 1 + adjust_pads[i])
1285 else if (padMode == "VALID")
1291 return preferableTarget == DNN_TARGET_CPU;
1293 if (preferableTarget == DNN_TARGET_OPENCL || preferableTarget == DNN_TARGET_OPENCL_FP16)
1294 return std::accumulate(dilations.begin(), dilations.end(), 1, std::multiplies<size_t>()) == 1;
1298 #endif // HAVE_INF_ENGINE
1299 return kernel_size.size() == 2 && (backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE);
1302 bool getMemoryShapes(const std::vector<MatShape> &inputs,
1303 const int requiredOutputs,
1304 std::vector<MatShape> &outputs,
1305 std::vector<MatShape> &internals) const CV_OVERRIDE
1307 CV_Assert(!hasBias() || blobs[1].total() == (size_t)numOutput);
1308 CV_Assert(inputs.size() != 0);
1310 int outCn = numOutput;
1311 std::vector<int> outShape;
1312 outShape.push_back(inputs[0][0]); // batch
1313 outShape.push_back(outCn);
1314 if (padMode.empty())
1316 for (int i = 0; i < kernel_size.size(); i++)
1317 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] - pads_begin[i] - pads_end[i] + adjust_pads[i]);
1319 else if (padMode == "VALID")
1321 for (int i = 0; i < kernel_size.size(); i++)
1322 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] + adjust_pads[i]);
1324 else if (padMode == "SAME")
1326 for (int i = 0; i < kernel_size.size(); i++)
1327 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + 1 + adjust_pads[i]);
1330 CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
1332 CV_Assert(outCn % blobs[0].size[1] == 0);
1333 int ngroups = outCn / blobs[0].size[1];
1335 int inpCn = inputs[0][1];
1336 CV_Assert(inpCn % ngroups == 0 && outCn % ngroups == 0);
1337 CV_Assert(blobs[0].size[0] == inpCn);
1339 outputs.resize(1, outShape);
1342 internals.push_back(computeColRowShape(inputs[0], outputs[0]));
1347 void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1349 BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
1351 std::vector<Mat> inputs, outputs;
1352 inputs_arr.getMatVector(inputs);
1353 outputs_arr.getMatVector(outputs);
1355 std::vector<int> inpShape;
1356 std::vector<int> outShape;
1357 for (int i = 2; i < inputs[0].dims; i++) {
1358 inpShape.push_back(inputs[0].size[i]);
1359 outShape.push_back(outputs[0].size[i]);
1361 getConvPoolPaddings(outShape, kernel_size, strides, padMode, pads_begin, pads_end);
1362 if (pads_begin.size() == 2) {
1363 for (int i = 0; i < pads_begin.size(); i++) {
1364 if (pads_begin[i] != pads_end[i])
1365 CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in deconvolution layer");
1367 pad = Size(pads_begin[1], pads_begin[0]);
1370 weightsMultipliers.assign(numOutput, 1.0);
1371 if (weightsMat.empty())
1373 transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1374 biasesMat = hasBias() ? blobs[1].reshape(1, numOutput)
1375 : Mat::zeros(numOutput, 1, CV_32F);
1379 void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
1381 Mat w = w_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(w_.at<float>(0))) : w_;
1382 Mat b = b_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(b_.at<float>(0))) : b_;
1384 CV_Assert_N(!weightsMat.empty(),
1385 w.empty() || numOutput == w.total(),
1386 b.empty() || numOutput == b.total());
1390 transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1391 weightsMat = weightsMat.reshape(1, numOutput);
1392 for (int i = 0; i < numOutput; ++i)
1394 double wi = w.at<float>(i);
1395 weightsMultipliers[i] *= wi;
1396 cv::multiply(weightsMat.row(i), weightsMultipliers[i], weightsMat.row(i));
1397 biasesMat.at<float>(i) *= wi;
1399 weightsMat = weightsMat.reshape(1, weightsMat.total() / blobs[0].size[0]);
1404 cv::add(biasesMat, b.reshape(1, numOutput), biasesMat);
1408 class MatMulInvoker : public ParallelLoopBody
1411 MatMulInvoker(const Mat& a, const Mat& b, Mat& c, int nstripes)
1416 nstripes_ = nstripes;
1417 useAVX = checkHardwareSupport(CPU_AVX);
1418 useAVX2 = checkHardwareSupport(CPU_AVX2);
1419 useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;
1422 void operator()(const Range& range_) const CV_OVERRIDE
1424 int stripeSize = (int)alignSize((b_->cols + nstripes_ - 1)/nstripes_, 16);
1425 Range range(range_.start*stripeSize, std::min(range_.end*stripeSize, b_->cols));
1426 int mmax = a_->rows;
1427 int nmax = range.end - range.start;
1428 int kmax = a_->cols;
1430 const float* aptr = a_->ptr<float>();
1431 const float* bptr = b_->ptr<float>() + range.start;
1432 float* cptr = c_->ptr<float>() + range.start;
1433 size_t astep = a_->step1();
1434 size_t bstep = b_->step1();
1435 size_t cstep = c_->step1();
1437 #if CV_TRY_AVX512_SKX
1439 opt_AVX512_SKX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1444 opt_AVX2::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1449 opt_AVX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1452 for( m = 0; m < mmax; m += 2 )
1454 float* dst0 = cptr + cstep*m;
1455 float* dst1 = cptr + cstep*std::min(m+1, mmax-1);
1456 const float* aptr0 = aptr + astep*m;
1457 const float* aptr1 = aptr + astep*std::min(m+1, mmax-1);
1459 for( n = 0; n < nmax; n++ )
1465 for( k = 0; k < kmax; k += 4 )
1467 float alpha00 = aptr0[k];
1468 float alpha01 = aptr1[k];
1469 float alpha10 = 0.f, alpha11 = 0.f;
1470 float alpha20 = 0.f, alpha21 = 0.f;
1471 float alpha30 = 0.f, alpha31 = 0.f;
1472 const float* bptr0 = bptr + k*bstep;
1473 const float* bptr1 = bptr0;
1474 const float* bptr2 = bptr0;
1475 const float* bptr3 = bptr0;
1479 alpha10 = aptr0[k+1];
1480 alpha11 = aptr1[k+1];
1481 bptr1 = bptr0 + bstep;
1484 alpha20 = aptr0[k+2];
1485 alpha21 = aptr1[k+2];
1486 bptr2 = bptr1 + bstep;
1489 alpha30 = aptr0[k+3];
1490 alpha31 = aptr1[k+3];
1491 bptr3 = bptr2 + bstep;
1498 v_float32x4 a00 = v_setall_f32(alpha00);
1499 v_float32x4 a01 = v_setall_f32(alpha01);
1500 v_float32x4 a10 = v_setall_f32(alpha10);
1501 v_float32x4 a11 = v_setall_f32(alpha11);
1502 v_float32x4 a20 = v_setall_f32(alpha20);
1503 v_float32x4 a21 = v_setall_f32(alpha21);
1504 v_float32x4 a30 = v_setall_f32(alpha30);
1505 v_float32x4 a31 = v_setall_f32(alpha31);
1507 for( ; n <= nmax - 4; n += 4 )
1509 v_float32x4 b0 = v_load(bptr0 + n);
1510 v_float32x4 b1 = v_load(bptr1 + n);
1511 v_float32x4 b2 = v_load(bptr2 + n);
1512 v_float32x4 b3 = v_load(bptr3 + n);
1513 v_float32x4 d0 = v_load(dst0 + n);
1514 v_float32x4 d1 = v_load(dst1 + n);
1523 v_store(dst0 + n, d0);
1524 v_store(dst1 + n, d1);
1528 for( ; n < nmax; n++ )
1530 float b0 = bptr0[n], b1 = bptr1[n];
1531 float b2 = bptr2[n], b3 = bptr3[n];
1532 float d0 = dst0[n] + alpha00*b0 + alpha10*b1 + alpha20*b2 + alpha30*b3;
1533 float d1 = dst1[n] + alpha01*b0 + alpha11*b1 + alpha21*b2 + alpha31*b3;
1549 class Col2ImInvoker : public cv::ParallelLoopBody
1552 const float* data_col;
1553 const float* biasvec;
1554 int channels, height, width;
1555 int kernel_h, kernel_w;
1557 int stride_h, stride_w;
1559 int height_col, width_col;
1564 : data_col(0), biasvec(0), channels(0), height(0), width(0),
1565 kernel_h(0), kernel_w(0), pad_h(0), pad_w(0), stride_h(0), stride_w(0), data_im(0),
1566 height_col(0), width_col(0), nstripes(0), is1x1(0)
1569 static void run(const float* data_col,
1570 int channels, int height, int width,
1571 int kernel_h, int kernel_w,
1572 int pad_h, int pad_w,
1573 int stride_h, int stride_w,
1574 int height_col, int width_col,
1576 const float* biasvec,
1579 const int nstripes = getNumThreads();
1582 t.data_col = data_col;
1583 t.data_im = data_im;
1584 t.channels = channels; t.height = height; t.width = width;
1585 t.kernel_h = kernel_h; t.kernel_w = kernel_w;
1586 t.pad_h = pad_h; t.pad_w = pad_w;
1587 t.stride_h = stride_h; t.stride_w = stride_w;
1588 t.height_col = height_col;
1589 t.width_col = width_col;
1590 t.nstripes = nstripes;
1592 t.biasvec = biasvec;
1594 parallel_for_(Range(0, nstripes), t, nstripes);
1597 virtual void operator ()(const Range &r) const CV_OVERRIDE
1599 const float* data_col_ = data_col;
1600 float* data_im_ = data_im;
1601 int coeff_h = (1 - stride_h * kernel_w * height_col) * width_col;
1602 int coeff_w = (1 - stride_w * height_col * width_col);
1603 size_t total = (size_t)channels * height * width;
1604 size_t stripeSize = (total + nstripes - 1)/nstripes;
1605 size_t startIndex = r.start*stripeSize;
1606 size_t endIndex = std::min(r.end*stripeSize, total);
1607 int w = (int)(startIndex % width + pad_w);
1608 int h = (int)((startIndex / width) % height + pad_h);
1609 int c = (int)(startIndex / (width * height));
1610 int h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1611 int h_col_end = std::min(h / stride_h + 1, height_col);
1612 int plane_size_col = height_col * width_col;
1613 int offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1614 bool is1x1_ = is1x1;
1615 const float* biasvec_ = biasvec;
1617 for (size_t index = startIndex; index < endIndex; index++)
1619 // compute the start and end of the output
1620 int w_col_start = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1;
1621 int w_col_end = std::min(w / stride_w + 1, width_col);
1625 val = data_im_[index];
1629 for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {
1630 for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {
1631 val += data_col_[offset + h_col * coeff_h + w_col * coeff_w];
1635 data_im_[index] = val + biasvec_[c];
1637 offset += plane_size_col;
1638 if( ++w >= width + pad_w )
1640 w = (int)((index + 1)% width + pad_w);
1641 h = (int)(((index + 1) / width) % height + pad_h);
1642 c = (int)((index + 1) / (width * height));
1643 h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1644 h_col_end = std::min(h / stride_h + 1, height_col);
1645 offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1652 bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
1654 std::vector<UMat> inputs;
1655 std::vector<UMat> outputs;
1656 std::vector<UMat> internals;
1658 if (inputs_.depth() == CV_16S)
1661 inputs_.getUMatVector(inputs);
1662 outputs_.getUMatVector(outputs);
1663 internals_.getUMatVector(internals);
1665 int outCn = numOutput;
1666 int inpCn = inputs[0].size[1];
1671 if (umat_weights.empty())
1674 weightsMat.copyTo(umat_weights);
1676 transpose(blobs[0].reshape(1, inpCn), umat_weights);
1679 biasesMat.copyTo(umat_biases);
1683 blobs[1].reshape(1, outCn).copyTo(umat_biases);
1685 umat_biases = UMat::zeros(outCn, 1, CV_32F);
1689 String buildopt = format("-DT=%s ", ocl::typeToStr(inputs[0].type()));
1690 buildopt += format("-DPAD_H=%d -DPAD_W=%d -DKERNEL_H=%d -DKERNEL_W=%d -DSTRIDE_H=%d -DSTRIDE_W=%d ",
1691 pad.height, pad.width, kernel.height, kernel.width, stride.height, stride.width);
1693 for (size_t ii = 0; ii < outputs.size(); ii++)
1695 int ngroups = outCn / blobs[0].size[1];
1696 int inpGroupCn = inpCn / ngroups;
1697 int outGroupCn = blobs[0].size[1];
1698 const UMat& inp = inputs[ii];
1699 UMat& out = outputs[ii];
1700 int numImg = inp.size[0];
1701 int inpH = inp.size[2], inpW = inp.size[3];
1702 int outH = out.size[2], outW = out.size[3];
1704 MatShape inpshape = shape(numImg*inpCn, inpH*inpW);
1705 MatShape outshape = shape(numImg*outCn, outH*outW);
1706 UMat convBlob = inputs[ii].reshape(1, inpshape.size(), &inpshape[0]);
1707 UMat decnBlob = out.reshape(1, outshape.size(), &outshape[0]);
1708 int rows = internals[0].rows / ngroups;
1710 for (int n = 0; n < numImg; n++)
1712 for (int g = 0; g < ngroups; g++)
1714 UMat colMat = internals[0].rowRange(_Range(g * rows, rows));
1715 UMat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1716 UMat wghtMat = umat_weights.colRange(_Range(g * inpGroupCn, inpGroupCn));
1717 gemm(wghtMat, convMat, 1, noArray(), 0, colMat, 0);
1720 for (int g = 0; g < ngroups; g++)
1722 int total = outGroupCn * decnBlob.cols;
1724 int height_col = inpH;
1725 int width_col = inpW;
1726 int coeff_h = (1 - stride.height * kernel.width * height_col) * width_col;
1727 int coeff_w = (1 - stride.width * height_col * width_col);
1729 ocl::Kernel k("col2im", ocl::dnn::col2im_oclsrc, buildopt);
1730 k.set(index++, total);
1731 k.set(index++, ocl::KernelArg::PtrReadOnly(internals[0]));
1732 k.set(index++, (int)(g * rows * internals[0].cols));
1733 k.set(index++, outGroupCn);
1734 k.set(index++, outH);
1735 k.set(index++, outW);
1736 k.set(index++, height_col);
1737 k.set(index++, width_col);
1738 k.set(index++, coeff_h);
1739 k.set(index++, coeff_w);
1740 k.set(index++, ocl::KernelArg::PtrReadOnly(umat_biases));
1741 k.set(index++, (int)(g * outGroupCn * umat_biases.cols));
1742 k.set(index++, ocl::KernelArg::PtrWriteOnly(decnBlob));
1743 k.set(index++, (int)((g + n * ngroups) * outGroupCn * decnBlob.cols));
1745 size_t global[] = { (size_t)total };
1746 bool ret = k.run(1, global, NULL, false);
1757 void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1759 CV_TRACE_FUNCTION();
1760 CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1762 CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1763 forward_ocl(inputs_arr, outputs_arr, internals_arr));
1765 if (inputs_arr.depth() == CV_16S)
1767 forward_fallback(inputs_arr, outputs_arr, internals_arr);
1771 std::vector<Mat> inputs, outputs, internals;
1772 inputs_arr.getMatVector(inputs);
1773 outputs_arr.getMatVector(outputs);
1774 internals_arr.getMatVector(internals);
1776 int outCn = numOutput;
1777 int inpCn = inputs[0].size[1];
1778 bool is1x1flag = is1x1();
1779 int nstripes = getNumThreads();
1781 if( weightsMat.empty() )
1783 transpose(blobs[0].reshape(1, inpCn), weightsMat);
1784 biasesMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);
1787 for (size_t ii = 0; ii < outputs.size(); ii++)
1789 int ngroups = outCn / blobs[0].size[1];
1790 int inpGroupCn = inpCn / ngroups;
1791 int outGroupCn = blobs[0].size[1];
1792 const Mat& inp = inputs[ii];
1793 Mat& out = outputs[ii];
1794 int numImg = inp.size[0];
1795 int inpH = inp.size[2], inpW = inp.size[3];
1796 int outH = out.size[2], outW = out.size[3];
1798 Mat convBlob = inputs[ii].reshape(1, numImg*inpCn);
1799 Mat decnBlob = out.reshape(1, numImg*outCn);
1801 for (int n = 0; n < numImg; n++)
1803 for (int g = 0; g < ngroups; g++)
1805 Mat dstMat = decnBlob.rowRange(_Range((g + n * ngroups) * outGroupCn, outGroupCn));
1806 Mat &colMat = is1x1flag ? dstMat : internals[0];
1808 Mat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1809 Mat wghtMat = weightsMat.colRange(_Range(g * inpGroupCn, inpGroupCn));
1810 Mat curBiasMat = biasesMat.rowRange(_Range(g * outGroupCn, outGroupCn));
1812 //gemm(wghtMat, convMat, 1, colMat, 0, colMat, 0);
1813 MatMulInvoker mminvoker(wghtMat, convMat, colMat, nstripes);
1814 parallel_for_(Range(0, nstripes), mminvoker, nstripes);
1816 Col2ImInvoker::run(colMat.ptr<float>(), outGroupCn, outH, outW,
1817 kernel.height, kernel.width, pad.height, pad.width,
1818 stride.height, stride.width, inpH, inpW, dstMat.ptr<float>(),
1819 curBiasMat.ptr<float>(), is1x1flag);
1825 virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
1828 Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
1830 int inW, inH, inC, inN;
1831 getCanonicalSize(inputBuffer, &inW, &inH, &inC, &inN);
1832 const int outGroupCn = blobs[0].size[1];
1833 const int group = numOutput / outGroupCn;
1834 const int inpGroupCn = blobs[0].size[0] / group;
1836 Halide::Var x("x"), y("y"), c("c"), n("n");
1837 Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
1838 Halide::Func padded_input(name + "_constant_exterior");
1839 auto weights = wrapToHalideBuffer(blobs[0]);
1841 Halide::Func dilated_input("dilated_input");
1842 dilated_input(x, y, c, n) = 0.0f;
1843 Halide::RDom r1(0, inW, 0, inH);
1844 dilated_input(r1.x * stride.width, r1.y * stride.height, c, n) =
1845 inputBuffer(r1.x, r1.y, c, n);
1846 dilated_input.compute_root();
1848 Halide::Func bounded =
1849 Halide::BoundaryConditions::constant_exterior(dilated_input, 0,
1850 0, (inW - 1) * stride.width + 1,
1851 0, (inH - 1) * stride.height + 1,
1853 padded_input(x, y, c, n) = bounded(x, y, c, n);
1855 Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
1856 Halide::Expr kx = x + pad.width - r.x;
1857 Halide::Expr ky = y + pad.height - r.y;
1858 Halide::Expr kInC = r.z;
1859 Halide::Expr kOutC = c;
1860 for (int i = 1; i < group; ++i)
1862 kInC = select(c < outGroupCn * i, kInC, inpGroupCn * i + r.z);
1863 kOutC = select(c < outGroupCn * i, kOutC, c - outGroupCn * i);
1865 Halide::Expr topExpr = sum(padded_input(kx, ky, kInC, n) *
1866 weights(r.x, r.y, kOutC, kInC));
1869 auto bias = wrapToHalideBuffer(blobs[1], {numOutput});
1872 top(x, y, c, n) = topExpr;
1873 return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
1874 #endif // HAVE_HALIDE
1875 return Ptr<BackendNode>();
1878 #ifdef HAVE_INF_ENGINE
1879 virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &) CV_OVERRIDE
1881 InferenceEngine::Layout layout = blobs[0].dims == 5? InferenceEngine::Layout::NCDHW :
1882 InferenceEngine::Layout::OIHW;
1884 auto ieWeights = wrapToInfEngineBlob(blobs[0], layout);
1887 ieWeights = InferenceEngine::make_shared_blob<float>({
1888 InferenceEngine::Precision::FP32,
1889 ieWeights->getTensorDesc().getDims(), layout
1891 ieWeights->allocate();
1893 int inpCn = blobs[0].size[0];
1894 Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, inpCn);
1895 transpose(weightsMat, newWeights);
1898 const int outGroupCn = blobs[0].size[1]; // Weights are in IOHW or OIDHW layout
1899 const int group = numOutput / outGroupCn;
1901 InferenceEngine::Builder::DeconvolutionLayer ieLayer(name);
1903 ieLayer.setKernel(kernel_size);
1904 ieLayer.setStrides(strides);
1905 ieLayer.setDilation(dilations);
1906 ieLayer.setPaddingsBegin(pads_begin);
1908 if (padMode.empty())
1910 std::vector<size_t> paddings_end;
1911 for (int i = 0; i < pads_end.size(); i++) {
1912 paddings_end.push_back(pads_end[i] - adjust_pads[i]);
1914 ieLayer.setPaddingsEnd(paddings_end);
1916 else if (padMode == "SAME")
1918 std::vector<size_t> paddings_end;
1919 for (int i = 0; i < pads_begin.size(); i++) {
1920 paddings_end.push_back(kernel_size[i] - pads_begin[i] - 1 - adjust_pads[i]);
1922 ieLayer.setPaddingsEnd(paddings_end);
1924 ieLayer.setGroup((size_t)group);
1925 ieLayer.setOutDepth((size_t)numOutput);
1927 InferenceEngine::Builder::Layer l = ieLayer;
1928 addConstantData("weights", ieWeights, l);
1930 addConstantData("biases", wrapToInfEngineBlob(biasesMat, {(size_t)numOutput}, InferenceEngine::Layout::C), l);
1931 return Ptr<BackendNode>(new InfEngineBackendNode(l));
1933 #endif // HAVE_INF_ENGINE
1935 virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
1936 const std::vector<MatShape> &outputs) const CV_OVERRIDE
1938 CV_Assert(inputs.size() == outputs.size());
1941 int outChannels = blobs[0].size[0];
1942 size_t karea = std::accumulate(kernel_size.begin(), kernel_size.end(),
1943 1, std::multiplies<size_t>());
1945 for (int i = 0; i < inputs.size(); i++)
1947 flops += CV_BIG_INT(2)*outChannels*karea*total(inputs[i]);
1954 Ptr<BaseConvolutionLayer> ConvolutionLayer::create(const LayerParams ¶ms)
1956 Ptr<ConvolutionLayerImpl> l(new ConvolutionLayerImpl(params));
1960 Ptr<BaseConvolutionLayer> DeconvolutionLayer::create(const LayerParams ¶ms)
1962 return Ptr<BaseConvolutionLayer>(new DeConvolutionLayerImpl(params));