graph.h 7.7 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.

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

#pragma once

#include <map>
#include <memory>
#include <string>
20
#include <unordered_set>
S
sneaxiy 已提交
21 22 23 24 25 26 27 28 29
#include <vector>

#include "paddle/fluid/framework/ir/node.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/variant.h"

namespace paddle {
namespace framework {
Y
Yancey1989 已提交
30 31

namespace details {
Y
Yancey1989 已提交
32 33 34

// This attr is not recommended, because the graph should not dependence
// the program once it is built.
X
Xin Pan 已提交
35
constexpr char kStaleProgramOpDescs[] = "stale_program_op_descs";
Y
Yancey1989 已提交
36 37
}  //  namespace details

S
sneaxiy 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
namespace ir {

/*
 * The graph is a Directed Acyclic Single Static Assignment Graph.
 *
 * In more detail, the following properties must hold:
 *
 *   The graph shouldn't contain cycle. Each node is a black-box to the graph
 *   so the node itself could be a loop operator.
 *
 *   Each Variable-type node has only one input (thus single static assignment).
 *
 *   The output/input of operator is variable and the output/input of variable
 *   is operator.
 *
 * The following data harzards in Program are addressed in the Graph:
 *
 *   Write-After-Read
 *     a = op1(x)
 *     x = op2(b)
 *     A control-dependency connection is created bettwen op1 and op2 such that
 *     op1->op2, so as to ensure correct order.
 *
 *   Write-After-Write
 *     x = op1(a)
 *     x = op2(b)
 *     A control-dependency connection is created between op1 and op2 such that
 *     op1->op2, so as to ensure correct order.
 *
 * Other properties currently hold, but is not enforced yet:
 *
 *   Variable-type node (not control dep) with the same variable name share
 *   the same underlying VarDesc.
 */
class Graph {
 public:
  explicit Graph(const ProgramDesc &program);

  virtual ~Graph() {
    for (auto &attr : attrs_) {
      attr_dels_[attr.first]();
    }
    attrs_.clear();
    attr_dels_.clear();
  }

  bool Has(const std::string &attr_name) const {
S
sneaxiy 已提交
85
    return attrs_.count(attr_name) > 0;
S
sneaxiy 已提交
86 87
  }

88 89 90 91 92 93 94 95
  template <typename AttrType>
  AttrType &GetOrInit(const std::string &attr_name) {
    if (!Has(attr_name)) {
      Set(attr_name, new AttrType);
    }
    return Get<AttrType>(attr_name);
  }

S
sneaxiy 已提交
96 97
  template <typename AttrType>
  AttrType &Get(const std::string &attr_name) const {
98 99
    PADDLE_ENFORCE_EQ(Has(attr_name), true, "%s attr not registered for graph.",
                      attr_name);
S
sneaxiy 已提交
100 101 102 103 104 105 106 107
    try {
      return *boost::any_cast<AttrType *>(attrs_.at(attr_name));
    } catch (boost::bad_any_cast &) {
      PADDLE_THROW(
          "Invalid attribute type of %s error, expected: %s, actual: %s",
          attr_name, typeid(AttrType *).name(),
          attrs_.at(attr_name).type().name());
    }
S
sneaxiy 已提交
108 109 110 111
  }

  template <typename AttrType>
  void Set(const std::string &attr_name, AttrType *attr) {
112 113 114 115
    PADDLE_ENFORCE_EQ(
        attrs_.count(attr_name), 0,
        platform::errors::AlreadyExists(
            "The attribute %s has been set in the graph.", attr_name));
S
sneaxiy 已提交
116 117
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = [attr, attr_name]() {
M
minqiyang 已提交
118
      VLOG(3) << "deleting " << attr_name;
S
sneaxiy 已提交
119 120 121 122 123 124
      delete attr;
    };
  }

  template <typename AttrType>
  void SetNotOwned(const std::string &attr_name, AttrType *attr) {
125 126 127 128
    PADDLE_ENFORCE_EQ(
        attrs_.count(attr_name), 0,
        platform::errors::AlreadyExists(
            "The attribute %s has been set in the graph.", attr_name));
S
sneaxiy 已提交
129 130 131 132
    attrs_[attr_name] = attr;
    attr_dels_[attr_name] = []() {};
  }

X
Xin Pan 已提交
133
  void Erase(const std::string &attr_name) {
134 135 136 137
    PADDLE_ENFORCE_NE(
        attrs_.count(attr_name), 0,
        platform::errors::NotFound(
            "The attribute %s has not been set in the graph.", attr_name));
X
Xin Pan 已提交
138 139 140 141 142
    attr_dels_[attr_name]();
    attrs_.erase(attr_name);
    attr_dels_.erase(attr_name);
  }

S
sneaxiy 已提交
143 144 145 146
  const std::unordered_set<ir::Node *> &Nodes() const { return node_set_; }

