aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/lite/toco/graph_transformations/identify_prelu.cc
blob: b90a156a0dcfcd77c3e2b47bb0d77e246f2fc625 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h"
#include "tensorflow/contrib/lite/toco/model.h"
#include "tensorflow/contrib/lite/toco/tooling_util.h"
#include "tensorflow/core/platform/logging.h"

// This transformation rule tries to identify the PRelu structure generated by
// Keras, and convert it to a single op.
//
// The formula of PReLU is:
// f(x) = alpha * x for x < 0, f(x) = x for x >= 0.
//
// `x` is the input, and `alpha` is a trainable tensor which can be broadcasted
// to the shape of `x`.
//
// There's no native PRelu op in TensorFlow, so Keras generates the following
// structure which does the equivalent calculation:
// f(x) = Relu(x) + (-alpha * Relu(-x))
//
// Practically, alpha is always a constant in the inference graph, and Toco have
// other graph transformations which fold the activation functions to other ops.
// Therefore, we're looking for the structure:
//
// f(x) = Relu(x) + (negative_alpha * Neg(x, activation=Relu))

namespace toco {

bool IdentifyPRelu::Run(Model* model, std::size_t op_index) {
  const auto add_op_it = model->operators.begin() + op_index;
  const auto* add_op = add_op_it->get();
  if (add_op == nullptr || add_op->type != OperatorType::kAdd ||
      add_op->inputs.size() != 2 ||
      add_op->fused_activation_function != FusedActivationFunctionType::kNone) {
    return false;
  }

  const auto* relu_input_op = GetOpWithOutput(*model, add_op->inputs[0]);
  if (relu_input_op == nullptr || relu_input_op->type != OperatorType::kRelu ||
      relu_input_op->inputs.size() != 1 ||
      relu_input_op->fused_activation_function !=
          FusedActivationFunctionType::kNone) {
    return false;
  }

  // TODO(ycling): Both Add and Mul are commutative. Support the case where
  // the position of operands are exchanged.
  const auto* mul_op = GetOpWithOutput(*model, add_op->inputs[1]);
  if (mul_op == nullptr || mul_op->type != OperatorType::kMul ||
      mul_op->inputs.size() != 2 ||
      mul_op->fused_activation_function != FusedActivationFunctionType::kNone) {
    return false;
  }

  const auto neg_alpha_tensor_name = mul_op->inputs[0];

  const auto* relu_neg_input_op = GetOpWithOutput(*model, mul_op->inputs[1]);

  if (relu_neg_input_op == nullptr ||
      relu_neg_input_op->inputs.size() != 1) {
    return false;
  }

  const Operator* final_input_op;
  if (relu_neg_input_op->type == OperatorType::kNeg &&
      relu_neg_input_op->fused_activation_function ==
          FusedActivationFunctionType::kRelu) {
    // This detects a Neg op with fused Relu activation function.
    final_input_op = relu_neg_input_op;
  } else {
    // This detects a Neg op followed by a separated Relu op.
    const auto* neg_input_op =
        GetOpWithOutput(*model, relu_neg_input_op->inputs[0]);
    if (neg_input_op == nullptr || neg_input_op->inputs.size() != 1 ||
        relu_neg_input_op->type != OperatorType::kRelu ||
        relu_neg_input_op->fused_activation_function !=
            FusedActivationFunctionType::kNone) {
      return false;
    }
    final_input_op = neg_input_op;
  }

  if (relu_input_op->inputs[0] != final_input_op->inputs[0]) {
    return false;
  }

  const auto input_tensor_name = relu_input_op->inputs[0];
  const auto output_tensor_name = add_op->outputs[0];

  // Construct a tensor for positive alpha (double negative).
  const auto alpha_tensor_name =
      AvailableArrayName(*model, neg_alpha_tensor_name + "_neg");
  model->GetOrCreateArray(alpha_tensor_name);

  auto* neg_neg_alpha_op = new NegOperator;
  neg_neg_alpha_op->inputs = {neg_alpha_tensor_name};
  neg_neg_alpha_op->outputs = {alpha_tensor_name};
  model->operators.emplace(add_op_it, neg_neg_alpha_op);

  auto* prelu_op = new PReluOperator;
  prelu_op->inputs = {input_tensor_name, alpha_tensor_name};
  prelu_op->outputs = {output_tensor_name};
  model->operators.emplace(add_op_it, prelu_op);
  AddMessageF("Creating %s replacing equivalent subgraph", LogName(*prelu_op));

  DeleteArrayIfUsedOnce(neg_alpha_tensor_name, model);
  DeleteArrayIfUsedOnce(add_op->inputs[0], model);
  DeleteArrayIfUsedOnce(add_op->inputs[1], model);
  DeleteArrayIfUsedOnce(mul_op->inputs[1], model);
  // Remove the existing Add op that outputs the final result. If the other
  // intermediate tensors aren't used by other ops, those will be removed by
  // other graph transformation rules.
  model->operators.erase(FindOp(*model, add_op));
  return true;
}

}  // namespace toco