graph.cc 7.9 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
better  
Xin Pan 已提交
25
/*
X
Xin Pan 已提交
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);
}
X
better  
Xin Pan 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55

std::vector<ir::Node*> TopologySort(
    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 已提交
56
}  // namespace
X
better  
Xin Pan 已提交
57
*/
X
Xin Pan 已提交
58

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

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

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

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

X
better  
Xin Pan 已提交
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
/*
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 已提交
141 142
    }
  }
X
better  
Xin Pan 已提交
143 144
  in_trace->erase(node);
  return false;
X
Xin Pan 已提交
145 146
}

X
better  
Xin Pan 已提交
147 148 149 150 151 152 153 154 155 156 157 158 159 160
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;
}

std::map<ir::Node *, std::unordered_set<ir::Node *>> BuildAdjList(
    const std::vector<ir::Node*> &nodes) {
X
Xin Pan 已提交
161 162 163 164
  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 已提交
165 166
    if (adj_list.find(n) == adj_list.end()) {
      adj_list[n] = std::unordered_set<ir::Node *>();
X
Xin Pan 已提交
167 168 169 170
    }
    for (auto &var : n->inputs) {
      for (auto &adj_n : var->inputs) {
        PADDLE_ENFORCE(adj_n->NodeType() == ir::Node::Type::kOperation);
X
better  
Xin Pan 已提交
171
        adj_list[n].insert(adj_n);
X
Xin Pan 已提交
172
        LOG(ERROR) << "adj " << adj_n->Name() << reinterpret_cast<void *>(adj_n)
X
better  
Xin Pan 已提交
173
                   << " -> " << n->Name() << reinterpret_cast<void *>(n)
X
Xin Pan 已提交
174 175 176 177
                   << "  via " << var->Name() << reinterpret_cast<void *>(var);
      }
    }
  }
X
better  
Xin Pan 已提交
178 179
  return adj_list;
}
X
Xin Pan 已提交
180

X
better  
Xin Pan 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
std::vector<ir::Node *> TopologySortOperationFromInToOut(
    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 =
BuildAdjList(tmp);

  PADDLE_ENFORCE(!HasCircle(adj_list));
  std::vector<ir::Node*> ret = TopologySort(adj_list);

  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 已提交
204 205 206
    }
  }

X
better  
Xin Pan 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
  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 已提交
222 223 224 225
  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 已提交
226 227
                       [n](ir::Node *t) {
                         return t->Name() == ir::Node::kControlDepVarName; }),
X
Xin Pan 已提交
228 229 230
        n->inputs.end());
    n->outputs.erase(
        std::remove_if(n->outputs.begin(), n->outputs.end(),
X
better  
Xin Pan 已提交
231 232
                       [n](ir::Node *t) {
                         return t->Name() == ir::Node::kControlDepVarName; }),
X
Xin Pan 已提交
233 234 235
        n->outputs.end());
  }
  return ret;
X
better  
Xin Pan 已提交
236
}*/
X
Xin Pan 已提交
237

X
Xin Pan 已提交
238
}  // namespace framework
X
start  
Xin Pan 已提交
239
}  // namespace paddle