order_mutation.cc 6.07 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
 * \file order_mutation.cc
22 23 24 25 26 27 28 29
 * \brief Add control flow dependencies between nodes
 *  To correctly order mutation and read to resolve
 *  write after read problem and read after write problems.
 */
#include <nnvm/pass.h>
#include <nnvm/op_attr_types.h>

namespace nnvm {
30
namespace pass {
31
namespace {
32 33 34 35 36 37 38 39 40 41

template<typename T>
inline T get_with_default(const std::unordered_map<Node*, T> &map,
                          Node* key,
                          const T& def) {
  auto it = map.find(key);
  if (it != map.end()) return it->second;
  return def;
}

42
inline bool IsMutate(const std::vector<uint32_t>& mutate_inputs, uint32_t i) {
Tianqi Chen committed
43
  return std::binary_search(mutate_inputs.begin(), mutate_inputs.end(), i);
44 45
}

46 47
Graph OrderMutation(const Graph& src) {
  std::unordered_map<Node*, std::vector<NodeEntry> > version_hist;
48
  DFSVisit(src.outputs, [&version_hist](const ObjectPtr& n) {
49 50 51 52 53 54 55 56 57 58 59
      for (const NodeEntry& e : n->inputs) {
        if (e.node->is_variable()) {
          if (e.version != 0 && version_hist.count(e.node.get()) == 0) {
            version_hist[e.node.get()] = std::vector<NodeEntry>{};
          }
        }
      }
    });
  // no mutation happens, everything if fine.
  if (version_hist.size() == 0) return src;
  // start preparing for remapping the nodes.
60 61
  std::unordered_map<Node*, ObjectPtr> old_new;
  auto prepare = [&version_hist, &old_new] (const ObjectPtr& n) {
62 63
    static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs");
    std::vector<uint32_t> mutate_inputs;
64 65
    if (!n->is_variable() && fmutate_inputs.count(n->op())) {
      mutate_inputs = fmutate_inputs[n->op()](n->attrs);
66 67 68
    }
    std::sort(mutate_inputs.begin(), mutate_inputs.end());

69 70 71 72 73 74 75 76
    bool need_repl = false;
    for (size_t i = 0; i < n->inputs.size(); ++i) {
      const NodeEntry& e = n->inputs[i];
      if (e.node->is_variable()) {
        if (e.version != 0) need_repl = true;
        auto it = version_hist.find(e.node.get());
        if (it != version_hist.end()) {
          std::vector<NodeEntry>& vec = it->second;
77
          vec.emplace_back(NodeEntry{n, IsMutate(mutate_inputs, i), e.version});
78 79 80 81 82
        }
      } else {
        if (old_new.count(e.node.get()) != 0) need_repl = true;
      }
    }
83
    for (const ObjectPtr& p : n->control_deps) {
84 85 86
      if (old_new.count(p.get()) != 0) need_repl = true;
    }
    if (need_repl) {
87
      ObjectPtr np = Node::Create();
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
      np->attrs = n->attrs;
      old_new[n.get()] = std::move(np);
    }
  };
  DFSVisit(src.outputs, prepare);
  // comparator of history entry
  auto comparator = [](const NodeEntry& a, const NodeEntry &b) {
    if (a.version < b.version) return true;
    if (a.version > b.version) return false;
    return a.index > b.index;
  };

  for (auto &kv : version_hist) {
    std::sort(kv.second.begin(), kv.second.end(), comparator);
  }
  // copy the nodes, as well as add control deps
  for (auto &kv : old_new) {
    // copy the nodes
    for (const NodeEntry& e : kv.first->inputs) {
      auto it = old_new.find(e.node.get());
      if (it != old_new.end()) {
        kv.second->inputs.emplace_back(NodeEntry{it->second, e.index, e.version});
      } else {
        kv.second->inputs.push_back(e);
      }
    }
114
    for (const ObjectPtr& p : kv.first->control_deps) {
115 116 117 118
      kv.second->control_deps.emplace_back(
          get_with_default(old_new, p.get(), p));
    }
    // add control deps
119 120
    static auto& fmutate_inputs = Op::GetAttr<FMutateInputs>("FMutateInputs");
    std::vector<uint32_t> mutate_inputs;
121 122
    if (fmutate_inputs.count(kv.first->op())) {
      mutate_inputs = fmutate_inputs[kv.first->op()](kv.first->attrs);
123 124 125
    }
    std::sort(mutate_inputs.begin(), mutate_inputs.end());

126 127 128 129 130 131 132
    for (size_t i = 0; i < kv.first->inputs.size(); ++i) {
      const NodeEntry& e = kv.first->inputs[i];
      if (e.node->is_variable() && version_hist.count(e.node.get()) != 0) {
        std::vector<NodeEntry>& vec = version_hist.at(e.node.get());
        auto it = std::lower_bound(vec.begin(), vec.end(),
                                   NodeEntry{nullptr, 1, e.version},
                                   comparator);
133
        if (IsMutate(mutate_inputs, i)) {
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
          int read_dep = 0;
          while (it != vec.begin()) {
            --it;
            if (it->index != 0) break;
            ++read_dep;
            // depend on previous read
            kv.second->control_deps.push_back(
                get_with_default(old_new, it->node.get(), it->node));
          }
          if (read_dep == 0 && it->index != 0) {
            // depend on last write
            kv.second->control_deps.push_back(
                get_with_default(old_new, it->node.get(), it->node));
          }
        } else {
          // depend on last write
          if (it->index != 0) {
            kv.second->control_deps.push_back(
                get_with_default(old_new, it->node.get(), it->node));
          }
        }
      }
    }
  }
  Graph ret;
  for (const NodeEntry &e : src.outputs) {
    ret.outputs.emplace_back(NodeEntry{
        get_with_default(old_new, e.node.get(), e.node), e.index, e.version});
  }
  return ret;
}

NNVM_REGISTER_PASS(OrderMutation)
.describe("Return a new graph that adds control dependencies, "\
          "to order the mutation and reads if mutation exists.")
.set_body(OrderMutation)
.set_change_graph(true);

172
}  // namespace
173
}  // namespace pass
174
}  // namespace nnvm