hash.cc 13.2 KB
Newer Older
1 2 3 4 5 6 7 8
/*
 * 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
9
 *
10
 *   http://www.apache.org/licenses/LICENSE-2.0
11
 *
12 13 14 15 16 17 18 19
 * 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 24 25 26
/*!
 *  Copyright (c) 2018 by Contributors
 * \file src/tvm/relay/ir/hash.cc
 * \brief Hash functions for Relay types and expressions.
 */
#include <tvm/ir_pass.h>
#include <tvm/relay/expr_functor.h>
27
#include <tvm/relay/pattern_functor.h>
28
#include <tvm/runtime/ndarray.h>
Zhi committed
29
#include <tvm/relay/analysis.h>
30 31 32 33 34 35 36 37 38
#include <tvm/attrs.h>
#include "type_functor.h"
#include "../../lang/attr_functor.h"

namespace tvm {
namespace relay {

// Hash handler for Relay.
class RelayHashHandler:
39 40
    public AttrsHashHandler,
    public TypeFunctor<size_t(const Type&)>,
41 42
    public ExprFunctor<size_t(const Expr&)>,
    public PatternFunctor<size_t(const Pattern&)> {
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 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 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
 public:
  explicit RelayHashHandler() {}

  /*!
   * Compute hash of a node.
   * \param ref The node to hash.
   * \return the hash value.
   */
  size_t Hash(const NodeRef& ref) {
    if (!ref.defined()) return ref.hash();

    if (ref->derived_from<TypeNode>()) {
      return TypeHash(Downcast<Type>(ref));
    }
    if (ref->derived_from<ExprNode>()) {
      return ExprHash(Downcast<Expr>(ref));
    }
    return AttrHash(ref);
  }

  /*!
   * Compute hash of the attributes.
   * \param ref The attributes.
   * \return the hash value
   */
  size_t AttrHash(const NodeRef& ref) {
    if (!ref.defined()) { return ref.hash(); }
    return AttrsHashHandler::Hash(ref);
  }
  /*!
   * Compute hash of a Relay type.
   * \param ref The type to hash.
   * \param rhs The right hand operand.
   * \return the hash value.
   */
  size_t TypeHash(const Type& type) {
    if (!type.defined()) { return type.hash(); }
    auto found = hash_map_.find(type);
    if (found != hash_map_.end()) {
      return found->second;
    } else {
      auto hash = this->VisitType(type);
      hash_map_.insert({type, hash});
      return hash;
    }
  }
  /*!
   * Compute the hash of an expression.
   *
   * \note We run graph structural equality checking when comparing two Exprs.
   *   This means that AlphaEqualHandler can only be used once for each pair.
   *   The equality checker checks data-flow equvalence of the Expr DAG.
   *   This function also runs faster as it memomizes equal_map.
   *
   * \param expr The expression to hash.
   * \return the hash value.
   */
  size_t ExprHash(const Expr& expr) {
    if (!expr.defined()) return expr.hash();
    auto found = hash_map_.find(expr);
    if (found != hash_map_.end()) {
      return found->second;
    } else {
      auto hash = this->VisitExpr(expr);
      hash_map_.insert({expr, hash});
      return hash;
    }
  }

 protected:
  /*!
   * \brief Hash a DataType.
   * \param dtype The dtype to hash.
   * \return the hash value.
   */
  size_t DataTypeHash(const DataType& dtype) {
    return ::tvm::AttrsHash()(dtype);
  }

  using AttrsHashHandler::VisitAttr_;
  size_t VisitAttr_(const Variable* var) final {
124
    size_t hash = std::hash<std::string>()(Variable::_type_key);
125 126 127 128 129 130 131 132 133
    auto it = hash_map_.find(GetRef<VarExpr>(var));
    if (it != hash_map_.end()) {
      return it->second;
    }
    return Combine(hash, std::hash<std::string>()(var->name_hint));
  }

  // Type hashing
  size_t VisitType_(const TensorTypeNode* tensor_type) final {
134
    size_t hash = std::hash<std::string>()(TensorTypeNode::_type_key);
135 136 137 138 139 140
    hash = Combine(hash, DataTypeHash(tensor_type->dtype));
    hash = Combine(hash, Hash(tensor_type->shape));
    return hash;
  }

  size_t VisitType_(const IncompleteTypeNode* incomplete) final {
141
    size_t hash = std::hash<std::string>()(IncompleteTypeNode::_type_key);
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    return Combine(hash, std::hash<int>()(incomplete->kind));
  }

  size_t VisitType_(const TypeVarNode* tyvar) final {
    /*
      TypeVar/Var/Variable have two locations where they are hashed:

        The declaration site of a function, let, or function type.
        The first occurence in the term.

      We will only reach this code if the TypeVar itself is unbound, we assign
      a free variable index to it, meaning this hashing function implements
      structural equality for both open (i.e graph equality) and closed terms
      (i.e alpha_equality).
    */
    return BindVar(GetRef<TypeVar>(tyvar));
  }

  size_t VisitType_(const FuncTypeNode* func_type) final {
161
    size_t hash = std::hash<std::string>()(FuncTypeNode::_type_key);
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

    for (auto type_param : func_type->type_params) {
      hash = Combine(hash, BindVar(type_param));
    }

    for (auto arg : func_type->arg_types) {
      hash = Combine(hash, TypeHash(arg));
    }

    hash = Combine(hash, TypeHash(func_type->ret_type));
    for (auto cs : func_type->type_constraints) {
      hash = Combine(hash, TypeHash(cs));
    }

    return hash;
  }

  size_t VisitType_(const TypeRelationNode* type_rel) final {
180
    size_t hash = std::hash<std::string>()(TypeRelationNode::_type_key);
181 182 183 184 185 186 187 188 189 190 191
    hash = Combine(hash, std::hash<std::string>()(type_rel->func->name));
    hash = Combine(hash, AttrHash(type_rel->attrs));

    for (auto arg : type_rel->args) {
      hash = Combine(hash, TypeHash(arg));
    }

    return hash;
  }

  size_t VisitType_(const TupleTypeNode* tuple_type) final {
192
    size_t hash = std::hash<std::string>()(TupleTypeNode::_type_key);
193 194 195 196 197 198
    for (size_t i = 0; i < tuple_type->fields.size(); i++) {
      hash = Combine(hash, TypeHash(tuple_type->fields[i]));
    }
    return hash;
  }

199 200 201 202 203 204
  size_t VisitType_(const RefTypeNode* rtn) final {
    size_t hash = std::hash<std::string>()(RefTypeNode::_type_key);
    hash = Combine(hash, TypeHash(rtn->value));
    return hash;
  }

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  // Expr hashing.
  size_t NDArrayHash(const runtime::NDArray& array) {
    size_t hash = std::hash<uint8_t>()(array->dtype.code);
    hash = Combine(hash, std::hash<uint8_t>()(array->dtype.bits));
    hash = Combine(hash, std::hash<uint16_t>()(array->dtype.lanes));
    CHECK_EQ(array->ctx.device_type, kDLCPU) << "can only compare CPU tensor";
    size_t data_size = runtime::GetDataSize(*array.operator->());
    uint8_t * data = reinterpret_cast<uint8_t*>(array->data);
    for (size_t i = 0; i < data_size; i++) {
      hash = Combine(hash, std::hash<uint8_t>()(data[i]));
    }
    return hash;
  }

  size_t BindVar(const NodeRef& var) {
    size_t hash = std::hash<int>()(var_counter++);
    CHECK_EQ(hash_map_.count(var), 0);
222 223 224
    if (auto var_node = var.as<VarNode>()) {
      hash = Combine(hash, TypeHash(var_node->type_annotation));
    }
225 226 227
    hash_map_[var] = hash;

    const auto* ty_param = var.as<TypeVarNode>();
228
    if (ty_param && ty_param->kind == Kind::kShapeVar) {
229 230 231 232 233 234
      hash_map_[ty_param->var] = hash;
    }
    return hash;
  }

  size_t VisitExpr_(const VarNode* var) final {
235 236
    // hash free variable
    size_t name_hash = std::hash<const Node*>()(var->vid.get());
237 238 239 240 241 242 243 244
    return Combine(name_hash, TypeHash(var->type_annotation));
  }

  size_t VisitExpr_(const GlobalVarNode* global) final {
    return std::hash<std::string>()(global->name_hint);
  }

  size_t VisitExpr_(const TupleNode* tuple) final {
245
    size_t hash = std::hash<std::string>()(TupleNode::_type_key);
246 247 248 249 250 251 252
    for (size_t i = 0; i < tuple->fields.size(); i++) {
      hash = Combine(hash, ExprHash(tuple->fields[i]));
    }
    return hash;
  }

  size_t VisitExpr_(const FunctionNode* func) final {
253
    size_t hash = std::hash<std::string>()(FunctionNode::_type_key);
254 255 256 257 258 259 260 261 262
    for (auto type_param : func->type_params) {
      hash = Combine(hash, BindVar(type_param));
    }

    for (auto param : func->params) {
      hash = Combine(hash, BindVar(param));
    }

    hash = Combine(hash, TypeHash(func->ret_type));
263
    hash = Combine(hash, ExprHash(func->body));
264 265 266 267 268

    return hash;
  }

  size_t VisitExpr_(const CallNode* call) final {
269
    size_t hash = std::hash<std::string>()(CallNode::_type_key);
270 271 272 273 274 275
    hash = Combine(hash, ExprHash(call->op));

    for (auto arg : call->args) {
      hash = Combine(hash, ExprHash(arg));
    }

276
    for (auto t : call->type_args) {
277
      CHECK(t.defined());
278 279 280
      hash = Combine(hash, TypeHash(t));
    }

281 282 283 284 285 286
    hash = Combine(hash, AttrHash(call->attrs));

    return hash;
  }

  size_t VisitExpr_(const LetNode* let) final {
287
    size_t hash = std::hash<std::string>()(LetNode::_type_key);
288 289 290 291 292 293 294
    hash = Combine(hash, BindVar(let->var));
    hash = Combine(hash, ExprHash(let->value));
    hash = Combine(hash, ExprHash(let->body));
    return hash;
  }

  size_t VisitExpr_(const IfNode* ite) final {
295 296
    size_t key = std::hash<std::string>()(IfNode::_type_key);
    size_t hash = key;
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    hash = Combine(hash, ExprHash(ite->cond));
    hash = Combine(hash, ExprHash(ite->true_branch));
    hash = Combine(hash, ExprHash(ite->false_branch));
    return hash;
  }

  size_t VisitExpr_(const OpNode* op) final {
    return GetRef<Op>(op).hash();
  }

  size_t VisitExpr_(const ConstantNode* rconst) final {
    return NDArrayHash(rconst->data);
  }

  size_t VisitExpr_(const TupleGetItemNode* get_item) final {
312
    size_t hash = std::hash<std::string>()(TupleGetItemNode::_type_key);
313 314 315 316 317
    hash = Combine(hash, ExprHash(get_item->tuple));
    hash = Combine(hash, std::hash<int>()(get_item->index));
    return hash;
  }

318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
  size_t VisitExpr_(const RefCreateNode* rn) final {
    size_t hash = std::hash<std::string>()(RefCreateNode::_type_key);
    hash = Combine(hash, ExprHash(rn->value));
    return hash;
  }

  size_t VisitExpr_(const RefReadNode* rn) final {
    size_t hash = std::hash<std::string>()(RefReadNode::_type_key);
    hash = Combine(hash, ExprHash(rn->ref));
    return hash;
  }

  size_t VisitExpr_(const RefWriteNode* rn) final {
    size_t hash = std::hash<std::string>()(RefWriteNode::_type_key);
    hash = Combine(hash, ExprHash(rn->ref));
    hash = Combine(hash, ExprHash(rn->value));
    return hash;
  }
336 337 338 339 340 341 342 343

  size_t VisitExpr_(const MatchNode* mn) final {
    size_t hash = std::hash<std::string>()(MatchNode::_type_key);
    hash = Combine(hash, ExprHash(mn->data));
    for (const auto& c : mn->clauses) {
      hash = Combine(hash, PatternHash(c->lhs));
      hash = Combine(hash, ExprHash(c->rhs));
    }
344
    hash = Combine(hash, std::hash<bool>()(mn->complete));
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 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
    return hash;
  }

  size_t VisitExpr_(const ConstructorNode* cn) final {
    size_t hash = std::hash<std::string>()(ConstructorNode::_type_key);
    hash = Combine(hash, std::hash<std::string>()(cn->name_hint));
    return hash;
  }

  size_t VisitType_(const TypeCallNode* tcn) final {
    size_t hash = std::hash<std::string>()(TypeCallNode::_type_key);
    hash = Combine(hash, TypeHash(tcn->func));
    for (const auto& t : tcn->args) {
      hash = Combine(hash, TypeHash(t));
    }
    return hash;
  }

  size_t VisitType_(const TypeDataNode* tdn) final {
    size_t hash = std::hash<std::string>()(TypeDataNode::_type_key);
    hash = Combine(hash, TypeHash(tdn->header));
    for (const auto& tv : tdn->type_vars) {
      hash = Combine(hash, TypeHash(tv));
    }
    for (const auto& cn : tdn->constructors) {
      hash = Combine(hash, ExprHash(cn));
    }
    return hash;
  }

  size_t VisitType_(const GlobalTypeVarNode* tvn) final {
    return BindVar(GetRef<GlobalTypeVar>(tvn));
  }

  size_t PatternHash(const Pattern& p) {
    return VisitPattern(p);
  }

  size_t VisitPattern_(const PatternConstructorNode* pcn) final {
    size_t hash = std::hash<std::string>()(PatternConstructorNode::_type_key);
    hash = Combine(hash, ExprHash(pcn->constructor));
    for (const auto& p : pcn->patterns) {
      hash = Combine(hash, PatternHash(p));
    }
    return hash;
  }

392 393 394 395 396 397 398 399
  size_t VisitPattern_(const PatternTupleNode* ptn) final {
    size_t hash = std::hash<std::string>()(PatternTupleNode::_type_key);
    for (const auto& p : ptn->patterns) {
      hash = Combine(hash, PatternHash(p));
    }
    return hash;
  }

400 401 402 403 404 405 406 407 408 409
  size_t VisitPattern_(const PatternVarNode* pvn) final {
    size_t hash = std::hash<std::string>()(PatternVarNode::_type_key);
    hash = Combine(hash, BindVar(pvn->var));
    return hash;
  }

  size_t VisitPattern_(const PatternWildcardNode* pwn) final {
    size_t hash = std::hash<std::string>()(PatternWildcardNode::_type_key);
    return hash;
  }
410 411 412 413 414 415
 private:
  // renaming of NodeRef to indicate two nodes equals to each other
  std::unordered_map<NodeRef, size_t, NodeHash, NodeEqual> hash_map_;
  int var_counter = 0;
};

416
size_t StructuralHash::operator()(const Type& type) const {
417 418 419
  return RelayHashHandler().TypeHash(type);
}

420
size_t StructuralHash::operator()(const Expr& expr) const {
421 422 423
  return RelayHashHandler().ExprHash(expr);
}

Zhi committed
424
TVM_REGISTER_API("relay._analysis._expr_hash")
425 426 427
.set_body_typed<int64_t(NodeRef)>([](NodeRef ref) {
  return static_cast<int64_t>(RelayHashHandler().Hash(ref));
});
428

Zhi committed
429
TVM_REGISTER_API("relay._analysis._type_hash")
430 431 432
.set_body_typed<int64_t(Type)>([](Type type) {
  return static_cast<int64_t>(RelayHashHandler().TypeHash(type));
});
433 434 435

}  // namespace relay
}  // namespace tvm