graph.cc 6.2 KB
Newer Older
X
Xin Pan 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
X
start  
Xin Pan 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

Licensed 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

    http://www.apache.org/licenses/LICENSE-2.0

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. */

X
Xin Pan 已提交
15 16 17
#include <algorithm>
#include <unordered_set>

X
start  
Xin Pan 已提交
18
#include "paddle/fluid/framework/ir/graph.h"
X
Xin Pan 已提交
19
#include "paddle/fluid/framework/op_proto_maker.h"
20 21
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/var_desc.h"
X
start  
Xin Pan 已提交
22 23

namespace paddle {
X
Xin Pan 已提交
24
namespace framework {
X
Xin Pan 已提交
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
namespace {
void SortHelper(
    const std::map<ir::Node *, std::unordered_set<ir::Node *>> &adj_list,
    ir::Node *node, std::unordered_set<ir::Node *> *visited,
    std::vector<ir::Node *> *ret) {
  visited->insert(node);

  for (auto adj : adj_list.at(node)) {
    if (visited->find(adj) == visited->end()) {
      SortHelper(adj_list, adj, visited, ret);
    }
  }

  VLOG(3) << "topology sort insert: " << node->Name()
          << reinterpret_cast<void *>(node) << " input " << node->inputs.size();
  ret->push_back(node);
}
}  // namespace
X
Xin Pan 已提交
43

X
clean  
Xin Pan 已提交
44
Graph::Graph(const ProgramDesc &program) : program_(program) {
Q
qiaolongfei 已提交
45
  VLOG(3) << "block in program:" << program_.Size();
46 47 48 49 50
  std::unordered_map<std::string, VarDesc *> all_vars;
  for (auto *var : program.Block(0).AllVars()) {
    all_vars.emplace(var->Name(), var);
  }

X
Xin Pan 已提交
51 52 53
  ir::Node *last_backward = nullptr;
  std::vector<ir::Node *> optimize_ops;
  std::map<std::string, std::vector<ir::Node *>> var_nodes;
54
  for (auto *op : program.Block(0).AllOps()) {
X
clean  
Xin Pan 已提交
55
    ir::Node *node = CreateOpNode(op);
X
Xin Pan 已提交
56 57 58 59 60 61 62 63 64
    if (boost::get<int>(
            op->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) ==
        static_cast<int>(OpRole::kBackward)) {
      last_backward = node;
    } else if (boost::get<int>(
                   op->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) ==
               static_cast<int>(OpRole::kOptimize)) {
      optimize_ops.push_back(node);
    }
65 66 67

    for (auto &each_var_name : op->InputArgumentNames()) {
      ir::Node *var = nullptr;
X
Xin Pan 已提交
68
      if (var_nodes.find(each_var_name) != var_nodes.end()) {
X
Xin Pan 已提交
69
        var = var_nodes.at(each_var_name).back();
X
Xin Pan 已提交
70
      } else if (all_vars.count(each_var_name) != 0) {
X
clean  
Xin Pan 已提交
71
        var = CreateVarNode(all_vars.at(each_var_name));
X
Xin Pan 已提交
72
        var_nodes[each_var_name].push_back(var);
73
      } else {
X
clean  
Xin Pan 已提交
74
        // TODO(paddle-dev): Seems some assumption doesn't hold?
X
Xin Pan 已提交
75 76
        VLOG(3) << op->Type()
                << " input var not in all_var list: " << each_var_name;
X
polish  
Xin Pan 已提交
77
        var = CreateEmptyNode(each_var_name, ir::Node::Type::kVariable);
X
Xin Pan 已提交
78
        var_nodes[each_var_name].push_back(var);
79 80 81 82 83 84
      }
      node->inputs.push_back(var);
      var->outputs.push_back(node);
    }

    for (auto &each_var_name : op->OutputArgumentNames()) {
X
Xin Pan 已提交
85 86
      ir::Node *var = CreateVarNode(all_vars.at(each_var_name));
      var_nodes[each_var_name].push_back(var);
87 88 89 90
      node->outputs.push_back(var);
      var->inputs.push_back(node);
    }
  }
X
Xin Pan 已提交
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 124 125 126 127 128 129 130 131 132 133 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
  for (auto &var : var_nodes) {
    auto &versions = var.second;
    if (versions.size() <= 1) continue;

    auto it_new = versions.rbegin();
    auto it_old = versions.rbegin();
    ++it_old;
    for (; it_old != versions.rend(); it_new = it_old, ++it_old) {
      ir::Node *write_op =
          (*it_new)->inputs.empty() ? nullptr : (*it_new)->inputs[0];
      const auto &read_ops = (*it_old)->outputs;

      for (auto *read_op : read_ops) {
        // Manually add a dependency var from read_op to write_op;
        if (read_op == write_op) {
          // Read Write is the same op.
          continue;
        }
        ir::Node *dep_var = CreateEmptyNode("dummy", ir::Node::Type::kVariable);
        read_op->outputs.push_back(dep_var);
        dep_var->inputs.push_back(read_op);
        write_op->inputs.push_back(dep_var);
        dep_var->outputs.push_back(write_op);
      }
    }
  }

  if (last_backward) {
    for (ir::Node *opt_node : optimize_ops) {
      ir::Node *dep_var = CreateEmptyNode("dummy", ir::Node::Type::kVariable);
      last_backward->outputs.push_back(dep_var);
      dep_var->inputs.push_back(last_backward);
      opt_node->inputs.push_back(dep_var);
      dep_var->outputs.push_back(opt_node);
      VLOG(3) << "appending connect: " << last_backward->Name()
              << reinterpret_cast<void *>(last_backward) << "->"
              << opt_node->Name() << reinterpret_cast<void *>(opt_node);
    }
  }
}

std::vector<ir::Node *> TopologySortOperationFromInToOut(
    const std::vector<std::unique_ptr<ir::Node>> &nodes) {
  std::map<ir::Node *, std::unordered_set<ir::Node *>> adj_list;
  std::unordered_set<ir::Node *> visited;
  std::vector<ir::Node *> ret;

  for (auto &n : nodes) {
    if (n->NodeType() != ir::Node::Type::kOperation) continue;
    if (adj_list.find(n.get()) == adj_list.end()) {
      adj_list[n.get()] = std::unordered_set<ir::Node *>();
    }
    for (auto &var : n->inputs) {
      for (auto &adj_n : var->inputs) {
        PADDLE_ENFORCE(adj_n->NodeType() == ir::Node::Type::kOperation);
        adj_list[n.get()].insert(adj_n);
        LOG(ERROR) << "adj " << adj_n->Name() << reinterpret_cast<void *>(adj_n)
                   << " -> " << n->Name() << reinterpret_cast<void *>(n.get())
                   << "  via " << var->Name() << reinterpret_cast<void *>(var);
      }
    }
  }

  for (auto adj : adj_list) {
    if (visited.find(adj.first) == visited.end()) {
      SortHelper(adj_list, adj.first, &visited, &ret);
    }
  }

  for (ir::Node *n : ret) {
    std::unordered_set<ir::Node *> dummy;
    n->inputs.erase(
        std::remove_if(n->inputs.begin(), n->inputs.end(),
                       [n](ir::Node *t) { return t->Name() == "dummy"; }),
        n->inputs.end());
    n->outputs.erase(
        std::remove_if(n->outputs.begin(), n->outputs.end(),
                       [n](ir::Node *t) { return t->Name() == "dummy"; }),
        n->outputs.end());
  }
  return ret;
X
Xin Pan 已提交
172
}
X
Xin Pan 已提交
173

X
Xin Pan 已提交
174
}  // namespace framework
X
start  
Xin Pan 已提交
175
}  // namespace paddle