expr_functor.cc 8.48 KB
Newer Older
1 2 3 4 5 6 7 8 9
/*!
 *  Copyright (c) 2018 by Contributors
 * \file src/tvm/relay/expr_mutator.cc
 * \brief A wrapper around ExprFunctor which functionally updates the AST.
 *
 * ExprMutator uses memoization and self return in order to amortize
 * the cost of using functional updates.
 */
#include <tvm/relay/expr_functor.h>
10
#include "type_functor.h"
11 12 13 14

namespace tvm {
namespace relay {

15
Expr ExprMutator::VisitExpr(const Expr& expr) {
16 17 18
  auto it = this->memo_.find(expr);
  if (it != this->memo_.end()) {
    return it->second;
19
  } else {
20
    Expr new_expr = ExprFunctor::VisitExpr(expr);
21
    memo_[expr] = new_expr;
22 23 24 25
    return new_expr;
  }
}

26
Expr ExprMutator::VisitExpr_(const VarNode* op) {
27 28 29 30 31 32
  // NOTE: var will only be mutated once
  // Thanks to the memo and reused during rewriting if necessary.
  // It is safe to assume that the
  if (op->type_annotation.defined()) {
    auto type = this->VisitType(op->type_annotation);
    if (!op->type_annotation.same_as(type)) {
33
      return VarNode::make(op->vid, type);
34 35 36
    }
  }
  // default case return self.
37
  return GetRef<Expr>(op);
38 39
}

40 41
Expr ExprMutator::VisitExpr_(const ConstantNode* op) {
  return GetRef<Expr>(op);
42 43
}

44 45
Expr ExprMutator::VisitExpr_(const GlobalVarNode* op) {
  return GetRef<Expr>(op);
46 47
}

48 49
Expr ExprMutator::VisitExpr_(const OpNode* op) {
  return GetRef<Expr>(op);
50 51
}

52
Expr ExprMutator::VisitExpr_(const TupleNode* op) {
53 54 55 56 57 58 59 60 61
  tvm::Array<Expr> fields;
  bool all_fields_unchanged = true;
  for (auto field : op->fields) {
    auto new_field = this->Mutate(field);
    fields.push_back(new_field);
    all_fields_unchanged &= new_field.same_as(field);
  }

  if (all_fields_unchanged) {
62
    return GetRef<Expr>(op);
63 64 65 66 67
  } else {
    return TupleNode::make(fields);
  }
}

68
Expr ExprMutator::VisitExpr_(const FunctionNode* op) {
69
  tvm::Array<TypeVar> ty_params;
70 71 72
  bool all_ty_params_changed = true;

  for (auto ty_param : op->type_params) {
73
    TypeVar new_ty_param = Downcast<TypeVar>(VisitType(ty_param));
74 75 76 77
    ty_params.push_back(new_ty_param);
    all_ty_params_changed &= new_ty_param.same_as(ty_param);
  }

78
  tvm::Array<Var> params;
79 80
  bool all_params_changed = true;
  for (auto param : op->params) {
81
    Var new_param = Downcast<Var>(this->Mutate(param));
82 83 84 85 86 87 88
    params.push_back(new_param);
    all_params_changed &= param.same_as(new_param);
  }

  auto ret_type = this->VisitType(op->ret_type);
  auto body = this->Mutate(op->body);

89 90 91 92 93
  if (ty_params.same_as(op->type_params) &&
      params.same_as(op->params) &&
      ret_type.same_as(op->ret_type) &&
      body.same_as(op->body)) {
    return GetRef<Expr>(op);
94
  } else {
95
    return FunctionNode::make(params, body, ret_type, ty_params, op->attrs);
96 97 98
  }
}

99 100 101
Expr ExprMutator::VisitExpr_(const CallNode* call_node) {
  auto new_op = this->Mutate(call_node->op);
  bool unchanged = call_node->op.same_as(new_op);
102 103 104 105 106

  tvm::Array<Type> ty_args;
  for (auto ty_arg : call_node->type_args) {
    auto new_ty_arg = this->VisitType(ty_arg);
    ty_args.push_back(new_ty_arg);
107
    unchanged &= new_ty_arg.same_as(ty_arg);
108 109 110 111 112 113
  }

  tvm::Array<Expr> call_args;
  for (auto arg : call_node->args) {
    auto new_arg = this->Mutate(arg);
    call_args.push_back(new_arg);
114
    unchanged &= new_arg.same_as(arg);
115 116
  }

117 118
  if (unchanged) {
    return GetRef<Expr>(call_node);
119
  } else {
120
    return CallNode::make(new_op, call_args, call_node->attrs, ty_args);
121 122 123
  }
}

124
Expr ExprMutator::VisitExpr_(const LetNode* op) {
125 126 127 128
  Var var = Downcast<Var>(this->Mutate(op->var));
  auto value = this->Mutate(op->value);
  auto body = this->Mutate(op->body);

129 130 131 132
  if (var.same_as(op->var) &&
      value.same_as(op->value) &&
      body.same_as(op->body)) {
    return GetRef<Expr>(op);
133
  } else {
134
    return LetNode::make(var, value, body);
135 136 137
  }
}

138
Expr ExprMutator::VisitExpr_(const IfNode* op) {
139 140 141
  auto guard = this->Mutate(op->cond);
  auto true_b = this->Mutate(op->true_branch);
  auto false_b = this->Mutate(op->false_branch);
142 143 144 145
  if (op->cond.same_as(guard) &&
      op->true_branch.same_as(true_b) &&
      op->false_branch.same_as(false_b)) {
    return GetRef<Expr>(op);;
146 147 148 149 150
  } else {
    return IfNode::make(guard, true_b, false_b);
  }
}

151 152 153 154 155 156 157
Expr ExprMutator::VisitExpr_(const TupleGetItemNode* g) {
  auto t = this->Mutate(g->tuple);
  if (g->tuple == t) {
    return GetRef<Expr>(g);
  } else {
    return TupleGetItemNode::make(t, g->index);
  }
158
}
159

160 161
Type ExprMutator::VisitType(const Type& t) { return t; }

162
void ExprVisitor::VisitExpr(const Expr& expr) {
163 164 165 166 167 168 169 170
  auto it = visit_counter_.find(expr.get());
  if (it != visit_counter_.end()) {
    ++it->second;
  } else {
    using TParent = ExprFunctor<void(const Expr&)>;
    TParent::VisitExpr(expr);
    visit_counter_.insert({expr.get(), 1});
  }
171 172
}

173
void ExprVisitor::ExprVisitor::VisitExpr_(const VarNode* op) {
174 175 176
  if (op->type_annotation.defined()) {
    this->VisitType(op->type_annotation);
  }
177
}
178

179 180
void ExprVisitor::ExprVisitor::VisitExpr_(const GlobalVarNode* op) {
}
181

182 183
void ExprVisitor::ExprVisitor::VisitExpr_(const ConstantNode* op) {
}
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

void ExprVisitor::ExprVisitor::VisitExpr_(const TupleNode* op) {
  for (auto field : op->fields) {
    this->VisitExpr(field);
  }
}

void ExprVisitor::ExprVisitor::VisitExpr_(const FunctionNode* op) {
  for (auto param : op->params) {
    this->VisitExpr(param);
  }

  this->VisitExpr(op->body);
}

void ExprVisitor::VisitExpr_(const CallNode* op) {
  this->VisitExpr(op->op);
201

202 203 204 205 206 207 208 209 210 211 212
  for (auto ty_arg : op->type_args) {
    this->VisitType(ty_arg);
  }

  for (auto arg : op->args) {
    this->VisitExpr(arg);
  }
}

void ExprVisitor::VisitExpr_(const LetNode* op) {
  this->VisitExpr(op->value);
213
  this->VisitExpr(op->var);
214 215 216 217 218 219 220 221 222 223 224
  this->VisitExpr(op->body);
}

void ExprVisitor::VisitExpr_(const IfNode* op) {
  this->VisitExpr(op->cond);
  this->VisitExpr(op->true_branch);
  this->VisitExpr(op->false_branch);
}

void ExprVisitor::VisitExpr_(const OpNode* op) { return; }

225 226 227 228
void ExprVisitor::VisitExpr_(const TupleGetItemNode* op) {
  this->VisitExpr(op->tuple);
}

229 230
void ExprVisitor::VisitType(const Type& t) { return; }

ziheng committed
231 232 233 234
// visitor to implement apply
class ExprApplyVisit : public ExprVisitor {
 public:
  explicit ExprApplyVisit(std::function<void(const Expr&)> f) : f_(f) {}
235

ziheng committed
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
  void VisitExpr(const Expr& e) final {
    if (visited_.count(e.get()) != 0) return;
    visited_.insert(e.get());
    ExprVisitor::VisitExpr(e);
    f_(e);
  }

