memory_optimize_helper.cc 15.9 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// 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.

D
dzhwinter 已提交
15
#include "paddle/fluid/framework/details/memory_optimize_helper.h"
16 17
#include <algorithm>
#include <deque>
D
dzhwinter 已提交
18
#include <functional>
19
#include <iterator>
D
dzhwinter 已提交
20
#include <numeric>
D
dzhwinter 已提交
21 22
#include <sstream>
#include <string>
23 24 25 26 27 28
#include "paddle/fluid/framework/var_desc.h"
#include "paddle/fluid/platform/cpu_info.h"

#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/gpu_info.h"
#endif  // PADDLE_WITH_CUDA
D
dzhwinter 已提交
29 30 31 32

namespace paddle {
namespace framework {
namespace details {
33 34 35 36 37 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 85 86 87 88 89 90 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
using paddle::framework::VarDesc;

std::vector<ir::Node*> SortOpLikeDescOrder(const ir::Graph& graph) {
  PADDLE_ENFORCE(graph.Has(kAllOpDescs),
                 "Graph has no attribute of kAllOpDescs.");
  // 1. get op desc order
  auto& op_descs = graph.Get<const std::vector<OpDesc*>>(kAllOpDescs);

  // 2. topology sort order
  auto nodes = graph.Nodes();
  std::deque<ir::Node*> ops;
  FilterVariables(nodes, [&](ir::Node* op) {
    if (op->IsOp() && op->Op() != nullptr) {
      ops.emplace_back(op);
    }
  });
  std::unordered_map<ir::Node*, size_t> op_deps;
  std::list<ir::Node*> ready_ops;
  std::unordered_map<ir::Node*, std::unordered_set<ir::Node*>> pending_ops;

  for (auto* op : ops) {
    std::unordered_set<ir::Node*> preceding_op;
    for (auto* in : op->inputs) {
      if (in->inputs.empty()) continue;
      PADDLE_ENFORCE(in->inputs.size() == 1 && in->inputs[0]->IsOp());
      preceding_op.emplace(in->inputs[0]);
      pending_ops[in->inputs[0]].emplace(op);
    }
    op_deps[op] = preceding_op.size();
    if (preceding_op.empty()) {
      ready_ops.emplace_back(op);
    }
  }

  // 3. generated op list based desc order and the topology order
  std::vector<ir::Node*> ret;
  std::list<OpDesc*> op_descs_list(op_descs.begin(), op_descs.end());

  auto update_by_found_node = [&](ir::Node* found_node) {
    for (auto* pending_op : pending_ops[found_node]) {
      if (--op_deps[pending_op] == 0) {
        ready_ops.emplace_back(pending_op);
      }
    }
    ready_ops.remove(found_node);
    ret.emplace_back(found_node);
  };

  while (!ready_ops.empty()) {
    bool all_of_ready_op_unmatched = true;
    for (auto it = op_descs_list.begin(); it != op_descs_list.end();) {
      auto op_desc = *it;
      ir::Node* found_node = nullptr;
      for (auto* op : ready_ops) {
        if (IsSameDesc(op->Op(), op_desc)) {
          found_node = op;
          break;
        }
      }

      // 3.1 op desc deleted by other pass
      if (found_node == nullptr) {
        ++it;
        continue;
      } else {
        all_of_ready_op_unmatched = false;
        it = op_descs_list.erase(it);
      }
      update_by_found_node(found_node);
    }

    // 3.2 op descs are added by other pass
    // preceding op non empty means some new op descs are
    // created, but not contained in return node list.
    // these new op desc may depend on each other.
    std::list<ir::Node*> prev_ready_ops(ready_ops);
    if (all_of_ready_op_unmatched) {
      for (auto op : prev_ready_ops) {
        update_by_found_node(op);
      }
    }
  }

  PADDLE_ENFORCE(std::all_of(
      op_deps.begin(), op_deps.end(),
      [&](const std::pair<ir::Node*, size_t>& p) { return p.second == 0; }));

  return ret;
}
D
dzhwinter 已提交
122

123
size_t NodeSize(const VarDesc& node) {
D
dzhwinter 已提交
124 125 126 127 128 129 130
  auto shape = node.GetShape();
  int size =
      std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>());
  size_t type_size = SizeOfType(node.GetDataType());
  return type_size * std::abs(size);
}

131
size_t NodeSize(ir::Node* n) {
D
dzhwinter 已提交
132
  auto* desc = FindVarDescInBlock(n);
133
  return NodeSize(*desc);
D
dzhwinter 已提交
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 172 173 174
}

std::string DebugStringImpl(VarDesc* var) {
  std::stringstream ss;
  ss << var->Name();
  ss << "[";
  try {
    auto shape = var->GetShape();
    for (size_t i = 0; i < shape.size(); ++i) {
      if (i != shape.size() - 1) {
        ss << shape[i] << ",";
      } else {
        ss << shape[i];
      }
    }
    ss << "]";
  } catch (...) {
    ss << "Var has no VarDesc !!! Name:" << var->Name();
  }
  return ss.str();
}

std::string DebugString(ir::Node* var) {
  return DebugStringImpl(FindVarDescInBlock(var));
}

// NOTE(dzh): based ir node, if a large node has been reused
// by a small size node, then next time it appear in pool, it will
// have the small size. Find the original node shap from blockdesc.
VarDesc* FindVarDescInBlock(ir::Node* n) {
  PADDLE_ENFORCE(n->IsVar() && !n->IsCtrlVar() && n->inputs.size() == 1);
  BlockDesc* block = n->inputs[0]->Op()->Block();
  PADDLE_ENFORCE(block->HasVar(n->Name()),
                 string::Sprintf("Block do not has var %s", n->Name()));
  return block->FindVar(n->Name());
}

struct NodeComparator {
  bool operator()(ir::Node* lhs, ir::Node* rhs) const {
    auto* lhs_desc = FindVarDescInBlock(lhs);
    auto* rhs_desc = FindVarDescInBlock(rhs);
175 176 177 178 179
    // match data type
    if (lhs_desc->GetDataType() != rhs_desc->GetDataType()) {
      return false;
    }
    // match shape
D
dzhwinter 已提交
180 181 182 183
    auto lhs_shape = lhs_desc->GetShape();
    auto rhs_shape = rhs_desc->GetShape();
    if ((lhs_shape[0] == -1 && rhs_shape[0] == -1) ||
        (lhs_shape[0] != -1 && rhs_shape[0] != -1)) {
184
      return NodeSize(lhs) <= NodeSize(rhs);
D
dzhwinter 已提交
185 186 187 188 189 190
    } else {
      return false;
    }
  }
};

191
void OrderedSet::Insert(ir::Node* var) {
D
dzhwinter 已提交
192 193
  PADDLE_ENFORCE(var->IsVar() && !var->IsCtrlVar());
  if (mark_table_.count(var->Name()) != 0) {
194
    mark_table_[var->Name()]->emplace_back(var);
D
dzhwinter 已提交
195 196 197 198 199 200 201
    return;
  }

  auto* var_desc = FindVarDescInBlock(var);
  auto var_shape = var_desc->GetShape();
  int batch_size = static_cast<int>(var_shape[0]);

202
  NodeComparator functor;
D
dzhwinter 已提交
203 204
  Iter it = nodes_.begin();
  while (it != nodes_.end()) {
205 206
    auto& prev = it->front();
    auto* cache_desc = FindVarDescInBlock(prev);
D
dzhwinter 已提交
207 208 209
    int cache_batch_size = cache_desc->GetShape()[0];
    if ((cache_batch_size == -1 && batch_size == -1) ||
        (cache_batch_size != -1 && batch_size != -1)) {
210
      if (functor(prev, var)) {
D
dzhwinter 已提交
211 212 213 214 215 216 217 218 219 220 221
        ++it;
      } else {
        break;
      }
    } else if (cache_batch_size == -1 && batch_size != -1) {
      ++it;
    } else if (cache_batch_size != -1 && batch_size == -1) {
      break;
    }
  }

222
  it = nodes_.insert(it, {var});
D
dzhwinter 已提交
223 224 225
  mark_table_[var->Name()] = it;
}

226
int OrderedSet::GetNodeIndexInPool(ir::Node* var) {
D
dzhwinter 已提交
227 228 229
  return std::distance(nodes_.begin(), mark_table_[var->Name()]);
}

230
ir::Node* OrderedSet::FindBestFitNode(ir::Node* var) const {
D
dzhwinter 已提交
231
  ir::Node* found_node = nullptr;
232
  NodeComparator functor;
D
dzhwinter 已提交
233 234

  for (auto it = nodes_.begin(); it != nodes_.end(); ++it) {
235 236 237
    auto& candidate = it->front();
    if (functor(var, candidate)) {
      found_node = candidate;
D
dzhwinter 已提交
238 239 240 241 242 243
      break;
    }
  }
  return found_node;
}

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
ir::Node* OrderedSet::FindNextBestFitNode(ir::Node* var, ir::Node* prev) const {
  ir::Node* found_node = nullptr;
  NodeComparator functor;
  auto it =
      std::find_if(nodes_.begin(), nodes_.end(), [&](const NodeVector& v) {
        if (v.front() == prev)
          return true;
        else
          return false;
      });
  PADDLE_ENFORCE(it != nodes_.end(), "Not found previous in node list!");
  for (it = std::next(it); it != nodes_.end(); ++it) {
    auto& candidate = it->front();
    if (functor(var, candidate)) {
      found_node = candidate;
      break;
    }
  }
  return found_node;
}

bool OrderedSet::Has(ir::Node* var) const {
  if (mark_table_.count(var->Name())) {
    auto& node_in_samename = mark_table_.at(var->Name());
    auto iter =
        std::find_if(node_in_samename->begin(), node_in_samename->end(),
                     [&](ir::Node* n) { return n->Name() == var->Name(); });
    return iter != node_in_samename->end();
  }
  return false;
}
D
dzhwinter 已提交
275

276
void OrderedSet::Erase(const std::string& var) {
D
dzhwinter 已提交
277 278 279
  PADDLE_ENFORCE(mark_table_.count(var));
  nodes_.erase(mark_table_[var]);
  mark_table_.erase(var);
D
dzhwinter 已提交
280 281
}

282 283 284 285 286 287
void OrderedSet::Erase(ir::Node* var) {
  PADDLE_ENFORCE(var != nullptr);
  Erase(var->Name());
}

std::string OrderedSet::ToString() const {
D
dzhwinter 已提交
288 289
  std::stringstream ss;
  for (auto it = nodes_.begin(); it != nodes_.end(); ++it) {
290 291 292
    for (auto& node : *it) {
      ss << DebugString(node) << " ";
    }
D
dzhwinter 已提交
293 294 295 296
  }
  return ss.str();
}

D
dzhwinter 已提交
297
bool NodeCanReused(ir::Node* node) {
298
  // valid the node is a var node
D
dzhwinter 已提交
299
  if (node == nullptr || !node->IsVar() || node->IsCtrlVar()) return false;
300 301 302

  bool flag = true;
  // op output force generated in cpu, can not be reused.
D
dzhwinter 已提交
303 304
  for (auto* op : node->inputs) {
    if (op->Op()->HasAttr("force_cpu")) {
D
dzhwinter 已提交
305 306
      flag &= framework::AttrReader(op->Op()->GetAttrMap())
                  .Get<bool>("force_cpu") == 0;
D
dzhwinter 已提交
307 308
    }
  }
309 310
  // var desc validation.
  flag &= NodeCanReused(*node->Var());
D
dzhwinter 已提交
311 312 313
  return flag;
}

314 315 316 317 318 319 320 321 322 323
int MinChunkSize() {
  int size{0};
#ifdef PADDLE_WITH_CUDA
  size = platform::GpuMinChunkSize();
#else
  size = platform::CpuMinChunkSize();
#endif  // PADDLE_WITH_CUDA
  return size;
}

D
dzhwinter 已提交
324 325
bool NodeCanReused(const VarDesc& node) {
  auto type = node.GetType();
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
  // only these types holds bulk of gpu memory
  if (!(type == proto::VarType::LOD_TENSOR ||
        type == proto::VarType::SELECTED_ROWS ||
        type == proto::VarType::LOD_TENSOR_ARRAY)) {
    return false;
  }
  // persistable variable is parameter
  if (node.Persistable()) {
    return false;
  }
  // shape < min_chunk_size is meaningless.
  // further more, fetched loss always has size = 1
  // which should not be reused.
  auto shape = node.GetShape();
  int size = std::abs(
      std::accumulate(shape.begin(), shape.end(), 1, std::multiplies<int>()));
  if (shape.empty() || size < MinChunkSize()) {
D
dzhwinter 已提交
343 344 345 346 347 348
    return false;
  }
  // vars can be @EMPTY@, @LR_DECAY_REUSE_ID@. For example, while_grad
  std::string name = node.Name();
  if (!name.empty() && name[0] == '@' && name[name.size() - 1] == '@')
    return false;
D
dzhwinter 已提交
349 350 351 352 353 354 355 356 357 358 359 360 361
  return true;
}

bool OpHasSubBlock(OpDesc* desc) {
  const AttributeMap& attrs = desc->GetAttrMap();
  for (auto& attr : attrs) {
    if (attr.second.type() == typeid(BlockDesc*) ||             // NOLINT
        attr.second.type() == typeid(std::vector<BlockDesc*>))  // NOLINT
      return true;
  }
  return false;
}

362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
ControlFlowGraph::ControlFlowGraph(const ir::Graph& graph) {
  ops_ = SortOpLikeDescOrder(graph);
  ConnectNodes();
}

void ControlFlowGraph::BuildCFGGraph() {
  // FIXME(dzh): same effect with ConnectNodes, but use the control
  // link to build dependency graph, it goes wrong in transformer.
  for (ir::Node* op : ops_) {
    for (auto& input_var : op->inputs) {
      if (!input_var->inputs.empty()) {
        PADDLE_ENFORCE(
            input_var->inputs.size() == 1 && input_var->inputs[0]->IsOp(),
            "Preceding Op Node of Var Node must be unique");
        auto* pred_op = input_var->inputs[0];
        if (pred_op->Op() != nullptr) {
          predecessors_[op].insert(pred_op);
          successors_[pred_op].insert(op);
        }
      }
      if (input_var->IsVar() && !input_var->IsCtrlVar()) {
        uses_[op].insert(input_var->Name());
      }
    }
    for (auto& output_var : op->outputs) {
      // output var may be used by many op
      for (auto* succ_op : output_var->outputs) {
        if (succ_op->Op() != nullptr) {
          successors_[op].insert(succ_op);
          predecessors_[succ_op].insert(op);
        }
      }
      if (output_var->IsVar() && !output_var->IsCtrlVar()) {
        defs_[op].insert(output_var->Name());
      }
    }
  }
}

void ControlFlowGraph::ConnectNodes() {
  for (size_t i = 0; i < ops_.size(); ++i) {
    auto& op = ops_[i];
    try {
      auto& next_op = ops_.at(i + 1);
      successors_[op].insert(next_op);
      predecessors_[next_op].insert(op);
    } catch (...) {
      // do nothing
    }

    FilterVariables(op->inputs,
                    [&](ir::Node* var) { uses_[op].emplace(var->Name()); });

    FilterVariables(op->outputs,
                    [&](ir::Node* var) { defs_[op].emplace(var->Name()); });
  }
}

void ControlFlowGraph::LiveVariableAnalysis() {
  // NOTE(dzh): variable liveless analysis (a.k.a reversed_ops algorithm)
  // compute the liveness of for each variable though reversed_ops algorithm.
  // It iterates the operators from end to begin, compute the live in/live out
  // variable set for each op, then the diff between in/out will be used for
  // the variable reuse. For detail refer to
  // http://www.cs.cornell.edu/courses/cs4120/2013fa/lectures/lec26-fa13.pdf
  std::list<ir::Node*> work_list(ops_.rbegin(), ops_.rend());
  while (!work_list.empty()) {
    ir::Node* op = work_list.front();
    work_list.pop_front();
    // get the live_in calculated before. Empty if first.
    auto prev_live_in = std::move(live_in_[op]);
    for (auto& s : successors_[op]) {
      for (auto& var : live_in_[s]) {
        live_out_[op].insert(var);
      }
    }
    for (auto& var : uses_[op]) {
      live_in_[op].insert(var);
    }
    for (auto& var : live_out_[op]) {
      live_in_[op].insert(var);
    }
    for (auto& var : defs_[op]) {
      live_in_[op].erase(var);
    }

    // If the live_in is not changed, then the liveness analysis of
    // predecessors is completed.
    //
    // Otherwise, recalculate the predecessors liveness
    if (live_in_[op] != prev_live_in) {
      for (auto& pre : predecessors_[op]) {
        work_list.push_back(pre);
      }
    }
  }
}

void ControlFlowGraph::RenameVarInCFGGraph(const std::string& old_node,
                                           const std::string& new_node,
                                           int begin_idx) {
  // update graph from begin idx to the end
  for (size_t i = begin_idx; i != ops_.size(); ++i) {
    auto* op = ops_[i];
    if (uses_[op].find(old_node) != uses_[op].end()) {
      uses_[op].erase(old_node);
      uses_[op].insert(new_node);
    }
    if (defs_[op].find(old_node) != defs_[op].end()) {
      defs_[op].erase(old_node);
      defs_[op].insert(new_node);
    }
    if (live_in_[op].find(old_node) != live_in_[op].end()) {
      live_in_[op].erase(old_node);
      live_in_[op].insert(new_node);
    }
    if (live_out_[op].find(old_node) != live_out_[op].end()) {
      live_out_[op].erase(old_node);
      live_out_[op].insert(new_node);
    }
  }
}

const std::set<std::string> ControlFlowGraph::LiveIn(ir::Node* op) const {
  auto it = live_in_.find(op);
  PADDLE_ENFORCE(
      it != live_in_.end(),
      string::Sprintf("Expect %s in live_in, but Not Found.", op->Name()));
  return it->second;
}

const std::set<std::string> ControlFlowGraph::LiveOut(ir::Node* op) const {
  auto it = live_out_.find(op);
  PADDLE_ENFORCE(
      it != live_out_.end(),
      string::Sprintf("Expect %s in live_out, but Not Found.", op->Name()));
  return it->second;
}

const std::set<std::string> ControlFlowGraph::Use(ir::Node* op) const {
  auto it = uses_.find(op);
  PADDLE_ENFORCE(
      it != uses_.end(),
      string::Sprintf("Expect %s in live_out, but Not Found.", op->Name()));
  return it->second;
}

const std::vector<ir::Node*> ControlFlowGraph::Ops() const { return ops_; }

std::vector<ir::Node*>& ControlFlowGraph::Ops() { return ops_; }

ir::Node* ControlFlowGraph::GetNodeByName(const std::string& name,
                                          ir::Node* op) const {
  // in ssa-graph, different version nodes have same name,
  // this function get the latest version var before target op
  // It may return nullptr, such as data node.
  ir::Node* found_node = nullptr;
  for (auto* node : ops_) {
    if (node == op) break;
    for (auto& output : node->outputs) {
      PADDLE_ENFORCE((output != nullptr && output->IsVar()),
                     "Output is empty!");
      if (output->Var() && output->Name() == name) {
        found_node = output;
      }
    }
  }
  return found_node;
}

D
dzhwinter 已提交
532 533 534
}  // namespace details
}  // namespace framework
}  // namespace paddle