Merge pull request #14661 from dkurt:ie_deconv_adj
[platform/upstream/opencv.git] / modules / dnn / src / layers / convolution_layer.cpp
1 /*M///////////////////////////////////////////////////////////////////////////////////////
2 //
3 //  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
4 //
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.
8 //
9 //
10 //                           License Agreement
11 //                For Open Source Computer Vision Library
12 //
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.
16 //
17 // Redistribution and use in source and binary forms, with or without modification,
18 // are permitted provided that the following conditions are met:
19 //
20 //   * Redistribution's of source code must retain the above copyright notice,
21 //     this list of conditions and the following disclaimer.
22 //
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.
26 //
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.
29 //
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.
40 //
41 //M*/
42
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"
49 #include <iostream>
50
51 #ifdef HAVE_OPENCL
52 #include "opencl_kernels_dnn.hpp"
53 using namespace cv::dnn::ocl4dnn;
54 #endif
55
56 namespace cv
57 {
58 namespace dnn
59 {
60
61 class BaseConvolutionLayerImpl : public ConvolutionLayer
62 {
63 public:
64     bool fusedWeights, fusedBias;
65     std::vector<double> weightsMultipliers;
66     BaseConvolutionLayerImpl(const LayerParams &params)
67     {
68         setParamsFrom(params);
69         getConvolutionKernelParams(params, kernel_size, pads_begin, pads_end, strides, dilations, padMode);
70
71         numOutput = params.get<int>("num_output");
72         int ngroups = params.get<int>("group", 1);
73         CV_Assert(numOutput % ngroups == 0);
74
75         if (kernel_size.size() == 2) {
76             kernel = Size(kernel_size[1], kernel_size[0]);
77             stride = Size(strides[1], strides[0]);
78             for (int i = 0; i < pads_begin.size(); i++) {
79                 if (pads_begin[i] != pads_end[i])
80                     CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
81             }
82             pad = Size(pads_begin[1], pads_begin[0]);
83             dilation = Size(dilations[1], dilations[0]);
84
85             adjust_pads.push_back(params.get<int>("adj_h", 0));
86             adjust_pads.push_back(params.get<int>("adj_w", 0));
87
88             adjustPad.height = adjust_pads[0];
89             adjustPad.width = adjust_pads[1];
90             CV_Assert(adjustPad.width < stride.width &&
91                       adjustPad.height < stride.height);
92         }
93         fusedWeights = false;
94         fusedBias = false;
95     }
96
97     virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
98     {
99         std::vector<Mat> inputs, outputs;
100         inputs_arr.getMatVector(inputs);
101         outputs_arr.getMatVector(outputs);
102
103         CV_Assert(inputs.size() > 0);
104
105         CV_Assert(blobs.size() == 1 || blobs.size() == 2);
106         CV_Assert(inputs[0].dims == outputs[0].dims);
107         CV_Assert(blobs[0].dims == kernel_size.size() + 2);
108         for (int i = 0; i < kernel_size.size(); i++) {
109             CV_Assert(blobs[0].size[i + 2] == kernel_size[i]);
110         }
111
112         const Mat &input = inputs[0];
113         CV_Assert((input.dims == 4 || input.dims == 5) && (input.type() == CV_32F || input.type() == CV_16S));
114         for (size_t i = 0; i < inputs.size(); i++)
115         {
116             CV_Assert(inputs[i].type() == input.type());
117             CV_Assert((inputs[i].dims == 4 || inputs[i].dims == 5) && inputs[i].size[1] == input.size[1]);
118             for (int j = 0; j < inputs[i].dims; j++) {
119                 CV_Assert(inputs[i].size[j] == input.size[j]);
120             }
121         }
122
123         std::vector<int> inpShape;
124         std::vector<int> outShape;
125         for (int i = 2; i < inputs[0].dims; i++) {
126             inpShape.push_back(inputs[0].size[i]);
127             outShape.push_back(outputs[0].size[i]);
128         }
129         getConvPoolPaddings(inpShape, kernel_size, strides, padMode, pads_begin, pads_end);
130         if (pads_begin.size() == 2) {
131             for (int i = 0; i < pads_begin.size(); i++) {
132                 if (pads_begin[i] != pads_end[i])
133                     CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in convolution layer");
134             }
135             pad = Size(pads_begin[1], pads_begin[0]);
136         }
137         fusedWeights = false;
138         fusedBias = false;
139     }
140
141     bool hasBias() const
142     {
143         return blobs.size() >= 2;
144     }
145
146     virtual MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const = 0;
147     bool is1x1() const
148     {
149         return (kernel.height == 1 && kernel.width == 1) &&
150                (stride.height == 1 && stride.width == 1) &&
151                (dilation.height == 1 && dilation.width == 1);
152     }
153
154     virtual bool tryFuse(Ptr<Layer>& top) CV_OVERRIDE
155     {
156         Mat w, b;
157         top->getScaleShift(w, b);
158         if (!w.empty() || !b.empty())
159         {
160             fuseWeights(w, b);
161             fusedWeights = fusedWeights || !w.empty();
162             fusedBias = fusedBias || (hasBias() && !w.empty()) || !b.empty();
163             return true;
164         }
165         return false;
166     }
167
168     virtual void fuseWeights(const Mat& w_, const Mat& b_) = 0;
169
170     virtual void applyHalideScheduler(Ptr<BackendNode>& node,
171                                       const std::vector<Mat*> &inputs,
172                                       const std::vector<Mat> &outputs,
173                                       int targetId) const CV_OVERRIDE
174     {
175 #ifdef HAVE_HALIDE
176         if (targetId != DNN_TARGET_CPU)
177         {
178             Layer::applyHalideScheduler(node, inputs, outputs, targetId);
179             return;
180         }
181         Halide::Var x("x"), y("y"), c("c"), n("n"), tile("tile"), yi("yi"), yo("yo"), co("co"), ci("ci");
182         Halide::Func& top = node.dynamicCast<HalideBackendNode>()->funcs[1];
183         Halide::Func& padded_input = node.dynamicCast<HalideBackendNode>()->funcs[0];
184
185         int outW, outH, outC, outN;
186         getCanonicalSize(outputs[0].size, &outW, &outH, &outC, &outN);
187
188         if (outW == 1 || outH <= 2)
189             return;
190
191         if (is1x1() || outC <= 16)
192             top.reorder(x, c, y)
193                .split(y, yo, yi, 2)
194                .fuse(yo, n, tile)
195                .parallel(tile)
196                .unroll(yi)
197                .vectorize(x, outW >= 16 ? 16 : outW);
198         else
199             top.reorder(x, c, y)
200                .split(y, yo, yi, 2)
201                .split(c, co, ci, 16)
202                .fuse(yo, co, tile).fuse(n, tile, tile)
203                .parallel(tile)
204                .unroll(yi)
205                .vectorize(x, outW >= 16 ? 16 : outW);
206         padded_input.compute_at(top, yi);
207 #endif  // HAVE_HALIDE
208     }
209 };
210
211
212 #define IS_POWER_LAYER(layer) \
213             (!layer.empty() && !layer->type.compare("Power"))
214 //TODO: simultaneously convolution and bias addition for cache optimization
215 class ConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
216 {
217 public:
218     enum { VEC_ALIGN = 8, DFT_TYPE = CV_32F };
219     Mat weightsMat;
220     std::vector<float> biasvec;
221     std::vector<float> reluslope;
222     Ptr<ActivationLayer> activ;
223
224 #ifdef HAVE_OPENCL
225     Ptr<OCL4DNNConvSpatial<float> > convolutionOp;
226     std::vector<UMat> umat_blobs;
227     bool newActiv;
228     ocl4dnnFusedActiv_t activType;
229     float power;
230 #endif
231     ConvolutionLayerImpl(const LayerParams &params) : BaseConvolutionLayerImpl(params)
232     {
233 #ifdef HAVE_OPENCL
234         newActiv = false;
235         activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
236         power = 0.f;
237 #endif
238     }
239
240     MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
241     {
242         Size out(outShape[3], outShape[2]);
243         int inpGroupCn = blobs[0].size[1];
244         int ksize = inpGroupCn * kernel.height * kernel.width;
245         return shape(out.area(), ksize);
246     }
247
248     virtual bool supportBackend(int backendId) CV_OVERRIDE
249     {
250 #ifdef HAVE_INF_ENGINE
251         if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
252         {
253             if (kernel_size.size() == 3)
254                 return preferableTarget == DNN_TARGET_CPU;
255             return INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2018R4) ||
256                    (preferableTarget != DNN_TARGET_MYRIAD || dilation.width == dilation.height);
257         }
258         else
259 #endif
260             return (kernel_size.size() == 2) && (backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE);
261     }
262
263     bool getMemoryShapes(const std::vector<MatShape> &inputs,
264                          const int requiredOutputs,
265                          std::vector<MatShape> &outputs,
266                          std::vector<MatShape> &internals) const CV_OVERRIDE
267     {
268         CV_Assert(blobs.size() != 0);
269         CV_Assert(!hasBias() || blobs[1].total() == (size_t)blobs[0].size[0]);
270         CV_Assert(inputs.size() == (size_t)1);
271
272         internals.clear();
273
274         CV_Assert(inputs.size() != 0);
275         std::vector<int> inpShape(inputs[0].begin() + 2, inputs[0].end());
276
277         int outCn = blobs[0].size[0];
278         std::vector<int> outShape;
279         outShape.push_back(inputs[0][0]);
280         outShape.push_back(outCn);
281
282         int inpCn = inputs[0][1];
283         if (padMode.empty())
284         {
285             for (int i = 0; i < inpShape.size(); i++)
286                 outShape.push_back((inpShape[i] + pads_begin[i] + pads_end[i] - dilations[i] * (kernel_size[i] - 1) - 1) / strides[i] + 1);
287         }
288         else
289         {
290             getConvPoolOutParams(inpShape, kernel_size, strides, padMode, dilations, outShape);
291         }
292
293         int ngroups = inpCn / blobs[0].size[1];
294         if (ngroups == 0 || ngroups * blobs[0].size[1] != inpCn)
295             CV_Error(Error::StsError, format("Number of input channels should "
296                      "be multiple of %d but got %d", blobs[0].size[1], inpCn));
297         CV_Assert(ngroups > 0 && inpCn % ngroups == 0 && outCn % ngroups == 0);
298
299         outputs.resize(1, outShape);
300
301         return false;
302     }
303
304     virtual void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
305     {
306         BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
307
308         CV_Assert(!blobs.empty());
309         const int outCn = blobs[0].size[0];
310         // prepare weightsMat where each row is aligned and has enough zero padding on the right to
311         // use vectorized (i.e. with intrinsics) loops without tail processing
312         Mat wm = blobs[0].reshape(1, outCn);
313         if( wm.step1() % VEC_ALIGN != 0 )
314         {
315             int newcols = (int)alignSize(wm.step1(), VEC_ALIGN);
316             Mat wm_buffer = Mat(outCn, newcols, wm.type());
317             Mat wm_padding = wm_buffer.colRange(wm.cols, newcols);
318             wm_padding.setTo(Scalar::all(0.));
319             Mat wm_aligned = wm_buffer.colRange(0, wm.cols);
320             wm.copyTo(wm_aligned);
321             wm = wm_aligned;
322         }
323         weightsMat = wm;
324         weightsMultipliers.assign(outCn, 1.0);
325
326         Mat biasMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat();
327         biasvec.resize(outCn+2);
328         if( biasMat.empty() )
329         {
330             for(int i = 0; i < outCn; i++ )
331                 biasvec[i] = 0.f;
332         }
333         else
334         {
335             for(int i = 0; i < outCn; i++ )
336                 biasvec[i] = biasMat.at<float>(i);
337         }
338 #ifdef HAVE_OPENCL
339         convolutionOp.release();
340 #endif
341     }
342
343     bool setActivation(const Ptr<ActivationLayer>& layer) CV_OVERRIDE
344     {
345         if (!activ.empty() && !layer.empty())
346             return false;
347
348         activ = layer;
349         if (activ.empty())
350             reluslope.clear();
351 #ifdef HAVE_OPENCL
352         newActiv = true;
353         activType = OCL4DNN_CONV_FUSED_ACTIV_NONE;
354
355         if (IS_DNN_OPENCL_TARGET(preferableTarget))
356         {
357             Ptr<PowerLayer> activ_power = activ.dynamicCast<PowerLayer>();
358             if (!activ_power.empty())
359             {
360                 if (activ_power->scale != 1.f || activ_power->shift != 0.f)
361                 {
362                     const int outCh = blobs[0].size[0];
363                     fuseWeights(Mat(1, outCh, CV_32F, Scalar(activ_power->scale)),
364                                 Mat(1, outCh, CV_32F, Scalar(activ_power->shift)));
365                 }
366
367                 power = activ_power->power;
368                 activType = OCL4DNN_CONV_FUSED_ACTIV_POWER;
369             }
370             Ptr<TanHLayer> activ_tanh = activ.dynamicCast<TanHLayer>();
371             if (!activ_tanh.empty())
372             {
373                 activType = OCL4DNN_CONV_FUSED_ACTIV_TANH;
374             }
375         }
376 #endif
377         return !activ.empty();
378     }
379
380     void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
381     {
382         // Convolution weights have OIHW data layout. Parameters fusion in case of
383         // (conv(I) + b1 ) * w + b2
384         // means to replace convolution's weights to [w*conv(I)] and bias to [b1 * w + b2]
385         const int outCn = weightsMat.size[0];
386         Mat w = w_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(w_.at<float>(0))) : w_;
387         Mat b = b_.total() == 1 ? Mat(1, outCn, CV_32F, Scalar(b_.at<float>(0))) : b_;
388         CV_Assert_N(!weightsMat.empty(), biasvec.size() == outCn + 2,
389                     w.empty() || outCn == w.total(), b.empty() || outCn == b.total());
390
391         if (!w.empty())
392         {
393             // Keep origin weights unchanged.
394             if (weightsMat.data == blobs[0].data)
395                 weightsMat = weightsMat.clone();
396
397             Mat originWeights = blobs[0].reshape(1, outCn);
398             for (int i = 0; i < outCn; ++i)
399             {
400                 double wi = w.at<float>(i);
401                 weightsMultipliers[i] *= wi;
402                 cv::multiply(originWeights.row(i), weightsMultipliers[i], weightsMat.row(i));
403                 biasvec[i] *= wi;
404             }
405         }
406
407         if (!b.empty())
408         {
409             for (int i = 0; i < outCn; ++i)
410                 biasvec[i] += b.at<float>(i);
411         }
412         biasvec[outCn] = biasvec[outCn+1] = biasvec[outCn-1];
413     }
414
415     virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
416     {
417 #ifdef HAVE_HALIDE
418         Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
419
420         const int inpCn = inputBuffer.channels();
421         const int outCn = blobs[0].size[0];
422         const int inpGroupCn = blobs[0].size[1];
423         const int group = inpCn / inpGroupCn;
424         const int outGroupCn = outCn / group;
425
426         Halide::Buffer<float> weights = wrapToHalideBuffer(blobs[0]);
427
428         Halide::Var x("x"), y("y"), c("c"), n("n");
429         Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
430         Halide::Func padded_input(name + "_constant_exterior");
431         if (pad.width || pad.height)
432         {
433             Halide::Func bounded =
434                 Halide::BoundaryConditions::constant_exterior(inputBuffer, 0);
435             padded_input(x, y, c, n) = bounded(x, y, c, n);
436         }
437         else
438         {
439             padded_input(x, y, c, n) = inputBuffer(x, y, c, n);
440         }
441
442         Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
443         Halide::Expr kx = x * stride.width - pad.width + r.x * dilation.width;
444         Halide::Expr ky = y * stride.height - pad.height + r.y * dilation.height;
445         Halide::Expr kc = r.z;
446         for (int i = 1; i < group; ++i)
447         {
448             kc = select(c < outGroupCn * i, kc, inpGroupCn * i + r.z);
449         }
450         Halide::Expr topExpr = sum(padded_input(kx, ky, kc, n) *
451                                    weights(r.x, r.y, r.z, c));
452         if (hasBias())
453         {
454             Halide::Buffer<float> bias = wrapToHalideBuffer(blobs[1], {outCn});
455             topExpr += bias(c);
456         }
457         top(x, y, c, n) = topExpr;
458         return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
459 #endif  // HAVE_HALIDE
460         return Ptr<BackendNode>();
461     }
462
463     virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
464     {
465 #ifdef HAVE_INF_ENGINE
466         InferenceEngine::DataPtr input = infEngineDataNode(inputs[0]);
467         CV_Assert(input->dims.size() == 4 || input->dims.size() == 5);
468
469         const int inpCn = input->dims[input->dims.size() - 2];  // NOTE: input->dims are reversed (WHIO or WHDIO)
470         const int outCn = blobs[0].size[0];
471         const int inpGroupCn = blobs[0].size[1];
472         const int group = inpCn / inpGroupCn;
473
474         InferenceEngine::Layout layout = (input->dims.size() == 4) ? InferenceEngine::Layout::OIHW :
475                                                                      InferenceEngine::Layout::NCDHW;
476
477         auto ieWeights = wrapToInfEngineBlob(blobs[0], layout);
478         if (fusedWeights)
479         {
480             if (weightsMat.isContinuous())
481             {
482                 Mat cvWeights = weightsMat.reshape(1, blobs[0].dims, blobs[0].size);
483                 ieWeights = wrapToInfEngineBlob(cvWeights, layout);
484             }
485             else
486             {
487                 ieWeights = InferenceEngine::make_shared_blob<float>(
488                                     InferenceEngine::Precision::FP32, layout,
489                                     ieWeights->dims());
490                 ieWeights->allocate();
491
492                 Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, outCn);
493                 Mat cvWeights = weightsMat.colRange(0, newWeights.cols);
494                 cvWeights.copyTo(newWeights);
495             }
496         }
497         InferenceEngine::Blob::Ptr ieBiases;
498         if (hasBias() || fusedBias)
499         {
500             Mat biasesMat({outCn}, CV_32F, &biasvec[0]);
501             ieBiases = wrapToInfEngineBlob(biasesMat, {(size_t)outCn}, InferenceEngine::Layout::C);
502         }
503
504 #if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2018R5)
505         InferenceEngine::Builder::ConvolutionLayer ieLayer(name);
506
507         ieLayer.setKernel(kernel_size);
508         ieLayer.setStrides(strides);
509         ieLayer.setDilation(dilations);
510         ieLayer.setPaddingsBegin(pads_begin);
511         ieLayer.setPaddingsEnd(pads_end);
512         ieLayer.setGroup((size_t)group);
513         ieLayer.setOutDepth((size_t)outCn);
514
515         InferenceEngine::Builder::Layer l = ieLayer;
516         addConstantData("weights", ieWeights, l);
517         if (ieBiases)
518             addConstantData("biases", ieBiases, l);
519
520         if (!padMode.empty())
521             l.getParameters()["auto_pad"] = padMode == "VALID" ? std::string("valid") : std::string("same_upper");
522
523         return Ptr<BackendNode>(new InfEngineBackendNode(l));
524 #else
525         InferenceEngine::LayerParams lp;
526         lp.name = name;
527         lp.type = "Convolution";
528         lp.precision = InferenceEngine::Precision::FP32;
529         std::shared_ptr<InferenceEngine::ConvolutionLayer> ieLayer(new InferenceEngine::ConvolutionLayer(lp));
530
531 #if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2018R3)
532         ieLayer->_kernel.insert(InferenceEngine::X_AXIS, kernel.width);
533         ieLayer->_kernel.insert(InferenceEngine::Y_AXIS, kernel.height);
534         ieLayer->_stride.insert(InferenceEngine::X_AXIS, stride.width);
535         ieLayer->_stride.insert(InferenceEngine::Y_AXIS, stride.height);
536         ieLayer->_padding.insert(InferenceEngine::X_AXIS, pad.width);
537         ieLayer->_padding.insert(InferenceEngine::Y_AXIS, pad.height);
538         ieLayer->_pads_end.insert(InferenceEngine::X_AXIS, pad.width);
539         ieLayer->_pads_end.insert(InferenceEngine::Y_AXIS, pad.height);
540         ieLayer->_dilation.insert(InferenceEngine::X_AXIS, dilation.width);
541         ieLayer->_dilation.insert(InferenceEngine::Y_AXIS, dilation.height);
542         ieLayer->params["output"] = format("%d", outCn);
543         ieLayer->params["kernel"] = format("%d,%d,%d,%d", outCn, inpGroupCn, kernel.height, kernel.width);
544         ieLayer->params["pads_begin"] = format("%d,%d", pad.height, pad.width);
545         ieLayer->params["pads_end"] = format("%d,%d", pad.height, pad.width);
546         ieLayer->params["strides"] = format("%d,%d", stride.height, stride.width);
547         ieLayer->params["dilations"] = format("%d,%d", dilation.height, dilation.width);
548 #else
549         ieLayer->_kernel_x = kernel.width;
550         ieLayer->_kernel_y = kernel.height;
551         ieLayer->_stride_x = stride.width;
552         ieLayer->_stride_y = stride.height;
553         ieLayer->_padding_x = pad.width;
554         ieLayer->_padding_y = pad.height;
555         ieLayer->_dilation_x = dilation.width;
556         ieLayer->_dilation_y = dilation.height;
557 #endif
558         ieLayer->_out_depth = outCn;
559         ieLayer->_group = group;
560
561         ieLayer->_weights = ieWeights;
562         if (ieBiases)
563             ieLayer->_biases = ieBiases;
564         return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
565 #endif
566 #endif  // HAVE_INF_ENGINE
567         return Ptr<BackendNode>();
568     }
569
570     class ParallelConv : public cv::ParallelLoopBody
571     {
572     public:
573         enum { BLK_SIZE = 32, BLK_SIZE_CN = 64 };
574
575         const Mat* input_;
576         const Mat* weights_;
577         Mat* output_;
578         int outShape[4];
579         Size kernel_, pad_, stride_, dilation_;
580         int ngroups_, nstripes_;
581         std::vector<int> ofstab_;
582         const std::vector<float>* biasvec_;
583         const std::vector<float>* reluslope_;
584         const ActivationLayer* activ_;
585         bool is1x1_;
586         bool useAVX;
587         bool useAVX2;
588         bool useAVX512;
589
590         ParallelConv()
591             : input_(0), weights_(0), output_(0), ngroups_(0), nstripes_(0),
592               biasvec_(0), reluslope_(0), activ_(0), is1x1_(false), useAVX(false), useAVX2(false), useAVX512(false)
593         {}
594
595         static void run( const Mat& input, Mat& output, const Mat& weights,
596                          const std::vector<float>& biasvec,
597                          const std::vector<float>& reluslope,
598                          Size kernel, Size pad, Size stride, Size dilation,
599                          const ActivationLayer* activ, int ngroups, int nstripes )
600         {
601             CV_Assert_N(
602                        input.dims == 4 && output.dims == 4,
603                        input.size[0] == output.size[0],
604                        weights.rows == output.size[1],
605                        weights.cols == (input.size[1]/ngroups)*kernel.width*kernel.height,
606                        input.type() == output.type(),
607                        input.type() == weights.type(),
608                        input.type() == CV_32FC1,
609                        input.isContinuous(),
610                        output.isContinuous(),
611                        biasvec.size() == (size_t)output.size[1]+2);
612             ParallelConv p;
613
614             p.input_ = &input;
615             p.weights_ = &weights;
616             p.output_ = &output;
617             for( int i = 0; i < 4; i++ ) p.outShape[i] = output.size[i];
618             p.outShape[1] /= ngroups;
619             p.kernel_ = kernel; p.pad_ = pad; p.stride_ = stride; p.dilation_ = dilation;
620             p.ngroups_ = ngroups;
621             p.nstripes_ = nstripes;
622
623             int inpCnAll = input.size[1], width = input.size[3], height = input.size[2];
624             int inpCn = inpCnAll / ngroups;
625             p.is1x1_ = kernel == Size(1,1) && pad == Size(0, 0);
626             p.useAVX = checkHardwareSupport(CPU_AVX);
627             p.useAVX2 = checkHardwareSupport(CPU_AVX2);
628             p.useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;
629
630             int ncn = std::min(inpCn, (int)BLK_SIZE_CN);
631             p.ofstab_.resize(kernel.width*kernel.height*ncn);
632             int* ofstab = &p.ofstab_[0];
633
634             for( int k = 0; k < ncn; k++ )
635                 for( int k_r = 0; k_r < kernel.height; k_r++ )
636                     for( int k_c = 0; k_c < kernel.width; k_c++ )
637                         ofstab[(k*kernel.height + k_r)*kernel.width + k_c] =
638                         (k*height + k_r*dilation.height)*width + k_c*dilation.width;
639
640             p.biasvec_ = &biasvec;
641             p.reluslope_ = &reluslope;
642             p.activ_ = p.reluslope_->empty() ? activ : 0;
643
644             parallel_for_(Range(0, nstripes), p, nstripes);
645         }
646
647         virtual void operator ()(const Range &r0) const CV_OVERRIDE
648         {
649             const int valign = ConvolutionLayerImpl::VEC_ALIGN;
650             int ngroups = ngroups_, batchSize = input_->size[0]*ngroups;
651             int outW = output_->size[3], outH = output_->size[2], outCn = output_->size[1]/ngroups;
652             int width = input_->size[3], height = input_->size[2], inpCn = input_->size[1]/ngroups;
653             const int nstripes = nstripes_;
654             int kernel_w = kernel_.width, kernel_h = kernel_.height;
655             int pad_w = pad_.width, pad_h = pad_.height;
656             int stride_w = stride_.width, stride_h = stride_.height;
657             int dilation_w = dilation_.width, dilation_h = dilation_.height;
658             int karea = kernel_w*kernel_h;
659             int i, j, k;
660             size_t inpPlaneSize = width*height;
661             size_t outPlaneSize = outW*outH;
662             bool is1x1 = is1x1_;
663
664             int stripesPerSample;
665             size_t stripeSize;
666             Range r = r0;
667
668             if( nstripes >= batchSize*2 )
669             {
670                 stripesPerSample = nstripes/batchSize;
671                 stripeSize = alignSize((outPlaneSize + stripesPerSample - 1)/stripesPerSample, valign);
672                 stripeSize = std::min(stripeSize, outPlaneSize);
673             }
674             else
675             {
676                 stripesPerSample = 1;
677                 int samplesPerStripe = std::max((batchSize + nstripes - 1)/nstripes, 1);
678                 r.start *= samplesPerStripe;
679                 r.end *= samplesPerStripe;
680                 stripeSize = outPlaneSize;
681             }
682
683             const float* data_inp0_ = input_->ptr<float>();
684             const int* ofstab = &ofstab_[0];
685             const float* wptr_orig_ = weights_->ptr<float>();
686             size_t wstep = weights_->step1();
687             const float* biasptr_ = &biasvec_->at(0);
688             const float* reluptr_ = reluslope_->empty() ? 0 : &reluslope_->at(0);
689             float* data_out0_ = output_->ptr<float>();
690             size_t rowbufsz = (size_t)karea*BLK_SIZE_CN*BLK_SIZE;
691             AutoBuffer<float> rowbuf0_(rowbufsz + valign);
692             float* rowbuf0 = alignPtr(rowbuf0_.data(), (int)(valign*sizeof(float)));
693
694             // we clear the buffer once; ultimately, it lets us to avoid
695             // tail processing after running the unrolled/vectorized loop.
696             // the main idea is to make sure that the tail (a.k.a. padding) of each row
697             // (i.e. the elements with indices between vsz=karea*ncn and vsz_a)
698             // does not contain NaNs or Infs. Because the padding in the weights
699             // matrix is explicitly initialized with 0's, we handle all other
700             // cases nicely, i.e. we can skip expliciting re-initialization
701             // of the padding - we just retain elements from the previous iteration
702             // of the loop over channels (cn0).
703             memset(rowbuf0, 0, rowbufsz*sizeof(rowbuf0[0]) );
704
705             for( int stripe = r.start; stripe < r.end; stripe++ )
706             {
707                 int subsampleIdx = stripe/stripesPerSample;
708                 if( subsampleIdx >= batchSize )
709                     break;
710                 int stripeStart = (int)((stripe - subsampleIdx*stripesPerSample)*stripeSize);
711                 int stripeEnd = (int)std::min(stripeStart + stripeSize, outPlaneSize);
712                 const float* data_inp0 = data_inp0_ + subsampleIdx*inpPlaneSize*inpCn;
713                 float* data_out0 = data_out0_ + subsampleIdx*outPlaneSize*outCn;
714                 int startOutCn = (subsampleIdx % ngroups)*outCn;
715                 const float* wptr_orig = wptr_orig_ + wstep*startOutCn;
716                 const float* biasptr = biasptr_ + startOutCn;
717
718                 for( int cn0 = 0; cn0 < inpCn; cn0 += BLK_SIZE_CN )
719                 {
720                     int cn1 = std::min(cn0 + BLK_SIZE_CN, inpCn);
721                     int ncn = cn1 - cn0, vsz = karea*ncn;
722                     int vsz_a = (int)alignSize(vsz, valign);
723                     const float* wptr = wptr_orig + cn0*karea;
724                     // we apply [Channels][P]ReLU (if any) during the final pass only.
725                     const float* relu = cn1 == inpCn && reluptr_ ? reluptr_ + startOutCn : 0;
726
727                     for( int ofs0 = stripeStart; ofs0 < stripeEnd; ofs0 += BLK_SIZE )
728                     {
729                         int ofs, ofs1 = std::min(ofs0 + BLK_SIZE, stripeEnd);
730                         int out_i = ofs0 / outW;
731                         int out_j = ofs0 - out_i * outW;
732
733                         // do im2row for a part of input tensor
734                         float* rowbuf = rowbuf0;
735                         for( ofs = ofs0; ofs < ofs1; out_j = 0, ++out_i )
736                         {
737                             int delta = std::min(ofs1 - ofs, outW - out_j);
738                             int out_j1 = out_j + delta;
739                             int in_i = out_i * stride_h - pad_h;
740                             int in_j = out_j * stride_w - pad_w;
741                             const float* imgptr = data_inp0 + (cn0*height + in_i)*width + in_j;
742                             ofs += delta;
743
744                             // do im2row for a part of input tensor
745                             if( is1x1 )
746                             {
747                                 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w )
748                                 {
749                                     for( k = 0; k < vsz; k++ )
750                                         rowbuf[k] = imgptr[k*inpPlaneSize];
751                                 }
752                             }
753                             else
754                             {
755                                 bool ok_i = 0 <= in_i && in_i < height - (kernel_h-1)*dilation_h;
756                                 int i0 = std::max(0, (-in_i + dilation_h-1)/dilation_h);
757                                 int i1 = std::min(kernel_h, (height - in_i + dilation_h-1)/dilation_h);
758
759                                 for( ; out_j < out_j1; out_j++, rowbuf += vsz_a, imgptr += stride_w, in_j += stride_w )
760                                 {
761                                     // this condition should be true for most of the tensor elements, i.e.
762                                     // most of the time the kernel aperture is inside the tensor X-Y plane.
763                                     if( ok_i && out_j + 2 <= out_j1 && 0 <= in_j && in_j + stride_w*2 <= width - (kernel_w-1)*dilation_w )
764                                     {
765                                         for( k = 0; k < vsz; k++ )
766                                         {
767                                             int k1 = ofstab[k];
768                                             float v0 = imgptr[k1];
769                                             float v1 = imgptr[k1 + stride_w];
770                                             rowbuf[k] = v0;
771                                             rowbuf[k+vsz_a] = v1;
772                                         }
773                                         out_j++;
774                                         rowbuf += vsz_a;
775                                         imgptr += stride_w;
776                                         in_j += stride_w;
777                                     }
778                                     else
779                                     {
780                                         int j0 = std::max(0, (-in_j + dilation_w-1)/dilation_w);
781                                         int j1 = std::min(kernel_w, (width - in_j + dilation_w-1)/dilation_w);
782
783                                         // here some non-continuous sub-row of the row will not be
784                                         // filled from the tensor; we need to make sure that the uncovered
785                                         // elements are explicitly set to 0's. the easiest way is to
786                                         // set all the elements to 0's before the loop.
787                                         memset(rowbuf, 0, vsz*sizeof(rowbuf[0]));
788                                         for( k = 0; k < ncn; k++ )
789                                         {
790                                             for( i = i0; i < i1; i++ )
791                                             {
792                                                 for( j = j0; j < j1; j++ )
793                                                 {
794                                                     int imgofs = k*(width*height) + i*(dilation_h*width) + j*dilation_w;
795                                                     rowbuf[(k*kernel_h + i)*kernel_w + j] = imgptr[imgofs];
796                                                 }
797                                             }
798                                         }
799                                     }
800                                 }
801                             }
802                         }
803
804                         // now compute dot product of the weights
805                         // and im2row-transformed part of the tensor
806                         int bsz = ofs1 - ofs0;
807                     #if CV_TRY_AVX512_SKX
808                         /* AVX512 convolution requires an alignment of 16, and ROI is only there for larger vector sizes */
809                         if(useAVX512)
810                             opt_AVX512_SKX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
811                                           outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
812                         else
813                     #endif
814                     #if CV_TRY_AVX2
815                         if(useAVX2)
816                             opt_AVX2::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
817                                           outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
818                         else
819                     #endif
820                     #if CV_TRY_AVX
821                         if(useAVX)
822                             opt_AVX::fastConv(wptr, wstep, biasptr, rowbuf0, data_out0 + ofs0,
823                                          outShape, bsz, vsz, vsz_a, relu, cn0 == 0);
824                         else
825                     #endif
826                         for( int i = 0; i < outCn; i += 2 )
827                         {
828                             const float* wptr0 = wptr + i*wstep;
829                             const float* wptr1 = wptr0 + wstep;
830                             float* outptr0 = data_out0 + ofs0 + i*outPlaneSize;
831                             float* outptr1 = outptr0 + outPlaneSize;
832                             float bias0 = biasptr[i], bias1 = biasptr[i+1];
833                             float r0 = 1.f, r1 = 1.f;
834
835                             if( i+1 >= outCn )
836                             {
837                                 wptr1 = wptr0;
838                                 outptr1 = outptr0;
839                                 bias1 = bias0;
840                             }
841
842                             if( relu )
843                             {
844                                 r0 = relu[i]; r1 = relu[i+1];
845                                 if( i+1 >= outCn )
846                                     r1 = r0;
847                             }
848
849                             int j = 0;
850                         #if CV_SIMD128
851                             v_float32x4 vr0 = v_setall_f32(r0), vr1 = v_setall_f32(r1), z = v_setzero_f32();
852
853                             for( ; j <= bsz - 4; j += 4 )
854                             {
855                                 const float* rptr = rowbuf0 + j*vsz_a;
856                                 v_float32x4 s0, s1;
857
858                                 if( cn0 == 0 )
859                                 {
860                                     s0 = v_setall_f32(bias0);
861                                     s1 = v_setall_f32(bias1);
862                                 }
863                                 else
864                                 {
865                                     s0 = v_load(outptr0 + j);
866                                     s1 = v_load(outptr1 + j);
867                                 }
868
869                                 v_float32x4 vs00 = v_setzero_f32(), vs01 = v_setzero_f32(),
870                                             vs02 = v_setzero_f32(), vs03 = v_setzero_f32(),
871                                             vs10 = v_setzero_f32(), vs11 = v_setzero_f32(),
872                                             vs12 = v_setzero_f32(), vs13 = v_setzero_f32();
873                                 for( k = 0; k < vsz; k += 4, rptr += 4 )
874                                 {
875                                     v_float32x4 w0 = v_load_aligned(wptr0 + k), w1 = v_load_aligned(wptr1 + k);
876                                     v_float32x4 r0 = v_load_aligned(rptr), r1 = v_load_aligned(rptr + vsz_a),
877                                                 r2 = v_load_aligned(rptr + vsz_a*2), r3 = v_load_aligned(rptr + vsz_a*3);
878
879                                     vs00 += w0*r0;
880                                     vs01 += w0*r1;
881                                     vs02 += w0*r2;
882                                     vs03 += w0*r3;
883
884                                     vs10 += w1*r0;
885                                     vs11 += w1*r1;
886                                     vs12 += w1*r2;
887                                     vs13 += w1*r3;
888                                 }
889                                 s0 += v_reduce_sum4(vs00, vs01, vs02, vs03);
890                                 s1 += v_reduce_sum4(vs10, vs11, vs12, vs13);
891                                 if( relu )
892                                 {
893                                     s0 = v_select(s0 > z, s0, s0*vr0);
894                                     s1 = v_select(s1 > z, s1, s1*vr1);
895                                 }
896
897                                 v_store(outptr0 + j, s0);
898                                 v_store(outptr1 + j, s1);
899                             }
900                         #endif
901                             for( ; j < bsz; j++ )
902                             {
903                                 const float* rptr = rowbuf0 + j*vsz_a;
904                                 float s00, s10;
905
906                                 if( cn0 == 0 )
907                                 {
908                                     s00 = bias0;
909                                     s10 = bias1;
910                                 }
911                                 else
912                                 {
913                                     s00 = outptr0[j];
914                                     s10 = outptr1[j];
915                                 }
916
917                                 for( k = 0; k < vsz; k++ )
918                                 {
919                                     float r0 = rptr[k];
920                                     s00 += wptr0[k]*r0;
921                                     s10 += wptr1[k]*r0;
922                                 }
923                                 if( relu )
924                                 {
925                                     s00 = s00 > 0.f ? s00 : s00*r0;
926                                     s10 = s10 > 0.f ? s10 : s10*r1;
927                                 }
928
929                                 outptr0[j] = s00;
930                                 outptr1[j] = s10;
931                             }
932                         }
933                     }
934                 }
935
936                 if( activ_ )
937                     activ_->forwardSlice(data_out0 + stripeStart, data_out0 + stripeStart,
938                                          (int)(stripeEnd - stripeStart),
939                                          outPlaneSize, startOutCn, startOutCn + outCn);
940             }
941         }
942     };
943
944 #ifdef HAVE_OPENCL
945     bool forward_ocl(InputArrayOfArrays inps, OutputArrayOfArrays outs, OutputArrayOfArrays internals)
946     {
947         std::vector<UMat> inputs;
948         std::vector<UMat> outputs;
949
950         bool use_half = (inps.depth() == CV_16S);
951         inps.getUMatVector(inputs);
952         outs.getUMatVector(outputs);
953
954         CV_Assert(outputs.size() == 1);
955         for (int i = 0; i < inputs.size(); ++i)
956             CV_Assert(inputs[i].u != outputs[0].u);
957
958         if (umat_blobs.empty())
959         {
960             size_t n = blobs.size();
961             umat_blobs.resize(n);
962             for (size_t i = 0; i < n; i++)
963             {
964                 blobs[i].copyTo(umat_blobs[i]);
965             }
966         }
967
968         if (convolutionOp.empty())
969         {
970             OCL4DNNConvConfig config;
971             config.in_shape = shape(inputs[0]);
972             config.out_shape = shape(outputs[0]);
973             config.kernel = kernel;
974             config.pad = pad;
975             config.stride = stride;
976             config.dilation = dilation;
977             config.group = inputs[0].size[1] / umat_blobs[0].size[1];
978             config.bias_term = (hasBias()) ? true : false;
979             config.use_half = use_half;
980
981             convolutionOp = Ptr<OCL4DNNConvSpatial<float> >(new OCL4DNNConvSpatial<float>(config));
982         }
983
984         int outCn = umat_blobs[0].size[0];
985
986         reluslope.clear();
987         if( activ )
988         {
989             Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
990             if( !activ_relu.empty() )
991             {
992                 reluslope.assign(outCn+2, activ_relu->negativeSlope);
993                 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU;
994             }
995
996             Ptr<ReLU6Layer> activ_relu6 = activ.dynamicCast<ReLU6Layer>();
997             if( !activ_relu6.empty() )
998             {
999                 reluslope.resize(2);
1000                 reluslope[0] = activ_relu6->minValue;
1001                 reluslope[1] = activ_relu6->maxValue;
1002                 activType = OCL4DNN_CONV_FUSED_ACTIV_RELU6;
1003             }
1004
1005             Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1006             if( !activ_chprelu.empty() )
1007             {
1008                 const Mat& m = activ_chprelu->blobs[0];
1009                 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1010                 const float* mdata = m.ptr<float>();
1011                 reluslope.resize(outCn+2);
1012                 std::copy(mdata, mdata + outCn, reluslope.begin());
1013                 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1014                 activType = OCL4DNN_CONV_FUSED_ACTIV_PRELU;
1015             }
1016         }
1017
1018         if (fusedWeights)
1019         {
1020             weightsMat.copyTo(umat_blobs[0]);
1021             fusedWeights = false;
1022         }
1023         if (fusedBias)
1024         {
1025             if ( umat_blobs.size() < 2 )
1026                 umat_blobs.resize(2);
1027             umat_blobs[1] = UMat(biasvec, true);
1028             convolutionOp->setBias(true);
1029             fusedBias = false;
1030         }
1031
1032         if ( newActiv )
1033         {
1034             if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU )
1035             {
1036                 CV_Assert(!reluslope.empty());
1037                 convolutionOp->setActivReLU(true, reluslope[0]);
1038             }
1039             else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_PRELU)
1040             {
1041                 CV_Assert(!reluslope.empty());
1042                 convolutionOp->setActivPReLU(true, reluslope);
1043             }
1044             else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_POWER)
1045             {
1046                 convolutionOp->setActivPower(true, power);
1047             }
1048             else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_TANH)
1049             {
1050                 convolutionOp->setActivTanh(true);
1051             }
1052             else if ( activType == OCL4DNN_CONV_FUSED_ACTIV_RELU6)
1053             {
1054                 convolutionOp->setActivReLU6(true, reluslope[0], reluslope[1]);
1055             }
1056             else
1057             {
1058                 convolutionOp->setActivReLU(false, 0);
1059                 convolutionOp->setActivPReLU(false, reluslope);
1060                 convolutionOp->setActivPower(false, 1.f);
1061                 convolutionOp->setActivTanh(false);
1062                 convolutionOp->setActivReLU6(false, 0, 0);
1063             }
1064             newActiv = false;
1065         }
1066
1067         UMat& inpMat = inputs[0];
1068         UMat& outMat = outputs[0];
1069         int batch_size = inpMat.size[0];
1070
1071         return convolutionOp->Forward(inpMat,
1072                                       inputs.size() == 2 ? inputs[1] : UMat(),
1073                                       umat_blobs[0],
1074                                       umat_blobs.size() > 1 ? umat_blobs[1] : UMat(),
1075                                       outMat,
1076                                       batch_size);
1077     }
1078 #endif
1079
1080     void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1081     {
1082         CV_TRACE_FUNCTION();
1083         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1084
1085         CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1086                    forward_ocl(inputs_arr, outputs_arr, internals_arr))
1087
1088         if (inputs_arr.depth() == CV_16S)
1089         {
1090             forward_fallback(inputs_arr, outputs_arr, internals_arr);
1091             return;
1092         }
1093
1094         std::vector<Mat> inputs, outputs;
1095         inputs_arr.getMatVector(inputs);
1096         outputs_arr.getMatVector(outputs);
1097
1098         /*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",
1099                name.c_str(), inputs[0].size[0], inputs[0].size[1], inputs[0].size[2], inputs[0].size[3],
1100                kernel.width, kernel.height, pad.width, pad.height,
1101                stride.width, stride.height, dilation.width, dilation.height);*/
1102         CV_Assert_N(inputs.size() == (size_t)1, inputs[0].size[1] % blobs[0].size[1] == 0,
1103                     outputs.size() == 1, inputs[0].data != outputs[0].data);
1104
1105         if (inputs[0].dims == 5) {
1106             CV_Error(Error::StsNotImplemented, "Convolution3D layer is not supported on OCV backend");
1107         }
1108
1109         int ngroups = inputs[0].size[1]/blobs[0].size[1];
1110         CV_Assert(outputs[0].size[1] % ngroups == 0);
1111         int outCn = blobs[0].size[0];
1112
1113         reluslope.clear();
1114         if( activ )
1115         {
1116             Ptr<ReLULayer> activ_relu = activ.dynamicCast<ReLULayer>();
1117             if( !activ_relu.empty() )
1118             {
1119                 reluslope.assign(outCn+2, activ_relu->negativeSlope);
1120             }
1121
1122             Ptr<ChannelsPReLULayer> activ_chprelu = activ.dynamicCast<ChannelsPReLULayer>();
1123             if( !activ_chprelu.empty() )
1124             {
1125                 const Mat& m = activ_chprelu->blobs[0];
1126                 CV_Assert(m.isContinuous() && m.type() == CV_32F && (int)m.total() == outCn);
1127                 const float* mdata = m.ptr<float>();
1128                 reluslope.resize(outCn+2);
1129                 std::copy(mdata, mdata + outCn, reluslope.begin());
1130                 reluslope[outCn] = reluslope[outCn+1] = reluslope[outCn-1];
1131             }
1132         }
1133
1134         int nstripes = std::max(getNumThreads(), 1);
1135
1136         ParallelConv::run(inputs[0], outputs[0], weightsMat, biasvec, reluslope,
1137                           kernel, pad, stride, dilation, activ.get(), ngroups, nstripes);
1138     }
1139
1140     virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
1141                            const std::vector<MatShape> &outputs) const CV_OVERRIDE
1142     {
1143         CV_Assert(inputs.size() == outputs.size());
1144
1145         int64 flops = 0;
1146         for (int i = 0; i < inputs.size(); i++)
1147         {
1148             flops += total(outputs[i])*(CV_BIG_INT(2)*kernel.area()*inputs[i][1] + 1);
1149         }
1150
1151         return flops;
1152     }
1153 };
1154
1155 class DeConvolutionLayerImpl CV_FINAL : public BaseConvolutionLayerImpl
1156 {
1157 public:
1158     Mat weightsMat, biasesMat;
1159     UMat umat_weights;
1160     UMat umat_biases;
1161
1162     DeConvolutionLayerImpl(const LayerParams& params) : BaseConvolutionLayerImpl(params) {}
1163
1164     MatShape computeColRowShape(const MatShape &inpShape, const MatShape &outShape) const CV_OVERRIDE
1165     {
1166         int inpCn = inpShape[1];
1167         int inpH = inpShape[2];
1168         int inpW = inpShape[3];
1169         int outCn = outShape[1];
1170         int ngroups = inpCn / blobs[0].size[0];
1171         int outGroupCn = outCn / ngroups;
1172         int ksize = outGroupCn * kernel.height * kernel.width;
1173         return shape(ksize, inpH * inpW);
1174     }
1175
1176     virtual bool supportBackend(int backendId) CV_OVERRIDE
1177     {
1178 #ifdef HAVE_INF_ENGINE
1179         const int outGroupCn = blobs[0].size[1];  // Weights are in IOHW layout
1180         const int group = numOutput / outGroupCn;
1181
1182         if (backendId == DNN_BACKEND_INFERENCE_ENGINE)
1183         {
1184             if (kernel_size.size() == 3)
1185                 CV_Error(Error::StsNotImplemented, "Unsupported deconvolution3D layer");
1186
1187             if (INF_ENGINE_RELEASE >= 2018050000 && (adjustPad.height || adjustPad.width))
1188             {
1189                 if (padMode.empty())
1190                 {
1191                     if (preferableTarget != DNN_TARGET_CPU && group != 1)
1192                     {
1193                         if ((adjustPad.height && pad.height) || (adjustPad.width && pad.width))
1194                             return false;
1195                     }
1196                     return pad.width >= adjustPad.width && pad.height >= adjustPad.height;
1197                 }
1198                 else if (padMode == "SAME")
1199                 {
1200                     return kernel.width >= pad.width + 1 + adjustPad.width &&
1201                            kernel.height >= pad.height + 1 + adjustPad.height;
1202                 }
1203                 else if (padMode == "VALID")
1204                     return false;
1205             }
1206
1207             if (group != 1)
1208             {
1209                 return preferableTarget == DNN_TARGET_CPU;
1210             }
1211             if (preferableTarget == DNN_TARGET_OPENCL || preferableTarget == DNN_TARGET_OPENCL_FP16)
1212                 return dilation.width == 1 && dilation.height == 1;
1213             return true;
1214         }
1215         else
1216 #endif  // HAVE_INF_ENGINE
1217             return kernel_size.size() == 2 && (backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_HALIDE);
1218     }
1219
1220     bool getMemoryShapes(const std::vector<MatShape> &inputs,
1221                          const int requiredOutputs,
1222                          std::vector<MatShape> &outputs,
1223                          std::vector<MatShape> &internals) const CV_OVERRIDE
1224     {
1225         CV_Assert(!hasBias() || blobs[1].total() == (size_t)numOutput);
1226         CV_Assert(inputs.size() != 0);
1227
1228         int outCn = numOutput;
1229         std::vector<int> outShape;
1230         outShape.push_back(inputs[0][0]);  // batch
1231         outShape.push_back(outCn);
1232         if (padMode.empty())
1233         {
1234             for (int i = 0; i < kernel_size.size(); i++)
1235                 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] - pads_begin[i] - pads_end[i] + adjust_pads[i]);
1236         }
1237         else if (padMode == "VALID")
1238         {
1239             for (int i = 0; i < kernel_size.size(); i++)
1240                 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + kernel_size[i] + adjust_pads[i]);
1241         }
1242         else if (padMode == "SAME")
1243         {
1244             for (int i = 0; i < kernel_size.size(); i++)
1245                 outShape.push_back(strides[i] * (inputs[0][2 + i] - 1) + 1 + adjust_pads[i]);
1246         }
1247         else
1248             CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
1249
1250         CV_Assert(outCn % blobs[0].size[1] == 0);
1251         int ngroups = outCn / blobs[0].size[1];
1252
1253         int inpCn = inputs[0][1];
1254         CV_Assert(inpCn % ngroups == 0 && outCn % ngroups == 0);
1255         CV_Assert(blobs[0].size[0] == inpCn);
1256
1257         outputs.resize(1, outShape);
1258
1259         if (!is1x1())
1260             internals.push_back(computeColRowShape(inputs[0], outputs[0]));
1261
1262         return false;
1263     }
1264
1265     void finalize(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1266     {
1267         BaseConvolutionLayerImpl::finalize(inputs_arr, outputs_arr);
1268
1269         std::vector<Mat> inputs, outputs;
1270         inputs_arr.getMatVector(inputs);
1271         outputs_arr.getMatVector(outputs);
1272
1273         std::vector<int> inpShape;
1274         std::vector<int> outShape;
1275         for (int i = 2; i < inputs[0].dims; i++) {
1276             inpShape.push_back(inputs[0].size[i]);
1277             outShape.push_back(outputs[0].size[i]);
1278         }
1279         getConvPoolPaddings(outShape, kernel_size, strides, padMode, pads_begin, pads_end);
1280         if (pads_begin.size() == 2) {
1281             for (int i = 0; i < pads_begin.size(); i++) {
1282                 if (pads_begin[i] != pads_end[i])
1283                     CV_Error(Error::StsNotImplemented, "Unsupported asymmetric padding in deconvolution layer");
1284             }
1285             pad = Size(pads_begin[1], pads_begin[0]);
1286         }
1287
1288         weightsMultipliers.assign(numOutput, 1.0);
1289         if (weightsMat.empty())
1290         {
1291             transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1292             biasesMat = hasBias() ? blobs[1].reshape(1, numOutput)
1293                                   : Mat::zeros(numOutput, 1, CV_32F);
1294         }
1295     }
1296
1297     void fuseWeights(const Mat& w_, const Mat& b_) CV_OVERRIDE
1298     {
1299         Mat w = w_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(w_.at<float>(0))) : w_;
1300         Mat b = b_.total() == 1 ? Mat(1, numOutput, CV_32F, Scalar(b_.at<float>(0))) : b_;
1301
1302         CV_Assert_N(!weightsMat.empty(),
1303                      w.empty() || numOutput == w.total(),
1304                      b.empty() || numOutput == b.total());
1305
1306         if (!w.empty())
1307         {
1308             transpose(blobs[0].reshape(1, blobs[0].size[0]), weightsMat);
1309             weightsMat = weightsMat.reshape(1, numOutput);
1310             for (int i = 0; i < numOutput; ++i)
1311             {
1312                 double wi = w.at<float>(i);
1313                 weightsMultipliers[i] *= wi;
1314                 cv::multiply(weightsMat.row(i), weightsMultipliers[i], weightsMat.row(i));
1315                 biasesMat.at<float>(i) *= wi;
1316             }
1317             weightsMat = weightsMat.reshape(1, weightsMat.total() / blobs[0].size[0]);
1318         }
1319
1320         if (!b.empty())
1321         {
1322             cv::add(biasesMat, b.reshape(1, numOutput), biasesMat);
1323         }
1324     }
1325
1326     class MatMulInvoker : public ParallelLoopBody
1327     {
1328     public:
1329         MatMulInvoker(const Mat& a, const Mat& b, Mat& c, int nstripes)
1330         {
1331             a_ = &a;
1332             b_ = &b;
1333             c_ = &c;
1334             nstripes_ = nstripes;
1335             useAVX = checkHardwareSupport(CPU_AVX);
1336             useAVX2 = checkHardwareSupport(CPU_AVX2);
1337             useAVX512 = CV_CPU_HAS_SUPPORT_AVX512_SKX;
1338         }
1339
1340         void operator()(const Range& range_) const CV_OVERRIDE
1341         {
1342             int stripeSize = (int)alignSize((b_->cols + nstripes_ - 1)/nstripes_, 16);
1343             Range range(range_.start*stripeSize, std::min(range_.end*stripeSize, b_->cols));
1344             int mmax = a_->rows;
1345             int nmax = range.end - range.start;
1346             int kmax = a_->cols;
1347             int m, n, k;
1348             const float* aptr = a_->ptr<float>();
1349             const float* bptr = b_->ptr<float>() + range.start;
1350             float* cptr = c_->ptr<float>() + range.start;
1351             size_t astep = a_->step1();
1352             size_t bstep = b_->step1();
1353             size_t cstep = c_->step1();
1354
1355         #if CV_TRY_AVX512_SKX
1356             if( useAVX512 )
1357                 opt_AVX512_SKX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1358             else
1359         #endif
1360         #if CV_TRY_AVX2
1361             if( useAVX2 )
1362                 opt_AVX2::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1363             else
1364         #endif
1365         #if CV_TRY_AVX
1366             if( useAVX )
1367                 opt_AVX::fastGEMM( aptr, astep, bptr, bstep, cptr, cstep, mmax, kmax, nmax );
1368             else
1369         #endif
1370             for( m = 0; m < mmax; m += 2 )
1371             {
1372                 float* dst0 = cptr + cstep*m;
1373                 float* dst1 = cptr + cstep*std::min(m+1, mmax-1);
1374                 const float* aptr0 = aptr + astep*m;
1375                 const float* aptr1 = aptr + astep*std::min(m+1, mmax-1);
1376
1377                 for( n = 0; n < nmax; n++ )
1378                 {
1379                     dst0[n] = 0.f;
1380                     dst1[n] = 0.f;
1381                 }
1382
1383                 for( k = 0; k < kmax; k += 4 )
1384                 {
1385                     float alpha00 = aptr0[k];
1386                     float alpha01 = aptr1[k];
1387                     float alpha10 = 0.f, alpha11 = 0.f;
1388                     float alpha20 = 0.f, alpha21 = 0.f;
1389                     float alpha30 = 0.f, alpha31 = 0.f;
1390                     const float* bptr0 = bptr + k*bstep;
1391                     const float* bptr1 = bptr0;
1392                     const float* bptr2 = bptr0;
1393                     const float* bptr3 = bptr0;
1394
1395                     if( k+1 < kmax )
1396                     {
1397                         alpha10 = aptr0[k+1];
1398                         alpha11 = aptr1[k+1];
1399                         bptr1 = bptr0 + bstep;
1400                         if( k+2 < kmax )
1401                         {
1402                             alpha20 = aptr0[k+2];
1403                             alpha21 = aptr1[k+2];
1404                             bptr2 = bptr1 + bstep;
1405                             if( k+3 < kmax )
1406                             {
1407                                 alpha30 = aptr0[k+3];
1408                                 alpha31 = aptr1[k+3];
1409                                 bptr3 = bptr2 + bstep;
1410                             }
1411                         }
1412                     }
1413                     n = 0;
1414
1415                 #if CV_SIMD128
1416                     v_float32x4 a00 = v_setall_f32(alpha00);
1417                     v_float32x4 a01 = v_setall_f32(alpha01);
1418                     v_float32x4 a10 = v_setall_f32(alpha10);
1419                     v_float32x4 a11 = v_setall_f32(alpha11);
1420                     v_float32x4 a20 = v_setall_f32(alpha20);
1421                     v_float32x4 a21 = v_setall_f32(alpha21);
1422                     v_float32x4 a30 = v_setall_f32(alpha30);
1423                     v_float32x4 a31 = v_setall_f32(alpha31);
1424
1425                     for( ; n <= nmax - 4; n += 4 )
1426                     {
1427                         v_float32x4 b0 = v_load(bptr0 + n);
1428                         v_float32x4 b1 = v_load(bptr1 + n);
1429                         v_float32x4 b2 = v_load(bptr2 + n);
1430                         v_float32x4 b3 = v_load(bptr3 + n);
1431                         v_float32x4 d0 = v_load(dst0 + n);
1432                         v_float32x4 d1 = v_load(dst1 + n);
1433                         d0 += b0*a00;
1434                         d1 += b0*a01;
1435                         d0 += b1*a10;
1436                         d1 += b1*a11;
1437                         d0 += b2*a20;
1438                         d1 += b2*a21;
1439                         d0 += b3*a30;
1440                         d1 += b3*a31;
1441                         v_store(dst0 + n, d0);
1442                         v_store(dst1 + n, d1);
1443                     }
1444                 #endif
1445
1446                     for( ; n < nmax; n++ )
1447                     {
1448                         float b0 = bptr0[n], b1 = bptr1[n];
1449                         float b2 = bptr2[n], b3 = bptr3[n];
1450                         float d0 = dst0[n] + alpha00*b0 + alpha10*b1 + alpha20*b2 + alpha30*b3;
1451                         float d1 = dst1[n] + alpha01*b0 + alpha11*b1 + alpha21*b2 + alpha31*b3;
1452                         dst0[n] = d0;
1453                         dst1[n] = d1;
1454                     }
1455                 }
1456             }
1457         }
1458
1459         const Mat *a_, *b_;
1460         Mat* c_;
1461         int nstripes_;
1462         bool useAVX;
1463         bool useAVX2;
1464         bool useAVX512;
1465     };
1466
1467     class Col2ImInvoker : public cv::ParallelLoopBody
1468     {
1469     public:
1470         const float* data_col;
1471         const float* biasvec;
1472         int channels, height, width;
1473         int kernel_h, kernel_w;
1474         int pad_h, pad_w;
1475         int stride_h, stride_w;
1476         float* data_im;
1477         int height_col, width_col;
1478         int nstripes;
1479         bool is1x1;
1480
1481         Col2ImInvoker()
1482             : data_col(0), biasvec(0), channels(0), height(0), width(0),
1483               kernel_h(0), kernel_w(0), pad_h(0), pad_w(0), stride_h(0), stride_w(0), data_im(0),
1484               height_col(0), width_col(0), nstripes(0), is1x1(0)
1485         {}
1486
1487         static void run(const float* data_col,
1488                         int channels, int height, int width,
1489                         int kernel_h, int kernel_w,
1490                         int pad_h, int pad_w,
1491                         int stride_h, int stride_w,
1492                         int height_col, int width_col,
1493                         float* data_im,
1494                         const float* biasvec,
1495                         bool is1x1)
1496         {
1497             const int nstripes = getNumThreads();
1498
1499             Col2ImInvoker t;
1500             t.data_col = data_col;
1501             t.data_im = data_im;
1502             t.channels = channels; t.height = height; t.width = width;
1503             t.kernel_h = kernel_h; t.kernel_w = kernel_w;
1504             t.pad_h = pad_h; t.pad_w = pad_w;
1505             t.stride_h = stride_h; t.stride_w = stride_w;
1506             t.height_col = height_col;
1507             t.width_col = width_col;
1508             t.nstripes = nstripes;
1509             t.is1x1 = is1x1;
1510             t.biasvec = biasvec;
1511
1512             parallel_for_(Range(0, nstripes), t, nstripes);
1513         }
1514
1515         virtual void operator ()(const Range &r) const CV_OVERRIDE
1516         {
1517             const float* data_col_ = data_col;
1518             float* data_im_ = data_im;
1519             int coeff_h = (1 - stride_h * kernel_w * height_col) * width_col;
1520             int coeff_w = (1 - stride_w * height_col * width_col);
1521             size_t total = (size_t)channels * height * width;
1522             size_t stripeSize = (total + nstripes - 1)/nstripes;
1523             size_t startIndex = r.start*stripeSize;
1524             size_t endIndex = std::min(r.end*stripeSize, total);
1525             int w = (int)(startIndex % width + pad_w);
1526             int h = (int)((startIndex / width) % height + pad_h);
1527             int c = (int)(startIndex / (width * height));
1528             int h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1529             int h_col_end = std::min(h / stride_h + 1, height_col);
1530             int plane_size_col = height_col * width_col;
1531             int offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1532             bool is1x1_ = is1x1;
1533             const float* biasvec_ = biasvec;
1534
1535             for (size_t index = startIndex; index < endIndex; index++)
1536             {
1537                 // compute the start and end of the output
1538                 int w_col_start = (w < kernel_w) ? 0 : (w - kernel_w) / stride_w + 1;
1539                 int w_col_end = std::min(w / stride_w + 1, width_col);
1540                 float val;
1541
1542                 if( is1x1_ )
1543                     val = data_im_[index];
1544                 else
1545                 {
1546                     val = 0.f;
1547                     for (int h_col = h_col_start; h_col < h_col_end; ++h_col) {
1548                         for (int w_col = w_col_start; w_col < w_col_end; ++w_col) {
1549                             val += data_col_[offset + h_col * coeff_h + w_col * coeff_w];
1550                         }
1551                     }
1552                 }
1553                 data_im_[index] = val + biasvec_[c];
1554
1555                 offset += plane_size_col;
1556                 if( ++w >= width + pad_w )
1557                 {
1558                     w = (int)((index + 1)% width + pad_w);
1559                     h = (int)(((index + 1) / width) % height + pad_h);
1560                     c = (int)((index + 1) / (width * height));
1561                     h_col_start = (h < kernel_h) ? 0 : (h - kernel_h) / stride_h + 1;
1562                     h_col_end = std::min(h / stride_h + 1, height_col);
1563                     offset = (c * kernel_h * kernel_w + h * kernel_w + w) * plane_size_col;
1564                 }
1565             }
1566         }
1567     };
1568
1569 #ifdef HAVE_OPENCL
1570     bool forward_ocl(InputArrayOfArrays inputs_, OutputArrayOfArrays outputs_, OutputArrayOfArrays internals_)
1571     {
1572         std::vector<UMat> inputs;
1573         std::vector<UMat> outputs;
1574         std::vector<UMat> internals;
1575
1576         if (inputs_.depth() == CV_16S)
1577             return false;
1578
1579         inputs_.getUMatVector(inputs);
1580         outputs_.getUMatVector(outputs);
1581         internals_.getUMatVector(internals);
1582
1583         int outCn = numOutput;
1584         int inpCn = inputs[0].size[1];
1585
1586         if (is1x1())
1587             return false;
1588
1589         if (umat_weights.empty())
1590         {
1591             if (fusedWeights)
1592                 weightsMat.copyTo(umat_weights);
1593             else
1594                 transpose(blobs[0].reshape(1, inpCn), umat_weights);
1595
1596             if (fusedBias)
1597                 biasesMat.copyTo(umat_biases);
1598             else
1599             {
1600                 if (hasBias())
1601                     blobs[1].reshape(1, outCn).copyTo(umat_biases);
1602                 else
1603                     umat_biases = UMat::zeros(outCn, 1, CV_32F);
1604             }
1605         }
1606
1607         String buildopt = format("-DT=%s ", ocl::typeToStr(inputs[0].type()));
1608         buildopt += format("-DPAD_H=%d -DPAD_W=%d -DKERNEL_H=%d -DKERNEL_W=%d -DSTRIDE_H=%d -DSTRIDE_W=%d ",
1609                            pad.height, pad.width, kernel.height, kernel.width, stride.height, stride.width);
1610
1611         for (size_t ii = 0; ii < outputs.size(); ii++)
1612         {
1613             int ngroups = outCn / blobs[0].size[1];
1614             int inpGroupCn = inpCn / ngroups;
1615             int outGroupCn = blobs[0].size[1];
1616             const UMat& inp = inputs[ii];
1617             UMat& out = outputs[ii];
1618             int numImg = inp.size[0];
1619             int inpH = inp.size[2], inpW = inp.size[3];
1620             int outH = out.size[2], outW = out.size[3];
1621
1622             MatShape inpshape = shape(numImg*inpCn, inpH*inpW);
1623             MatShape outshape = shape(numImg*outCn, outH*outW);
1624             UMat convBlob = inputs[ii].reshape(1, inpshape.size(), &inpshape[0]);
1625             UMat decnBlob = out.reshape(1, outshape.size(), &outshape[0]);
1626             int rows = internals[0].rows / ngroups;
1627
1628             for (int n = 0; n < numImg; n++)
1629             {
1630                 for (int g = 0; g < ngroups; g++)
1631                 {
1632                     UMat colMat = internals[0].rowRange(_Range(g * rows, rows));
1633                     UMat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1634                     UMat wghtMat = umat_weights.colRange(_Range(g * inpGroupCn, inpGroupCn));
1635                     gemm(wghtMat, convMat, 1, noArray(), 0, colMat, 0);
1636                 }
1637
1638                 for (int g = 0; g < ngroups; g++)
1639                 {
1640                     int total = outGroupCn * decnBlob.cols;
1641                     int index = 0;
1642                     int height_col = inpH;
1643                     int width_col = inpW;
1644                     int coeff_h = (1 - stride.height * kernel.width * height_col) * width_col;
1645                     int coeff_w = (1 - stride.width * height_col * width_col);
1646
1647                     ocl::Kernel k("col2im", ocl::dnn::col2im_oclsrc, buildopt);
1648                     k.set(index++, total);
1649                     k.set(index++, ocl::KernelArg::PtrReadOnly(internals[0]));
1650                     k.set(index++, (int)(g * rows * internals[0].cols));
1651                     k.set(index++, outGroupCn);
1652                     k.set(index++, outH);
1653                     k.set(index++, outW);
1654                     k.set(index++, height_col);
1655                     k.set(index++, width_col);
1656                     k.set(index++, coeff_h);
1657                     k.set(index++, coeff_w);
1658                     k.set(index++, ocl::KernelArg::PtrReadOnly(umat_biases));
1659                     k.set(index++, (int)(g * outGroupCn * umat_biases.cols));
1660                     k.set(index++, ocl::KernelArg::PtrWriteOnly(decnBlob));
1661                     k.set(index++, (int)((g + n * ngroups) * outGroupCn * decnBlob.cols));
1662
1663                     size_t global[] = { (size_t)total };
1664                     bool ret = k.run(1, global, NULL, false);
1665                     if (!ret)
1666                         return false;
1667                 }
1668             }
1669         }
1670
1671         return true;
1672     }
1673 #endif
1674
1675     void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1676     {
1677         CV_TRACE_FUNCTION();
1678         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1679
1680         CV_OCL_RUN(IS_DNN_OPENCL_TARGET(preferableTarget),
1681                    forward_ocl(inputs_arr, outputs_arr, internals_arr));
1682
1683         if (inputs_arr.depth() == CV_16S)
1684         {
1685             forward_fallback(inputs_arr, outputs_arr, internals_arr);
1686             return;
1687         }
1688
1689         std::vector<Mat> inputs, outputs, internals;
1690         inputs_arr.getMatVector(inputs);
1691         outputs_arr.getMatVector(outputs);
1692         internals_arr.getMatVector(internals);
1693
1694         int outCn = numOutput;
1695         int inpCn = inputs[0].size[1];
1696         bool is1x1flag = is1x1();
1697         int nstripes = getNumThreads();
1698
1699         if( weightsMat.empty() )
1700         {
1701             transpose(blobs[0].reshape(1, inpCn), weightsMat);
1702             biasesMat = hasBias() ? blobs[1].reshape(1, outCn) : Mat::zeros(outCn, 1, CV_32F);
1703         }
1704
1705         for (size_t ii = 0; ii < outputs.size(); ii++)
1706         {
1707             int ngroups = outCn / blobs[0].size[1];
1708             int inpGroupCn = inpCn / ngroups;
1709             int outGroupCn = blobs[0].size[1];
1710             const Mat& inp = inputs[ii];
1711             Mat& out = outputs[ii];
1712             int numImg = inp.size[0];
1713             int inpH = inp.size[2], inpW = inp.size[3];
1714             int outH = out.size[2], outW = out.size[3];
1715
1716             Mat convBlob = inputs[ii].reshape(1, numImg*inpCn);
1717             Mat decnBlob = out.reshape(1, numImg*outCn);
1718
1719             for (int n = 0; n < numImg; n++)
1720             {
1721                 for (int g = 0; g < ngroups; g++)
1722                 {
1723                     Mat dstMat = decnBlob.rowRange(_Range((g + n * ngroups) * outGroupCn, outGroupCn));
1724                     Mat &colMat = is1x1flag ? dstMat : internals[0];
1725
1726                     Mat convMat = convBlob.rowRange(_Range((g + n * ngroups) * inpGroupCn, inpGroupCn));
1727                     Mat wghtMat = weightsMat.colRange(_Range(g * inpGroupCn, inpGroupCn));
1728                     Mat curBiasMat = biasesMat.rowRange(_Range(g * outGroupCn, outGroupCn));
1729
1730                     //gemm(wghtMat, convMat, 1, colMat, 0, colMat, 0);
1731                     MatMulInvoker mminvoker(wghtMat, convMat, colMat, nstripes);
1732                     parallel_for_(Range(0, nstripes), mminvoker, nstripes);
1733
1734                     Col2ImInvoker::run(colMat.ptr<float>(), outGroupCn, outH, outW,
1735                                        kernel.height, kernel.width, pad.height, pad.width,
1736                                        stride.height, stride.width, inpH, inpW, dstMat.ptr<float>(),
1737                                        curBiasMat.ptr<float>(), is1x1flag);
1738                 }
1739             }
1740         }
1741     }
1742
1743     virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &inputs) CV_OVERRIDE
1744     {
1745 #ifdef HAVE_HALIDE
1746         Halide::Buffer<float> inputBuffer = halideBuffer(inputs[0]);
1747
1748         int inW, inH, inC, inN;
1749         getCanonicalSize(inputBuffer, &inW, &inH, &inC, &inN);
1750         const int outGroupCn = blobs[0].size[1];
1751         const int group = numOutput / outGroupCn;
1752         const int inpGroupCn = blobs[0].size[0] / group;
1753
1754         Halide::Var x("x"), y("y"), c("c"), n("n");
1755         Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name));
1756         Halide::Func padded_input(name + "_constant_exterior");
1757         auto weights = wrapToHalideBuffer(blobs[0]);
1758
1759         Halide::Func dilated_input("dilated_input");
1760         dilated_input(x, y, c, n) = 0.0f;
1761         Halide::RDom r1(0, inW, 0, inH);
1762         dilated_input(r1.x * stride.width, r1.y * stride.height, c, n) =
1763               inputBuffer(r1.x, r1.y, c, n);
1764         dilated_input.compute_root();
1765
1766         Halide::Func bounded =
1767             Halide::BoundaryConditions::constant_exterior(dilated_input, 0,
1768                                                           0, (inW - 1) * stride.width + 1,
1769                                                           0, (inH - 1) * stride.height + 1,
1770                                                           0, inC, 0, inN);
1771         padded_input(x, y, c, n) = bounded(x, y, c, n);
1772
1773         Halide::RDom r(0, kernel.width, 0, kernel.height, 0, inpGroupCn);
1774         Halide::Expr kx = x + pad.width - r.x;
1775         Halide::Expr ky = y + pad.height - r.y;
1776         Halide::Expr kInC = r.z;
1777         Halide::Expr kOutC = c;
1778         for (int i = 1; i < group; ++i)
1779         {
1780             kInC = select(c < outGroupCn * i, kInC, inpGroupCn * i + r.z);
1781             kOutC = select(c < outGroupCn * i, kOutC, c - outGroupCn * i);
1782         }
1783         Halide::Expr topExpr = sum(padded_input(kx, ky, kInC, n) *
1784                                    weights(r.x, r.y, kOutC, kInC));
1785         if (hasBias())
1786         {
1787             auto bias = wrapToHalideBuffer(blobs[1], {numOutput});
1788             topExpr += bias(c);
1789         }
1790         top(x, y, c, n) = topExpr;
1791         return Ptr<BackendNode>(new HalideBackendNode({ padded_input, top }));
1792 #endif  // HAVE_HALIDE
1793         return Ptr<BackendNode>();
1794     }
1795
1796     virtual Ptr<BackendNode> initInfEngine(const std::vector<Ptr<BackendWrapper> > &) CV_OVERRIDE
1797     {
1798 #ifdef HAVE_INF_ENGINE
1799         auto ieWeights = wrapToInfEngineBlob(blobs[0], InferenceEngine::Layout::OIHW);
1800         if (fusedWeights)
1801         {
1802             ieWeights = InferenceEngine::make_shared_blob<float>(
1803                                 InferenceEngine::Precision::FP32, InferenceEngine::Layout::OIHW,
1804                                 ieWeights->dims());
1805             ieWeights->allocate();
1806
1807             int inpCn = blobs[0].size[0];
1808             Mat newWeights = infEngineBlobToMat(ieWeights).reshape(1, inpCn);
1809             transpose(weightsMat, newWeights);
1810         }
1811
1812 #if INF_ENGINE_VER_MAJOR_GE(INF_ENGINE_RELEASE_2018R5)
1813         const int outGroupCn = blobs[0].size[1];  // Weights are in IOHW layout
1814         const int group = numOutput / outGroupCn;
1815
1816         InferenceEngine::Builder::DeconvolutionLayer ieLayer(name);
1817
1818         ieLayer.setKernel(kernel_size);
1819         ieLayer.setStrides(strides);
1820         ieLayer.setDilation(dilations);
1821         ieLayer.setPaddingsBegin(pads_begin);
1822
1823         if (padMode.empty())
1824         {
1825             ieLayer.setPaddingsEnd({pads_end[0] - adjust_pads[0], pads_end[1] - adjust_pads[1]});
1826         }
1827         else if (padMode == "SAME")
1828         {
1829             ieLayer.setPaddingsEnd({kernel_size[0] - pads_begin[0] - 1 - adjust_pads[0],
1830                                     kernel_size[1] - pads_begin[1] - 1 - adjust_pads[1]});
1831         }
1832         ieLayer.setGroup((size_t)group);
1833         ieLayer.setOutDepth((size_t)numOutput);
1834
1835         InferenceEngine::Builder::Layer l = ieLayer;
1836         addConstantData("weights", ieWeights, l);
1837         if (hasBias())
1838             addConstantData("biases", wrapToInfEngineBlob(biasesMat, {(size_t)numOutput}, InferenceEngine::Layout::C), l);
1839         return Ptr<BackendNode>(new InfEngineBackendNode(l));
1840 #else
1841         const int outGroupCn = blobs[0].size[1];  // Weights are in IOHW layout
1842         const int group = numOutput / outGroupCn;
1843
1844         InferenceEngine::LayerParams lp;
1845         lp.name = name;
1846         lp.type = "Deconvolution";
1847         lp.precision = InferenceEngine::Precision::FP32;
1848         std::shared_ptr<InferenceEngine::DeconvolutionLayer> ieLayer(new InferenceEngine::DeconvolutionLayer(lp));
1849
1850 #if INF_ENGINE_VER_MAJOR_GT(INF_ENGINE_RELEASE_2018R3)
1851         ieLayer->_kernel.insert(InferenceEngine::X_AXIS, kernel.width);
1852         ieLayer->_kernel.insert(InferenceEngine::Y_AXIS, kernel.height);
1853         ieLayer->_stride.insert(InferenceEngine::X_AXIS, stride.width);
1854         ieLayer->_stride.insert(InferenceEngine::Y_AXIS, stride.height);
1855         ieLayer->_padding.insert(InferenceEngine::X_AXIS, pad.width);
1856         ieLayer->_padding.insert(InferenceEngine::Y_AXIS, pad.height);
1857         ieLayer->_pads_end.insert(InferenceEngine::X_AXIS, pad.width);
1858         ieLayer->_pads_end.insert(InferenceEngine::Y_AXIS, pad.height);
1859         ieLayer->_dilation.insert(InferenceEngine::X_AXIS, dilation.width);
1860         ieLayer->_dilation.insert(InferenceEngine::Y_AXIS, dilation.height);
1861 #else
1862         ieLayer->_kernel_x = kernel.width;
1863         ieLayer->_kernel_y = kernel.height;
1864         ieLayer->_stride_x = stride.width;
1865         ieLayer->_stride_y = stride.height;
1866         ieLayer->_padding_x = pad.width;
1867         ieLayer->_padding_y = pad.height;
1868         ieLayer->_dilation_x = dilation.width;
1869         ieLayer->_dilation_y = dilation.height;
1870 #endif
1871         ieLayer->_out_depth = numOutput;
1872         ieLayer->_group = group;
1873
1874         ieLayer->_weights = wrapToInfEngineBlob(blobs[0], InferenceEngine::Layout::OIHW);
1875         if (hasBias())
1876         {
1877             ieLayer->_biases = wrapToInfEngineBlob(blobs[1], {(size_t)numOutput}, InferenceEngine::Layout::C);
1878         }
1879         return Ptr<BackendNode>(new InfEngineBackendNode(ieLayer));
1880 #endif
1881 #endif  // HAVE_INF_ENGINE
1882         return Ptr<BackendNode>();
1883     }
1884
1885     virtual int64 getFLOPS(const std::vector<MatShape> &inputs,
1886                            const std::vector<MatShape> &outputs) const CV_OVERRIDE
1887     {
1888         CV_Assert(inputs.size() == outputs.size());
1889
1890         float flops = 0;
1891         int outChannels = blobs[0].size[0];
1892
1893         for (int i = 0; i < inputs.size(); i++)
1894         {
1895             flops += CV_BIG_INT(2)*outChannels*kernel.area()*total(inputs[i]);
1896         }
1897
1898         return flops;
1899     }
1900 };
1901
1902 Ptr<BaseConvolutionLayer> ConvolutionLayer::create(const LayerParams &params)
1903 {
1904     Ptr<ConvolutionLayerImpl> l(new ConvolutionLayerImpl(params));
1905     return l;
1906 }
1907
1908 Ptr<BaseConvolutionLayer> DeconvolutionLayer::create(const LayerParams &params)
1909 {
1910     return Ptr<BaseConvolutionLayer>(new DeConvolutionLayerImpl(params));
1911 }
1912
1913 }
1914 }