reflection.cc 17.6 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
/*!
 *  Copyright (c) 2016 by Contributors
22 23
 * \file reflection.cc
 * \brief Utilities to save/load/construct TVM objects
24 25
 */
#include <tvm/base.h>
26
#include <tvm/expr.h>
27
#include <tvm/attrs.h>
28
#include <tvm/node/container.h>
29
#include <tvm/packed_func_ext.h>
30
#include <tvm/runtime/ndarray.h>
31
#include <tvm/runtime/packed_func.h>
32
#include <dmlc/json.h>
33
#include <dmlc/memory_io.h>
34
#include <string>
35
#include "../common/base64.h"
36

37 38 39 40
namespace dmlc {
DMLC_REGISTRY_ENABLE(::tvm::NodeFactoryReg);
}  // namespace dmlc

41 42
namespace tvm {

43 44 45 46
::dmlc::Registry<NodeFactoryReg>* NodeFactoryReg::Registry() {
  return ::dmlc::Registry<NodeFactoryReg>::Get();
}

47
inline std::string Type2String(const Type& t) {
48
  return runtime::TVMType2String(Type2TVMType(t));
49 50
}

51

52
inline Type String2Type(std::string s) {
53
  return TVMType2Type(runtime::String2TVMType(s));
54 55
}

56 57
using runtime::Object;
using runtime::ObjectCell;
58

59 60 61 62 63
// indexer to index all the ndoes
class NodeIndexer : public AttrVisitor {
 public:
  std::unordered_map<Node*, size_t> node_index{{nullptr, 0}};
  std::vector<Node*> node_list{nullptr};
64 65
  std::unordered_map<DLTensor*, size_t> tensor_index;
  std::vector<DLTensor*> tensor_list;
66 67
  std::unordered_map<ObjectCell*, size_t> vm_obj_index;
  std::vector<ObjectCell*> vm_obj_list;
68 69 70 71 72 73 74

  void Visit(const char* key, double* value) final {}
  void Visit(const char* key, int64_t* value) final {}
  void Visit(const char* key, uint64_t* value) final {}
  void Visit(const char* key, int* value) final {}
  void Visit(const char* key, bool* value) final {}
  void Visit(const char* key, std::string* value) final {}
75
  void Visit(const char* key, void** value) final {}
76 77 78 79
  void Visit(const char* key, Type* value) final {}
  void Visit(const char* key, NodeRef* value) final {
    MakeIndex(value->node_.get());
  }
80

81 82 83 84 85 86 87
  void Visit(const char* key, runtime::NDArray* value) final {
    DLTensor* ptr = const_cast<DLTensor*>((*value).operator->());
    if (tensor_index.count(ptr)) return;
    CHECK_EQ(tensor_index.size(), tensor_list.size());
    tensor_index[ptr] = tensor_list.size();
    tensor_list.push_back(ptr);
  }
88 89 90 91 92 93 94 95 96

