Imported Upstream version 1.7.0
[platform/core/ml/nnfw.git] / compiler / mir / src / mir_onnx_importer / Op / Pad.cpp
1 /*
2  * Copyright (c) 2019 Samsung Electronics Co., Ltd. All Rights Reserved
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *    http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include "Pad.h"
18
19 #include "ONNXHelpers.h"
20 #include "AttributeHelpers.h"
21
22 #include "mir/ops/PadOp.h"
23
24 namespace mir_onnx
25 {
26
27 void convertPadAttrName(const std::string &pad_attr_name, const onnx::NodeProto &onnx_node,
28                         ConverterContext *context)
29 {
30   std::vector<mir::Operation::Output *> inputs = context->getNodeInputs(onnx_node);
31   mir::Graph *graph = context->getGraph();
32
33   assert(inputs.size() == 1);
34   auto input = inputs[0];
35
36   // 0.0f is the default value to be filled into padded cells.
37   const auto value = getAttributeValue<float>(onnx_node, "value", 0.0f);
38   const auto pads = getAttributeValue<std::vector<std::int64_t>>(onnx_node, pad_attr_name);
39   // "constant" is the default mode.
40   const auto mode = getAttributeValue<std::string>(onnx_node, "mode", "constant");
41   if (mode != "constant")
42     throw std::runtime_error("Not supported Pad mode attribute!");
43
44   const int num_dims = input->getShape().rank();
45   assert(static_cast<int>(pads.size()) == num_dims * 2);
46   mir::PadOpAttributes attributes(num_dims);
47   for (int i = 0; i < num_dims; i++)
48   {
49     attributes.padding_before[i] = pads[i];
50     attributes.padding_after[i] = pads[num_dims + i];
51   }
52
53   attributes.padding_value = value;
54
55   auto result = createOp<mir::ops::PadOp>(graph, input, attributes)->getOutput(0);
56
57   context->setNodeOutputs(onnx_node, {result});
58 }
59
60 void convertPadV1(const onnx::NodeProto &onnx_node, ConverterContext *context)
61 {
62   convertPadAttrName("paddings", onnx_node, context);
63 }
64
65 void convertPadV2(const onnx::NodeProto &onnx_node, ConverterContext *context)
66 {
67   convertPadAttrName("pads", onnx_node, context);
68 }
69
70 } // namespace mir_onnx