1 /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
2
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6
7 http://www.apache.org/licenses/LICENSE-2.0
8
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15
16 #include "tensorflow/lite/toco/graph_transformations/identify_util.h"
17
18 #include <string>
19
20 #include "tensorflow/lite/toco/model.h"
21 #include "tensorflow/lite/toco/tooling_util.h"
22
23 namespace toco {
24 namespace util {
25
IsBinaryOp(const Operator * op,OperatorType optype,FusedActivationFunctionType act)26 bool IsBinaryOp(const Operator* op, OperatorType optype,
27 FusedActivationFunctionType act) {
28 return op && op->type == optype && op->inputs.size() == 2 &&
29 op->fused_activation_function == act;
30 }
31
CheckArrayIsScalarFloat(Model * model,const std::string & name,float val)32 bool CheckArrayIsScalarFloat(Model* model, const std::string& name, float val) {
33 const auto& op_array = model->GetArray(name);
34 if (!op_array.buffer || op_array.buffer->type != ArrayDataType::kFloat ||
35 RequiredBufferSizeForShape(op_array.shape()) != 1) {
36 return false;
37 }
38 const auto& op_data = op_array.GetBuffer<ArrayDataType::kFloat>().data;
39 return op_data[0] == val;
40 }
41
GetSingleScalarInputIndexOfBinaryOp(Model * model,const Operator * op,float val)42 int GetSingleScalarInputIndexOfBinaryOp(Model* model, const Operator* op,
43 float val) {
44 bool input0_is_scalar = CheckArrayIsScalarFloat(model, op->inputs[0], val);
45 bool input1_is_scalar = CheckArrayIsScalarFloat(model, op->inputs[1], val);
46 return input0_is_scalar == input1_is_scalar ? -1 : input0_is_scalar ? 0 : 1;
47 }
48
49 } // namespace util
50 } // namespace toco
51