  void Visit(const char* key, Object* value) final {
    ObjectCell* ptr = value->ptr_.get();
    if (vm_obj_index.count(ptr)) return;
    CHECK_EQ(vm_obj_index.size(), vm_obj_list.size());
    vm_obj_index[ptr] = vm_obj_list.size();
    vm_obj_list.push_back(ptr);
  }

97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
  // make index of all the children of node
  void MakeIndex(Node* node) {
    if (node == nullptr) return;
    if (node_index.count(node)) return;
    CHECK_EQ(node_index.size(), node_list.size());
    node_index[node] = node_list.size();
    node_list.push_back(node);

    if (node->is_type<ArrayNode>()) {
      ArrayNode* n = static_cast<ArrayNode*>(node);
      for (const auto& sp : n->data) {
        MakeIndex(sp.get());
      }
    } else if (node->is_type<MapNode>()) {
      MapNode* n = static_cast<MapNode*>(node);
      for (const auto& kv : n->data) {
        MakeIndex(kv.first.get());
        MakeIndex(kv.second.get());
      }
116 117 118 119 120
    } else if (node->is_type<StrMapNode>()) {
      StrMapNode* n = static_cast<StrMapNode*>(node);
      for (const auto& kv : n->data) {
        MakeIndex(kv.second.get());
      }
121 122 123 124 125 126 127 128 129 130 131 132 133
    } else {
      node->VisitAttrs(this);
    }
  }
};

// use map so attributes are ordered.
using AttrMap = std::map<std::string, std::string>;

// A Node structure for JSON node.
struct JSONNode {
  // The type key of the data
  std::string type_key;
134 135
  // The global key for global object
  std::string global_key;
136 137
  // the attributes
  AttrMap attrs;
138 139
  // container keys
  std::vector<std::string> keys;
140 141 142 143 144 145
  // container data
  std::vector<size_t> data;

  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    writer->WriteObjectKeyValue("type_key", type_key);
146 147 148
    if (global_key.size() != 0) {
      writer->WriteObjectKeyValue("global_key", global_key);
    }
149 150 151
    if (attrs.size() != 0) {
      writer->WriteObjectKeyValue("attrs", attrs);
    }
152 153 154
    if (keys.size() != 0) {
      writer->WriteObjectKeyValue("keys", keys);
    }
155 156 157 158 159 160 161 162 163
    if (data.size() != 0) {
      writer->WriteObjectKeyValue("data", data);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    attrs.clear();
    data.clear();
164
    global_key.clear();
165 166 167
    type_key.clear();
    dmlc::JSONObjectReadHelper helper;
    helper.DeclareOptionalField("type_key", &type_key);
168
    helper.DeclareOptionalField("global_key", &global_key);
169
    helper.DeclareOptionalField("attrs", &attrs);
170
    helper.DeclareOptionalField("keys", &keys);
171 172 173 174 175 176 177 178
    helper.DeclareOptionalField("data", &data);
    helper.ReadAllFields(reader);
  }
};

class JSONAttrGetter : public AttrVisitor {
 public:
  const std::unordered_map<Node*, size_t>* node_index_;
179
  const std::unordered_map<DLTensor*, size_t>* tensor_index_;
180
  const std::unordered_map<ObjectCell*, size_t>* vm_obj_index_;
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
  JSONNode* node_;

  void Visit(const char* key, double* value) final {
    node_->attrs[key] = std::to_string(*value);
  }
  void Visit(const char* key, int64_t* value) final {
    node_->attrs[key] = std::to_string(*value);
  }
  void Visit(const char* key, uint64_t* value) final {
    node_->attrs[key] = std::to_string(*value);
  }
  void Visit(const char* key, int* value) final {
    node_->attrs[key] = std::to_string(*value);
  }
  void Visit(const char* key, bool* value) final {
    node_->attrs[key] = std::to_string(*value);
  }
  void Visit(const char* key, std::string* value) final {
    node_->attrs[key] = *value;
  }
201 202 203
  void Visit(const char* key, void** value) final {
    LOG(FATAL) << "not allowed to serialize a pointer";
  }
204 205 206 207 208 209 210
  void Visit(const char* key, Type* value) final {
    node_->attrs[key] = Type2String(*value);
  }
  void Visit(const char* key, NodeRef* value) final {
    node_->attrs[key] = std::to_string(
        node_index_->at(value->node_.get()));
  }
211 212 213 214
  void Visit(const char* key, runtime::NDArray* value) final {
    node_->attrs[key] = std::to_string(
        tensor_index_->at(const_cast<DLTensor*>((*value).operator->())));
  }
215 216 217 218
  void Visit(const char* key, Object* value) final {
    node_->attrs[key] = std::to_string(
        vm_obj_index_->at(value->ptr_.get()));
  }
219 220 221 222 223 224 225
  // Get the node
  void Get(Node* node) {
    if (node == nullptr) {
      node_->type_key.clear();
      return;
    }
    node_->type_key = node->type_key();
226 227
    // sepcially handle global object
    auto* f = dmlc::Registry<NodeFactoryReg>::Find(node_->type_key);
228 229
    CHECK(f != nullptr)
        << "Node type \'" << node_->type_key << "\' is not registered in TVM";
230 231 232 233
    if (f->fglobal_key != nullptr) {
      node_->global_key = f->fglobal_key(node);
      return;
    }
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
    node_->attrs.clear();
    node_->data.clear();
    if (node->is_type<ArrayNode>()) {
      ArrayNode* n = static_cast<ArrayNode*>(node);
      for (size_t i = 0; i < n->data.size(); ++i) {
        node_->data.push_back(
            node_index_->at(n->data[i].get()));
      }
    } else if (node->is_type<MapNode>()) {
      MapNode* n = static_cast<MapNode*>(node);
      for (const auto& kv : n->data) {
        node_->data.push_back(
            node_index_->at(kv.first.get()));
        node_->data.push_back(
            node_index_->at(kv.second.get()));
      }
250 251 252 253 254 255 256
    } else if (node->is_type<StrMapNode>()) {
      StrMapNode* n = static_cast<StrMapNode*>(node);
      for (const auto& kv : n->data) {
        node_->keys.push_back(kv.first);
        node_->data.push_back(
            node_index_->at(kv.second.get()));
      }
257
    } else {
258 259 260 261 262
      // do not need to recover content of global singleton object
      // they are registered via the environment
      auto* f = dmlc::Registry<NodeFactoryReg>::Find(node->type_key());
      if (f != nullptr && f->fglobal_key != nullptr) return;
      // recursively index normal object.
263 264 265 266 267 268 269
      node->VisitAttrs(this);
    }
  }
};

class JSONAttrSetter : public AttrVisitor {
 public:
270
  const std::vector<NodePtr<Node> >* node_list_;
271
  const std::vector<runtime::NDArray>* tensor_list_;
272 273
  const std::vector<Object>* vm_obj_list_;

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
  JSONNode* node_;

