simplify_inference.cc 6.49 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */

20 21 22 23
/*!
 * Copyright (c) 2018 by Contributors
 * \file simplify_inference.cc
 */
Zhi committed
24
#include <tvm/relay/analysis.h>
25 26
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/attrs/nn.h>
27
#include <tvm/relay/transform.h>
28
#include <tvm/relay/op.h>
29 30 31 32 33 34 35 36 37 38
#include "./pattern_util.h"

namespace tvm {
namespace relay {

Expr BatchNormToInferUnpack(const Attrs attrs,
                            Expr data,
                            Expr gamma,
                            Expr beta,
                            Expr moving_mean,
39 40
                            Expr moving_var,
                            Type tdata) {
41 42
  auto ttype = tdata.as<TensorTypeNode>();
  CHECK(ttype);
43
  const auto param = attrs.as<BatchNormAttrs>();
44
  Expr epsilon = MakeConstantScalar(ttype->dtype, static_cast<float>(param->epsilon));
45 46
  Expr var_add_eps = Add(moving_var, epsilon);
  Expr sqrt_var = Sqrt(var_add_eps);
47
  Expr scale = Divide(MakeConstantScalar(ttype->dtype, 1.0f), sqrt_var);
48 49 50 51 52 53 54 55 56 57

  if (param->scale) {
    scale = Multiply(scale, gamma);
  }
  Expr neg_mean = Negative(moving_mean);
  Expr shift = Multiply(neg_mean, scale);
  if (param->center) {
    shift = Add(shift, beta);
  }

58
  auto ndim = ttype->shape.size();
59
  int axis = (param->axis < 0) ? param->axis + ndim : param->axis;
60 61
  scale = ExpandBiasToMatchAxis(scale, ndim, {axis});
  shift = ExpandBiasToMatchAxis(shift, ndim, {axis});
62 63 64 65 66 67

  Expr out = Multiply(data, scale);
  out = Add(out, shift);
  return out;
}

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
Expr LayerNormToInferUnpack(const Attrs attrs,
                            Expr data,
                            Expr gamma,
                            Expr beta,
                            Type tdata) {
  auto ttype = tdata.as<TensorTypeNode>();
  CHECK(ttype);
  const auto param = attrs.as<LayerNormAttrs>();
  CHECK(param);

  Expr epsilon = MakeConstantScalar(Float(32), static_cast<float>(param->epsilon));
  Expr mean = Mean(data, {param->axis}, true, false);
  Expr var = Variance(data, mean, {param->axis}, true, false);
  Expr denom = Sqrt(Add(var, epsilon));
  Expr out = Divide(Subtract(data, mean), denom);

  size_t ndim = ttype->shape.size();
  int axis = (param->axis < 0) ? param->axis + ndim : param->axis;
  if (param->scale) {
    out = Multiply(out, ExpandBiasToMatchAxis(gamma, ndim, {axis}));
  }
  if (param->center) {
    out = Add(out, ExpandBiasToMatchAxis(beta, ndim, {axis}));
  }
  return out;
}

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

Expr InstanceNormToInferUnpack(const Attrs attrs,
                               Expr data,
                               Expr gamma,
                               Expr beta,
                               Type tdata) {
  auto ttype = tdata.as<TensorTypeNode>();
  CHECK(ttype);
  const auto param = attrs.as<InstanceNormAttrs>();
  CHECK(param);

  int ndim = ttype->shape.size();
  int axis = (param->axis < 0) ? param->axis + ndim : param->axis;
  Array<Integer> reduced_axes;
  for (int i = 1; i < ndim; ++i) {
      if (i != axis)
          reduced_axes.push_back(i);
  }

  Expr epsilon = MakeConstantScalar(Float(32), static_cast<float>(param->epsilon));
  Expr mean = Mean(data, reduced_axes, true, false);
  Expr var = Variance(data, mean, reduced_axes, true, false);
  Expr denom = Sqrt(Add(var, epsilon));
  Expr out = Divide(Subtract(data, mean), denom);

  if (param->scale) {
    out = Multiply(out, ExpandBiasToMatchAxis(gamma, ndim, {axis}));
  }
  if (param->center) {
    out = Add(out, ExpandBiasToMatchAxis(beta, ndim, {axis}));
  }
  return out;
}


130 131 132 133 134 135 136 137 138 139 140 141 142
class InferenceSimplifier : public ExprMutator {
 public:
  Expr VisitExpr_(const TupleGetItemNode* n) final {
    static const Op& batch_norm = Op::Get("nn.batch_norm");
    static const Op& dropout = Op::Get("nn.dropout");

    Expr new_e = ExprMutator::VisitExpr_(n);
    const auto* new_n = new_e.as<TupleGetItemNode>();
    if (new_n->index != 0) {
      return new_e;
    }
    if (const auto* call = new_n->tuple.as<CallNode>()) {
      if (call->op.same_as(batch_norm)) {
143 144
        return BatchNormToInferUnpack(call->attrs, call->args[0], call->args[1], call->args[2],
                                      call->args[3], call->args[4], ty_map_.at(call->args[0]));
145 146 147 148 149 150
      } else if (call->op.same_as(dropout)) {
        return call->args[0];
      }
    }
    return new_e;
  }
151 152 153

  Expr VisitExpr_(const CallNode* n) {
    static const Op& batch_norm = Op::Get("nn.batch_norm");
154
    static const Op& instance_norm = Op::Get("nn.instance_norm");
155
    static const Op& layer_norm = Op::Get("nn.layer_norm");
156 157 158
    auto new_n = ExprMutator::VisitExpr_(n);
    if (n->op.same_as(batch_norm)) {
      ty_map_[new_n.as<CallNode>()->args[0]] = n->args[0]->checked_type();
159 160 161 162
    } else if (n->op.same_as(layer_norm)) {
      const auto* call = new_n.as<CallNode>();
      return LayerNormToInferUnpack(call->attrs, call->args[0], call->args[1],
                                    call->args[2], n->args[0]->checked_type());
163 164 165 166
    } else if (n->op.same_as(instance_norm)) {
      const auto* call = new_n.as<CallNode>();
      return InstanceNormToInferUnpack(call->attrs, call->args[0], call->args[1],
                                    call->args[2], n->args[0]->checked_type());
167 168 169 170 171 172
    }
    return new_n;
  }

 private:
  std::unordered_map<Expr, Type, NodeHash, NodeEqual> ty_map_;
173 174 175 176 177 178
};

Expr SimplifyInference(const Expr& e) {
  return InferenceSimplifier().Mutate(e);
}

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
namespace transform {

Pass SimplifyInference() {
  runtime::TypedPackedFunc<Function(Function, Module, PassContext)> pass_func =
    [=](Function f, Module m, PassContext pc) {
    return Downcast<Function>(SimplifyInference(f));
  };
  return CreateFunctionPass(pass_func, 0, "SimplifyInference",
                            {ir::StringImm::make("InferType")});
}

TVM_REGISTER_API("relay._transform.SimplifyInference")
.set_body_typed(SimplifyInference);

}  // namespace transform

195 196
}  // namespace relay
}  // namespace tvm