fast_math.cc 2.35 KB
Newer Older
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
/*
 * 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.
 */

/*!
 * \file fast_math.cc
 * \brief Replaces non linear activation functions with their fast but approximate counterparts.
 */
#include <tvm/relay/analysis.h>
#include <tvm/relay/expr_functor.h>
#include <tvm/relay/attrs/nn.h>
#include <tvm/relay/transform.h>
#include <tvm/relay/op.h>
#include "pattern_util.h"

namespace tvm {
namespace relay {

34
class FastMathMutator : public ExprRewriter {
35 36 37 38 39
 public:
  FastMathMutator()
      : exp_op_(Op::Get("exp")),
        tanh_op_(Op::Get("tanh")) {}

40 41 42 43 44
  Expr Rewrite_(const CallNode* pre, const Expr& post) override {
    if (pre->op == exp_op_) {
      return FastExp(post.as<CallNode>()->args[0]);
    } else if (pre->op == tanh_op_) {
      return FastTanh(post.as<CallNode>()->args[0]);
45
    }
46
    return post;
47 48 49 50 51 52 53 54 55 56 57
  }

 private:
  // Cache the following ops. They will be used in the passes repeatedly for
  // operator equivalence checking so that the registry lookup overhead can be
  // reduced.
  const Op& exp_op_;
  const Op& tanh_op_;
};

Expr FastMath(const Expr& e) {
58 59
  auto rewriter = FastMathMutator();
  return PostOrderRewrite(e, &rewriter);
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
}

namespace transform {

Pass FastMath() {
  runtime::TypedPackedFunc<Function(Function, IRModule, PassContext)> pass_func =
    [=](Function f, IRModule m, PassContext pc) {
    return Downcast<Function>(FastMath(f));
  };
  return CreateFunctionPass(pass_func, 4, "FastMath",
                            {tir::StringImmNode::make("InferType")});
}

TVM_REGISTER_GLOBAL("relay._transform.FastMath")
.set_body_typed(FastMath);

}  // namespace transform

}  // namespace relay
}  // namespace tvm