memory_optimize_helper.h 5.6 KB
Newer Older
D
dzhwinter 已提交
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 <algorithm>
#include <iostream>
#include <iterator>
#include <list>
D
dzhwinter 已提交
20 21
#include <map>
#include <set>
D
dzhwinter 已提交
22
#include <string>
23
#include <unordered_map>
Z
Zeng Jinle 已提交
24
#include <unordered_set>
D
dzhwinter 已提交
25 26 27 28 29 30 31
#include <utility>
#include <vector>
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/ir/graph.h"

namespace paddle {
namespace framework {
32
namespace ir {
D
dzhwinter 已提交
33

Z
Zeng Jinle 已提交
34 35 36 37 38
/// this attribute is used to avoid some core variables removed/reused
/// in memory optimize related passes
constexpr char kMemOptSkipVars[] = "@MEM_OPT_SKIP_VARS@";
typedef std::unordered_set<std::string> MemOptSkipVars;

39 40
constexpr char kUseCuda[] = "use_cuda";

D
dzhwinter 已提交
41
std::vector<ir::Node*> SortOpLikeDescOrder(const ir::Graph& graph);
D
dzhwinter 已提交
42

D
dzhwinter 已提交
43 44 45 46 47 48 49 50 51 52
// NOTE(dzh): A ordered set for node reuse in memory optimize.
// the orderedset sort node in ascend order(by node bytes size).
// in fluid, -1 means the batch_size, which is determined in runtime.
// So the reuse happens between nodes who's batch_size both are -1
// simultaneously or not.
//
// sort rule:
// rule 0 : smaller node ranking in front.
// rule 1 : batch_size equal -1 ranking in the front than the node not.
//
D
dzhwinter 已提交
53 54 55
// For example,
// node0[-1, 1] node1[-1, 1, 1], node2[1,1], node3[1,1024], ..

D
dzhwinter 已提交
56 57 58 59 60 61
class OrderedSet {
 public:
  // nodes with same name exists in pool.
  using NodeVector = std::vector<ir::Node*>;
  using Iter = typename std::list<NodeVector>::iterator;
  using ConstIter = typename std::list<NodeVector>::const_iterator;
D
dzhwinter 已提交
62

D
dzhwinter 已提交
63
  void Insert(ir::Node* var);
D
dzhwinter 已提交
64
  void Erase(ir::Node* var);
65
  void Erase(const std::string& var);
D
dzhwinter 已提交
66 67 68 69 70 71 72
  bool Has(ir::Node* var) const;
  void Clear() {
    mark_table_.clear();
    nodes_.clear();
  }
  // find the bestfit shape node block with var.
  ir::Node* FindBestFitNode(ir::Node* var) const;
D
dzhwinter 已提交
73
  ir::Node* FindNextBestFitNode(ir::Node* var, ir::Node* prev) const;
D
dzhwinter 已提交
74
  // map store non-const iterator, can not promise const
D
dzhwinter 已提交
75
  int GetNodeIndexInPool(ir::Node* var);
D
dzhwinter 已提交
76 77 78 79 80 81 82 83
  // pool all node to string
  std::string ToString() const;

  Iter begin() { return nodes_.begin(); }
  Iter end() { return nodes_.end(); }
  ConstIter begin() const { return nodes_.begin(); }
  ConstIter end() const { return nodes_.end(); }

D
dzhwinter 已提交
84
  size_t size() const { return nodes_.size(); }
D
dzhwinter 已提交
85

D
dzhwinter 已提交
86 87 88
 private:
  // for searching.
  std::unordered_map<std::string, Iter> mark_table_;
D
dzhwinter 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
  // node pool
  std::list<NodeVector> nodes_;
};

class ControlFlowGraph {
 public:
  ControlFlowGraph() = default;
  // IR Graph
  explicit ControlFlowGraph(const ir::Graph& graph);

  void LiveVariableAnalysis();

  void RenameVarInCFGGraph(const std::string& old_node,
                           const std::string& new_node, int begin_idx);

D
dzhwinter 已提交
104 105 106 107 108
  const std::set<std::string>& LiveIn(ir::Node* op) const;
  const std::set<std::string>& LiveOut(ir::Node* op) const;
  const std::set<std::string>& Use(ir::Node* op) const;
  const std::set<std::string>& Unlived(ir::Node* op) const;
  const std::vector<ir::Node*>& Ops() const;
D
dzhwinter 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
  std::vector<ir::Node*>& Ops();

  // for ssa-graph nodes
  ir::Node* GetNodeByName(const std::string& name, ir::Node* op) const;

 private:
  void BuildCFGGraph();
  void ConnectNodes();

  using NodeListMap = std::unordered_map<ir::Node*, std::set<ir::Node*>>;
  using VarSetMap = std::map<ir::Node*, std::set<std::string>>;
  // successors ops use the output variables.
  NodeListMap successors_;
  // predecessors ops generated input variables.
  NodeListMap predecessors_;
  // variables lived before run current op.
  VarSetMap live_in_;
  // variables lived after run current op.
  VarSetMap live_out_;
  VarSetMap uses_;  // op inputs
  VarSetMap defs_;  // op outputs
D
dzhwinter 已提交
130
  std::unordered_map<ir::Node*, std::set<std::string>> unlived_vars_;
D
dzhwinter 已提交
131 132

  std::vector<ir::Node*> ops_;  // op sequence by topology sort
D
dzhwinter 已提交
133 134
};

D
dzhwinter 已提交
135 136 137
// valid a tensor can be reuse or not
bool NodeCanReused(ir::Node* node);

D
dzhwinter 已提交
138 139 140
// valid a tensor can be reuse or not.
bool NodeCanReused(const VarDesc& node);

D
dzhwinter 已提交
141 142 143
// check op has subblock or not
bool OpHasSubBlock(OpDesc* desc);

D
dzhwinter 已提交
144
// node memory size in bytes
D
dzhwinter 已提交
145
size_t NodeSize(ir::Node* n);
D
dzhwinter 已提交
146

D
dzhwinter 已提交
147
// node memory size in bytes
D
dzhwinter 已提交
148
size_t NodeSize(const VarDesc&);
D
dzhwinter 已提交
149

D
dzhwinter 已提交
150 151
std::string DebugString(ir::Node* var);

152
VarDesc* GetVarDesc(ir::Node* n);
D
dzhwinter 已提交
153

D
dzhwinter 已提交
154 155 156 157 158
static inline bool IsSameDesc(OpDesc* op1, OpDesc* op2) {
  return op1->Type() == op2->Type() && op1->Inputs() == op2->Inputs() &&
         op1->Outputs() == op2->Outputs();
}

D
dzhwinter 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
template <typename Container, typename Callback>
class FilterVariableImpl {
 public:
  void operator()(const Container& nodes, Callback callback) {
    for (auto* node : nodes) {
      callback(node);
    }
  }
};

// filter var node for op->inputs/outputs
template <typename Callback>
class FilterVariableImpl<std::vector<ir::Node*>, Callback> {
 public:
  void operator()(const std::vector<ir::Node*>& nodes, Callback callback) {
    for (auto* var : nodes) {
      if (var->IsVar() && !var->IsCtrlVar()) {
        callback(var);
      }
    }
  }
};

template <typename Container, typename Callback>
void FilterVariables(const Container& nodes, Callback callback) {
  FilterVariableImpl<Container, Callback>()(nodes, callback);
}

187
}  // namespace ir
D
dzhwinter 已提交
188 189
}  // namespace framework
}  // namespace paddle