memory_optimize_pass.cc 12.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_pass.h"
D
dzhwinter 已提交
16 17 18 19 20 21 22 23 24 25 26
#include <algorithm>
#include <atomic>
#include <deque>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <queue>
#include <sstream>
#include <string>
#include <type_traits>
Z
Zhen Wang 已提交
27
#include <unordered_set>
D
dzhwinter 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <vector>
#include "gflags/gflags.h"
#include "paddle/fluid/framework/data_type.h"
#include "paddle/fluid/framework/ir/graph.h"
#include "paddle/fluid/framework/ir/graph_helper.h"

DEFINE_bool(enable_subgraph_optimize, false,
            "SubGraph also reuse global graph variables, it will reduce the "
            "memory occupation"
            "but a higher risk of memory reuse error. default disabled.");
DEFINE_string(memory_optimize_debug, "",
              "debug the operator output variable when do the variable reuse."
              "memory reuse pass."
              "only for debug, default disabled.");

namespace paddle {
namespace framework {
namespace details {

47
void MemoryOptimizePass::ApplyImpl(ir::Graph* graph) const {
48
  CollectSkipVarsSet(graph);
D
dzhwinter 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70

  cfg_.reset(new details::ControlFlowGraph(*graph));
  cfg_->LiveVariableAnalysis();
  InitSSAGraphNodes();

  int reuse_id = 0;
  for (size_t idx = 0; idx < cfg_->Ops().size(); ++idx) {
    auto& op = cfg_->Ops()[idx];
    auto* op_desc = op->Op();
    // some op in graph has no op desc
    if (op_desc == nullptr) continue;
    if (OpHasSubBlock(op_desc)) {
      if (FLAGS_enable_subgraph_optimize) {
        SubGraphOptimize(op_desc);
      } else {
        VLOG(3) << op->Name()
                << " has subblock, but disable subgraph optimize. skipped.";
        continue;
      }
    }

    for (auto& var : op->outputs) {
71
      if (var->IsVar() && !var->IsCtrlVar() && skip_set_.count(var->Name())) {
D
dzhwinter 已提交
72 73
        VLOG(3) << "Skip set contains variable of " << var->Name()
                << "disable reuse on it. skipped";
D
dzhwinter 已提交
74 75
        continue;
      }
D
dzhwinter 已提交
76 77
      if (NodeCanReused(var) && cfg_->Use(op).count(var->Name()) == 0) {
        ir::Node* cache = pool_.FindBestFitNode(var);
D
dzhwinter 已提交
78
        while (cache != nullptr && var->Name() == cache->Name()) {
79
          VLOG(3) << "The same cache variable is cascade reused. "
D
dzhwinter 已提交
80
                  << cache->Name() << " is re-filled to the pool after "
D
dzhwinter 已提交
81 82 83 84
                  << "the reused op is finished. Current op can not "
                  << "replace it again. Skip this candidate.";
          cache = pool_.FindNextBestFitNode(var, cache);
        }
D
dzhwinter 已提交
85 86 87 88 89 90 91
        if (var->Name() == FLAGS_memory_optimize_debug) {
          VLOG(3) << "start match var " << DebugString(var) << " of op "
                  << op->Name();
          VLOG(3) << pool_.ToString();
          VLOG(3) << "matched in pool : "
                  << ((cache == nullptr) ? "False" : "True");
        }
D
dzhwinter 已提交
92

D
dzhwinter 已提交
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
        if (cache != nullptr) {
          int node_idx_in_pool = pool_.GetNodeIndexInPool(cache);
          VLOG(3) << string::Sprintf(
              "!!! %s,  %s => %s, cache idx %d, pool size %d",
              std::to_string(reuse_id++), DebugString(var), DebugString(cache),
              node_idx_in_pool, static_cast<int>(pool_.size()));
          // NOTE(dzhwinter): update the ProgramDesc/IR Graph
          // and the CFG Graph on the fly.
          //
          // IR Graph define the dependence relationship between nodes.
          //
          // ProgramDesc defines the input/output vars. Its used in
          // CreateOp, CreateVar when running happens.
          //
          // CFG Graph store the liveness information, when reuse happens
          // we also need to update the variable liveness.
109 110
          const std::string var_name = var->Name();
          const std::string cache_name = cache->Name();
D
dzhwinter 已提交
111

112 113
          cfg_->RenameVarInCFGGraph(var_name, cache_name, idx);
          RenameVarInGraphDesc(var_name, cache_name, idx);
114
          RenameVarInGraphNode(var_name, cache_name, idx, graph);
115
          pool_.Erase(cache_name);
D
dzhwinter 已提交
116 117
        }
      }
D
dzhwinter 已提交
118 119
    }
    // fill the pool
D
dzhwinter 已提交
120 121 122 123 124
    for (auto& var : cfg_->Unlived(op)) {
      ir::Node* var_node = cfg_->GetNodeByName(var, op);
      if (var_node == nullptr || var_node->IsCtrlVar()) continue;
      if (NodeCanReused(var_node) && !pool_.Has(var_node)) {
        pool_.Insert(var_node);
D
dzhwinter 已提交
125 126 127
      }
    }
  }
128
  graph->ResolveHazard(var_nodes_);
D
dzhwinter 已提交
129 130
}

D
dzhwinter 已提交
131
void MemoryOptimizePass::SubGraphOptimize(OpDesc* op_desc) const {
D
dzhwinter 已提交
132 133 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 175
  // conditional block, while op and their grad op
  auto* sub_block_desc =
      AttrReader(op_desc->GetAttrMap()).Get<BlockDesc*>("sub_block");

  // create a mirror block to construct an IR Graph.
  ProgramDesc prog;
  auto* copy_block = prog.MutableBlock(0);
  for (auto* op : sub_block_desc->AllOps()) {
    auto* copy_op = copy_block->AppendOp();
    copy_op->CopyFrom(*op);
    copy_op->Flush();
  }

  for (auto* var : sub_block_desc->AllVars()) {
    auto* copy_var = copy_block->Var(var->Name());
    copy_var->SetDataType(var->GetDataType());
    // only lod tensor can be reused. So ignore the multiple dims case.
    copy_var->SetType(var->GetType());
    copy_var->SetShape(var->GetShape());
    copy_var->SetPersistable(var->Persistable());
  }

  ir::Graph sub_graph(prog);
  std::unordered_set<ir::Node*> sub_graph_all_ops;
  FilterVariables(sub_graph.Nodes(), [&](ir::Node* var) {
    // sub_graph_all_ops.emplace(var);
    if (var->IsVar() && !var->IsCtrlVar()) {
      sub_graph_all_ops.emplace(var);
    }
  });
  int sub_reuse_id = 0;
  // subgraph nodes is unordered, reuse need to follow the desc order.
  // find the right op node through the descs
  for (auto* sub_op_desc : sub_block_desc->AllOps()) {
    ir::Node* sub_op = nullptr;
    for (auto* node : sub_graph_all_ops) {
      if (node->Op() == sub_op_desc) {
        sub_op = node;
        break;
      }
    }
    PADDLE_ENFORCE(sub_op != nullptr);
    for (auto* var : sub_op->outputs) {
      if (NodeCanReused(var)) {
D
dzhwinter 已提交
176
        ir::Node* cache = pool_.FindBestFitNode(var);
D
dzhwinter 已提交
177 178 179 180
        if (cache != nullptr) {
          if (var->Var()->GetDataType() != cache->Var()->GetDataType()) {
            continue;
          }
D
dzhwinter 已提交
181
          int node_idx_in_pool = pool_.GetNodeIndexInPool(cache);
D
dzhwinter 已提交
182 183 184 185 186 187 188 189 190
          VLOG(3) << string::Sprintf(
              "!!! %s,  %s => %s, cache idx %d, pool size %d",
              std::to_string(sub_reuse_id++), DebugString(var),
              DebugString(cache), node_idx_in_pool,
              static_cast<int>(pool_.size()));
          // NOTE(dzh): subblock is not in IR graph. Modify the block_desc
          // immediately to make the subblock variable reuse strategy take
          // effect. Because it is a single op in graph. No need to
          // update the ir nodes.
Z
Zhen Wang 已提交
191 192 193 194
          // FIXME(liuwei1031): Graph is not aware of the existence of
          // BlockDescs and ProgramDescs.
          // The operations related to BlockDesc or ProgramDesc should perform
          // on Graph or Node directly!
D
dzhwinter 已提交
195
          sub_op_desc->Rename(var->Name(), cache->Name());
D
dzhwinter 已提交
196 197
          if (sub_op_desc->Block() != nullptr &&
              sub_op_desc->Block()->HasVar(var->Name())) {
D
dzhwinter 已提交
198 199 200 201 202 203 204 205
            sub_op_desc->Block()->RemoveVar(var->Name());
          }
        }
      }
    }
  }
}

206 207 208 209 210 211
void MemoryOptimizePass::CollectSkipVarsSet(ir::Graph* graph) const {
  // fill skip_set_
  PADDLE_ENFORCE(graph->Has(details::kMemOptSkipVars));
  auto& mem_opt_whitelist = graph->Get<MemOptSkipVars>(kMemOptSkipVars);
  for (const auto& var : mem_opt_whitelist) skip_set_.emplace(var);

D
dzhwinter 已提交
212 213 214 215 216 217
  auto update_skip_set = [&](OpDesc* op_desc) {
    auto inputs = op_desc->InputArgumentNames();
    auto outputs = op_desc->OutputArgumentNames();
    skip_set_.insert(inputs.begin(), inputs.end());
    skip_set_.insert(outputs.begin(), outputs.end());
  };
218 219

  auto nodes = graph->Nodes();
D
dzhwinter 已提交
220 221 222
  for (auto& op : nodes) {
    if (!op->IsOp() || op->Op() == nullptr) continue;
    auto* op_desc = op->Op();
D
dzhwinter 已提交
223 224
    // NOTE(dzhwinter):
    // current block can not reuse next level block vars.
D
dzhwinter 已提交
225
    if (OpHasSubBlock(op_desc)) update_skip_set(op_desc);
D
dzhwinter 已提交
226 227 228
    // NOTE(dzhwinter):
    // distributed ops input/output name need to
    // keep same bettwen trainer/pserver
D
dzhwinter 已提交
229 230
    if (op_desc->Type() == "send") update_skip_set(op_desc);
    if (op_desc->Type() == "recv") update_skip_set(op_desc);
D
dzhwinter 已提交
231
    if (op_desc->Type() == "prefetch") update_skip_set(op_desc);
D
dzhwinter 已提交
232 233 234
  }
}

D
dzhwinter 已提交
235 236 237
void MemoryOptimizePass::RenameVarInGraphDesc(const std::string& var,
                                              const std::string& cache_var,
                                              size_t idx) const {
D
dzhwinter 已提交
238 239 240 241 242 243
  for (size_t i = idx; i < cfg_->Ops().size(); ++i) {
    auto* op = cfg_->Ops()[i];
    PADDLE_ENFORCE(op->IsOp() && op->Op());
    auto* op_desc = op->Op();
    op_desc->RenameInput(var, cache_var);
    op_desc->RenameOutput(var, cache_var);
D
dzhwinter 已提交
244
    if (op_desc->Block() != nullptr) {
D
dzhwinter 已提交
245
      op_desc->Block()->RemoveVar(var);
D
dzhwinter 已提交
246 247 248 249
    } else {
      LOG(WARNING) << "op " << op->Name() << " not know its block."
                   << "Is the op_desc created without block pointer? "
                   << "Can not find " << var << " in Block(0)";
D
dzhwinter 已提交
250
    }
D
dzhwinter 已提交
251 252 253 254
    op_desc->Flush();
  }
}

D
dzhwinter 已提交
255
void MemoryOptimizePass::InitSSAGraphNodes() const {
D
dzhwinter 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
  std::unordered_map<std::string, std::unordered_set<ir::Node*>> all_vars;
  if (var_nodes_.empty()) {
    for (auto* op : cfg_->Ops()) {
      for (auto* node : op->inputs) {
        if (all_vars[node->Name()].count(node) == 0) {
          all_vars[node->Name()].emplace(node);
          var_nodes_[node->Name()].emplace_back(node);
        }
      }
      for (auto* node : op->outputs) {
        if (all_vars[node->Name()].count(node) == 0) {
          all_vars[node->Name()].emplace(node);
          var_nodes_[node->Name()].emplace_back(node);
        }
      }
    }
  }
}

D
dzhwinter 已提交
275 276 277 278
void MemoryOptimizePass::RenameVarInGraphNode(const std::string& var,
                                              const std::string& cache_var,
                                              size_t idx,
                                              ir::Graph* graph) const {
D
dzhwinter 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291
  // if replace happens, we need to create a newer version cache_var
  // but use the same dims/data_type with var.
  PADDLE_ENFORCE(var_nodes_[var].size() >= 1 &&
                 var_nodes_[var].at(0)->Var() != nullptr);
  std::unique_ptr<VarDesc> var_desc(new VarDesc(*var_nodes_[var].at(0)->Var()));
  var_desc->SetName(cache_var);

  for (size_t i = idx; i < cfg_->Ops().size(); ++i) {
    auto* op = cfg_->Ops()[i];

    // redirect the input to the latest version of cache_var
    for (auto* node : op->inputs) {
      if (node->Name() == var) {
292
        ir::Node* cache_node = var_nodes_[cache_var].back();
D
dzhwinter 已提交
293 294 295 296 297 298 299 300 301 302 303 304

        // swap node to cache_node
        cache_node->outputs.insert(cache_node->outputs.end(),
                                   node->outputs.begin(), node->outputs.end());
        PADDLE_ENFORCE(node->inputs.size() == 1 && node->inputs[0]->IsOp());
        auto* prev_op = node->inputs[0];
        std::replace(prev_op->outputs.begin(), prev_op->outputs.end(), node,
                     cache_node);
        for (auto* next_op : node->outputs) {
          std::replace(next_op->inputs.begin(), next_op->inputs.end(), node,
                       cache_node);
        }
305 306 307 308 309

        // erase unused node
        auto& nodes = var_nodes_.at(var);
        nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
        graph->RemoveNode(node);
D
dzhwinter 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
      }
    }

    // if we need to rename the output,
    // always create a newer version of cache_var
    for (auto* node : op->outputs) {
      if (node->Name() == var) {
        ir::Node* cache_node = graph->CreateVarNode(var_desc.get());
        var_nodes_[cache_var].emplace_back(cache_node);

        // swap node to cache node
        cache_node->outputs.insert(cache_node->outputs.end(),
                                   node->outputs.begin(), node->outputs.end());
        cache_node->inputs.emplace_back(op);
        std::replace(op->outputs.begin(), op->outputs.end(), node, cache_node);
        for (auto* next_op : node->outputs) {
          std::replace(next_op->inputs.begin(), next_op->inputs.end(), node,
                       cache_node);
        }
329 330 331 332 333

        // erase unused node
        auto& nodes = var_nodes_.at(var);
        nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
        graph->RemoveNode(node);
D
dzhwinter 已提交
334 335 336 337 338 339 340 341 342
      }
    }
  }
}

}  // namespace details
}  // namespace framework
}  // namespace paddle

D
dzhwinter 已提交
343
REGISTER_PASS(memory_optimize_pass,
X
Xin Pan 已提交
344
              paddle::framework::details::MemoryOptimizePass)
X
fix  
Xin Pan 已提交
345
    .RequireGraphAttr(paddle::framework::details::kStaleProgramOpDescs);