445c524639fde9e1a11b79ce6fdc0f98e1c1ccf1
[platform/upstream/opencv.git] / modules / dnn / test / test_layers.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) 2017, Intel Corporation, all rights reserved.
14 // Third party copyrights are property of their respective owners.
15 //
16 // Redistribution and use in source and binary forms, with or without modification,
17 // are permitted provided that the following conditions are met:
18 //
19 //   * Redistribution's of source code must retain the above copyright notice,
20 //     this list of conditions and the following disclaimer.
21 //
22 //   * Redistribution's in binary form must reproduce the above copyright notice,
23 //     this list of conditions and the following disclaimer in the documentation
24 //     and/or other materials provided with the distribution.
25 //
26 //   * The name of the copyright holders may not be used to endorse or promote products
27 //     derived from this software without specific prior written permission.
28 //
29 // This software is provided by the copyright holders and contributors "as is" and
30 // any express or implied warranties, including, but not limited to, the implied
31 // warranties of merchantability and fitness for a particular purpose are disclaimed.
32 // In no event shall the Intel Corporation or contributors be liable for any direct,
33 // indirect, incidental, special, exemplary, or consequential damages
34 // (including, but not limited to, procurement of substitute goods or services;
35 // loss of use, data, or profits; or business interruption) however caused
36 // and on any theory of liability, whether in contract, strict liability,
37 // or tort (including negligence or otherwise) arising in any way out of
38 // the use of this software, even if advised of the possibility of such damage.
39 //
40 //M*/
41
42 #include "test_precomp.hpp"
43 #include <opencv2/core/ocl.hpp>
44 #include "npy_blob.hpp"
45 #include <opencv2/dnn/shape_utils.hpp>
46 #include <opencv2/dnn/all_layers.hpp>
47 #include <opencv2/dnn/layer.details.hpp>  // CV_DNN_REGISTER_LAYER_CLASS
48
49 #ifdef HAVE_INF_ENGINE
50 #include <thread>
51 #endif
52
53 namespace opencv_test { namespace {
54
55 template<typename TString>
56 static String _tf(TString filename)
57 {
58     String basetestdir = getOpenCVExtraDir();
59     size_t len = basetestdir.size();
60     if(len > 0 && basetestdir[len-1] != '/' && basetestdir[len-1] != '\\')
61         return (basetestdir + "/dnn/layers") + filename;
62     return (basetestdir + "dnn/layers/") + filename;
63 }
64
65 void runLayer(Ptr<Layer> layer, std::vector<Mat> &inpBlobs, std::vector<Mat> &outBlobs)
66 {
67     size_t ninputs = inpBlobs.size();
68     std::vector<Mat> inp(ninputs), outp, intp;
69     std::vector<MatShape> inputs, outputs, internals;
70
71     for (size_t i = 0; i < ninputs; i++)
72     {
73         inp[i] = inpBlobs[i].clone();
74         inputs.push_back(shape(inp[i]));
75     }
76
77     layer->getMemoryShapes(inputs, 0, outputs, internals);
78     for (size_t i = 0; i < outputs.size(); i++)
79     {
80         outp.push_back(Mat(outputs[i], CV_32F));
81     }
82     for (size_t i = 0; i < internals.size(); i++)
83     {
84         intp.push_back(Mat(internals[i], CV_32F));
85     }
86
87     layer->finalize(inp, outp);
88     layer->forward(inp, outp, intp);
89
90     size_t noutputs = outp.size();
91     outBlobs.resize(noutputs);
92     for (size_t i = 0; i < noutputs; i++)
93         outBlobs[i] = outp[i];
94 }
95
96 class Test_Caffe_layers : public DNNTestLayer
97 {
98 public:
99     void testLayerUsingCaffeModels(const String& basename, bool useCaffeModel = false,
100                                    bool useCommonInputBlob = true, double l1 = 0.0,
101                                    double lInf = 0.0)
102     {
103         String prototxt = _tf(basename + ".prototxt");
104         String caffemodel = _tf(basename + ".caffemodel");
105
106         String inpfile = (useCommonInputBlob) ? _tf("blob.npy") : _tf(basename + ".input.npy");
107         String outfile = _tf(basename + ".npy");
108
109         Mat inp = blobFromNPY(inpfile);
110         Mat ref = blobFromNPY(outfile);
111         checkBackend(&inp, &ref);
112
113         Net net = readNetFromCaffe(prototxt, (useCaffeModel) ? caffemodel : String());
114         ASSERT_FALSE(net.empty());
115
116         net.setPreferableBackend(backend);
117         net.setPreferableTarget(target);
118
119         net.setInput(inp, "input");
120         Mat out = net.forward("output");
121
122         normAssert(ref, out, "", l1 ? l1 : default_l1, lInf ? lInf : default_lInf);
123     }
124 };
125
126 TEST_P(Test_Caffe_layers, Softmax)
127 {
128     testLayerUsingCaffeModels("layer_softmax");
129 }
130
131 TEST_P(Test_Caffe_layers, LRN)
132 {
133     testLayerUsingCaffeModels("layer_lrn_spatial");
134     testLayerUsingCaffeModels("layer_lrn_channels");
135 }
136
137 TEST_P(Test_Caffe_layers, Convolution)
138 {
139     testLayerUsingCaffeModels("layer_convolution", true);
140 }
141
142 TEST_P(Test_Caffe_layers, DeConvolution)
143 {
144     testLayerUsingCaffeModels("layer_deconvolution", true, false);
145 }
146
147 TEST_P(Test_Caffe_layers, InnerProduct)
148 {
149     if (backend == DNN_BACKEND_INFERENCE_ENGINE)
150         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
151     if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
152         applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
153     testLayerUsingCaffeModels("layer_inner_product", true);
154 }
155
156 TEST_P(Test_Caffe_layers, Pooling_max)
157 {
158     testLayerUsingCaffeModels("layer_pooling_max");
159 }
160
161 TEST_P(Test_Caffe_layers, Pooling_ave)
162 {
163     testLayerUsingCaffeModels("layer_pooling_ave");
164 }
165
166 TEST_P(Test_Caffe_layers, MVN)
167 {
168     testLayerUsingCaffeModels("layer_mvn");
169 }
170
171 void testReshape(const MatShape& inputShape, const MatShape& targetShape,
172                  int axis = 0, int num_axes = -1,
173                  MatShape mask = MatShape())
174 {
175     LayerParams params;
176     params.set("axis", axis);
177     params.set("num_axes", num_axes);
178     if (!mask.empty())
179     {
180         params.set("dim", DictValue::arrayInt<int*>(&mask[0], mask.size()));
181     }
182
183     Mat inp(inputShape.size(), &inputShape[0], CV_32F);
184     std::vector<Mat> inpVec(1, inp);
185     std::vector<Mat> outVec, intVec;
186
187     Ptr<Layer> rl = LayerFactory::createLayerInstance("Reshape", params);
188     runLayer(rl, inpVec, outVec);
189
190     Mat& out = outVec[0];
191     MatShape shape(out.size.p, out.size.p + out.dims);
192     EXPECT_EQ(shape, targetShape);
193 }
194
195 TEST(Layer_Test_Reshape, Accuracy)
196 {
197     {
198         int inp[] = {4, 3, 1, 2};
199         int out[] = {4, 3, 2};
200         testReshape(MatShape(inp, inp + 4), MatShape(out, out + 3), 2, 1);
201     }
202     {
203         int inp[] = {1, 128, 4, 4};
204         int out[] = {1, 2048};
205         int mask[] = {-1, 2048};
206         testReshape(MatShape(inp, inp + 4), MatShape(out, out + 2), 0, -1,
207                     MatShape(mask, mask + 2));
208     }
209     {
210         int inp[] = {1, 2, 3};
211         int out[] = {3, 1, 2};
212         int mask[] = {3, 1, 2};
213         testReshape(MatShape(inp, inp + 3), MatShape(out, out + 3), 0, -1,
214                     MatShape(mask, mask + 3));
215     }
216 }
217
218 TEST_P(Test_Caffe_layers, BatchNorm)
219 {
220     testLayerUsingCaffeModels("layer_batch_norm", true);
221     testLayerUsingCaffeModels("layer_batch_norm_local_stats", true, false);
222 }
223
224 TEST_P(Test_Caffe_layers, ReLU)
225 {
226     testLayerUsingCaffeModels("layer_relu");
227 }
228
229 TEST_P(Test_Caffe_layers, Dropout)
230 {
231     testLayerUsingCaffeModels("layer_dropout");
232 }
233
234 TEST_P(Test_Caffe_layers, Concat)
235 {
236 #if defined(INF_ENGINE_RELEASE)
237 #if INF_ENGINE_VER_MAJOR_GE(2019010000) && INF_ENGINE_VER_MAJOR_LT(2019020000)
238     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
239         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2019R1, CV_TEST_TAG_DNN_SKIP_IE_2019R1_1);
240 #elif INF_ENGINE_VER_MAJOR_EQ(2019020000)
241     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_OPENCL)
242         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL, CV_TEST_TAG_DNN_SKIP_IE_2019R2);
243 #endif
244 #endif
245     testLayerUsingCaffeModels("layer_concat");
246     testLayerUsingCaffeModels("layer_concat_optim", true, false);
247     testLayerUsingCaffeModels("layer_concat_shared_input", true, false);
248 }
249
250 TEST_P(Test_Caffe_layers, Fused_Concat)
251 {
252     if (backend == DNN_BACKEND_INFERENCE_ENGINE && (target == DNN_TARGET_OPENCL || target == DNN_TARGET_OPENCL_FP16))
253         applyTestTag(target == DNN_TARGET_OPENCL ? CV_TEST_TAG_DNN_SKIP_IE_OPENCL : CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16);
254
255     checkBackend();
256
257     // Test case
258     // input
259     //   |
260     //   v
261     // some_layer
262     // |   |
263     // v   v
264     // concat
265     Net net;
266     int interLayer;
267     {
268         LayerParams lp;
269         lp.type = "AbsVal";
270         lp.name = "someLayer";
271         interLayer = net.addLayerToPrev(lp.name, lp.type, lp);
272     }
273     {
274         LayerParams lp;
275         lp.set("axis", 1);
276         lp.type = "Concat";
277         lp.name = "testConcat";
278         int id = net.addLayer(lp.name, lp.type, lp);
279         net.connect(interLayer, 0, id, 0);
280         net.connect(interLayer, 0, id, 1);
281     }
282     int shape[] = {1, 2, 3, 4};
283     Mat input(4, shape, CV_32F);
284     randu(input, 0.0f, 1.0f);  // [0, 1] to make AbsVal an identity transformation.
285
286     net.setInput(input);
287     net.setPreferableBackend(backend);
288     net.setPreferableTarget(target);
289     Mat out = net.forward();
290
291     normAssert(slice(out, Range::all(), Range(0, 2), Range::all(), Range::all()), input, "", default_l1, default_lInf);
292     normAssert(slice(out, Range::all(), Range(2, 4), Range::all(), Range::all()), input, "", default_l1, default_lInf);
293 }
294
295 TEST_P(Test_Caffe_layers, Eltwise)
296 {
297     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
298         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
299     testLayerUsingCaffeModels("layer_eltwise");
300 }
301
302 TEST_P(Test_Caffe_layers, PReLU)
303 {
304     testLayerUsingCaffeModels("layer_prelu", true);
305 }
306
307 // TODO: fix an unstable test case
308 TEST_P(Test_Caffe_layers, layer_prelu_fc)
309 {
310     if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
311         applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
312     // Reference output values are in range [-0.0001, 10.3906]
313     double l1 = (target == DNN_TARGET_MYRIAD) ? 0.005 : 0.0;
314     double lInf = (target == DNN_TARGET_MYRIAD) ? 0.021 : 0.0;
315     testLayerUsingCaffeModels("layer_prelu_fc", true, false, l1, lInf);
316 }
317
318 TEST_P(Test_Caffe_layers, Reshape_Split_Slice)
319 {
320     if (backend == DNN_BACKEND_INFERENCE_ENGINE)
321         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
322
323     Net net = readNetFromCaffe(_tf("reshape_and_slice_routines.prototxt"));
324     ASSERT_FALSE(net.empty());
325
326     net.setPreferableBackend(backend);
327     net.setPreferableTarget(target);
328
329     Mat input(6, 12, CV_32F);
330     RNG rng(0);
331     rng.fill(input, RNG::UNIFORM, -1, 1);
332
333     net.setInput(input, "input");
334     Mat output = net.forward("output");
335
336     normAssert(input, output, "", default_l1, default_lInf);
337 }
338
339 TEST_P(Test_Caffe_layers, Conv_Elu)
340 {
341 #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_RELEASE <= 2018050000
342     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
343         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_2018R5);
344 #endif
345
346     Net net = readNetFromTensorflow(_tf("layer_elu_model.pb"));
347     ASSERT_FALSE(net.empty());
348
349     Mat inp = blobFromNPY(_tf("layer_elu_in.npy"));
350     Mat ref = blobFromNPY(_tf("layer_elu_out.npy"));
351
352     net.setInput(inp, "input");
353     net.setPreferableBackend(backend);
354     net.setPreferableTarget(target);
355     Mat out = net.forward();
356
357     normAssert(ref, out, "", default_l1, default_lInf);
358 }
359
360 class Layer_LSTM_Test : public ::testing::Test
361 {
362 public:
363     int numInp, numOut;
364     Mat Wh, Wx, b;
365     Ptr<LSTMLayer> layer;
366     std::vector<Mat> inputs, outputs;
367
368     Layer_LSTM_Test() {}
369
370     void init(const MatShape &inpShape_, const MatShape &outShape_,
371               bool produceCellOutput, bool useTimestampDim)
372     {
373         numInp = total(inpShape_);
374         numOut = total(outShape_);
375
376         Wh = Mat::ones(4 * numOut, numOut, CV_32F);
377         Wx = Mat::ones(4 * numOut, numInp, CV_32F);
378         b  = Mat::ones(4 * numOut, 1, CV_32F);
379
380         LayerParams lp;
381         lp.blobs.resize(3);
382         lp.blobs[0] = Wh;
383         lp.blobs[1] = Wx;
384         lp.blobs[2] = b;
385         lp.set<bool>("produce_cell_output", produceCellOutput);
386         lp.set<bool>("use_timestamp_dim", useTimestampDim);
387
388         layer = LSTMLayer::create(lp);
389         layer->setOutShape(outShape_);
390     }
391 };
392
393 TEST_F(Layer_LSTM_Test, get_set_test)
394 {
395     const int TN = 4;
396     MatShape inpShape = shape(5, 3, 2);
397     MatShape outShape = shape(3, 1, 2);
398     MatShape inpResShape = concat(shape(TN), inpShape);
399     MatShape outResShape = concat(shape(TN), outShape);
400
401     init(inpShape, outShape, true, false);
402     layer->setOutShape(outShape);
403
404     Mat C((int)outResShape.size(), &outResShape[0], CV_32F);
405     randu(C, -1., 1.);
406     Mat H = C.clone();
407     randu(H, -1., 1.);
408
409     Mat inp((int)inpResShape.size(), &inpResShape[0], CV_32F);
410     randu(inp, -1., 1.);
411
412     inputs.push_back(inp);
413     runLayer(layer, inputs, outputs);
414
415     EXPECT_EQ(2u, outputs.size());
416
417     print(outResShape, "outResShape");
418     print(shape(outputs[0]), "out0");
419     print(shape(outputs[0]), "out1");
420
421     EXPECT_EQ(outResShape, shape(outputs[0]));
422     EXPECT_EQ(outResShape, shape(outputs[1]));
423
424     EXPECT_EQ(0, layer->inputNameToIndex("x"));
425     EXPECT_EQ(0, layer->outputNameToIndex("h"));
426     EXPECT_EQ(1, layer->outputNameToIndex("c"));
427 }
428
429 TEST(Layer_LSTM_Test_Accuracy_with_, CaffeRecurrent)
430 {
431     LayerParams lp;
432     lp.blobs.resize(3);
433     lp.blobs[0] = blobFromNPY(_tf("lstm.prototxt.w_2.npy"));  // Wh
434     lp.blobs[1] = blobFromNPY(_tf("lstm.prototxt.w_0.npy"));  // Wx
435     lp.blobs[2] = blobFromNPY(_tf("lstm.prototxt.w_1.npy"));  // bias
436     Ptr<LSTMLayer> layer = LSTMLayer::create(lp);
437
438     Mat inp = blobFromNPY(_tf("recurrent.input.npy"));
439     std::vector<Mat> inputs(1, inp), outputs;
440     runLayer(layer, inputs, outputs);
441
442     Mat h_t_reference = blobFromNPY(_tf("lstm.prototxt.h_1.npy"));
443     normAssert(h_t_reference, outputs[0]);
444 }
445
446 TEST(Layer_RNN_Test_Accuracy_with_, CaffeRecurrent)
447 {
448     Ptr<RNNLayer> layer = RNNLayer::create(LayerParams());
449
450     layer->setWeights(
451                 blobFromNPY(_tf("rnn.prototxt.w_0.npy")),
452                 blobFromNPY(_tf("rnn.prototxt.w_1.npy")),
453                 blobFromNPY(_tf("rnn.prototxt.w_2.npy")),
454                 blobFromNPY(_tf("rnn.prototxt.w_3.npy")),
455                 blobFromNPY(_tf("rnn.prototxt.w_4.npy")) );
456
457     std::vector<Mat> output, input(1, blobFromNPY(_tf("recurrent.input.npy")));
458     runLayer(layer, input, output);
459
460     Mat h_ref = blobFromNPY(_tf("rnn.prototxt.h_1.npy"));
461     normAssert(h_ref, output[0]);
462 }
463
464 TEST(Layer_LSTM_Test_Accuracy_, Reverse)
465 {
466     // This handcrafted setup calculates (approximately) the prefix sum of the
467     // input, assuming the inputs are suitably small.
468     cv::Mat input(2, 1, CV_32FC1);
469     input.at<float>(0, 0) = 1e-5f;
470     input.at<float>(1, 0) = 2e-5f;
471
472     cv::Mat Wx(4, 1, CV_32FC1);
473     Wx.at<float>(0, 0) = 0.f;  // Input gate
474     Wx.at<float>(1, 0) = 0.f;  // Forget gate
475     Wx.at<float>(2, 0) = 0.f;  // Output gate
476     Wx.at<float>(3, 0) = 1.f;  // Update signal
477
478     cv::Mat Wh(4, 1, CV_32FC1);
479     Wh.at<float>(0, 0) = 0.f;  // Input gate
480     Wh.at<float>(1, 0) = 0.f;  // Forget gate
481     Wh.at<float>(2, 0) = 0.f;  // Output gate
482     Wh.at<float>(3, 0) = 0.f;  // Update signal
483
484     cv::Mat bias(4, 1, CV_32FC1);
485     bias.at<float>(0, 0) = 1e10f;  // Input gate - always allows input to c
486     bias.at<float>(1, 0) = 1e10f;  // Forget gate - never forget anything on c
487     bias.at<float>(2, 0) = 1e10f;  // Output gate - always output everything
488     bias.at<float>(3, 0) = 0.f;  // Update signal
489
490     LayerParams lp;
491     lp.set("reverse", true);
492     lp.set("use_timestamp_dim", true);
493     lp.blobs.clear();
494     lp.blobs.push_back(Wh);
495     lp.blobs.push_back(Wx);
496     lp.blobs.push_back(bias);
497
498     cv::Ptr<cv::dnn::LSTMLayer> layer = LSTMLayer::create(lp);
499     std::vector<cv::Mat> outputs;
500     std::vector<cv::Mat> inputs;
501     inputs.push_back(input);
502     runLayer(layer, inputs, outputs);
503
504     ASSERT_EQ(1, outputs.size());
505     cv::Mat out = outputs[0];
506     ASSERT_EQ(3, out.dims);
507     ASSERT_EQ(shape(2, 1, 1), shape(out));
508     float* data = reinterpret_cast<float*>(out.data);
509     EXPECT_NEAR(std::tanh(1e-5f) + std::tanh(2e-5f), data[0], 1e-10);
510     EXPECT_NEAR(std::tanh(2e-5f), data[1], 1e-10);
511 }
512
513
514 class Layer_RNN_Test : public ::testing::Test
515 {
516 public:
517     int nX, nH, nO, nT, nS;
518     Mat Whh, Wxh, bh, Who, bo;
519     Ptr<RNNLayer> layer;
520
521     std::vector<Mat> inputs, outputs;
522
523     Layer_RNN_Test()
524     {
525         nT = 3;
526         nS = 5;
527         nX = 31;
528         nH = 64;
529         nO = 100;
530
531         Whh = Mat::ones(nH, nH, CV_32F);
532         Wxh = Mat::ones(nH, nX, CV_32F);
533         bh  = Mat::ones(nH, 1, CV_32F);
534         Who = Mat::ones(nO, nH, CV_32F);
535         bo  = Mat::ones(nO, 1, CV_32F);
536
537         layer = RNNLayer::create(LayerParams());
538         layer->setProduceHiddenOutput(true);
539         layer->setWeights(Wxh, bh, Whh, Who, bo);
540     }
541 };
542
543 TEST_F(Layer_RNN_Test, get_set_test)
544 {
545     int sz[] = { nT, nS, 1, nX };
546     Mat inp(4, sz, CV_32F);
547     randu(inp, -1., 1.);
548     inputs.push_back(inp);
549     runLayer(layer, inputs, outputs);
550
551     EXPECT_EQ(outputs.size(), 2u);
552     EXPECT_EQ(shape(outputs[0]), shape(nT, nS, nO));
553     EXPECT_EQ(shape(outputs[1]), shape(nT, nS, nH));
554 }
555
556 TEST(Layer_Test_ROIPooling, Accuracy)
557 {
558     Net net = readNetFromCaffe(_tf("net_roi_pooling.prototxt"));
559
560     Mat inp = blobFromNPY(_tf("net_roi_pooling.input.npy"));
561     Mat rois = blobFromNPY(_tf("net_roi_pooling.rois.npy"));
562     Mat ref = blobFromNPY(_tf("net_roi_pooling.npy"));
563
564     net.setInput(inp, "input");
565     net.setInput(rois, "rois");
566     net.setPreferableBackend(DNN_BACKEND_OPENCV);
567
568     Mat out = net.forward();
569
570     normAssert(out, ref);
571 }
572
573 TEST_P(Test_Caffe_layers, FasterRCNN_Proposal)
574 {
575     if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16)
576         applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16);
577     if (backend == DNN_BACKEND_INFERENCE_ENGINE)
578         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE);
579
580     Net net = readNetFromCaffe(_tf("net_faster_rcnn_proposal.prototxt"));
581
582     Mat scores = blobFromNPY(_tf("net_faster_rcnn_proposal.scores.npy"));
583     Mat deltas = blobFromNPY(_tf("net_faster_rcnn_proposal.deltas.npy"));
584     Mat imInfo = (Mat_<float>(1, 3) << 600, 800, 1.6f);
585
586     net.setInput(scores, "rpn_cls_prob_reshape");
587     net.setInput(deltas, "rpn_bbox_pred");
588     net.setInput(imInfo, "im_info");
589
590     std::vector<Mat> outs;
591     net.setPreferableBackend(backend);
592     net.setPreferableTarget(target);
593     net.forward(outs, "output");
594
595     for (int i = 0; i < 2; ++i)
596     {
597         Mat ref = blobFromNPY(_tf(i == 0 ? "net_faster_rcnn_proposal.out_rois.npy" :
598                                            "net_faster_rcnn_proposal.out_scores.npy"));
599         const int numDets = ref.size[0];
600         EXPECT_LE(numDets, outs[i].size[0]);
601         normAssert(outs[i].rowRange(0, numDets), ref);
602
603         if (numDets < outs[i].size[0])
604         {
605             EXPECT_EQ(countNonZero(outs[i].rowRange(numDets, outs[i].size[0])), 0);
606         }
607     }
608 }
609
610 typedef testing::TestWithParam<tuple<Vec4i, Vec2i, bool> > Scale_untrainable;
611 TEST_P(Scale_untrainable, Accuracy)
612 {
613     Vec4i inpShapeVec = get<0>(GetParam());
614     int axis = get<1>(GetParam())[0];
615     int weightsDims = get<1>(GetParam())[1];
616     bool testFusion = get<2>(GetParam());
617     const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
618
619     // Create a network with two inputs. Scale layer multiplies a first input to
620     // a second one. See http://caffe.berkeleyvision.org/tutorial/layers/scale.html
621     Net net;
622     // Check that this version of Scale layer won't be fused with Convolution layer.
623     if (testFusion)
624     {
625         LayerParams lp;
626         lp.set("kernel_size", 1);
627         lp.set("num_output", 3);
628         lp.set("group", 3);
629         lp.set("bias_term", false);
630         lp.type = "Convolution";
631         lp.name = "testConv";
632
633         std::vector<int> weightsShape(4);
634         weightsShape[0] = 3;  // #outChannels
635         weightsShape[1] = 1;  // #inpChannels / group
636         weightsShape[2] = 1;  // height
637         weightsShape[3] = 1;  // width
638         Mat weights(weightsShape, CV_32F);
639         weights.setTo(1);
640         lp.blobs.push_back(weights);
641         net.addLayerToPrev(lp.name, lp.type, lp);
642     }
643     LayerParams lp;
644     lp.type = "Scale";
645     lp.name = "testLayer";
646     lp.set("axis", axis);
647     int id = net.addLayerToPrev(lp.name, lp.type, lp);
648     net.connect(0, 1, id, 1);
649
650     Mat input(4, inpShape, CV_32F);
651     Mat weights(weightsDims, &inpShape[axis], CV_32F);
652     randu(input, -1, 1);
653     randu(weights, -1, 1);
654
655     std::vector<String> inpNames(2);
656     inpNames[0] = "scale_input";
657     inpNames[1] = "scale_weights";
658     net.setInputsNames(inpNames);
659     net.setInput(input, inpNames[0]);
660     net.setInput(weights, inpNames[1]);
661     net.setPreferableBackend(DNN_BACKEND_OPENCV);
662     Mat out = net.forward();
663
664     Mat ref(input.dims, input.size, CV_32F);
665     float* inpData = (float*)input.data;
666     float* refData = (float*)ref.data;
667     float* weightsData = (float*)weights.data;
668     int spatialSize = 1;
669     for (int i = axis + weightsDims; i < 4; ++i)
670         spatialSize *= inpShape[i];
671     for (int i = 0; i < ref.total(); ++i)
672     {
673         float w = weightsData[(i / spatialSize) % weights.total()];
674         refData[i] = inpData[i] * w;
675     }
676     normAssert(out, ref);
677 }
678
679 INSTANTIATE_TEST_CASE_P(Layer_Test, Scale_untrainable, Combine(
680 /*input size*/   Values(Vec4i(2, 3, 4, 5)),
681 /*axis, #dims*/  Values(Vec2i(0, 1), Vec2i(0, 2), Vec2i(0, 3), Vec2i(0, 4),
682                                      Vec2i(1, 1), Vec2i(1, 2), Vec2i(1, 3),
683                                                   Vec2i(2, 1), Vec2i(2, 2),
684                                                                Vec2i(3, 1)),
685 /*conv fusion*/  testing::Bool()
686 ));
687
688 typedef testing::TestWithParam<tuple<Vec4i, Vec4i, int, int, int> > Crop;
689 TEST_P(Crop, Accuracy)
690 {
691     Vec4i inpShapeVec = get<0>(GetParam());
692     Vec4i sizShapeVec = get<1>(GetParam());
693     int axis = get<2>(GetParam());
694     int numOffsets = get<3>(GetParam());
695     int offsetVal = get<4>(GetParam());
696     const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
697     const int sizShape[] = {sizShapeVec[0], sizShapeVec[1], sizShapeVec[2], sizShapeVec[3]};
698
699     // Create a network with two inputs. Crop layer crops a first input to
700     // the size of a second one.
701     // See http://caffe.berkeleyvision.org/tutorial/layers/crop.html
702     Net net;
703
704     LayerParams lp;
705     lp.name = "testCrop";
706     lp.type = "Crop";
707     lp.set("axis", axis);
708     if (numOffsets > 0)
709     {
710         std::vector<int> offsets(numOffsets, offsetVal);
711         lp.set("offset", DictValue::arrayInt<int*>(&offsets[0], offsets.size()));
712     }
713     else
714         offsetVal = 0;
715     int id = net.addLayerToPrev(lp.name, lp.type, lp);
716     net.connect(0, 1, id, 1);
717
718     Mat inpImage(4, inpShape, CV_32F);
719     Mat sizImage(4, sizShape, CV_32F);
720     randu(inpImage, -1, 1);
721     randu(sizImage, -1, 1);
722
723     std::vector<String> inpNames(2);
724     inpNames[0] = "cropImage";
725     inpNames[1] = "sizImage";
726     net.setInputsNames(inpNames);
727     net.setInput(inpImage, inpNames[0]);
728     net.setInput(sizImage, inpNames[1]);
729     net.setPreferableBackend(DNN_BACKEND_OPENCV);
730
731     // There are a few conditions that represent invalid input to the crop
732     // layer, so in those cases we want to verify an exception is thrown.
733
734     bool shouldThrowException = false;
735     if (numOffsets > 1 && numOffsets != 4 - axis)
736         shouldThrowException = true;
737     else
738         for (int i = axis; i < 4; i++)
739             if (sizShape[i] + offsetVal > inpShape[i])
740                 shouldThrowException = true;
741
742     Mat out;
743     if (shouldThrowException)
744     {
745         ASSERT_ANY_THROW(out = net.forward());
746         return;
747     }
748     else
749         out = net.forward();
750
751     // Finally, compare the cropped output blob from the DNN layer (out)
752     // to a reference blob (ref) that we compute here.
753
754     std::vector<Range> crop_range;
755     crop_range.resize(4, Range::all());
756     for (int i = axis; i < 4; i++)
757         crop_range[i] = Range(offsetVal, sizShape[i] + offsetVal);
758
759     Mat ref(sizImage.dims, sizImage.size, CV_32F);
760     inpImage(&crop_range[0]).copyTo(ref);
761     normAssert(out, ref);
762 }
763
764 INSTANTIATE_TEST_CASE_P(Layer_Test, Crop, Combine(
765 /*input blob shape*/    Values(Vec4i(1, 3, 20, 30)),
766 /*cropsize blob shape*/ Values(Vec4i(1, 3, 10, 12)),
767 /*start axis*/          Values(0, 1, 2),
768 /*number of offsets*/   Values(0, 1, 2, 4),
769 /*offset value*/        Values(3, 4)
770 ));
771
772 // Check that by default average pooling layer should not count zero padded values
773 // into the normalization area.
774 TEST_P(Test_Caffe_layers, Average_pooling_kernel_area)
775 {
776     LayerParams lp;
777     lp.name = "testAvePool";
778     lp.type = "Pooling";
779     lp.set("kernel_size", 2);
780     lp.set("stride", 2);
781     lp.set("pool", "AVE");
782
783     Net net;
784     net.addLayerToPrev(lp.name, lp.type, lp);
785     // 1 2 | 3
786     // 4 5 | 6
787     // ----+--
788     // 7 8 | 9
789     Mat inp = (Mat_<float>(3, 3) << 1, 2, 3, 4, 5, 6, 7, 8, 9);
790     Mat ref = (Mat_<float>(2, 2) << (1 + 2 + 4 + 5) / 4.f, (3 + 6) / 2.f, (7 + 8) / 2.f, 9);
791     Mat tmp = blobFromImage(inp);
792     net.setInput(blobFromImage(inp));
793     net.setPreferableBackend(backend);
794     net.setPreferableTarget(target);
795     Mat out = net.forward();
796     normAssert(out, blobFromImage(ref));
797 }
798
799 TEST_P(Test_Caffe_layers, PriorBox_repeated)
800 {
801     Net net = readNet(_tf("prior_box.prototxt"));
802     int inp_size[] = {1, 3, 10, 10};
803     int shape_size[] = {1, 2, 3, 4};
804     Mat inp(4, inp_size, CV_32F);
805     randu(inp, -1.0f, 1.0f);
806     Mat shape(4, shape_size, CV_32F);
807     randu(shape, -1.0f, 1.0f);
808     net.setInput(inp, "data");
809     net.setInput(shape, "shape");
810     Mat out = net.forward();
811     Mat ref = blobFromNPY(_tf("priorbox_output.npy"));
812     normAssert(out, ref, "");
813 }
814
815 // Test PriorBoxLayer in case of no aspect ratios (just squared proposals).
816 TEST_P(Test_Caffe_layers, PriorBox_squares)
817 {
818     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
819         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
820     LayerParams lp;
821     lp.name = "testPriorBox";
822     lp.type = "PriorBox";
823     lp.set("min_size", 2);
824     lp.set("flip", true);
825     lp.set("clip", true);
826     float variance[] = {0.1f, 0.1f, 0.2f, 0.2f};
827     float aspectRatios[] = {1.0f};  // That should be ignored.
828     lp.set("variance", DictValue::arrayReal<float*>(&variance[0], 4));
829     lp.set("aspect_ratio", DictValue::arrayReal<float*>(&aspectRatios[0], 1));
830
831     Net net;
832     int id = net.addLayerToPrev(lp.name, lp.type, lp);
833     net.connect(0, 0, id, 1);  // The second input is an input image. Shapes are used for boxes normalization.
834     Mat inp(1, 2, CV_32F);
835     randu(inp, -1, 1);
836     net.setInput(blobFromImage(inp));
837     net.setPreferableBackend(backend);
838     net.setPreferableTarget(target);
839     Mat out = net.forward();
840
841     Mat ref = (Mat_<float>(4, 4) << 0.0, 0.0, 0.75, 1.0,
842                                        0.25, 0.0, 1.0, 1.0,
843                                        0.1f, 0.1f, 0.2f, 0.2f,
844                                        0.1f, 0.1f, 0.2f, 0.2f);
845     double l1 = (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) ? 2e-5 : 1e-5;
846     normAssert(out.reshape(1, 4), ref, "", l1);
847 }
848
849 typedef TestWithParam<tuple<int, int> > Layer_Test_DWconv_Prelu;
850 TEST_P(Layer_Test_DWconv_Prelu, Accuracy)
851 {
852     // Test case
853     // input       img size 3x16x16  value all 1
854     //   |
855     //   v
856     // dw_conv     weight[0]=-1 weight[1]=-2 weight[2]=-3   bias={1,2,3}
857     //   |
858     //   v
859     // prelu       weight={1,2,3}
860     //   |
861     //   v
862     // output      out size 3x14x14  if right: out[0]=-8 out[0]=-32 out[0]=-72
863     //             but current opencv output: out[0]=-24 out[0]=-48 out[0]=-72
864
865     const int num_input = get<0>(GetParam());   //inpChannels
866     const int group = 3;                        //outChannels=group when group>1
867     const int num_output = get<1>(GetParam());
868     const int kernel_depth = num_input/group;
869     CV_Assert_N(num_output >= group, num_output % group == 0, num_input % group == 0);
870
871     Net net;
872     //layer 1: dwconv
873     LayerParams lp;
874     lp.name = "dwconv";
875     lp.type = "Convolution";
876     lp.set("kernel_size", 3);
877     lp.set("num_output", num_output);
878     lp.set("pad", 0);
879     lp.set("group", group);
880     lp.set("stride", 1);
881     lp.set("engine", "CAFFE");
882     lp.set("bias_term", "true");
883
884     std::vector<int> weightsShape(4);
885     weightsShape[0] = num_output;   // #outChannels
886     weightsShape[1] = kernel_depth; // #inpChannels / group
887     weightsShape[2] = 3;            // height
888     weightsShape[3] = 3;            // width
889     Mat weights(weightsShape, CV_32F, Scalar(1));
890
891     //assign weights
892     for (int i = 0; i < weightsShape[0]; ++i)
893     {
894         for (int j = 0; j < weightsShape[1]; ++j)
895         {
896             for (int k = 0; k < weightsShape[2]; ++k)
897             {
898                 for (int l = 0; l < weightsShape[3]; ++l)
899                 {
900                     weights.ptr<float>(i, j, k)[l]=-1*(i+1);
901                 }
902             }
903         }
904     }
905     lp.blobs.push_back(weights);
906
907     //assign bias
908     Mat bias(1, num_output, CV_32F, Scalar(1));
909     for (int i = 0; i < 1; ++i)
910     {
911         for (int j = 0; j < num_output; ++j)
912         {
913             bias.ptr<float>(i)[j]=j+1;
914         }
915     }
916     lp.blobs.push_back(bias);
917     net.addLayerToPrev(lp.name, lp.type, lp);
918
919     //layer 2: prelu
920     LayerParams lpr;
921     lpr.name = "dw_relu";
922     lpr.type = "PReLU";
923     Mat weightsp(1, num_output, CV_32F, Scalar(1));
924
925     //assign weights
926     for (int i = 0; i < 1; ++i)
927     {
928         for (int j = 0; j < num_output; ++j)
929         {
930             weightsp.ptr<float>(i)[j]=j+1;
931         }
932     }
933
934     lpr.blobs.push_back(weightsp);
935     net.addLayerToPrev(lpr.name, lpr.type, lpr);
936
937     int shape[] = {1, num_input, 16, 16};
938     Mat in_blob(4, &shape[0], CV_32FC1, Scalar(1));
939
940     net.setPreferableBackend(DNN_BACKEND_OPENCV);
941     net.setInput(in_blob);
942     Mat out = net.forward();
943
944     //assign target
945     std::vector<int> outShape(4);
946     outShape[0] = 1;
947     outShape[1] = num_output;       // outChannels
948     outShape[2] = 14;          // height
949     outShape[3] = 14;          // width
950     Mat target(outShape, CV_32F, Scalar(1));
951     for (int i = 0; i < outShape[0]; ++i)
952     {
953         for (int j = 0; j < outShape[1]; ++j)
954         {
955             for (int k = 0; k < outShape[2]; ++k)
956             {
957                 for (int l = 0; l < outShape[3]; ++l)
958                 {
959                     target.ptr<float>(i, j, k)[l]=(-9*kernel_depth*(j+1)+j+1)*(j+1);
960                 }
961             }
962         }
963     }
964
965     normAssert(out, target);
966 }
967 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_DWconv_Prelu, Combine(Values(3, 6), Values(3, 6)));
968
969 #ifdef HAVE_INF_ENGINE
970 // Using Intel's Model Optimizer generate .xml and .bin files:
971 // ./ModelOptimizer -w /path/to/caffemodel -d /path/to/prototxt \
972 //                  -p FP32 -i -b ${batch_size} -o /path/to/output/folder
973 typedef testing::TestWithParam<Target> Layer_Test_Convolution_DLDT;
974 TEST_P(Layer_Test_Convolution_DLDT, Accuracy)
975 {
976     Target targetId = GetParam();
977
978     std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
979     Net netDefault = readNet(_tf("layer_convolution.caffemodel"), _tf("layer_convolution.prototxt"));
980     Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
981
982     Mat inp = blobFromNPY(_tf("blob.npy"));
983
984     netDefault.setInput(inp);
985     netDefault.setPreferableBackend(DNN_BACKEND_OPENCV);
986     Mat outDefault = netDefault.forward();
987
988     net.setInput(inp);
989     net.setPreferableTarget(targetId);
990
991     Mat out = net.forward();
992
993     double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
994     double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
995     normAssert(outDefault, out, "", l1, lInf);
996
997     std::vector<int> outLayers = net.getUnconnectedOutLayers();
998     ASSERT_EQ(net.getLayer(outLayers[0])->name, "output");
999     ASSERT_EQ(net.getLayer(outLayers[0])->type, "Convolution");
1000 }
1001
1002 TEST_P(Layer_Test_Convolution_DLDT, setInput_uint8)
1003 {
1004     Target targetId = GetParam();
1005     Mat inp = blobFromNPY(_tf("blob.npy"));
1006
1007     Mat inputs[] = {Mat(inp.dims, inp.size, CV_8U), Mat()};
1008     randu(inputs[0], 0, 255);
1009     inputs[0].convertTo(inputs[1], CV_32F);
1010
1011     std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1012
1013     Mat outs[2];
1014     for (int i = 0; i < 2; ++i)
1015     {
1016         Net net = readNet(_tf("layer_convolution" + suffix + ".xml"), _tf("layer_convolution" + suffix + ".bin"));
1017         net.setPreferableTarget(targetId);
1018         net.setInput(inputs[i]);
1019         outs[i] = net.forward();
1020         ASSERT_EQ(outs[i].type(), CV_32F);
1021     }
1022     if (targetId != DNN_TARGET_MYRIAD)
1023         normAssert(outs[0], outs[1]);
1024 }
1025
1026 TEST_P(Layer_Test_Convolution_DLDT, multithreading)
1027 {
1028     Target targetId = GetParam();
1029     std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1030     std::string xmlPath = _tf("layer_convolution" + suffix + ".xml");
1031     std::string binPath = _tf("layer_convolution" + suffix + ".bin");
1032     Net firstNet = readNet(xmlPath, binPath);
1033     Net secondNet = readNet(xmlPath, binPath);
1034     Mat inp = blobFromNPY(_tf("blob.npy"));
1035
1036     firstNet.setInput(inp);
1037     secondNet.setInput(inp);
1038     firstNet.setPreferableTarget(targetId);
1039     secondNet.setPreferableTarget(targetId);
1040
1041     Mat out1, out2;
1042     std::thread t1([&]{out1 = firstNet.forward();});
1043     std::thread t2([&]{out2 = secondNet.forward();});
1044
1045     t1.join();
1046     t2.join();
1047
1048     Mat ref = blobFromNPY(_tf("layer_convolution.npy"));
1049     double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.5e-3 : 1e-5;
1050     double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 1.8e-2 : 1e-4;
1051     normAssert(out1, ref, "first thread", l1, lInf);
1052     normAssert(out2, ref, "second thread", l1, lInf);
1053 }
1054
1055 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_Convolution_DLDT,
1056     testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)));
1057
1058 // 1. Create a .prototxt file with the following network:
1059 // layer {
1060 //   type: "Input" name: "data" top: "data"
1061 //   input_param { shape { dim: 1 dim: 2 dim: 3 } }
1062 // }
1063 // layer {
1064 //   type: "Input" name: "second_input" top: "second_input"
1065 //   input_param { shape { dim: 1 dim: 2 dim: 3 } }
1066 // }
1067 // layer {
1068 //  type: "Eltwise" name: "output" top: "output"
1069 //  bottom: "data" bottom: "second_input"
1070 //  eltwise_param { operation: SUM }
1071 // }
1072 //
1073 // 2. Create a .caffemodel file using Caffe:
1074 //
1075 // import caffe
1076 // net = caffe.Net('/path/to/prototxt', caffe.TEST)
1077 // net.save('/path/to/caffemodel')
1078 //
1079 // 3. Convert using ModelOptimizer.
1080 typedef testing::TestWithParam<tuple<int, int, Target, std::vector<int> > > Test_DLDT_two_inputs_3dim;
1081 TEST_P(Test_DLDT_two_inputs_3dim, as_IR)
1082 {
1083     int firstInpType = get<0>(GetParam());
1084     int secondInpType = get<1>(GetParam());
1085     Target targetId = get<2>(GetParam());
1086
1087     std::string suffix = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? "_fp16" : "";
1088     Net net = readNet(_tf("net_two_inputs" + suffix + ".xml"), _tf("net_two_inputs.bin"));
1089     std::vector<int> inpSize = get<3>(GetParam());
1090     Mat firstInp(3, inpSize.data(), firstInpType);
1091     Mat secondInp(3, inpSize.data(), secondInpType);
1092     randu(firstInp, 0, 255);
1093     randu(secondInp, 0, 255);
1094
1095     net.setInput(firstInp, "data");
1096     net.setInput(secondInp, "second_input");
1097     net.setPreferableTarget(targetId);
1098
1099     double l1 = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1100                  (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.06 : 0.0;
1101     double lInf = ((targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) &&
1102                    (firstInpType == CV_32F || secondInpType == CV_32F)) ? 0.23 : 0.0;
1103
1104     Mat out = net.forward();
1105
1106     Mat ref;
1107     cv::add(firstInp, secondInp, ref, Mat(), CV_32F);
1108     normAssert(out, ref, "", l1, lInf);
1109 }
1110
1111 std::vector< std::vector<int> > list_sizes{ {1, 2, 3}, {3, 2, 1}, {5, 5, 5}, {13, 7, 11} };
1112
1113 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs_3dim, Combine(
1114   Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1115   testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE)),
1116   testing::ValuesIn(list_sizes)
1117 ));
1118
1119 typedef testing::TestWithParam<tuple<int, int, Target> > Test_DLDT_two_inputs;
1120 TEST_P(Test_DLDT_two_inputs, as_backend)
1121 {
1122     static const float kScale = 0.5f;
1123     static const float kScaleInv = 1.0f / kScale;
1124
1125     Target targetId = get<2>(GetParam());
1126
1127     Net net;
1128     LayerParams lp;
1129     lp.type = "Eltwise";
1130     lp.name = "testLayer";
1131     lp.set("operation", "sum");
1132     int eltwiseId = net.addLayerToPrev(lp.name, lp.type, lp);  // connect to a first input
1133     net.connect(0, 1, eltwiseId, 1);  // connect to a second input
1134
1135     int inpSize[] = {1, 2, 3, 4};
1136     Mat firstInp(4, &inpSize[0], get<0>(GetParam()));
1137     Mat secondInp(4, &inpSize[0], get<1>(GetParam()));
1138     randu(firstInp, 0, 255);
1139     randu(secondInp, 0, 255);
1140
1141     net.setInputsNames({"data", "second_input"});
1142     net.setInput(firstInp, "data", kScale);
1143     net.setInput(secondInp, "second_input", kScaleInv);
1144     net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1145     net.setPreferableTarget(targetId);
1146     Mat out = net.forward();
1147
1148     Mat ref;
1149     addWeighted(firstInp, kScale, secondInp, kScaleInv, 0, ref, CV_32F);
1150     // Output values are in range [0, 637.5].
1151     double l1 = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.06 : 1e-6;
1152     double lInf = (targetId == DNN_TARGET_OPENCL_FP16 || targetId == DNN_TARGET_MYRIAD) ? 0.3 : 1e-5;
1153     normAssert(out, ref, "", l1, lInf);
1154 }
1155
1156 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_DLDT_two_inputs, Combine(
1157   Values(CV_8U, CV_32F), Values(CV_8U, CV_32F),
1158   testing::ValuesIn(getAvailableTargets(DNN_BACKEND_INFERENCE_ENGINE))
1159 ));
1160
1161 class UnsupportedLayer : public Layer
1162 {
1163 public:
1164     UnsupportedLayer(const LayerParams &params) : Layer(params) {}
1165
1166     static Ptr<Layer> create(const LayerParams& params)
1167     {
1168         return Ptr<Layer>(new UnsupportedLayer(params));
1169     }
1170
1171     virtual bool supportBackend(int backendId) CV_OVERRIDE
1172     {
1173         return backendId == DNN_BACKEND_OPENCV;
1174     }
1175
1176     virtual void forward(cv::InputArrayOfArrays inputs, cv::OutputArrayOfArrays outputs, cv::OutputArrayOfArrays internals) CV_OVERRIDE {}
1177 };
1178
1179 TEST(Test_DLDT, fused_output)
1180 {
1181     static const int kNumChannels = 3;
1182     CV_DNN_REGISTER_LAYER_CLASS(Unsupported, UnsupportedLayer);
1183     Net net;
1184     {
1185         LayerParams lp;
1186         lp.set("kernel_size", 1);
1187         lp.set("num_output", 3);
1188         lp.set("bias_term", false);
1189         lp.type = "Convolution";
1190         lp.name = "testConv";
1191         lp.blobs.push_back(Mat({kNumChannels, 1, 1, 1}, CV_32F, Scalar(1)));
1192         net.addLayerToPrev(lp.name, lp.type, lp);
1193     }
1194     {
1195         LayerParams lp;
1196         lp.set("bias_term", false);
1197         lp.type = "Scale";
1198         lp.name = "testScale";
1199         lp.blobs.push_back(Mat({kNumChannels}, CV_32F, Scalar(1)));
1200         net.addLayerToPrev(lp.name, lp.type, lp);
1201     }
1202     {
1203         LayerParams lp;
1204         net.addLayerToPrev("unsupported_layer", "Unsupported", lp);
1205     }
1206     net.setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1207     net.setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1208     ASSERT_NO_THROW(net.forward());
1209     LayerFactory::unregisterLayer("Unsupported");
1210 }
1211
1212 TEST(Test_DLDT, multiple_networks)
1213 {
1214     Net nets[2];
1215     for (int i = 0; i < 2; ++i)
1216     {
1217         nets[i].setInputsNames(std::vector<String>(1, format("input_%d", i)));
1218
1219         LayerParams lp;
1220         lp.set("kernel_size", 1);
1221         lp.set("num_output", 1);
1222         lp.set("bias_term", false);
1223         lp.type = "Convolution";
1224         lp.name = format("testConv_%d", i);
1225         lp.blobs.push_back(Mat({1, 1, 1, 1}, CV_32F, Scalar(1 + i)));
1226         nets[i].addLayerToPrev(lp.name, lp.type, lp);
1227         nets[i].setPreferableBackend(DNN_BACKEND_INFERENCE_ENGINE);
1228         nets[i].setInput(Mat({1, 1, 1, 1}, CV_32FC1, Scalar(1)));
1229     }
1230     Mat out_1 = nets[0].forward();
1231     Mat out_2 = nets[1].forward();
1232     // After the second model is initialized we try to receive an output from the first network again.
1233     out_1 = nets[0].forward();
1234     normAssert(2 * out_1, out_2);
1235 }
1236 #endif  // HAVE_INF_ENGINE
1237
1238 // Test a custom layer.
1239 class CustomInterpLayer CV_FINAL : public Layer
1240 {
1241 public:
1242     CustomInterpLayer(const LayerParams &params) : Layer(params)
1243     {
1244         zoomFactor = params.get<int>("zoom_factor", 0);
1245         outWidth = params.get<int>("width", 0);
1246         outHeight = params.get<int>("height", 0);
1247     }
1248
1249     static Ptr<Layer> create(LayerParams& params)
1250     {
1251         return Ptr<Layer>(new CustomInterpLayer(params));
1252     }
1253
1254     virtual bool getMemoryShapes(const std::vector<std::vector<int> > &inputs,
1255                                  const int requiredOutputs,
1256                                  std::vector<std::vector<int> > &outputs,
1257                                  std::vector<std::vector<int> > &internals) const CV_OVERRIDE
1258     {
1259         const int batchSize = inputs[0][0];
1260         const int numChannels = inputs[0][1];
1261         const int inpHeight = inputs[0][2];
1262         const int inpWidth = inputs[0][3];
1263
1264         std::vector<int> outShape(4);
1265         outShape[0] = batchSize;
1266         outShape[1] = numChannels;
1267         outShape[2] = outHeight != 0 ? outHeight : (inpHeight + (inpHeight - 1) * (zoomFactor - 1));
1268         outShape[3] = outWidth != 0 ? outWidth : (inpWidth + (inpWidth - 1) * (zoomFactor - 1));
1269         outputs.assign(1, outShape);
1270         return false;
1271     }
1272
1273     virtual void finalize(InputArrayOfArrays, OutputArrayOfArrays outputs_arr) CV_OVERRIDE
1274     {
1275         std::vector<Mat> outputs;
1276         outputs_arr.getMatVector(outputs);
1277
1278         if (!outWidth && !outHeight)
1279         {
1280             outHeight = outputs[0].size[2];
1281             outWidth = outputs[0].size[3];
1282         }
1283     }
1284
1285     // Implementation of this custom layer is based on https://github.com/cdmh/deeplab-public/blob/master/src/caffe/layers/interp_layer.cpp
1286     void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) CV_OVERRIDE
1287     {
1288         CV_TRACE_FUNCTION();
1289         CV_TRACE_ARG_VALUE(name, "name", name.c_str());
1290
1291         if (inputs_arr.depth() == CV_16S)
1292         {
1293             forward_fallback(inputs_arr, outputs_arr, internals_arr);
1294             return;
1295         }
1296
1297         std::vector<Mat> inputs, outputs;
1298         inputs_arr.getMatVector(inputs);
1299         outputs_arr.getMatVector(outputs);
1300
1301         Mat& inp = inputs[0];
1302         Mat& out = outputs[0];
1303         const float* inpData = (float*)inp.data;
1304         float* outData = (float*)out.data;
1305
1306         const int batchSize = inp.size[0];
1307         const int numChannels = inp.size[1];
1308         const int inpHeight = inp.size[2];
1309         const int inpWidth = inp.size[3];
1310
1311         const float rheight = (outHeight > 1) ? static_cast<float>(inpHeight - 1) / (outHeight - 1) : 0.f;
1312         const float rwidth = (outWidth > 1) ? static_cast<float>(inpWidth - 1) / (outWidth - 1) : 0.f;
1313         for (int h2 = 0; h2 < outHeight; ++h2)
1314         {
1315             const float h1r = rheight * h2;
1316             const int h1 = h1r;
1317             const int h1p = (h1 < inpHeight - 1) ? 1 : 0;
1318             const float h1lambda = h1r - h1;
1319             const float h0lambda = 1.f - h1lambda;
1320             for (int w2 = 0; w2 < outWidth; ++w2)
1321             {
1322                 const float w1r = rwidth * w2;
1323                 const int w1 = w1r;
1324                 const int w1p = (w1 < inpWidth - 1) ? 1 : 0;
1325                 const float w1lambda = w1r - w1;
1326                 const float w0lambda = 1.f - w1lambda;
1327                 const float* pos1 = inpData + h1 * inpWidth + w1;
1328                 float* pos2 = outData + h2 * outWidth + w2;
1329                 for (int c = 0; c < batchSize * numChannels; ++c)
1330                 {
1331                     pos2[0] =
1332                       h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) +
1333                       h1lambda * (w0lambda * pos1[h1p * inpWidth] + w1lambda * pos1[h1p * inpWidth + w1p]);
1334                     pos1 += inpWidth * inpHeight;
1335                     pos2 += outWidth * outHeight;
1336                 }
1337             }
1338         }
1339     }
1340
1341 private:
1342     int outWidth, outHeight, zoomFactor;
1343 };
1344
1345 #ifndef OPENCV_DNN_EXTERNAL_PROTOBUF
1346 TEST_P(Test_Caffe_layers, Interp)
1347 #else
1348 TEST_P(Test_Caffe_layers, DISABLED_Interp)  // requires patched protobuf (available in OpenCV source tree only)
1349 #endif
1350 {
1351     if (backend == DNN_BACKEND_INFERENCE_ENGINE && target == DNN_TARGET_MYRIAD)
1352         applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD);
1353
1354     // Test a custom layer.
1355     CV_DNN_REGISTER_LAYER_CLASS(Interp, CustomInterpLayer);
1356     try
1357     {
1358         testLayerUsingCaffeModels("layer_interp", false, false);
1359     }
1360     catch (...)
1361     {
1362         LayerFactory::unregisterLayer("Interp");
1363         throw;
1364     }
1365     LayerFactory::unregisterLayer("Interp");
1366
1367     // Test an implemented layer.
1368     testLayerUsingCaffeModels("layer_interp", false, false);
1369 }
1370
1371 INSTANTIATE_TEST_CASE_P(/*nothing*/, Test_Caffe_layers, dnnBackendsAndTargets());
1372
1373 TEST(Layer_Test_PoolingIndices, Accuracy)
1374 {
1375     Net net;
1376
1377     LayerParams lp;
1378     lp.set("pool", "max");
1379     lp.set("kernel_w", 2);
1380     lp.set("kernel_h", 2);
1381     lp.set("stride_w", 2);
1382     lp.set("stride_h", 2);
1383     lp.set("pad_w", 0);
1384     lp.set("pad_h", 0);
1385     lp.name = "testLayer.name";  // This test also checks that OpenCV lets use names with dots.
1386     lp.type = "Pooling";
1387     net.addLayerToPrev(lp.name, lp.type, lp);
1388
1389     Mat inp(10, 10, CV_8U);
1390     randu(inp, 0, 255);
1391
1392     Mat maxValues(5, 5, CV_32F, Scalar(-1)), indices(5, 5, CV_32F, Scalar(-1));
1393     for (int y = 0; y < 10; ++y)
1394     {
1395         int dstY = y / 2;
1396         for (int x = 0; x < 10; ++x)
1397         {
1398             int dstX = x / 2;
1399             uint8_t val = inp.at<uint8_t>(y, x);
1400             if ((float)inp.at<uint8_t>(y, x) > maxValues.at<float>(dstY, dstX))
1401             {
1402                 maxValues.at<float>(dstY, dstX) = val;
1403                 indices.at<float>(dstY, dstX) = y * 10 + x;
1404             }
1405         }
1406     }
1407     net.setPreferableBackend(DNN_BACKEND_OPENCV);
1408     net.setInput(blobFromImage(inp));
1409
1410     std::vector<Mat> outputs;
1411     net.forward(outputs, lp.name);
1412     normAssert(maxValues, outputs[0].reshape(1, 5));
1413     normAssert(indices, outputs[1].reshape(1, 5));
1414 }
1415
1416 typedef testing::TestWithParam<tuple<Vec4i, int, tuple<Backend, Target> > > Layer_Test_ShuffleChannel;
1417 TEST_P(Layer_Test_ShuffleChannel, Accuracy)
1418 {
1419     Vec4i inpShapeVec = get<0>(GetParam());
1420     int group = get<1>(GetParam());
1421     ASSERT_EQ(inpShapeVec[1] % group, 0);
1422     const int groupSize = inpShapeVec[1] / group;
1423     int backendId = get<0>(get<2>(GetParam()));
1424     int targetId = get<1>(get<2>(GetParam()));
1425
1426     Net net;
1427     LayerParams lp;
1428     lp.set("group", group);
1429     lp.type = "ShuffleChannel";
1430     lp.name = "testLayer";
1431     net.addLayerToPrev(lp.name, lp.type, lp);
1432
1433     const int inpShape[] = {inpShapeVec[0], inpShapeVec[1], inpShapeVec[2], inpShapeVec[3]};
1434     Mat inp(4, inpShape, CV_32F);
1435     randu(inp, 0, 255);
1436
1437     net.setInput(inp);
1438     net.setPreferableBackend(backendId);
1439     net.setPreferableTarget(targetId);
1440     Mat out = net.forward();
1441
1442     double l1 = (targetId == DNN_TARGET_OPENCL_FP16) ? 5e-2 : 1e-5;
1443     double lInf = (targetId == DNN_TARGET_OPENCL_FP16) ? 7e-2 : 1e-4;
1444     for (int n = 0; n < inpShapeVec[0]; ++n)
1445     {
1446         for (int c = 0; c < inpShapeVec[1]; ++c)
1447         {
1448             Mat outChannel = getPlane(out, n, c);
1449             Mat inpChannel = getPlane(inp, n, groupSize * (c % group) + c / group);
1450             normAssert(outChannel, inpChannel, "", l1, lInf);
1451         }
1452     }
1453 }
1454 INSTANTIATE_TEST_CASE_P(/**/, Layer_Test_ShuffleChannel, Combine(
1455 /*input shape*/  Values(Vec4i(1, 6, 5, 7), Vec4i(3, 12, 1, 4)),
1456 /*group*/        Values(1, 2, 3, 6), dnnBackendsAndTargets(/*with IE*/ false)
1457 ));
1458
1459 // Check if relu is not fused to convolution if we requested it's output
1460 TEST(Layer_Test_Convolution, relu_fusion)
1461 {
1462     Net net;
1463     {
1464         LayerParams lp;
1465         lp.set("kernel_size", 1);
1466         lp.set("num_output", 1);
1467         lp.set("bias_term", false);
1468         lp.type = "Convolution";
1469         lp.name = "testConv";
1470
1471         int weightsShape[] = {1, 1, 1, 1};
1472         Mat weights(4, &weightsShape[0], CV_32F, Scalar(1));
1473         lp.blobs.push_back(weights);
1474         net.addLayerToPrev(lp.name, lp.type, lp);
1475     }
1476     {
1477         LayerParams lp;
1478         lp.type = "ReLU";
1479         lp.name = "testReLU";
1480         net.addLayerToPrev(lp.name, lp.type, lp);
1481     }
1482     int sz[] = {1, 1, 2, 3};
1483     Mat input(4, &sz[0], CV_32F);
1484     randu(input, -1.0, -0.1);
1485     net.setInput(input);
1486     net.setPreferableBackend(DNN_BACKEND_OPENCV);
1487     Mat output = net.forward("testConv");
1488     normAssert(input, output);
1489 }
1490
1491 }} // namespace