 private:
  std::function<void(const Expr&)> f_;
  std::unordered_set<const Node*> visited_;
};

void PostOrderVisit(const Expr& e, std::function<void(const Expr&)> fvisit) {
  ExprApplyVisit(fvisit).VisitExpr(e);
}

TVM_REGISTER_API("relay._ir_pass.post_order_visit")
.set_body([](TVMArgs args, TVMRetValue *ret) {
    PackedFunc f = args[1];
    PostOrderVisit(args[0], [f](const Expr& n) {
        f(n);
      });
  });

260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
// Implement bind.
class ExprBinder : public ExprMutator {
 public:
  explicit ExprBinder(const tvm::Map<Var, Expr>& args_map)
    : args_map_(args_map) {
  }

  Expr VisitExpr_(const LetNode* op) final {
    CHECK(!args_map_.count(op->var))
        << "Cannot bind an internel variable in let";
    return ExprMutator::VisitExpr_(op);
  }

  Expr VisitExpr_(const FunctionNode* op) final {
    for (Var param : op->params) {
      CHECK(!args_map_.count(param))
          << "Cannnot bind an internal function parameter";
    }
    return ExprMutator::VisitExpr_(op);
  }

  Expr VisitExpr_(const VarNode* op) final {
    auto id = GetRef<Var>(op);
    auto it = args_map_.find(id);
    if (it != args_map_.end()) {
      return (*it).second;
    } else {
      return id;
    }
  }

 private:
  const tvm::Map<Var, Expr>& args_map_;
};

Expr Bind(const Expr& expr, const tvm::Map<Var, Expr>& args_map) {
  if (const FunctionNode* func = expr.as<FunctionNode>()) {
    Expr new_body = ExprBinder(args_map).Mutate(func->body);
    Array<Var> new_params;
    for (Var param : func->params) {
      if (!args_map.count(param)) {
        new_params.push_back(param);
      }
    }
    if (new_body.same_as(func->body) &&
        new_params.size() == func->params.size()) {
      return expr;
    }
    return FunctionNode::make(new_params,
                              new_body,
                              func->ret_type,
                              func->type_params,
                              func->attrs);
  } else {
    return ExprBinder(args_map).Mutate(expr);
  }
}


TVM_REGISTER_API("relay._expr.Bind")
.set_body([](TVMArgs args, TVMRetValue* ret) {
    NodeRef input = args[0];
    if (input->derived_from<ExprNode>()) {
      *ret = Bind(Downcast<Expr>(input), args[1]);
    } else {
      CHECK(input->derived_from<TypeNode>());
      *ret = Bind(Downcast<Type>(input), args[1]);
    }
  });
329 330
}  // namespace relay
}  // namespace tvm