graph_fuse.cc 14.6 KB
Newer Older
1 2 3 4 5
/*!
 *  Copyright (c) 2017 by Contributors
 * \file graph_fuse.cc
 * \brief Fuse the operators together.
 */
6 7
#include <dmlc/parameter.h>
#include <nnvm/compiler/packed_func_ext.h>
8
#include <nnvm/graph.h>
9
#include <nnvm/graph_attr_types.h>
10
#include <nnvm/node.h>
11 12
#include <nnvm/op_attr_types.h>
#include <nnvm/pass.h>
13
#include <nnvm/pass_functions.h>
14
#include <nnvm/tuple.h>
15
#include <tvm/lowered_func.h>
16
#include <tvm/runtime/packed_func.h>
17
#include <limits>
18

19 20 21
#include "graph_fuse.h"
#include "graph_runtime.h"
#include "pattern_util.h"
22 23 24 25 26 27 28

namespace nnvm {
namespace compiler {
using namespace tvm;

// Partition the graph into segments
// Each segment will be compiled into one operator.
29 30
// Also mark the property of the segment.
nnvm::Graph GraphFindFusibleGroups(nnvm::Graph g) {
31
  const IndexedGraph& idx = g.indexed_graph();
32 33 34 35 36
  int opt_level = 2;
  if (g.attrs.count("opt_level") != 0) {
    opt_level = g.MoveCopyAttr<int>("opt_level");
  }

37 38 39 40 41
  // Get attributes from the graph
  const ShapeVector& shape_vec = g.GetAttr<ShapeVector>("shape");

  // Reference counter of each op node
  // For now, always store result when an op is referred more than once.
42
  std::vector<uint32_t> ref_count = GetNodeRefCounts(idx);
43 44
  for (const auto& e : idx.outputs()) {
    // this line will realize all the outputs
45
    ref_count[e.node_id] += 1;
46
  }
47
  // Pattern for the subgraph
48
  PatternVec pattern_vec(idx.num_nodes(),  kOpaque);
49 50 51 52 53 54 55 56 57 58 59 60
  // Whether node can be fused to parent.
  std::vector<FuseRule> fuse_vec(idx.num_nodes(), FuseRule::kUknown);
  // Master node id of fusion segment.
  std::vector<int> master_vec(idx.num_nodes(), -1);
  // Operator pattern
  static auto& op_pattern = nnvm::Op::GetAttr<TOpPattern>("TOpPattern");

  for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
    const auto& inode = idx[nid];
    if (inode.source->is_variable()) {
      fuse_vec[nid] = FuseRule::kRealize; continue;
    }
61
    TOpPattern pt = op_pattern.get(inode.source->op(), kOpaque);
62 63

    if (pt <= kBroadcast) {
64
      // Check if we can fuse to the master.
65 66
      int chosen_master = -1;
      bool ewise = inode.source->num_outputs() == 1;
67
      bool mark_as_injective = false;
68 69 70 71
      for (const auto& e : inode.inputs) {
        if (fuse_vec[e.node_id] == FuseRule::kUknown) {
          TOpPattern ipt = pattern_vec[e.node_id];
          if (ipt != kElemWise) ewise = false;
72 73 74
          if (ipt <= kBroadcast) {
            fuse_vec[e.node_id] = FuseRule::kFuseToMaster;
          } else if (ipt == kInjective) {
75
            fuse_vec[e.node_id] = FuseRule::kFuseToMaster;
76
            mark_as_injective = true;
77 78 79
          } else if (ipt == kOutEWiseFusable &&
                     chosen_master == -1 &&
                     shape_vec[idx.entry_id(nid, 0)] == shape_vec[idx.entry_id(e)]) {
80 81 82 83 84 85 86 87 88 89 90 91 92 93
            chosen_master = master_vec[e.node_id];
            fuse_vec[e.node_id] = FuseRule::kFuseToMaster;
          } else {
            fuse_vec[e.node_id] = FuseRule::kRealize;
          }
        }
        if (ewise) {
          if (shape_vec[idx.entry_id(nid, 0)] != shape_vec[idx.entry_id(e)]) {
            ewise = false;
          }
        }
      }
      master_vec[nid] = chosen_master;
      if (chosen_master != -1) {
94
        pt = kOutEWiseFusable;
95 96
      } else if (mark_as_injective) {
        pt = kInjective;
97 98 99
      } else {
        pt = ewise ? kElemWise : kBroadcast;
      }
100
    } else if (pt == kInjective || pt == kCommReduce) {
101
      // Fuse to the comm reduce or injective
102 103 104 105 106 107 108 109 110 111 112 113 114
      for (const auto& e : inode.inputs) {
        if (fuse_vec[e.node_id] == FuseRule::kUknown) {
          TOpPattern ipt = pattern_vec[e.node_id];
          if (ipt <= kInjective) {
            fuse_vec[e.node_id] = FuseRule::kFuseToMaster;
          } else {
            fuse_vec[e.node_id] = FuseRule::kRealize;
          }
        }
      }
      if (pt == kCommReduce) {
        master_vec[nid] = nid;
      }
115
    } else {
116
      // Realize
117 118 119 120 121 122 123 124 125 126 127 128
      master_vec[nid] = nid;
      for (const auto& e : inode.inputs) {
        if (fuse_vec[e.node_id] == FuseRule::kUknown) {
          fuse_vec[e.node_id] = FuseRule::kRealize;
          if (master_vec[e.node_id] == -1) {
            master_vec[e.node_id] = e.node_id;
          }
        }
      }
    }

    pattern_vec[nid] = pt;
129
    if (ref_count[nid] > 1 || opt_level < 1) {
130 131 132 133 134 135 136
      fuse_vec[nid] = FuseRule::kRealize;
      if (master_vec[nid] == -1) {
        master_vec[nid] = nid;
      }
    }
  }

137 138
  // Point to the group root id of each node.
  GroupVec group_vec(idx.num_nodes(), -1);
139
  std::vector<std::vector<uint32_t> > node_ids_per_group(idx.num_nodes());
140 141 142
  for (uint32_t i = idx.num_nodes(); i != 0; --i) {
    uint32_t nid = i - 1;
    const auto& inode = idx[nid];
143
    bool is_root = false;
144 145
    if (group_vec[nid] == -1) {
      group_vec[nid] = nid;
146 147
      node_ids_per_group[nid].push_back(nid);
      is_root = true;
148
    }
149 150 151 152 153

    // Check if injective op and out_ewise_fusable op (e.g. conv2d) are in the same group.
    bool parent_out_ewise = false;
    bool parent_injective = false;
    for (const auto& e : inode.inputs) {
154
      if (fuse_vec[e.node_id] != FuseRule::kFuseToMaster) continue;
155 156 157 158 159 160 161 162
      TOpPattern pt = pattern_vec[e.node_id];
      if (pt == kOutEWiseFusable) {
        parent_out_ewise = true;
      } else if (pt == kInjective) {
        parent_injective = true;
      }
    }
    // Change the master node from out_ewise_fusable op to itself
163 164 165 166 167 168 169 170 171
    if (parent_injective && parent_out_ewise) {
      master_vec[nid] = nid;
      if (!is_root) {
        // Children nodes in the same group might be pointing to a master node in a different group.
        for (uint32_t j : node_ids_per_group[group_vec[nid]]) {
          master_vec[j] = nid;
        }
      }
    }
172

173
    // Propagate the group id.
174
    for (const auto& e : inode.inputs) {
175 176 177 178 179 180 181 182
      TOpPattern pt = pattern_vec[e.node_id];
      if (parent_out_ewise && parent_injective) {
        if (pt == kOutEWiseFusable) {
          continue;  // Do not fuse out_ewise_fusable op
        } else if (pt == kInjective) {
          master_vec[e.node_id] = nid;
        }
      }
183 184 185 186
      if (fuse_vec[e.node_id] == FuseRule::kFuseToMaster) {
        CHECK(group_vec[e.node_id] == -1||
              group_vec[e.node_id] == group_vec[nid]);
        group_vec[e.node_id] = group_vec[nid];
187
        node_ids_per_group[group_vec[nid]].push_back(e.node_id);
188 189 190
      }
    }
  }
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 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

