memory_optimize_helper.cc 16.8 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"
D
dzhwinter 已提交
16
#include <algorithm>
D
dzhwinter 已提交
17
#include <deque>
D
dzhwinter 已提交
18
#include <functional>
D
dzhwinter 已提交
19
#include <iterator>
D
dzhwinter 已提交
20
#include <numeric>
D
dzhwinter 已提交
21 22
#include <sstream>
#include <string>
23 24 25
#include <unordered_map>
#include <unordered_set>
#include "paddle/fluid/framework/operator.h"
D
dzhwinter 已提交
26
#include "paddle/fluid/framework/var_desc.h"
D
dzhwinter 已提交
27 28 29 30 31
#include "paddle/fluid/platform/cpu_info.h"

#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/gpu_info.h"
#endif  // PADDLE_WITH_CUDA
D
dzhwinter 已提交
32 33 34 35

namespace paddle {
namespace framework {
namespace details {
D
dzhwinter 已提交
36
using paddle::framework::VarDesc;
D
dzhwinter 已提交
37

D
dzhwinter 已提交
38
std::vector<ir::Node*> SortOpLikeDescOrder(const ir::Graph& graph) {
X
Xin Pan 已提交
39 40
  PADDLE_ENFORCE(graph.Has(kStaleProgramOpDescs),
                 "Graph has no attribute of kStaleProgramOpDescs.");
D
dzhwinter 已提交
41
  // 1. get op desc order
X
Xin Pan 已提交
42
  auto& op_descs = graph.Get<const std::vector<OpDesc*>>(kStaleProgramOpDescs);
D
dzhwinter 已提交
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 122 123 124 125 126

  // 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;
}

size_t NodeSize(const VarDesc& node) {
D
dzhwinter 已提交
127 128 129 130 131 132 133
  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);
}

134
size_t NodeSize(ir::Node* n) { return NodeSize(*(n->Var())); }
D
dzhwinter 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

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) {
157
  return DebugStringImpl(GetVarDesc(var));
D
dzhwinter 已提交
158 159 160 161 162
}

// 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.
163
VarDesc* GetVarDesc(ir::Node* n) {
D
dzhwinter 已提交
164
  PADDLE_ENFORCE(n->IsVar() && !n->IsCtrlVar() && n->inputs.size() == 1);
165
  return n->Var();
D
dzhwinter 已提交
166 167 168 169
}

struct NodeComparator {
  bool operator()(ir::Node* lhs, ir::Node* rhs) const {
170 171 172
    if (lhs->Var()->GetType() != rhs->Var()->GetType()) return false;
    auto* lhs_desc = GetVarDesc(lhs);
    auto* rhs_desc = GetVarDesc(rhs);
173 174 175 176 177
    // match data type
    if (lhs_desc->GetDataType() != rhs_desc->GetDataType()) {
      return false;
    }
    // match shape
D
dzhwinter 已提交
178 179 180 181
    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)) {
L
liuwei1031 已提交
182
      return NodeSize(lhs) == NodeSize(rhs);
D
dzhwinter 已提交
183 184 185 186 187 188
    } else {
      return false;
    }
  }
};

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

196
  auto* var_desc = var->Var();
D
dzhwinter 已提交
197 198 199
  auto var_shape = var_desc->GetShape();
  int batch_size = static_cast<int>(var_shape[0]);

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

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

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

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

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

D
dzhwinter 已提交
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
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;
}

D
dzhwinter 已提交
263 264 265 266 267 268 269 270 271 272
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 已提交
273

274 275 276 277 278 279
void OrderedSet::Erase(const std::string& var) {
  PADDLE_ENFORCE(mark_table_.count(var));
  nodes_.erase(mark_table_[var]);
  mark_table_.erase(var);
}

D
dzhwinter 已提交
280
void OrderedSet::Erase(ir::Node* var) {
281 282
  PADDLE_ENFORCE(var != nullptr);
  Erase(var->Name());
D
dzhwinter 已提交
283 284
}

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