  // Create a normal variable with non-null VarDesc.
  ir::Node *CreateVarNode(VarDesc *var_desc) {
147
    PADDLE_ENFORCE_NOT_NULL(var_desc);
148 149 150
    auto *x = AddNode(new ir::Node(var_desc));
    x->SetId(num_node_created_++);
    return x;
S
sneaxiy 已提交
151 152 153 154
  }

  // Create a normal runnable operator with OpDesc.
  ir::Node *CreateOpNode(OpDesc *op_desc) {
155
    PADDLE_ENFORCE_NOT_NULL(op_desc);
156 157 158
    auto *x = AddNode(new ir::Node(op_desc));
    x->SetId(num_node_created_++);
    return x;
S
sneaxiy 已提交
159 160 161 162 163 164 165 166
  }

  // Create a control dependency var that connects 2 operations. The
  // var doesn't hold any data. Other than that, it's no different from
  // other var, considering dependency analysis.
  ir::Node *CreateControlDepVar() {
    // TODO(panyx0718): control var name should be really unique.
    const std::string name = string::Sprintf(
167
        "%s@%llu", static_cast<const char *>(ir::Node::kControlDepVarName),
D
Dun Liang 已提交
168
        num_node_created_);
169 170 171
    auto *x = AddNode(new ir::Node(name, ir::Node::Type::kVariable));
    x->SetId(num_node_created_++);
    return x;
S
sneaxiy 已提交
172 173 174 175 176
  }

  // A more free style way of creating a graph node. Mostly use for test
  // or "copy" from another node. Avoid using it if possible.
  ir::Node *CreateEmptyNode(const std::string &name, ir::Node::Type type) {
177 178 179
    auto *x = AddNode(new ir::Node(name, type));
    x->SetId(num_node_created_++);
    return x;
S
sneaxiy 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193
  }

  // Clear all node information of the graph and return the ownership of the
  // nodes.
  std::vector<std::unique_ptr<ir::Node>> ReleaseNodes() {
    std::vector<std::unique_ptr<ir::Node>> ret;
    for (auto &n : nodes_) {
      ret.emplace_back(n.second.release());
    }
    nodes_.clear();
    node_set_.clear();
    return ret;
  }

Y
Yancey1989 已提交
194
  std::unique_ptr<ir::Node> RemoveNode(ir::Node *node) {
195
    PADDLE_ENFORCE_EQ(node_set_.find(node) != node_set_.end(), true);
Y
Yancey1989 已提交
196 197 198 199 200 201 202
    std::unique_ptr<ir::Node> ret;
    ret.reset(nodes_.at(node).release());
    nodes_.erase(node);
    node_set_.erase(node);
    return ret;
  }

S
sneaxiy 已提交
203
  // NOTE low performance, but simple and secure.
204
  Node *RetrieveNode(int id) {
S
sneaxiy 已提交
205 206 207 208 209 210 211 212
    for (auto &node : nodes_) {
      if (node.second->id() == id) {
        return node.second.get();
      }
    }
    return nullptr;
  }

X
fix  
Xin Pan 已提交
213 214 215 216
  // Returns reference to the original program.
  // WARN: After a series of passes, the current graph can be quite
  // different from OriginProgram. Caller shouldn't assume much from
  // the returned OriginProgram.
217
  const ProgramDesc &OriginProgram() const { return program_; }
X
fix  
Xin Pan 已提交
218

S
sneaxiy 已提交
219 220
  // This method takes ownership of `node`.
  ir::Node *AddNode(ir::Node *node) {
221
    PADDLE_ENFORCE_EQ(node_set_.find(node) == node_set_.end(), true);
S
sneaxiy 已提交
222 223 224 225 226
    nodes_[node].reset(node);
    node_set_.insert(node);
    return node;
  }

Y
Yancey1989 已提交
227 228 229
  void ResolveHazard(
      const std::map<std::string, std::vector<ir::Node *>> &var_nodes);

230 231 232 233
  // Create a new and duplicated graph.
  // WARN: The method only clones the graph structure, not its attributes.
  std::shared_ptr<Graph> Clone();

Y
Yancey1989 已提交
234 235 236 237
 private:
  std::map<std::string, std::vector<ir::Node *>> InitFromProgram(
      const ProgramDesc &program);

S
sneaxiy 已提交
238 239 240 241 242 243
  // NOTE: program_ shouldn't be exposed to user.
  const ProgramDesc program_;
  std::map<std::string, boost::any> attrs_;
  std::map<std::string, std::function<void(void)>> attr_dels_;
  std::map<ir::Node *, std::unique_ptr<ir::Node>> nodes_;
  std::unordered_set<ir::Node *> node_set_;
244
  size_t num_node_created_{0};  // help to generate a unique node id.
S
sneaxiy 已提交
245 246 247 248 249 250
};

bool IsControlDepVar(const ir::Node &var);
}  // namespace ir
}  // namespace framework
}  // namespace paddle