2 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "kernels/Pad.h"
19 #include "kernels/Utils.h"
21 #include <tensorflow/lite/kernels/internal/reference/pad.h>
23 namespace luci_interpreter
28 Pad::Pad(const Tensor *input, const Tensor *paddings, Tensor *output)
29 : Kernel({input, paddings}, {output})
35 const Shape &input_shape = input()->shape();
36 const int num_dims = input_shape.num_dims();
39 throw std::runtime_error("Unsupported number of dimensions.");
41 assert(output()->element_type() == input()->element_type());
42 assert(paddings()->element_type() == DataType::S32);
43 // Paddings shape should be [N, 2].
44 assert(paddings()->shape().num_dims() == 2);
45 assert(paddings()->shape().dim(0) == num_dims);
46 assert(paddings()->shape().dim(1) == 2);
48 Shape output_shape(num_dims);
49 const auto *paddings_data = getTensorData<int32_t>(paddings());
50 for (int i = 0; i < num_dims; ++i)
52 const int32_t padding_before = paddings_data[i * 2];
53 const int32_t padding_after = paddings_data[i * 2 + 1];
54 assert(padding_before >= 0 && padding_after >= 0);
55 output_shape.dim(i) = input_shape.dim(i) + padding_before + padding_after;
58 output()->resize(output_shape);
61 void Pad::execute() const
63 const int num_dims = input()->shape().num_dims();
65 tflite::PadParams params{};
66 params.left_padding_count = num_dims;
67 params.right_padding_count = num_dims;
69 const auto *paddings_data = getTensorData<int32_t>(paddings());
70 for (int i = num_dims - 1; i >= 0; --i)
72 params.left_padding[i] = paddings_data[i * 2];
73 params.right_padding[i] = paddings_data[i * 2 + 1];
76 switch (input()->element_type())
78 case DataType::FLOAT32:
80 const float pad_value = 0.0f;
81 tflite::reference_ops::Pad(params, getTensorShape(input()), getTensorData<float>(input()),
82 &pad_value, getTensorShape(output()),
83 getTensorData<float>(output()));
88 assert(output()->zero_point() >= std::numeric_limits<uint8_t>::min());
89 assert(output()->zero_point() <= std::numeric_limits<uint8_t>::max());
90 const auto pad_value = static_cast<uint8_t>(output()->zero_point());
91 tflite::reference_ops::Pad(params, getTensorShape(input()), getTensorData<uint8_t>(input()),
92 &pad_value, getTensorShape(output()),
93 getTensorData<uint8_t>(output()));
97 throw std::runtime_error("Unsupported type.");
101 } // namespace kernels
102 } // namespace luci_interpreter