  /*
     Above algorithm will not fuse a node whose output is fed to more than one
     child node. This is because in general, it does not make sense to fuse multiple
     children branches with their parent, as in the following example.

            conv2d
            /  |  \
           /   |   \
         op    op   op
          |    |    |
          |    |    |

     However, when all children branches meet at a certain node, there is a possibility for
     further operator fusion. For example, all nodes in the following subgraph can be fused
     into a single node, if three 'in-between' nodes and the bottom node are all element wise
     operation.

            conv2d
            /  |  \
           /   |   \
         op    op   op
          \    |    /
           \   |   /
          elemwise add
               |

     This pattern is not uncommon. For example, it arises when conv2d op is followed by exponential
     linear unit. If bias add and batch normalization are also present, they can be fused as well.

     In fact, above fusion algorithm already fuses three in-between nodes and the element wise
     add node in the figure above. The following code fuses the conv2d node with the already
     fused children nodes. The following patterns are supported.

     * Any number of child nodes from the top node
     * The path from the top node to bottom node can contain any number of element wise ops.

     The only restriction is that in-between nodes cannot have more than one child.

     The overview of the algorithm below is as follows:

     1. Check if all children nodes are fused into a single op by the existing fusion algorithm
     2. Fuse the parent node to children nodes, and update its group id to be the children's group id
     3. If the parent node originally belongs to another group (for example, conv + batch norm),
        propagate the new group id to a grand parent and upward
  */
  if (opt_level >= 1) {
    std::vector<std::vector<uint32_t> > children_group_ids(idx.num_nodes());
    for (uint32_t nid = idx.num_nodes() - 1; nid != 0; --nid) {
      const auto& inode = idx[nid];
      if (inode.source->is_variable()) continue;
      CHECK_NE(group_vec[nid], -1);
      if (inode.inputs.size() != 1) continue;
      const uint32_t parent_nid = inode.inputs[0].node_id;
      // if parent node has more than one child, record each child's group id.
      if (ref_count[parent_nid] > 1) children_group_ids[parent_nid].push_back(group_vec[nid]);
    }

    std::vector<int> new_group_id(idx.num_nodes(), -1);
    for (uint32_t nid = idx.num_nodes() - 1; nid != 0; --nid) {
      if (new_group_id[group_vec[nid]] != -1) {
        // propagate new group id from child
        group_vec[nid] = new_group_id[group_vec[nid]];
      }
      TOpPattern pt = op_pattern.get(idx[nid].source->op(), kOpaque);
      if (pt == kOpaque) continue;
      const auto& group_ids = children_group_ids[nid];
      if (group_ids.size() <= 1) continue;
      const uint32_t child_group_id = group_ids[0];
      const auto& children_node_ids = node_ids_per_group[child_group_id];

      auto is_same_group_id = [child_group_id](uint32_t id) {
          return id == child_group_id;
      };
      auto is_fusible_pattern = [&idx](uint32_t child_nid) {
        TOpPattern child_pt = op_pattern.get(idx[child_nid].source->op(), kOpaque);
        return child_pt  <= kBroadcast;
      };
      // fuse this node with children if
      // all children belong to the same group and
      // all nodes in the group are element wise or broadcast op.
      const bool can_be_fused = std::all_of(group_ids.begin(), group_ids.end(), is_same_group_id) &&
        std::all_of(children_node_ids.begin(), children_node_ids.end(), is_fusible_pattern);

      if (can_be_fused) {
        new_group_id[group_vec[nid]] = child_group_id;
        group_vec[nid] = child_group_id;
        for (uint32_t nid2 : node_ids_per_group[child_group_id]) {
          pattern_vec[nid2] = pattern_vec[nid];
          master_vec[nid2] = master_vec[nid];
        }
      }
    }
  }

286 287 288 289 290 291
  g.attrs["group_root"] = std::make_shared<any>(std::move(group_vec));
  g.attrs["group_master"] = std::make_shared<any>(std::move(master_vec));
  g.attrs["pattern"] = std::make_shared<any>(std::move(pattern_vec));
  return g;
}

292 293
NNVM_REGISTER_PASS(GraphFindFusibleGroups)
.set_body(GraphFindFusibleGroups)
294
.depend_graph_attr("shape")
295
.depend_graph_attr("dtype");
296 297

// Fuse the partitioned graph into segments.
298 299 300 301 302 303
// Create a new graph with fused nodes.
// Also inherit attribute shape, dltype from the previous graph.
nnvm::Graph GraphFuse(nnvm::Graph g) {
  CHECK(g.HasAttr("group_root") && g.HasAttr("pattern"))
      << "GraphFindFusibleGroups pass hasn't been applied yet.";

304 305 306 307
  const IndexedGraph& idx = g.indexed_graph();
  // Get attributes from the graph
  const ShapeVector& shape_vec = g.GetAttr<ShapeVector>("shape");
  const DTypeVector& dtype_vec = g.GetAttr<DTypeVector>("dtype");
308 309
  const GroupVec& group_vec = g.GetAttr<GroupVec>("group_root");
  const PatternVec& pattern_vec = g.GetAttr<PatternVec>("pattern");
310

311
  // Specially handle assign op.
312
  const nnvm::Op* assign_op = nnvm::Op::Get("_assign");
313

314 315
  FuseEntryVec fuse_entries(idx.num_nodes());
  // Setup inputs and placeholder.
316 317 318 319 320
  for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
    const auto& inode = idx[nid];
    if (inode.source->is_variable()) continue;
    CHECK_GE(group_vec[nid], 0);
    int root_id = group_vec[nid];
321
    FuseEntry& fe = fuse_entries[root_id];
322 323
    fe.flatten_data = (pattern_vec[root_id] == kElemWise ||
                       inode.source->op() == assign_op);
324 325 326
    for (const auto& e : inode.inputs) {
      if (group_vec[e.node_id] != root_id && fe.imap.count(e) == 0) {
        Array<Expr> shape;
327
        if (fe.flatten_data) {
328
          // Elementwise support flatten
329 330 331 332 333 334 335 336 337 338 339 340 341
          int64_t prod = 1;
          for (int64_t x : shape_vec[idx.entry_id(e)]) {
            prod *= x;
          }
          CHECK_LE(prod, static_cast<int64_t>(std::numeric_limits<int>::max()));
          shape.push_back(make_const(Int(32), prod));
        } else {
          for (int64_t x : shape_vec[idx.entry_id(e)]) {
            CHECK_LE(x, static_cast<int64_t>(std::numeric_limits<int>::max()));
            shape.push_back(make_const(Int(32), x));
          }
        }
        std::ostringstream os_name;
342
        os_name << "input" << fe.imap.size();
343
        Tensor data = placeholder(
344
            shape, TVMType2Type(GetDLType(dtype_vec[idx.entry_id(e)])),
345
            os_name.str());
346 347 348 349
        NodeEntry garg = Symbol::CreateVariable(os_name.str()).outputs[0];
        fe.imap[e] = garg;
        fe.reverse_imap[garg.node.get()] = e;
        fe.input_info[garg.node.get()] = std::move(data);
350 351 352
      }
    }
  }
353

354 355
  // Setup the Subgraph
  std::vector<NodeEntry> subgraph_vec(idx.num_node_entries());
356 357 358 359
  for (uint32_t nid = 0; nid < idx.num_nodes(); ++nid) {
    const auto& inode = idx[nid];
    if (inode.source->is_variable()) continue;
    int root_id = group_vec[nid];
360 361
    FuseEntry& fe = fuse_entries[root_id];
    // Create a subgraph node.
362 363
    NodePtr gnode = Node::Create();
    gnode->attrs = inode.source->attrs;
364
    // Set input entries for the subgraph node.
365 366 367 368
    for (const auto& e : inode.inputs) {
      if (group_vec[e.node_id] != root_id) {
        auto it = fe.imap.find(e);
        CHECK(it != fe.imap.end());
369
        gnode->inputs.push_back(it->second);
370
      } else {
371 372 373 374
        const NodeEntry& ne = subgraph_vec[idx.entry_id(e)];
        CHECK(!idx[e.node_id].source->is_variable());
        CHECK(ne.node != nullptr);
        gnode->inputs.push_back(ne);
375 376
      }
    }
377
    // Schedule on the root node and use the master's schedule
378
    if (static_cast<int>(nid) != root_id) {
379 380
      for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {
        uint32_t eid = idx.entry_id(nid, index);
381
        subgraph_vec[eid] = NodeEntry{gnode, index, 0};
382 383
      }
    } else {
384 385 386
      for (uint32_t index = 0; index < inode.source->num_outputs(); ++index) {
        fe.subgraph.outputs.push_back(NodeEntry{gnode, index, 0});
      }
387 388
    }
  }
389 390
  g.attrs["fused_entry"] = std::make_shared<any>(std::move(fuse_entries));
  return g;
391 392
}

393 394 395 396 397 398 399 400
NNVM_REGISTER_PASS(GraphFuse)
    .set_body(GraphFuse)
    .set_change_graph(true)
    .provide_graph_attr("fused_entry")
    .depend_graph_attr("shape")
    .depend_graph_attr("dtype")
    .depend_graph_attr("group_root")
    .depend_graph_attr("group_master");
401

402 403
}  // namespace compiler
}  // namespace nnvm