util.cc 9.21 KB
Newer Older
1 2 3 4 5
/*!
 * Copyright (c) 2018 by Contributors
 *
 * \file util.cc
 *
6
 * \brief Utility functions for Relay.
7 8 9
 */
#include <tvm/relay/pass.h>
#include <tvm/relay/expr_functor.h>
10
#include <tvm/relay/pattern_functor.h>
11
#include "../ir/type_functor.h"
12 13 14 15

namespace tvm {
namespace relay {

16 17 18 19 20 21 22 23 24 25 26 27 28
template<typename T>
struct InsertionSet {
  std::unordered_set<T, NodeHash, NodeEqual> set;
  std::vector<T> data;
  void Insert(const T& t) {
    if (set.count(t) == 0) {
      set.insert(t);
      data.push_back(t);
    }
  }
};

class TypeVarTVisitor : public TypeVisitor {
29
 public:
30 31 32
  TypeVarTVisitor(
      InsertionSet<TypeVar>* type_vars,
      InsertionSet<TypeVar>* bound_type_vars)
33
    : type_vars_(type_vars), bound_type_vars_(bound_type_vars) { }
34

35
  void VisitType_(const TypeVarNode* tp) final {
36
    TypeVar var = GetRef<TypeVar>(tp);
37
    type_vars_->Insert(var);
38 39 40 41
  }

  void VisitType_(const FuncTypeNode* f) final {
    for (auto type_param : f->type_params) {
42 43
      type_vars_->Insert(type_param);
      bound_type_vars_->Insert(type_param);
44
    }
45 46
    TypeVisitor::VisitType_(f);
  }
47

48
 private:
49 50
  InsertionSet<TypeVar>* type_vars_;
  InsertionSet<TypeVar>* bound_type_vars_;
51
};
52

53
class TypeVarEVisitor : private ExprVisitor {
54
 public:
55 56
  explicit TypeVarEVisitor(const Module& mod) : mod_(mod) {}

57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
  Array<TypeVar> CollectFree() {
    Array<TypeVar> ret;
    for (const auto& v : type_vars_.data) {
      if (bound_type_vars_.set.count(v) == 0) {
        ret.push_back(v);
      }
    }
    return ret;
  }

  Array<TypeVar> CollectBound() {
    Array<TypeVar> ret;
    for (const auto& v : bound_type_vars_.data) {
      ret.push_back(v);
    }
    return ret;
  }

  Array<TypeVar> CollectAll() {
    Array<TypeVar> ret;
    for (const auto& v : type_vars_.data) {
      ret.push_back(v);
    }
    return ret;
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
  Array<TypeVar> Free(const Expr& expr) {
    VisitExpr(expr);
    return CollectFree();
  }

  Array<TypeVar> Free(const Type& type) {
    VisitType(type);
    return CollectFree();
  }

  Array<TypeVar> Bound(const Expr& expr) {
    VisitExpr(expr);
    return CollectBound();
  }

  Array<TypeVar> Bound(const Type& type) {
    VisitType(type);
    return CollectBound();
  }

  Array<TypeVar> All(const Expr& expr) {
    VisitExpr(expr);
    return CollectAll();
  }

  Array<TypeVar> All(const Type& type) {
    VisitType(type);
    return CollectAll();
111 112
  }

113
  void VisitExpr_(const FunctionNode* f) final {
114
    for (const auto& tp : f->type_params) {
115 116
      type_vars_.Insert(tp);
      bound_type_vars_.Insert(tp);
117
    }
118
    ExprVisitor::VisitExpr_(f);
119 120
  }

121 122 123 124 125 126 127 128 129 130
  void VisitExpr_(const ConstructorNode* cn) final {
    // for constructors, type vars will be bound in the module
    auto data = mod_->LookupDef(cn->belong_to);
    for (const auto& tv : data->type_vars) {
      type_vars_.Insert(tv);
      bound_type_vars_.Insert(tv);
    }
    ExprVisitor::VisitExpr_(cn);
  }

131
  void VisitType(const Type& t) final {
132
    TypeVarTVisitor(&type_vars_, &bound_type_vars_)
133
        .VisitType(t);
134 135
  }

136
 private:
137 138
  InsertionSet<TypeVar> type_vars_;
  InsertionSet<TypeVar> bound_type_vars_;
139
  const Module& mod_;
140 141
};

142
class VarVisitor : protected ExprVisitor, protected PatternVisitor {
143
 public:
144
  Array<Var> Free(const Expr& expr) {
145
    this->VisitExpr(expr);
146 147 148 149 150 151 152
    Array<Var> ret;
    for (const auto& v : vars_.data) {
      if (bound_vars_.set.count(v) == 0) {
        ret.push_back(v);
      }
    }
    return ret;
153 154
  }

155 156 157 158 159
  Array<Var> Bound(const Expr& expr) {
    this->VisitExpr(expr);
    Array<Var> ret;
    for (const auto& v : bound_vars_.data) {
      ret.push_back(v);
160
    }
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
    return ret;
  }