  std::string GetValue(const char* key) const {
    auto it = node_->attrs.find(key);
    if (it == node_->attrs.end()) {
      LOG(FATAL) << "JSONReader: cannot find field " << key;
    }
    return it->second;
  }
  template<typename T>
  void ParseValue(const char* key, T* value) const {
    std::istringstream is(GetValue(key));
    is >> *value;
    if (is.fail()) {
      LOG(FATAL) << "Wrong value format for field " << key;
    }
  }
  void Visit(const char* key, double* value) final {
    ParseValue(key, value);
  }
  void Visit(const char* key, int64_t* value) final {
    ParseValue(key, value);
  }
  void Visit(const char* key, uint64_t* value) final {
    ParseValue(key, value);
  }
  void Visit(const char* key, int* value) final {
    ParseValue(key, value);
  }
  void Visit(const char* key, bool* value) final {
    ParseValue(key, value);
  }
  void Visit(const char* key, std::string* value) final {
    *value = GetValue(key);
  }
309 310 311
  void Visit(const char* key, void** value) final {
    LOG(FATAL) << "not allowed to deserialize a pointer";
  }
312 313 314 315 316 317 318
  void Visit(const char* key, Type* value) final {
    std::string stype = GetValue(key);
    *value = String2Type(stype);
  }
  void Visit(const char* key, NodeRef* value) final {
    size_t index;
    ParseValue(key, &index);
319
    CHECK_LE(index, node_list_->size());
320 321
    value->node_ = node_list_->at(index);
  }
322 323 324 325 326 327
  void Visit(const char* key, runtime::NDArray* value) final {
    size_t index;
    ParseValue(key, &index);
    CHECK_LE(index, tensor_list_->size());
    *value = tensor_list_->at(index);
  }
328 329 330 331 332 333
  void Visit(const char* key, Object* value) final {
    size_t index;
    ParseValue(key, &index);
    CHECK_LE(index, vm_obj_list_->size());
    *value = vm_obj_list_->at(index);
  }
334
  // set node to be current JSONNode
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
  void Set(Node* node) {
    if (node == nullptr) return;
    if (node->is_type<ArrayNode>()) {
      ArrayNode* n = static_cast<ArrayNode*>(node);
      n->data.clear();
      for (size_t index : node_->data) {
        n->data.push_back(node_list_->at(index));
      }
    } else if (node->is_type<MapNode>()) {
      MapNode* n = static_cast<MapNode*>(node);
      CHECK_EQ(node_->data.size() % 2, 0U);
      for (size_t i = 0; i < node_->data.size(); i += 2) {
        n->data[node_list_->at(node_->data[i])]
            = node_list_->at(node_->data[i + 1]);
      }
350 351 352 353 354 355 356
    } else if (node->is_type<StrMapNode>()) {
      StrMapNode* n = static_cast<StrMapNode*>(node);
      CHECK_EQ(node_->data.size(), node_->keys.size());
      for (size_t i = 0; i < node_->data.size(); ++i) {
        n->data[node_->keys[i]]
            = node_list_->at(node_->data[i]);
      }
357 358 359 360 361 362 363 364 365 366 367 368
    } else {
      node->VisitAttrs(this);
    }
  }
};

// json graph structure to store node
struct JSONGraph {
  // the root of the graph
  size_t root;
  // the nodes of the graph
  std::vector<JSONNode> nodes;
369 370
  // base64 b64ndarrays of arrays
  std::vector<std::string> b64ndarrays;
371 372 373 374 375 376 377
  // global attributes
  AttrMap attrs;

