Imported Upstream version 1.9.0
[platform/core/ml/nnfw.git] / compiler / luci-interpreter / src / kernels / Mul.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
3  * Copyright 2019 The TensorFlow Authors. All Rights Reserved.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *    http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include "kernels/Mul.h"
19
20 #include "kernels/Utils.h"
21
22 #include <tensorflow/lite/kernels/internal/optimized/optimized_ops.h>
23 #include <tensorflow/lite/kernels/internal/reference/process_broadcast_shapes.h>
24
25 #include <stdexcept>
26
27 namespace luci_interpreter
28 {
29 namespace kernels
30 {
31
32 Mul::Mul(const Tensor *input1, const Tensor *input2, Tensor *output, const MulParams &params)
33     : KernelWithParams<MulParams>({input1, input2}, {output}, params)
34 {
35 }
36
37 void Mul::configure()
38 {
39   assert(input1()->element_type() == input2()->element_type());
40   output()->resize(calculateShapeForBroadcast(input1()->shape(), input2()->shape()));
41 }
42
43 void Mul::execute() const
44 {
45   switch (input1()->element_type())
46   {
47     case DataType::FLOAT32:
48       evalFloat();
49       break;
50     default:
51       throw std::runtime_error("Unsupported type.");
52   }
53 }
54
55 void Mul::evalFloat() const
56 {
57   float activation_min{};
58   float activation_max{};
59   calculateActivationRange(_params.activation, &activation_min, &activation_max);
60
61   tflite::ArithmeticParams params{};
62   params.float_activation_min = activation_min;
63   params.float_activation_max = activation_max;
64
65   const bool need_broadcast = tflite::reference_ops::ProcessBroadcastShapes(
66       getTensorShape(input1()), getTensorShape(input2()), &params);
67
68   if (need_broadcast)
69   {
70     tflite::optimized_ops::BroadcastMul4DSlow(
71         params, getTensorShape(input1()), getTensorData<float>(input1()), getTensorShape(input2()),
72         getTensorData<float>(input2()), getTensorShape(output()), getTensorData<float>(output()));
73   }
74   else
75   {
76     tflite::optimized_ops::Mul(params, getTensorShape(input1()), getTensorData<float>(input1()),
77                                getTensorShape(input2()), getTensorData<float>(input2()),
78                                getTensorShape(output()), getTensorData<float>(output()));
79   }
80 }
81
82 } // namespace kernels
83 } // namespace luci_interpreter