ONNX: upsample subgraph fusion added
[platform/upstream/opencv.git] / modules / dnn / src / onnx / onnx_importer.cpp
1 // This file is part of OpenCV project.
2 // It is subject to the license terms in the LICENSE file found in the top-level directory
3 // of this distribution and at http://opencv.org/license.html.
4
5 // Copyright (C) 2018, Intel Corporation, all rights reserved.
6 // Third party copyrights are property of their respective owners.
7
8 #include "../precomp.hpp"
9 #include <opencv2/dnn/shape_utils.hpp>
10
11 #ifdef HAVE_PROTOBUF
12
13 #include <iostream>
14 #include <fstream>
15 #include <string>
16 #include <limits>
17 #include <algorithm>
18
19
20 #if defined(__GNUC__) && __GNUC__ >= 5
21 #pragma GCC diagnostic push
22 #pragma GCC diagnostic ignored "-Wsuggest-override"
23 #endif
24 #include "opencv-onnx.pb.h"
25 #if defined(__GNUC__) && __GNUC__ >= 5
26 #pragma GCC diagnostic pop
27 #endif
28
29 #include "onnx_graph_simplifier.hpp"
30
31 namespace cv {
32 namespace dnn {
33 CV__DNN_EXPERIMENTAL_NS_BEGIN
34
35
36 class ONNXImporter
37 {
38     opencv_onnx::ModelProto model_proto;
39     struct LayerInfo {
40         int layerId;
41         int outputId;
42         LayerInfo(int _layerId, int _outputId) : layerId(_layerId), outputId(_outputId) {}
43     };
44
45     std::map<std::string, Mat> getGraphTensors(
46                                     const opencv_onnx::GraphProto& graph_proto);
47     Mat getBlob(const opencv_onnx::NodeProto& node_proto, const std::map<std::string, Mat>& constBlobs, int index);
48
49     LayerParams getLayerParams(const opencv_onnx::NodeProto& node_proto);
50     bool isCeilMode(const LayerParams& layerParams);
51
52 public:
53
54     ONNXImporter(const char *onnxFile)
55     {
56         std::fstream input(onnxFile, std::ios::in | std::ios::binary);
57
58         if (!model_proto.ParseFromIstream(&input))
59             CV_Error(Error::StsUnsupportedFormat, "Failed to parse onnx model");
60     }
61
62     ONNXImporter(const char* buffer, size_t sizeBuffer)
63     {
64         struct _Buf : public std::streambuf
65         {
66             _Buf(const char* buffer, size_t sizeBuffer)
67             {
68                 char* p = const_cast<char*>(buffer);
69                 setg(p, p, p + sizeBuffer);
70             }
71         };
72
73         _Buf buf(buffer, sizeBuffer);
74         std::istream input(&buf);
75
76         if (!model_proto.ParseFromIstream(&input))
77             CV_Error(Error::StsUnsupportedFormat, "Failed to parse onnx model from in-memory byte array.");
78     }
79
80     void populateNet(Net dstNet);
81 };
82
83 inline void replaceLayerParam(LayerParams& layerParams, const String& oldKey, const String& newKey)
84 {
85     if (layerParams.has(oldKey)) {
86         layerParams.set(newKey, layerParams.get(oldKey));
87         layerParams.erase(oldKey);
88     }
89 }
90
91 void releaseONNXTensor(opencv_onnx::TensorProto& tensor_proto)
92 {
93     if (!tensor_proto.raw_data().empty()) {
94         delete tensor_proto.release_raw_data();
95     }
96 }
97
98 void runLayer(LayerParams& params, const std::vector<Mat>& inputs,
99               std::vector<Mat>& outputs)
100 {
101     Ptr<Layer> layer = LayerFactory::createLayerInstance(params.type, params);
102     CV_Assert((bool)layer);
103
104     std::vector<MatShape> inpShapes(inputs.size());
105     int ddepth = CV_32F;
106     for (size_t i = 0; i < inputs.size(); ++i)
107     {
108         inpShapes[i] = shape(inputs[i]);
109         if (i > 0 && ddepth != inputs[i].depth())
110             CV_Error(Error::StsNotImplemented, "Mixed input data types.");
111         ddepth = inputs[i].depth();
112     }
113
114     std::vector<MatShape> outShapes, internalShapes;
115     layer->getMemoryShapes(inpShapes, 0, outShapes, internalShapes);
116
117     std::vector<Mat> internals(internalShapes.size());
118     outputs.resize(outShapes.size());
119     for (size_t i = 0; i < outShapes.size(); ++i)
120         outputs[i].create(outShapes[i], ddepth);
121     for (size_t i = 0; i < internalShapes.size(); ++i)
122         internals[i].create(internalShapes[i], ddepth);
123
124     layer->finalize(inputs, outputs);
125     layer->forward(inputs, outputs, internals);
126 }
127
128 std::map<std::string, Mat> ONNXImporter::getGraphTensors(
129                                         const opencv_onnx::GraphProto& graph_proto)
130 {
131   opencv_onnx::TensorProto tensor_proto;
132   std::map<std::string, Mat> layers_weights;
133
134   for (int i = 0; i < graph_proto.initializer_size(); i++)
135   {
136     tensor_proto = graph_proto.initializer(i);
137     Mat mat = getMatFromTensor(tensor_proto);
138     releaseONNXTensor(tensor_proto);
139     layers_weights.insert(std::make_pair(tensor_proto.name(), mat));
140   }
141   return layers_weights;
142 }
143
144 static DictValue parse(const ::google::protobuf::RepeatedField< ::google::protobuf::int64>& src) {
145     std::vector<int32_t> dst(src.size());
146     convertInt64ToInt32(src, dst, src.size());
147     return DictValue::arrayInt(&dst[0], src.size());
148 }
149
150 LayerParams ONNXImporter::getLayerParams(const opencv_onnx::NodeProto& node_proto)
151 {
152     LayerParams lp;
153     for(int i = 0; i < node_proto.attribute_size(); i++)
154     {
155         opencv_onnx::AttributeProto attribute_proto = node_proto.attribute(i);
156         std::string attribute_name = attribute_proto.name();
157
158         if(attribute_name == "kernel_shape")
159         {
160             CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
161             lp.set("kernel_size", parse(attribute_proto.ints()));
162         }
163         else if(attribute_name == "strides")
164         {
165             CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
166             lp.set("stride", parse(attribute_proto.ints()));
167         }
168         else if(attribute_name == "pads")
169         {
170             if (node_proto.op_type() == "Pad")
171             {
172                 // Padding layer.
173                 // Paddings are in order begin0, begin1, .. beginN, end0, end1, ..., endN.
174                 // We need to shuffle it to begin0, end0, begin1, end1, ...
175                 CV_Assert(attribute_proto.ints_size() % 2 == 0);
176                 const int dims = attribute_proto.ints_size() / 2;
177                 std::vector<int32_t> paddings;
178                 paddings.reserve(attribute_proto.ints_size());
179                 for (int i = 0; i < dims; ++i)
180                 {
181                     paddings.push_back(attribute_proto.ints(i));
182                     paddings.push_back(attribute_proto.ints(dims + i));
183                 }
184                 lp.set("paddings", DictValue::arrayInt(&paddings[0], paddings.size()));
185             }
186             else
187             {
188                 // Convolution or pooling.
189                 CV_Assert(attribute_proto.ints_size() == 4 || attribute_proto.ints_size() == 6);
190                 lp.set("pad", parse(attribute_proto.ints()));
191             }
192         }
193         else if(attribute_name == "auto_pad")
194         {
195             if (attribute_proto.s() == "SAME_UPPER" || attribute_proto.s() == "SAME_LOWER") {
196                 lp.set("pad_mode",  "SAME");
197             }
198             else if (attribute_proto.s() == "VALID") {
199                 lp.set("pad_mode", "VALID");
200             }
201         }
202         else if(attribute_name == "dilations")
203         {
204             CV_Assert(attribute_proto.ints_size() == 2 || attribute_proto.ints_size() == 3);
205             lp.set("dilation", parse(attribute_proto.ints()));
206         }
207         else if (attribute_proto.has_i())
208         {
209             ::google::protobuf::int64 src = attribute_proto.i();
210             if (src < std::numeric_limits<int32_t>::min() || src > std::numeric_limits<int32_t>::max())
211                 CV_Error(Error::StsOutOfRange, "Input is out of OpenCV 32S range");
212             else
213                 lp.set(attribute_name, saturate_cast<int32_t>(src));
214         }
215         else if (attribute_proto.has_f())
216         {
217             lp.set(attribute_name, attribute_proto.f());
218         }
219         else if (attribute_proto.has_s())
220         {
221             lp.set(attribute_name, attribute_proto.s());
222         }
223         else if (attribute_proto.floats_size() > 0)
224         {
225             lp.set(attribute_name, DictValue::arrayReal(
226                 attribute_proto.floats().data(), attribute_proto.floats_size()));
227         }
228         else if (attribute_proto.ints_size() > 0)
229         {
230             lp.set(attribute_proto.name(), parse(attribute_proto.ints()));
231         }
232         else if (attribute_proto.has_t())
233         {
234             opencv_onnx::TensorProto tensor = attribute_proto.t();
235             Mat blob = getMatFromTensor(tensor);
236             lp.blobs.push_back(blob);
237         }
238         else if (attribute_proto.has_g() || attribute_proto.strings_size() > 0 ||
239                     attribute_proto.tensors_size() > 0 || attribute_proto.graphs_size() > 0)
240         {
241                 CV_Error(Error::StsNotImplemented, "Unexpected attribute type");
242         }
243         else
244             CV_Error(Error::StsNotImplemented, "Unsupported attribute type");
245     }
246     return lp;
247 }
248
249 Mat ONNXImporter::getBlob(const opencv_onnx::NodeProto& node_proto,
250                     const std::map<std::string, Mat>& constBlobs, int index)
251 {
252     CV_Assert(index < node_proto.input_size());
253     std::map<std::string, Mat>::const_iterator constBlob;
254     constBlob = constBlobs.find(node_proto.input(index));
255     if (constBlob == constBlobs.end()) {
256         CV_Error(Error::StsObjectNotFound,
257              "Blob " + node_proto.input(index) + " not found in const blobs");
258     }
259     return constBlob->second;
260 }
261
262 void ONNXImporter::populateNet(Net dstNet)
263 {
264     CV_Assert(model_proto.has_graph());
265     opencv_onnx::GraphProto graph_proto = model_proto.graph();
266
267     simplifySubgraphs(graph_proto);
268
269     std::map<std::string, Mat> constBlobs = getGraphTensors(graph_proto);
270     // List of internal blobs shapes.
271     std::map<std::string, MatShape> outShapes;
272     // Add all the inputs shapes. It includes as constant blobs as network's inputs shapes.
273     for (int i = 0; i < graph_proto.input_size(); ++i)
274     {
275         opencv_onnx::ValueInfoProto valueInfoProto = graph_proto.input(i);
276         CV_Assert(valueInfoProto.has_type());
277         opencv_onnx::TypeProto typeProto = valueInfoProto.type();
278         CV_Assert(typeProto.has_tensor_type());
279         opencv_onnx::TypeProto::Tensor tensor = typeProto.tensor_type();
280         CV_Assert(tensor.has_shape());
281         opencv_onnx::TensorShapeProto tensorShape = tensor.shape();
282
283         MatShape inpShape(tensorShape.dim_size());
284         for (int j = 0; j < inpShape.size(); ++j)
285         {
286             inpShape[j] = tensorShape.dim(j).dim_value();
287         }
288         outShapes[valueInfoProto.name()] = inpShape;
289     }
290
291     std::string framework_name;
292     if (model_proto.has_producer_name()) {
293         framework_name = model_proto.producer_name();
294     }
295
296     // create map with network inputs (without const blobs)
297     std::map<std::string, LayerInfo> layer_id;
298     std::map<std::string, LayerInfo>::iterator layerId;
299     std::map<std::string, MatShape>::iterator shapeIt;
300     // fill map: push layer name, layer id and output id
301     std::vector<String> netInputs;
302     for (int j = 0; j < graph_proto.input_size(); j++)
303     {
304         const std::string& name = graph_proto.input(j).name();
305         if (constBlobs.find(name) == constBlobs.end()) {
306             netInputs.push_back(name);
307             layer_id.insert(std::make_pair(name, LayerInfo(0, netInputs.size() - 1)));
308         }
309     }
310     dstNet.setInputsNames(netInputs);
311
312     int layersSize = graph_proto.node_size();
313     LayerParams layerParams;
314     opencv_onnx::NodeProto node_proto;
315
316     for(int li = 0; li < layersSize; li++)
317     {
318         node_proto = graph_proto.node(li);
319         layerParams = getLayerParams(node_proto);
320         CV_Assert(node_proto.output_size() >= 1);
321         layerParams.name = node_proto.output(0);
322
323         std::string layer_type = node_proto.op_type();
324         layerParams.type = layer_type;
325
326
327         if (layer_type == "MaxPool")
328         {
329             layerParams.type = "Pooling";
330             layerParams.set("pool", "MAX");
331             layerParams.set("ceil_mode", layerParams.has("pad_mode"));
332         }
333         else if (layer_type == "AveragePool")
334         {
335             layerParams.type = "Pooling";
336             layerParams.set("pool", "AVE");
337             layerParams.set("ceil_mode", layerParams.has("pad_mode"));
338             layerParams.set("ave_pool_padded_area", framework_name == "pytorch");
339         }
340         else if (layer_type == "GlobalAveragePool" || layer_type == "GlobalMaxPool" || layer_type == "ReduceMean")
341         {
342             CV_Assert(node_proto.input_size() == 1);
343             layerParams.type = "Pooling";
344             layerParams.set("pool", layer_type == "GlobalMaxPool"? "MAX" : "AVE");
345             layerParams.set("global_pooling", layer_type == "GlobalAveragePool" || layer_type == "GlobalMaxPool");
346
347             if (layer_type == "ReduceMean")
348             {
349                 if (layerParams.get<int>("keepdims") == 0 || !layerParams.has("axes"))
350                     CV_Error(Error::StsNotImplemented, "Unsupported mode of ReduceMean operation.");
351
352                 MatShape inpShape = outShapes[node_proto.input(0)];
353                 if (inpShape.size() != 4 && inpShape.size() != 5)
354                     CV_Error(Error::StsNotImplemented, "Unsupported input shape of reduce_mean operation.");
355
356                 DictValue axes = layerParams.get("axes");
357                 CV_Assert(axes.size() <= inpShape.size() - 2);
358                 std::vector<int> kernel_size(inpShape.size() - 2, 1);
359                 for (int i = 0; i < axes.size(); i++) {
360                     int axis = axes.get<int>(i);
361                     CV_Assert_N(axis >= 2 + i, axis < inpShape.size());
362                     kernel_size[axis - 2] = inpShape[axis];
363                 }
364
365                 layerParams.set("kernel_size", DictValue::arrayInt(&kernel_size[0], kernel_size.size()));
366             }
367         }
368         else if (layer_type == "Slice")
369         {
370             if (layerParams.has("steps")) {
371                 DictValue steps = layerParams.get("steps");
372                 for (int i = 0; i < steps.size(); ++i) {
373                     if (steps.get<int>(i) != 1)
374                         CV_Error(Error::StsNotImplemented,
375                                  "Slice layer only supports steps = 1");
376                 }
377             }
378
379             int axis = 0;
380             if (layerParams.has("axes")) {
381                 DictValue axes = layerParams.get("axes");
382                 for (int i = 1; i < axes.size(); ++i) {
383                     CV_Assert(axes.get<int>(i - 1) == axes.get<int>(i) - 1);
384                 }
385                 axis = axes.get<int>(0);
386             }
387             layerParams.set("axis", axis);
388
389             DictValue starts = layerParams.get("starts");
390             DictValue ends = layerParams.get("ends");
391             CV_Assert(starts.size() == ends.size());
392
393             std::vector<int> begin;
394             std::vector<int> end;
395             if (axis > 0) {
396                 begin.resize(axis, 0);
397                 end.resize(axis, -1);
398             }
399
400             for (int i = 0; i < starts.size(); ++i)
401             {
402                 begin.push_back(starts.get<int>(i));
403                 int finish = ends.get<int>(i);
404                 end.push_back((finish < 0) ? --finish : finish); // numpy doesn't include last dim
405             }
406             layerParams.set("begin", DictValue::arrayInt(&begin[0], begin.size()));
407             layerParams.set("end", DictValue::arrayInt(&end[0], end.size()));
408          }
409         else if (layer_type == "Split")
410         {
411             if (layerParams.has("split"))
412             {
413                 DictValue splits = layerParams.get("split");
414                 const int numSplits = splits.size();
415                 CV_Assert(numSplits > 1);
416
417                 std::vector<int> slicePoints(numSplits - 1, splits.get<int>(0));
418                 for (int i = 1; i < splits.size() - 1; ++i)
419                 {
420                     slicePoints[i] = slicePoints[i - 1] + splits.get<int>(i - 1);
421                 }
422                 layerParams.set("slice_point", DictValue::arrayInt(&slicePoints[0], slicePoints.size()));
423             }
424             else
425             {
426                 layerParams.set("num_split", node_proto.output_size());
427             }
428             layerParams.type = "Slice";
429         }
430         else if (layer_type == "Add" || layer_type == "Sum")
431         {
432             if (layer_id.find(node_proto.input(1)) == layer_id.end())
433             {
434                 Mat blob = getBlob(node_proto, constBlobs, 1);
435                 blob = blob.reshape(1, 1);
436                 if (blob.total() == 1) {
437                     layerParams.type = "Power";
438                     layerParams.set("shift", blob.at<float>(0));
439                 }
440                 else {
441                     layerParams.type = "Scale";
442                     layerParams.set("bias_term", true);
443                     layerParams.blobs.push_back(blob);
444                 }
445             }
446             else {
447                 layerParams.type = "Eltwise";
448             }
449         }
450         else if (layer_type == "Max")
451         {
452             layerParams.type = "Eltwise";
453             layerParams.set("operation", "max");
454         }
455         else if (layer_type == "Sub")
456         {
457             Mat blob = getBlob(node_proto, constBlobs, 1);
458             if (blob.total() == 1) {
459                 layerParams.type = "Power";
460                 layerParams.set("shift", -blob.at<float>(0));
461             }
462             else {
463                 layerParams.type = "Scale";
464                 layerParams.set("has_bias", true);
465                 layerParams.blobs.push_back(-1.0f * blob.reshape(1, 1));
466             }
467         }
468         else if (layer_type == "Div")
469         {
470             if (constBlobs.find(node_proto.input(1)) == constBlobs.end())
471             {
472                 layerParams.type = "Eltwise";
473                 layerParams.set("operation", "div");
474             }
475             else
476             {
477                 Mat blob = getBlob(node_proto, constBlobs, 1);
478                 CV_Assert_N(blob.type() == CV_32F, blob.total());
479                 if (blob.total() == 1)
480                 {
481                     layerParams.set("scale", 1.0f / blob.at<float>(0));
482                     layerParams.type = "Power";
483                 }
484                 else
485                 {
486                     layerParams.type = "Scale";
487                     divide(1.0, blob, blob);
488                     layerParams.blobs.push_back(blob);
489                     layerParams.set("bias_term", false);
490                 }
491             }
492         }
493         else if (layer_type == "Neg")
494         {
495             layerParams.type = "Power";
496             layerParams.set("scale", -1);
497         }
498         else if (layer_type == "Constant")
499         {
500             CV_Assert(node_proto.input_size() == 0);
501             CV_Assert(layerParams.blobs.size() == 1);
502             constBlobs.insert(std::make_pair(layerParams.name, layerParams.blobs[0]));
503             continue;
504         }
505         else if (layer_type == "ImageScaler")
506         {
507             const float scale = layerParams.has("scale") ? layerParams.get<float>("scale") : 1.0f;
508             layerParams.erase("scale");
509
510             if (layerParams.has("bias"))
511             {
512                 layerParams.type = "Scale";
513                 layerParams.blobs.push_back(
514                     Mat(Size(1,  layerParams.get("bias").size()), CV_32FC1, scale));
515
516                 layerParams.set("bias_term", true);
517                 Mat bias(1, layerParams.get("bias").size(), CV_32FC1);
518                 for (int j = 0; j < bias.total(); j++) {
519                     bias.at<float>(0, j) = layerParams.get("bias").getRealValue(j);
520                 }
521                 layerParams.blobs.push_back(bias);
522                 layerParams.erase("bias");
523             }
524             else {
525                 layerParams.set("scale", scale);
526                 layerParams.type = "Power";
527             }
528         }
529         else if (layer_type == "Clip")
530         {
531             layerParams.type = "ReLU6";
532             replaceLayerParam(layerParams, "min", "min_value");
533             replaceLayerParam(layerParams, "max", "max_value");
534
535         }
536         else if (layer_type == "LeakyRelu")
537         {
538             layerParams.type = "ReLU";
539             replaceLayerParam(layerParams, "alpha", "negative_slope");
540         }
541         else if (layer_type == "LRN")
542         {
543             replaceLayerParam(layerParams, "size", "local_size");
544         }
545         else if (layer_type == "InstanceNormalization")
546         {
547             if (node_proto.input_size() != 3)
548                 CV_Error(Error::StsNotImplemented,
549                          "Expected input, scale, bias");
550
551             layerParams.blobs.resize(4);
552             layerParams.blobs[2] = getBlob(node_proto, constBlobs, 1);  // weightData
553             layerParams.blobs[3] = getBlob(node_proto, constBlobs, 2);  // biasData
554             layerParams.set("has_bias", true);
555             layerParams.set("has_weight", true);
556
557             // Get number of channels in input
558             int size = layerParams.blobs[2].total();
559             layerParams.blobs[0] = Mat::zeros(size, 1, CV_32F); // mean
560             layerParams.blobs[1] = Mat::ones(size, 1, CV_32F); // std
561
562             LayerParams mvnParams;
563             mvnParams.name = layerParams.name + "/MVN";
564             mvnParams.type = "MVN";
565             mvnParams.set("eps", layerParams.get<float>("epsilon"));
566             layerParams.erase("epsilon");
567
568             //Create MVN layer
569             int id = dstNet.addLayer(mvnParams.name, mvnParams.type, mvnParams);
570             //Connect to input
571             layerId = layer_id.find(node_proto.input(0));
572             CV_Assert(layerId != layer_id.end());
573             dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, 0);
574             //Add shape
575             layer_id.insert(std::make_pair(mvnParams.name, LayerInfo(id, 0)));
576             outShapes[mvnParams.name] = outShapes[node_proto.input(0)];
577
578             //Replace Batch Norm's input to MVN
579             node_proto.set_input(0, mvnParams.name);
580             layerParams.type = "BatchNorm";
581         }
582         else if (layer_type == "BatchNormalization")
583         {
584             if (node_proto.input_size() != 5)
585                 CV_Error(Error::StsNotImplemented,
586                          "Expected input, scale, bias, mean and var");
587
588             layerParams.type = "BatchNorm";
589             replaceLayerParam(layerParams, "epsilon", "eps");
590             replaceLayerParam(layerParams, "spatial", "use_global_stats");
591
592             Mat meanData = getBlob(node_proto, constBlobs, 3);
593             Mat stdData =  getBlob(node_proto, constBlobs, 4);
594
595             layerParams.blobs.push_back(meanData);
596             layerParams.blobs.push_back(stdData);
597
598             if (!node_proto.input(1).empty()) {
599                 layerParams.set("has_weight", true);
600                 layerParams.blobs.push_back(getBlob(node_proto, constBlobs, 1));  // weightData
601             } else {
602                 layerParams.set("has_weight", false);
603             }
604
605             if (!node_proto.input(2).empty()) {
606                 layerParams.set("has_bias", true);
607                 layerParams.blobs.push_back(getBlob(node_proto, constBlobs, 2)); // biasData
608             } else {
609                 layerParams.set("has_bias", false);
610             }
611         }
612         else if (layer_type == "Gemm")
613         {
614             CV_Assert(node_proto.input_size() >= 2);
615             layerParams.type = "InnerProduct";
616             Mat weights = getBlob(node_proto, constBlobs, 1);
617             int ind_num_out = 0;
618             if (layerParams.has("transB") && !layerParams.get<int>("transB")) {
619                 transpose(weights, weights);
620                 ind_num_out = 1;
621             }
622             layerParams.blobs.push_back(weights);
623
624             if (node_proto.input_size() == 3) {
625                 Mat bias = getBlob(node_proto, constBlobs, 2);
626                 layerParams.blobs.push_back(bias);
627             }
628
629             layerParams.set("num_output", layerParams.blobs[0].size[ind_num_out]);
630             layerParams.set("bias_term", node_proto.input_size() == 3);
631         }
632         else if (layer_type == "MatMul")
633         {
634             CV_Assert(node_proto.input_size() == 2);
635             layerParams.type = "InnerProduct";
636             Mat blob = getBlob(node_proto, constBlobs, 1);
637             layerParams.blobs.push_back(blob.t());
638             layerParams.set("bias_term", false);
639             layerParams.set("num_output", layerParams.blobs[0].size[0]);
640         }
641         else if (layer_type == "Mul")
642         {
643             CV_Assert(node_proto.input_size() == 2);
644             if (layer_id.find(node_proto.input(1)) == layer_id.end()) {
645                 Mat blob = getBlob(node_proto, constBlobs, 1);
646                 blob = blob.reshape(1, 1);
647                 if (blob.total() == 1) {
648                     layerParams.set("scale", blob.at<float>(0));
649                     layerParams.type = "Power";
650                 }
651                 else {
652                     layerParams.blobs.push_back(blob);
653                     layerParams.type = "Scale";
654                 }
655             }
656             else {
657                 layerParams.type = "Eltwise";
658                 layerParams.set("operation", "prod");
659             }
660         }
661         else if (layer_type == "Conv")
662         {
663             CV_Assert(node_proto.input_size() >= 2);
664             layerParams.type = "Convolution";
665             for (int j = 1; j < node_proto.input_size(); j++) {
666                 layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
667             }
668             layerParams.set("num_output", layerParams.blobs[0].size[0]);
669             layerParams.set("bias_term", node_proto.input_size() == 3);
670         }
671         else if (layer_type == "ConvTranspose")
672         {
673             CV_Assert(node_proto.input_size() >= 2);
674             layerParams.type = "Deconvolution";
675             for (int j = 1; j < node_proto.input_size(); j++) {
676                 layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
677             }
678             layerParams.set("num_output", layerParams.blobs[0].size[1] * layerParams.get<int>("group", 1));
679             layerParams.set("bias_term", node_proto.input_size() == 3);
680
681             if (!layerParams.has("kernel_size"))
682                 CV_Error(Error::StsNotImplemented,
683                          "Required attribute 'kernel_size' is not present.");
684
685             if (layerParams.has("output_shape"))
686             {
687                 const DictValue& outShape = layerParams.get("output_shape");
688                 DictValue strides = layerParams.get("stride");
689                 DictValue kernel = layerParams.get("kernel_size");
690
691                 String padMode;
692                 std::vector<int> adjust_pads;
693                 if (layerParams.has("pad_mode"))
694                 {
695                     padMode = toUpperCase(layerParams.get<String>("pad_mode"));
696                     if (padMode != "SAME" && padMode != "VALID")
697                         CV_Error(Error::StsError, "Unsupported padding mode " + padMode);
698
699                     for (int i = 0; i < strides.size(); i++)
700                     {
701                         int sz = outShape.get<int>(2 + i);
702                         int stride = strides.get<int>(i);
703                         adjust_pads.push_back(padMode == "SAME"? (sz - 1) % stride :
704                                                                  (sz - kernel.get<int>(i)) % stride);
705                     }
706                     layerParams.set("adj", DictValue::arrayInt(&adjust_pads[0], adjust_pads.size()));
707                 }
708             }
709             else if (layerParams.has("output_padding"))
710             {
711                 replaceLayerParam(layerParams, "output_padding", "adj");
712             }
713         }
714         else if (layer_type == "Transpose")
715         {
716             layerParams.type = "Permute";
717             replaceLayerParam(layerParams, "perm", "order");
718
719             CV_Assert(node_proto.input_size() == 1);
720             if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
721             {
722                 std::vector<Mat> inputs(1, getBlob(node_proto, constBlobs, 0)), transposed;
723                 runLayer(layerParams, inputs, transposed);
724                 CV_Assert(transposed.size() == 1);
725                 constBlobs.insert(std::make_pair(layerParams.name, transposed[0]));
726                 continue;
727             }
728         }
729         else if (layer_type == "ReduceL2")
730         {
731             CV_Assert_N(node_proto.input_size() == 1, layerParams.has("axes"));
732             CV_Assert(graph_proto.node_size() > li + 1 && graph_proto.node(li + 1).op_type() == "Div");
733             ++li;
734             node_proto = graph_proto.node(li);
735             layerParams.name = node_proto.output(0);
736             layerParams.type = "Normalize";
737
738             DictValue axes_dict = layerParams.get("axes");
739             if (axes_dict.size() != 1)
740                 CV_Error(Error::StsNotImplemented, "Multidimensional reduceL2");
741             int axis = axes_dict.getIntValue(0);
742             layerParams.set("axis",axis);
743             layerParams.set("end_axis", axis);
744         }
745         else if (layer_type == "Squeeze")
746         {
747             CV_Assert_N(node_proto.input_size() == 1, layerParams.has("axes"));
748             DictValue axes_dict = layerParams.get("axes");
749             if (axes_dict.size() != 1)
750                 CV_Error(Error::StsNotImplemented, "Multidimensional squeeze");
751
752             int axis = axes_dict.getIntValue(0);
753             layerParams.set("axis", axis - 1);
754             layerParams.set("end_axis", axis);
755             layerParams.type = "Flatten";
756         }
757         else if (layer_type == "Unsqueeze")
758         {
759             CV_Assert(node_proto.input_size() == 1);
760             DictValue axes = layerParams.get("axes");
761             if (constBlobs.find(node_proto.input(0)) != constBlobs.end())
762             {
763                 // Constant input.
764                 Mat input = getBlob(node_proto, constBlobs, 0);
765
766                 std::vector<int> dims;
767                 for (int j = 0; j < input.dims; j++) {
768                     dims.push_back(input.size[j]);
769                 }
770                 CV_Assert(axes.getIntValue(axes.size()-1) <= dims.size());
771                 for (int j = 0; j < axes.size(); j++) {
772                     dims.insert(dims.begin() + axes.getIntValue(j), 1);
773                 }
774
775                 Mat out = input.reshape(0, dims);
776                 constBlobs.insert(std::make_pair(layerParams.name, out));
777                 continue;
778             }
779
780             // Variable input.
781             if (axes.size() != 1)
782                 CV_Error(Error::StsNotImplemented, "Multidimensional unsqueeze");
783
784             MatShape inpShape = outShapes[node_proto.input(0)];
785             int axis = axes.getIntValue(0);
786             CV_Assert(0 <= axis && axis <= inpShape.size());
787             std::vector<int> outShape = inpShape;
788             outShape.insert(outShape.begin() + axis, 1);
789             layerParams.type = "Reshape";
790             layerParams.set("dim", DictValue::arrayInt(&outShape[0], outShape.size()));
791         }
792         else if (layer_type == "Reshape")
793         {
794             CV_Assert(node_proto.input_size() == 2 || layerParams.has("shape"));
795
796             if (node_proto.input_size() == 2) {
797                 Mat blob = getBlob(node_proto, constBlobs, 1);
798                 CV_Assert(blob.type() == CV_32SC1);
799
800                 layerParams.set("dim", DictValue::arrayInt<int*>(
801                             blob.ptr<int>(), blob.total() ));
802
803                 if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
804                     std::vector<Mat> inputs(1, getBlob(node_proto, constBlobs, 0)), outputs;
805                     runLayer(layerParams, inputs, outputs);
806                     constBlobs.insert(std::make_pair(layerParams.name, outputs[0]));
807                     continue;
808                 }
809             }
810             else {
811                 DictValue shape = layerParams.get("shape");
812                 std::vector<int> dim;
813                 for (int j = 0; j < shape.size(); j++) {
814                     dim.push_back(shape.getIntValue(j));
815                 }
816
817                 if (layer_id.find(node_proto.input(0)) == layer_id.end()) {
818                     Mat input = getBlob(node_proto, constBlobs, 0);
819                     Mat out = input.reshape(0, dim);
820                     constBlobs.insert(std::make_pair(layerParams.name, out));
821                     continue;
822                 }
823                 replaceLayerParam(layerParams, "shape", "dim");
824             }
825         }
826         else if (layer_type == "Pad")
827         {
828             layerParams.type = "Padding";
829         }
830         else if (layer_type == "Shape")
831         {
832             CV_Assert(node_proto.input_size() == 1);
833             shapeIt = outShapes.find(node_proto.input(0));
834             CV_Assert(shapeIt != outShapes.end());
835             MatShape inpShape = shapeIt->second;
836
837             Mat shapeMat(inpShape.size(), 1, CV_32S);
838             for (int j = 0; j < inpShape.size(); ++j)
839                 shapeMat.at<int>(j) = inpShape[j];
840             shapeMat.dims = 1;
841
842             constBlobs.insert(std::make_pair(layerParams.name, shapeMat));
843             continue;
844         }
845         else if (layer_type == "Gather")
846         {
847             CV_Assert(node_proto.input_size() == 2);
848             CV_Assert(layerParams.has("axis"));
849             Mat input = getBlob(node_proto, constBlobs, 0);
850             Mat indexMat = getBlob(node_proto, constBlobs, 1);
851             CV_Assert_N(indexMat.type() == CV_32S, indexMat.total() == 1);
852             int index = indexMat.at<int>(0);
853             int axis = layerParams.get<int>("axis");
854
855             std::vector<cv::Range> ranges(input.dims, Range::all());
856             ranges[axis] = Range(index, index + 1);
857
858             Mat out = input(ranges);
859             constBlobs.insert(std::make_pair(layerParams.name, out));
860             continue;
861         }
862         else if (layer_type == "Concat")
863         {
864             bool hasVariableInps = false;
865             for (int i = 0; i < node_proto.input_size(); ++i)
866             {
867                 if (layer_id.find(node_proto.input(i)) != layer_id.end())
868                 {
869                     hasVariableInps = true;
870                     break;
871                 }
872             }
873
874             if (!hasVariableInps)
875             {
876                 std::vector<Mat> inputs(node_proto.input_size()), concatenated;
877                 for (size_t i = 0; i < inputs.size(); ++i)
878                 {
879                     inputs[i] = getBlob(node_proto, constBlobs, i);
880                 }
881                 runLayer(layerParams, inputs, concatenated);
882
883                 CV_Assert(concatenated.size() == 1);
884                 constBlobs.insert(std::make_pair(layerParams.name, concatenated[0]));
885                 continue;
886             }
887         }
888         else if (layer_type == "Upsample")
889         {
890             layerParams.type = "Resize";
891             if (layerParams.has("scales"))
892             {
893                 // Pytorch layer
894                 DictValue scales = layerParams.get("scales");
895                 CV_Assert(scales.size() == 4);
896                 layerParams.set("zoom_factor_y", scales.getIntValue(2));
897                 layerParams.set("zoom_factor_x", scales.getIntValue(3));
898             }
899             else
900             {
901                 // Caffe2 layer
902                 replaceLayerParam(layerParams, "height_scale", "zoom_factor_y");
903                 replaceLayerParam(layerParams, "width_scale", "zoom_factor_x");
904             }
905             replaceLayerParam(layerParams, "mode", "interpolation");
906
907             if (layerParams.get<String>("interpolation") == "linear" && framework_name == "pytorch") {
908                 layerParams.type = "Resize";
909                 Mat scales = getBlob(node_proto, constBlobs, 1);
910                 CV_Assert(scales.total() == 4);
911                 layerParams.set("interpolation", "opencv_linear");
912                 layerParams.set("zoom_factor_y", scales.at<float>(2));
913                 layerParams.set("zoom_factor_x", scales.at<float>(3));
914             }
915         }
916         else if (layer_type == "LogSoftmax")
917         {
918             layerParams.type = "Softmax";
919             layerParams.set("log_softmax", true);
920         }
921         else
922         {
923             for (int j = 0; j < node_proto.input_size(); j++) {
924                 if (layer_id.find(node_proto.input(j)) == layer_id.end())
925                     layerParams.blobs.push_back(getBlob(node_proto, constBlobs, j));
926             }
927         }
928
929         int id = dstNet.addLayer(layerParams.name, layerParams.type, layerParams);
930         for (int i = 0; i < node_proto.output_size(); ++i)
931         {
932             layer_id.insert(std::make_pair(node_proto.output(i), LayerInfo(id, i)));
933         }
934
935         std::vector<MatShape> layerInpShapes, layerOutShapes, layerInternalShapes;
936         for (int j = 0; j < node_proto.input_size(); j++) {
937             layerId = layer_id.find(node_proto.input(j));
938             if (layerId != layer_id.end()) {
939                 dstNet.connect(layerId->second.layerId, layerId->second.outputId, id, j);
940                 // Collect input shapes.
941                 shapeIt = outShapes.find(node_proto.input(j));
942                 CV_Assert(shapeIt != outShapes.end());
943                 layerInpShapes.push_back(shapeIt->second);
944             }
945         }
946
947         // Compute shape of output blob for this layer.
948         Ptr<Layer> layer = dstNet.getLayer(id);
949         layer->getMemoryShapes(layerInpShapes, 0, layerOutShapes, layerInternalShapes);
950         for (int i = 0; i < node_proto.output_size() && i < (int)layerOutShapes.size(); ++i)
951         {
952             outShapes[node_proto.output(i)] = layerOutShapes[i];
953         }
954     }
955 }
956
957 Net readNetFromONNX(const String& onnxFile)
958 {
959     ONNXImporter onnxImporter(onnxFile.c_str());
960     Net net;
961     onnxImporter.populateNet(net);
962     return net;
963 }
964
965 Net readNetFromONNX(const char* buffer, size_t sizeBuffer)
966 {
967     ONNXImporter onnxImporter(buffer, sizeBuffer);
968     Net net;
969     onnxImporter.populateNet(net);
970     return net;
971 }
972
973 Net readNetFromONNX(const std::vector<uchar>& buffer)
974 {
975     return readNetFromONNX(reinterpret_cast<const char*>(buffer.data()), buffer.size());
976 }
977
978 Mat readTensorFromONNX(const String& path)
979 {
980     opencv_onnx::TensorProto tensor_proto = opencv_onnx::TensorProto();
981     std::fstream input(path.c_str(), std::ios::in | std::ios::binary);
982     if (!tensor_proto.ParseFromIstream(&input)) {
983         CV_Error(Error::StsUnsupportedFormat, "Failed to parse data");
984     }
985     Mat mat = getMatFromTensor(tensor_proto);
986     releaseONNXTensor(tensor_proto);
987     return mat;
988 }
989
990 CV__DNN_EXPERIMENTAL_NS_END
991 }} // namespace
992
993 #endif