  void Save(dmlc::JSONWriter *writer) const {
    writer->BeginObject();
    writer->WriteObjectKeyValue("root", root);
    writer->WriteObjectKeyValue("nodes", nodes);
378
    writer->WriteObjectKeyValue("b64ndarrays", b64ndarrays);
379 380 381 382 383 384 385 386 387 388 389
    if (attrs.size() != 0) {
      writer->WriteObjectKeyValue("attrs", attrs);
    }
    writer->EndObject();
  }

  void Load(dmlc::JSONReader *reader) {
    attrs.clear();
    dmlc::JSONObjectReadHelper helper;
    helper.DeclareField("root", &root);
    helper.DeclareField("nodes", &nodes);
390
    helper.DeclareOptionalField("b64ndarrays", &b64ndarrays);
391 392 393 394 395 396 397 398 399 400
    helper.DeclareOptionalField("attrs", &attrs);
    helper.ReadAllFields(reader);
  }

  static JSONGraph Create(const NodeRef& root) {
    JSONGraph g;
    NodeIndexer indexer;
    indexer.MakeIndex(root.node_.get());
    JSONAttrGetter getter;
    getter.node_index_ = &indexer.node_index;
401
    getter.tensor_index_ = &indexer.tensor_index;
402 403 404 405 406 407
    for (Node* n : indexer.node_list) {
      JSONNode jnode;
      getter.node_ = &jnode;
      getter.Get(n);
      g.nodes.emplace_back(std::move(jnode));
    }
408
    g.attrs["tvm_version"] = TVM_VERSION;
409
    g.root = indexer.node_index.at(root.node_.get());
410 411 412 413 414 415 416 417 418
    // serialize tensor
    for (DLTensor* tensor : indexer.tensor_list) {
      std::string blob;
      dmlc::MemoryStringStream mstrm(&blob);
      common::Base64OutStream b64strm(&mstrm);
      runtime::SaveDLTensor(&b64strm, tensor);
      b64strm.Finish();
      g.b64ndarrays.emplace_back(std::move(blob));
    }
419 420 421 422 423 424 425 426 427 428 429 430
    return g;
  }
};

std::string SaveJSON(const NodeRef& n) {
  auto jgraph = JSONGraph::Create(n);
  std::ostringstream os;
  dmlc::JSONWriter writer(&os);
  jgraph.Save(&writer);
  return os.str();
}

431
NodePtr<Node> LoadJSON_(std::string json_str) {
432 433 434 435 436
  std::istringstream is(json_str);
  dmlc::JSONReader reader(&is);
  JSONGraph jgraph;
  // load in json graph.
  jgraph.Load(&reader);
437
  std::vector<NodePtr<Node> > nodes;
438 439 440 441 442 443 444 445 446 447
  std::vector<runtime::NDArray> tensors;
  // load in tensors
  for (const std::string& blob : jgraph.b64ndarrays) {
    dmlc::MemoryStringStream mstrm(const_cast<std::string*>(&blob));
    common::Base64InStream b64strm(&mstrm);
    b64strm.InitPosition();
    runtime::NDArray temp;
    CHECK(temp.Load(&b64strm));
    tensors.emplace_back(temp);
  }
448 449 450 451 452 453 454
  // node 0 is always null
  nodes.reserve(jgraph.nodes.size());
  for (const JSONNode& jnode : jgraph.nodes) {
    if (jnode.type_key.length() != 0) {
      auto* f = dmlc::Registry<NodeFactoryReg>::Find(jnode.type_key);
      CHECK(f != nullptr)
          << "Node type \'" << jnode.type_key << "\' is not registered in TVM";
455
      nodes.emplace_back(f->fcreator(jnode.global_key));
456
    } else {
457
      nodes.emplace_back(NodePtr<Node>());
458 459 460 461 462
    }
  }
  CHECK_EQ(nodes.size(), jgraph.nodes.size());
  JSONAttrSetter setter;
  setter.node_list_ = &nodes;
463
  setter.tensor_list_ = &tensors;
464 465 466

  for (size_t i = 0; i < nodes.size(); ++i) {
    setter.node_ = &jgraph.nodes[i];
467 468 469 470 471
    // do not need to recover content of global singleton object
    // they are registered via the environment
    if (setter.node_->global_key.length() == 0) {
      setter.Set(nodes[i].get());
    }
472 473 474 475
  }
  return nodes.at(jgraph.root);
}

476 477 478 479 480 481
class NodeAttrSetter : public AttrVisitor {
 public:
  std::string type_key;
  std::unordered_map<std::string, runtime::TVMArgValue> attrs;

