graph.cc 8.0 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
namespace ir {
X
better  
Xin Pan 已提交
26
/*
X
Xin Pan 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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);
}
X
better  
Xin Pan 已提交
44

X
Xin Pan 已提交
45
std::vector<ir::Node*> TopologySortOperations(
X
better  
Xin Pan 已提交
46 47 48 49 50 51 52 53 54 55 56
    const std::map<ir::Node *, std::unordered_set<ir::Node *>> &adj_list) {
  std::unordered_set<ir::Node *> visited;
  std::vector<ir::Node *> ret;

  for (auto adj : adj_list) {
    if (visited.find(adj.first) == visited.end()) {
      SortHelper(adj_list, adj.first, &visited, &ret);
    }
  }
  return ret;
}
X
Xin Pan 已提交
57
}  // namespace
X
better  
Xin Pan 已提交
58
*/
X
Xin Pan 已提交
59

X
clean  
Xin Pan 已提交
60
Graph::Graph(const ProgramDesc &program) : program_(program) {
Q
qiaolongfei 已提交
61
  VLOG(3) << "block in program:" << program_.Size();
62 63 64 65 66
  std::unordered_map<std::string, VarDesc *> all_vars;
  for (auto *var : program.Block(0).AllVars()) {
    all_vars.emplace(var->Name(), var);
  }

X
Xin Pan 已提交
67
  std::map<std::string, std::vector<ir::Node *>> var_nodes;
68
  for (auto *op : program.Block(0).AllOps()) {
X
clean  
Xin Pan 已提交
69
    ir::Node *node = CreateOpNode(op);
70 71 72

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

    for (auto &each_var_name : op->OutputArgumentNames()) {
X
Xin Pan 已提交
90 91
      ir::Node *var = CreateVarNode(all_vars.at(each_var_name));
      var_nodes[each_var_name].push_back(var);
92 93 94 95
      node->outputs.push_back(var);
      var->inputs.push_back(node);
    }
  }
X
Xin Pan 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  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;
        }
X
better  
Xin Pan 已提交
114 115
        ir::Node *dep_var = CreateEmptyNode(ir::Node::kControlDepVarName,
                                            ir::Node::Type::kVariable);
X
Xin Pan 已提交
116 117 118 119 120 121 122
        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);
      }
    }
  }
X
better  
Xin Pan 已提交
123
}
X
Xin Pan 已提交
124