  Array<Var> All(const Expr& expr) {
    this->VisitExpr(expr);
    Array<Var> ret;
    for (const auto& v : vars_.data) {
      ret.push_back(v);
    }
    return ret;
  }

  void MarkBounded(const Var& v) {
    bound_vars_.Insert(v);
    vars_.Insert(v);
  }

  void VisitExpr_(const VarNode* var) final {
    vars_.Insert(GetRef<Var>(var));
180
  }
181 182 183

  void VisitExpr_(const FunctionNode* op) final {
    for (const auto& param : op->params) {
184
      MarkBounded(param);
185 186 187 188 189
    }
    VisitExpr(op->body);
  }

  void VisitExpr_(const LetNode* op) final {
190
    MarkBounded(op->var);
191 192 193 194
    VisitExpr(op->value);
    VisitExpr(op->body);
  }

195 196 197 198 199 200 201 202
  void VisitPattern(const Pattern& p) final {
    PatternVisitor::VisitPattern(p);
  }

  void VisitPattern_(const PatternVarNode* op) final {
    MarkBounded(op->var);
  }

203
 private:
204 205
  InsertionSet<Var> vars_;
  InsertionSet<Var> bound_vars_;
206 207
};

208 209
tvm::Array<TypeVar> FreeTypeVars(const Expr& expr, const Module& mod) {
  return TypeVarEVisitor(mod).Free(expr);
210 211
}

212 213
tvm::Array<TypeVar> FreeTypeVars(const Type& type, const Module& mod) {
  return TypeVarEVisitor(mod).Free(type);
214 215
}

216 217
tvm::Array<TypeVar> BoundTypeVars(const Expr& expr, const Module& mod) {
  return TypeVarEVisitor(mod).Bound(expr);
218 219
}

220 221
tvm::Array<TypeVar> BoundTypeVars(const Type& type, const Module& mod) {
  return TypeVarEVisitor(mod).Bound(type);
222 223
}

224 225
tvm::Array<TypeVar> AllTypeVars(const Expr& expr, const Module& mod) {
  return TypeVarEVisitor(mod).All(expr);
226 227
}

228 229
tvm::Array<TypeVar> AllTypeVars(const Type& type, const Module& mod) {
  return TypeVarEVisitor(mod).All(type);
230 231
}

232
tvm::Array<Var> FreeVars(const Expr& expr) {
233 234 235 236 237 238 239 240 241
  return VarVisitor().Free(expr);
}

tvm::Array<Var> BoundVars(const Expr& expr) {
  return VarVisitor().Bound(expr);
}

tvm::Array<Var> AllVars(const Expr& expr) {
  return VarVisitor().All(expr);
242 243 244 245
}

TVM_REGISTER_API("relay._ir_pass.free_vars")
.set_body([](TVMArgs args, TVMRetValue* ret) {
246
    *ret = FreeVars(args[0]);
247 248
  });

249 250 251 252 253 254 255 256 257 258
TVM_REGISTER_API("relay._ir_pass.bound_vars")
  .set_body([](TVMArgs args, TVMRetValue* ret) {
      *ret = BoundVars(args[0]);
    });

TVM_REGISTER_API("relay._ir_pass.all_vars")
  .set_body([](TVMArgs args, TVMRetValue* ret) {
      *ret = AllVars(args[0]);
    });

259 260 261
TVM_REGISTER_API("relay._ir_pass.free_type_vars")
.set_body([](TVMArgs args, TVMRetValue* ret) {
    NodeRef x = args[0];
262
    Module mod = args[1];
263
    if (x.as_derived<TypeNode>()) {
264
      *ret = FreeTypeVars(Downcast<Type>(x), mod);
265
    } else {
266
      *ret = FreeTypeVars(Downcast<Expr>(x), mod);
267 268 269
    }
  });

270 271 272
TVM_REGISTER_API("relay._ir_pass.bound_type_vars")
  .set_body([](TVMArgs args, TVMRetValue* ret) {
      NodeRef x = args[0];
273
      Module mod = args[1];
274
      if (x.as_derived<TypeNode>()) {
275
        *ret = BoundTypeVars(Downcast<Type>(x), mod);
276
      } else {
277
        *ret = BoundTypeVars(Downcast<Expr>(x), mod);
278 279 280 281 282 283
      }
    });

TVM_REGISTER_API("relay._ir_pass.all_type_vars")
  .set_body([](TVMArgs args, TVMRetValue* ret) {
      NodeRef x = args[0];
284
      Module mod = args[1];
285
      if (x.as_derived<TypeNode>()) {
286
        *ret = AllTypeVars(Downcast<Type>(x), mod);
287
      } else {
288
        *ret = AllTypeVars(Downcast<Expr>(x), mod);
289 290 291
      }
    });

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
/*!
 * \brief Get reference counter of each internal ExprNode in body.
 * \param body The body expression.
 * \return The reference count mapping.
 */
std::unordered_map<const Node*, size_t>
GetExprRefCount(const Expr& body) {
  class ExprRefCounter : private ExprVisitor {
   public:
    std::unordered_map<const Node*, size_t>
    Get(const Expr& body) {
      this->VisitExpr(body);
      return std::move(this->visit_counter_);
    }
  };
  return ExprRefCounter().Get(body);
}

310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
template <typename T>
bool IsNDArrayAllGreaterEqual(const runtime::NDArray& tensor, T value) {
  CHECK_EQ(tensor->ctx.device_type, kDLCPU);
  CHECK(tensor->strides == nullptr);
  CHECK_EQ(tensor->byte_offset, 0);
  const T* data = static_cast<const T*>(tensor->data);
  int64_t num_elems = 1;
  for (int i = 0; i < tensor->ndim; ++i) {
    num_elems *= tensor->shape[i];
  }

  for (int64_t i = 0; i < num_elems; i++) {
    if (*data < value) {
      return false;
    }
    data++;
  }
  return true;
}

bool IsAllPositiveConstant(const Expr& expr) {
  // peel through a few common transform ops.
  static const auto& expand_dims = Op::Get("expand_dims");
  static const auto& reshape = Op::Get("reshape");
  static const auto& transpose = Op::Get("transpose");
  static const auto& squeeze = Op::Get("squeeze");

  if (const auto* constant = expr.as<ConstantNode>()) {
    const auto& tensor = constant->data;
    const auto& dtype = tensor->dtype;
    if (dtype.lanes != 1) {
      return false;
    } else if (dtype.code == kDLFloat && dtype.bits == 32) {
      return IsNDArrayAllGreaterEqual<float>(tensor, 0);
    } else if (dtype.code == kDLFloat && dtype.bits == 64) {
      return IsNDArrayAllGreaterEqual<double>(tensor, 0);
    } else if (dtype.code == kDLInt && dtype.bits == 8) {
      return IsNDArrayAllGreaterEqual<int8_t>(tensor, 0);
    } else if (dtype.code == kDLInt && dtype.bits == 32) {
      return IsNDArrayAllGreaterEqual<int32_t>(tensor, 0);
    } else if (dtype.code == kDLUInt && dtype.bits == 8) {
      return IsNDArrayAllGreaterEqual<uint8_t>(tensor, 0);
    } else if (dtype.code == kDLUInt && dtype.bits == 32) {
      return IsNDArrayAllGreaterEqual<uint32_t>(tensor, 0);
    } else {
      return false;
    }
  } else if (const auto* op = expr.as<CallNode>()) {
    // tail recursion.
    if (op->op.same_as(expand_dims) ||
        op->op.same_as(reshape) ||
        op->op.same_as(transpose) ||
        op->op.same_as(squeeze)) {
      return IsAllPositiveConstant(op->args[0]);
    } else {
      return false;
    }
  } else {
    return false;
  }
}

372 373
}  // namespace relay
}  // namespace tvm