  void Visit(const char* key, double* value) final {
482
    *value = GetAttr(key).operator double();
483 484
  }
  void Visit(const char* key, int64_t* value) final {
485
    *value = GetAttr(key).operator int64_t();
486 487
  }
  void Visit(const char* key, uint64_t* value) final {
488
    *value = GetAttr(key).operator uint64_t();
489 490
  }
  void Visit(const char* key, int* value) final {
491
    *value = GetAttr(key).operator int();
492 493
  }
  void Visit(const char* key, bool* value) final {
494
    *value = GetAttr(key).operator bool();
495 496
  }
  void Visit(const char* key, std::string* value) final {
497
    *value = GetAttr(key).operator std::string();
498
  }
499
  void Visit(const char* key, void** value) final {
500
    *value = GetAttr(key).operator void*();
501
  }
502
  void Visit(const char* key, Type* value) final {
503
    *value = GetAttr(key).operator Type();
504 505
  }
  void Visit(const char* key, NodeRef* value) final {
506 507
    *value = GetAttr(key).operator NodeRef();
  }
508 509 510
  void Visit(const char* key, runtime::NDArray* value) final {
    *value = GetAttr(key).operator runtime::NDArray();
  }
511 512 513
  void Visit(const char* key, Object* value) final {
    *value = GetAttr(key).operator Object();
  }
514 515 516 517 518 519 520 521 522 523

 private:
  runtime::TVMArgValue GetAttr(const char* key) {
    auto it = attrs.find(key);
    if (it == attrs.end()) {
      LOG(FATAL) << type_key << ": require field " << key;
    }
    runtime::TVMArgValue v = it->second;
    attrs.erase(it);
    return v;
524 525 526
  }
};

527 528

void InitNodeByPackedArgs(Node* n, const TVMArgs& args) {
529
  NodeAttrSetter setter;
530 531 532 533 534 535
  setter.type_key = n->type_key();
  CHECK_EQ(args.size() % 2, 0);
  for (int i = 0; i < args.size(); i += 2) {
    setter.attrs.emplace(args[i].operator std::string(),
                         args[i + 1]);
  }
536 537 538 539 540 541 542 543 544
  n->VisitAttrs(&setter);
  if (setter.attrs.size() != 0) {
    std::ostringstream os;
    os << setter.type_key << " does not contain field ";
    for (const auto &kv : setter.attrs) {
      os << " " << kv.first;
    }
    LOG(FATAL) << os.str();
  }
545 546 547 548 549 550 551
}

// API function to make node.
// args format:
//   key1, value1, ..., key_n, value_n
void MakeNode(const TVMArgs& args, TVMRetValue* rv) {
  std::string type_key = args[0];
552
  std::string empty_str;
553 554 555 556
  auto* f = dmlc::Registry<NodeFactoryReg>::Find(type_key);
  CHECK(f != nullptr)
      << "Node type \'" << type_key << "\' is not registered in TVM";
  TVMArgs kwargs(args.values + 1, args.type_codes + 1, args.size() - 1);
557 558
  CHECK(f->fglobal_key == nullptr)
      << "Cannot make node type \'" << type_key << "\' with global_key.";
559
  NodePtr<Node> n = f->fcreator(empty_str);
560 561 562 563 564
  if (n->derived_from<BaseAttrsNode>()) {
    static_cast<BaseAttrsNode*>(n.get())->InitByPackedArgs(kwargs);
  } else {
    InitNodeByPackedArgs(n.get(), kwargs);
  }
565 566 567 568 569
  *rv = NodeRef(n);
}

TVM_REGISTER_GLOBAL("make._Node")
.set_body(MakeNode);
570
}  // namespace tvm