operation.cc 6.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* Copyright (c) 2019 PaddlePaddle 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 "paddle/fluid/framework/ir/fusion_group/operation.h"
16
#include "paddle/fluid/framework/operator.h"
17 18 19 20 21 22 23 24 25 26 27

namespace paddle {
namespace framework {
namespace ir {
namespace fusion_group {

OperationMap* OperationMap::map = nullptr;

OperationMap::OperationMap() {
  InsertUnaryElementwiseOperations();
  InsertBinaryElementwiseOperations();
28
  InsertMultivariateElementwiseOperations();
29 30
}

31
std::unordered_set<std::string> OperationMap::Find(int type) {
32 33
  std::unordered_set<std::string> res;
  for (auto& t : operations_) {
34
    if (t.second.type == type) {
35 36 37 38 39 40 41
      res.insert(t.first);
    }
  }
  return res;
}

void OperationMap::Insert(int type, int num_operands, std::string op_type,
42 43 44 45
                          std::string expr, std::vector<std::string> grad_exprs,
                          std::vector<std::string> input_names,
                          std::vector<std::string> output_names) {
  Operation op(type, num_operands, op_type, {expr}, input_names, output_names);
46 47 48 49 50
  PADDLE_ENFORCE_EQ(op.IsValid(), true,
                    platform::errors::InvalidArgument(
                        "Operation %s is invalid. Please set correct "
                        "expression for forward calculation.",
                        op_type));
51 52 53 54
  operations_[op_type] = op;

  if (grad_exprs.size() > 0U) {
    std::string grad_op_type = op_type + "_grad";
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
    // grad_inputs = inputs + outputs + grad of outputs
    std::vector<std::string> grad_input_names = input_names;
    for (auto name : output_names) {
      grad_input_names.push_back(name);
    }
    for (auto name : output_names) {
      grad_input_names.push_back(GradVarName(name));
    }
    // grad_output = grad of inputs
    std::vector<std::string> grad_output_names;
    for (auto name : input_names) {
      grad_output_names.push_back(GradVarName(name));
    }
    Operation grad_op(type, num_operands, grad_op_type, grad_exprs,
                      grad_input_names, grad_output_names);
70 71 72 73 74
    PADDLE_ENFORCE_EQ(grad_op.IsValid(), true,
                      platform::errors::InvalidArgument(
                          "Operation %s is invalid. Please set correct "
                          "expression for backward calculation.",
                          grad_op_type));
75 76 77 78 79 80 81 82 83
    operations_[grad_op_type] = grad_op;
  }
}

void OperationMap::InsertUnaryElementwiseOperations() {
  // For unary elementwise operations:
  //  ${0} - x
  //  ${1} - out
  //  ${2} - dout
84 85 86 87 88 89
  auto insert_handler = [&](std::string op_type, std::string expr,
                            std::vector<std::string> grad_exprs) {
    int type = 0;
    int num_oprands = 1;
    Insert(type, num_oprands, op_type, expr, grad_exprs, {"X"}, {"Out"});
  };
90 91 92

  // relu:
  //  out = f(x) = x > 0 ? x : 0
93
  //  dx = dout * (out > 0 ? 1 : 0)
94
  insert_handler("relu", "${0} > 0 ? ${0} : 0", {"${1} > 0 ? ${2} : 0"});
95 96 97
  // sigmoid:
  //  out = f(x) = 1.0 / (1.0 + exp(-x))
  //  dx = dout * out * (1 - out)
98 99
  insert_handler("sigmoid", "1.0 / (1.0 + real_exp(- ${0}))",
                 {"${2} * ${1} * (1.0 - ${1})"});
100 101 102
  // tanh:
  //  out = f(x) = 2.0 / (1.0 + exp(-2.0 * x)) - 1.0;
  //  dx = dout * (1 - out * out)
103 104
  insert_handler("tanh", "2.0 / (1.0 + real_exp(-2.0 * ${0})) - 1.0",
                 {"${2} * (1.0 - ${1} * ${1})"});
105 106 107 108 109 110 111

  // cast
  // out = static_cast<T>(d)
  // dx = static_cast<T>(d_out)
  // TODO(wangchaochaohu): This is not the compelete definition of
  // cast Op, We need refine it later.
  insert_handler("cast", "${0}", {"${0}"});
112 113 114 115 116 117 118 119
}

void OperationMap::InsertBinaryElementwiseOperations() {
  // For binary elementwise oprations:
  //  ${0} - x
  //  ${1} - y
  //  ${2} - out
  //  ${3} - dout
120 121 122 123 124 125
  auto insert_handler = [&](std::string op_type, std::string expr,
                            std::vector<std::string> grad_exprs) {
    int type = 0;
    int num_oprands = 2;
    Insert(type, num_oprands, op_type, expr, grad_exprs, {"X", "Y"}, {"Out"});
  };
126 127 128 129 130

  // elementwise_add:
  //  out = x + y
  //  dx = dout * 1
  //  dy = dout * 1
131
  insert_handler("elementwise_add", "${0} + ${1}", {"${3}", "${3}"});
132 133 134 135
  // elementwise_sub:
  //  out = x - y
  //  dx = dout * 1
  //  dy = dout * (-1)
136
  insert_handler("elementwise_sub", "${0} - ${1}", {"${3}", "- ${3}"});
137 138 139 140
  // elementwise_mul:
  //  out = x * y
  //  dx = dout * y
  //  dy = dout * x
141 142
  insert_handler("elementwise_mul", "${0} * ${1}",
                 {"${3} * ${1}", "${3} * ${0}"});
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  // elementwise_div:
  //  out = x / y
  //  dx = dout / y
  //  dy = - dout * out / y
  insert_handler("elementwise_div", "${0} / ${1}",
                 {"${3} / ${1}", "- ${3} * ${2} / ${1}"});
  // elementwise_min:
  //  out = x < y ? x : y
  //  dx = dout * (x < y)
  //  dy = dout * (x >= y)
  insert_handler("elementwise_min", "${0} < ${1} ? ${0} : ${1}",
                 {"${3} * (${0} < ${1})", "${3} * (${0} >= ${1})"});
  // elementwise_max:
  //  out = x > y ? x : y
  //  dx = dout * (x > y)
  //  dy = dout * (x <= y)
  insert_handler("elementwise_max", "${0} > ${1} ? ${0} : ${1}",
                 {"${3} * (${0} > ${1})", "${3} * (${0} <= ${1})"});
161 162
}

163 164 165 166 167 168 169 170
void OperationMap::InsertMultivariateElementwiseOperations() {
  auto insert_handler = [&](std::string op_type, std::string expr,
                            std::vector<std::string> grad_exprs) {
    int type = 0;
    int num_oprands = -1;
    Insert(type, num_oprands, op_type, expr, grad_exprs, {"X"}, {"Out"});
  };

171 172 173
  // here [] represent the number of input is positive(>=0).
  // if input list size of Sum Op is 3, It will expand as
  // ${0} + ${1} + ${2}
174 175 176
  insert_handler("sum", "${0}[ + ${?}]", {});
}

177 178 179 180
}  // namespace fusion_group
}  // namespace ir
}  // namespace framework
}  // namespace paddle