D
dzhwinter 已提交
295
bool NodeCanReused(ir::Node* node) {
D
dzhwinter 已提交
296
  // valid the node is a var node
297 298 299 300
  // vars can be @EMPTY@, @LR_DECAY_REUSE_ID@. For example, while_grad
  if (node == nullptr || !node->IsVar() || node->IsCtrlVar() ||
      node->Name() == kEmptyVarName)
    return false;
D
dzhwinter 已提交
301 302 303

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

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

D
dzhwinter 已提交
325 326
bool NodeCanReused(const VarDesc& node) {
  auto type = node.GetType();
D
dzhwinter 已提交
327
  // only these types holds bulk of gpu memory
328 329 330 331 332 333 334 335 336 337
  // FIXME(liuwei1031) did not find good ways to test SELECTED_ROWS and
  // LOD_TENSOR_ARRAY re-use logic,
  // disable them in version 1.4
  // if (!(type == proto::VarType::LOD_TENSOR ||
  //       type == proto::VarType::SELECTED_ROWS ||
  //       type == proto::VarType::LOD_TENSOR_ARRAY)) {
  //   return false;
  // }
  if (type != proto::VarType::LOD_TENSOR) return false;

D
dzhwinter 已提交
338 339 340 341 342 343 344 345 346 347 348
  // 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 已提交
349 350
    return false;
  }
D
dzhwinter 已提交
351 352 353 354 355 356 357 358 359 360 361 362 363
  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;
}

D
dzhwinter 已提交
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
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]) {
L
liuwei1031 已提交
447
      if (uses_[op].count(var)) continue;
D
dzhwinter 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460
      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);
      }
    }
  }
D
dzhwinter 已提交
461 462 463 464 465 466 467 468 469

  for (auto* op : ops_) {
    unlived_vars_[op] = std::set<std::string>();
    for (auto& var : this->LiveIn(op)) {
      if (!this->LiveOut(op).count(var)) {
        unlived_vars_[op].insert(var);
      }
    }
  }
D
dzhwinter 已提交
470 471 472 473 474
}

void ControlFlowGraph::RenameVarInCFGGraph(const std::string& old_node,
                                           const std::string& new_node,
                                           int begin_idx) {
D
dzhwinter 已提交
475
  std::vector<bool> need_update(ops_.size(), false);
D
dzhwinter 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489
  // 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);
D
dzhwinter 已提交
490
      need_update[i] = true;
D
dzhwinter 已提交
491 492 493 494
    }
    if (live_out_[op].find(old_node) != live_out_[op].end()) {
      live_out_[op].erase(old_node);
      live_out_[op].insert(new_node);
D
dzhwinter 已提交
495 496 497 498 499 500 501 502 503 504 505
      need_update[i] = true;
    }
  }

  for (size_t i = begin_idx; i < ops_.size(); ++i) {
    if (!need_update[i]) continue;
    auto* op = ops_[i];
    for (auto& var : this->LiveIn(op)) {
      if (!this->LiveOut(op).count(var)) {
        unlived_vars_[op].insert(var);
      }
D
dzhwinter 已提交
506 507 508 509
    }
  }
}

D
dzhwinter 已提交
510
const std::set<std::string>& ControlFlowGraph::LiveIn(ir::Node* op) const {
D
dzhwinter 已提交
511 512 513 514 515 516 517
  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;
}

D
dzhwinter 已提交
518
const std::set<std::string>& ControlFlowGraph::LiveOut(ir::Node* op) const {
D
dzhwinter 已提交
519 520 521 522 523 524 525
  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;
}

D
dzhwinter 已提交
526
const std::set<std::string>& ControlFlowGraph::Use(ir::Node* op) const {
D
dzhwinter 已提交
527 528 529
  auto it = uses_.find(op);
  PADDLE_ENFORCE(
      it != uses_.end(),
D
dzhwinter 已提交
530 531 532 533 534 535 536 537 538 539
      string::Sprintf("Expect %s in use, but Not Found.", op->Name()));
  return it->second;
}

const std::set<std::string>& ControlFlowGraph::Unlived(ir::Node* op) const {
  auto it = unlived_vars_.find(op);
  PADDLE_ENFORCE(
      it != unlived_vars_.end(),
      string::Sprintf("Expect %s in unlived_set, but Not Found.", op->Name()));
  return it->second;
D
dzhwinter 已提交
540 541 542
  return it->second;
}

D
dzhwinter 已提交
543
const std::vector<ir::Node*>& ControlFlowGraph::Ops() const { return ops_; }
D
dzhwinter 已提交
544 545 546 547 548 549 550 551 552 553 554 555

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) {
556 557 558
      PADDLE_ENFORCE((output != nullptr && output->IsVar()),
                     "Output is empty!");
      if (output->Var() && output->Name() == name) {
D
dzhwinter 已提交
559 560 561 562 563 564 565
        found_node = output;
      }
    }
  }
  return found_node;
}

D
dzhwinter 已提交
566 567 568
}  // namespace details
}  // namespace framework
}  // namespace paddle