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