X
better  
Xin Pan 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
/*
bool HasCircleHelper(ir::Node* node,
                     const std::map<ir::Node *, std::unordered_set<ir::Node *>>
&adj_list,
                     std::unordered_set<ir::Node*>* visited,
                     std::unordered_set<ir::Node*>* in_trace) {
  if (visited->find(node) == visited->end()) {
    visited->insert(node);
    in_trace->insert(node);

    for (ir::Node *in : adj_list.at(node)) {
      if (visited->find(in) == visited->end() &&
          HasCircleHelper(in, adj_list, visited, in_trace)) {
        return true;
      } else if (in_trace->find(in) != in_trace->end()) {
        return true;
      }
X
Xin Pan 已提交
142 143
    }
  }
X
better  
Xin Pan 已提交
144 145
  in_trace->erase(node);
  return false;
X
Xin Pan 已提交
146 147
}

X
better  
Xin Pan 已提交
148 149 150 151 152 153 154 155 156 157 158 159
bool HasCircle(const std::map<ir::Node *, std::unordered_set<ir::Node *>>
&adj_list) {
  std::unordered_set<ir::Node*> visited;
  std::unordered_set<ir::Node*> in_trace;
  for (auto& adj : adj_list) {
    if (HasCircleHelper(adj.first, adj_list, &visited, &in_trace)) {
      return true;
    }
  }
  return false;
}

X
Xin Pan 已提交
160
std::map<ir::Node *, std::unordered_set<ir::Node *>> BuildOperationAdjList(
X
better  
Xin Pan 已提交
161
    const std::vector<ir::Node*> &nodes) {
X
Xin Pan 已提交
162 163 164 165
  std::map<ir::Node *, std::unordered_set<ir::Node *>> adj_list;

  for (auto &n : nodes) {
    if (n->NodeType() != ir::Node::Type::kOperation) continue;
X
better  
Xin Pan 已提交
166 167
    if (adj_list.find(n) == adj_list.end()) {
      adj_list[n] = std::unordered_set<ir::Node *>();
X
Xin Pan 已提交
168 169 170 171
    }
    for (auto &var : n->inputs) {
      for (auto &adj_n : var->inputs) {
        PADDLE_ENFORCE(adj_n->NodeType() == ir::Node::Type::kOperation);
X
better  
Xin Pan 已提交
172
        adj_list[n].insert(adj_n);
X
Xin Pan 已提交
173
        LOG(ERROR) << "adj " << adj_n->Name() << reinterpret_cast<void *>(adj_n)
X
better  
Xin Pan 已提交
174
                   << " -> " << n->Name() << reinterpret_cast<void *>(n)
X
Xin Pan 已提交
175 176 177 178
                   << "  via " << var->Name() << reinterpret_cast<void *>(var);
      }
    }
  }
X
better  
Xin Pan 已提交
179 180
  return adj_list;
}
X
Xin Pan 已提交
181

X
Xin Pan 已提交
182
std::vector<ir::Node *> TopologySortOperationsOperationFromInToOut(
X
better  
Xin Pan 已提交
183 184 185 186 187 188
    const std::vector<std::unique_ptr<ir::Node>> &nodes) {
  std::vector<ir::Node*> tmp;
  for (auto& n : nodes) {
    tmp.push_back(n.get());
  }
  std::map<ir::Node *, std::unordered_set<ir::Node *>> adj_list =
X
Xin Pan 已提交
189
BuildOperationAdjList(tmp);
X
better  
Xin Pan 已提交
190 191

  PADDLE_ENFORCE(!HasCircle(adj_list));
X
Xin Pan 已提交
192
  std::vector<ir::Node*> ret = TopologySortOperations(adj_list);
X
better  
Xin Pan 已提交
193 194 195 196 197 198 199 200 201 202 203 204

  ir::Node *last_backward = nullptr;
  std::vector<ir::Node *> optimize_ops;
  for (ir::Node* n : ret) {
    if (boost::get<int>(
        n->Op()->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) ==
        static_cast<int>(OpRole::kBackward)) {
      last_backward = n;
    } else if (boost::get<int>(
        n->Op()->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName())) ==
        static_cast<int>(OpRole::kOptimize)) {
      optimize_ops.push_back(n);
X
Xin Pan 已提交
205 206 207
    }
  }

X
better  
Xin Pan 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
  if (last_backward) {
    for (ir::Node *opt_node : optimize_ops) {
      ir::Node *dep_var = CreateEmptyNode(ir::Node::kControlDepVarName,
                                          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);
    }
  }

  PADDLE_ENFORCE(!HasCircle(adj_list));
X
Xin Pan 已提交
223 224 225 226
  for (ir::Node *n : ret) {
    std::unordered_set<ir::Node *> dummy;
    n->inputs.erase(
        std::remove_if(n->inputs.begin(), n->inputs.end(),
X
better  
Xin Pan 已提交
227 228
                       [n](ir::Node *t) {
                         return t->Name() == ir::Node::kControlDepVarName; }),
X
Xin Pan 已提交
229 230 231
        n->inputs.end());
    n->outputs.erase(
        std::remove_if(n->outputs.begin(), n->outputs.end(),
X
better  
Xin Pan 已提交
232 233
                       [n](ir::Node *t) {
                         return t->Name() == ir::Node::kControlDepVarName; }),
X
Xin Pan 已提交
234 235 236
        n->outputs.end());
  }
  return ret;
X
better  
Xin Pan 已提交
237
}*/
X
Xin Pan 已提交
238

X
Xin Pan 已提交
239
}  // namespace ir
X
Xin Pan 已提交
240
}  // namespace framework
X
start  
Xin Pan 已提交
241
}  // namespace paddle