1 /* Copyright 2017 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 #include <memory> 16 #include <string> 17 #include <unordered_map> 18 #include <vector> 19 20 #include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" 21 #include "tensorflow/contrib/lite/toco/model.h" 22 #include "tensorflow/contrib/lite/toco/runtime/types.h" 23 #include "tensorflow/contrib/lite/toco/tooling_util.h" 24 #include "tensorflow/core/platform/logging.h" 25 26 namespace toco { 27 28 bool UnfuseActivationFunctions::Run(Model* model, std::size_t op_index) { 29 const auto it = model->operators.begin() + op_index; 30 auto* op = it->get(); 31 32 // If a conv operation has an im2col array, yield: it should be dropped first. 33 if ((op->type == OperatorType::kConv) && (op->outputs.size() == 2)) { 34 return false; 35 } 36 37 Operator* ac_op = nullptr; 38 switch (op->fused_activation_function) { 39 case FusedActivationFunctionType::kRelu: 40 ac_op = new ReluOperator; 41 break; 42 case FusedActivationFunctionType::kRelu6: 43 ac_op = new Relu6Operator; 44 break; 45 case FusedActivationFunctionType::kRelu1: 46 ac_op = new Relu1Operator; 47 break; 48 default: 49 return false; 50 } 51 52 // At this point we know that the op has a fused activation function. At the 53 // moment that only happens with ops having a single output, may be 54 // relaxed in the future. 55 CHECK_EQ(op->outputs.size(), 1); 56 57 // Emplace unfused activation function, drop the fused one. 58 model->operators.emplace(it + 1, ac_op); 59 op->fused_activation_function = FusedActivationFunctionType::kNone; 60 61 // Wire up arrays, constructing a new intermediate array to connect the 62 // op to its new unfused activation function. 63 ac_op->outputs = op->outputs; 64 const string& tmp_array_name = 65 AvailableArrayName(*model, op->outputs[0] + "_unfused"); 66 CHECK(!model->HasArray(tmp_array_name)); 67 model->GetOrCreateArray(tmp_array_name); 68 ac_op->inputs = {tmp_array_name}; 69 op->outputs = {tmp_array_name}; 70 return true; 71 } 72 73 } // namespace toco 74