memory_optimize_pass.cc 13.0 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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
#include <algorithm>
#include <atomic>
#include <deque>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <queue>
#include <sstream>
#include <string>
#include <type_traits>
#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 {

D
dzhwinter 已提交
46
std::unique_ptr<ir::Graph> MemoryOptimizePass::ApplyImpl(
D
dzhwinter 已提交
47 48
    std::unique_ptr<ir::Graph> graph) const {
  auto nodes = graph->Nodes();
49
  ClearControlDepVars(graph.get());
D
dzhwinter 已提交
50
  CollectSkipVarsSet(nodes);
D
dzhwinter 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

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

D
dzhwinter 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
        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.
111 112
          const std::string var_name = var->Name();
          const std::string cache_name = cache->Name();
D
dzhwinter 已提交
113

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

  return graph;
}

D
dzhwinter 已提交
137
void MemoryOptimizePass::SubGraphOptimize(OpDesc* op_desc) const {
D
dzhwinter 已提交
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 176 177 178 179 180 181
  // 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 已提交
182
        ir::Node* cache = pool_.FindBestFitNode(var);
D
dzhwinter 已提交
183 184 185 186
        if (cache != nullptr) {
          if (var->Var()->GetDataType() != cache->Var()->GetDataType()) {
            continue;
          }
D
dzhwinter 已提交
187
          int node_idx_in_pool = pool_.GetNodeIndexInPool(cache);
D
dzhwinter 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
          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.
          sub_op_desc->Rename(var->Name(), cache->Name());
          if (sub_op_desc->Block()->HasVar(var->Name())) {
            sub_op_desc->Block()->RemoveVar(var->Name());
          }
        }
      }
    }
  }
}

D
dzhwinter 已提交
207
void MemoryOptimizePass::CollectSkipVarsSet(
D
dzhwinter 已提交
208
    const std::unordered_set<ir::Node*>& nodes) const {
D
dzhwinter 已提交
209 210 211 212 213 214
  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());
  };
D
dzhwinter 已提交
215 216 217
  for (auto& op : nodes) {
    if (!op->IsOp() || op->Op() == nullptr) continue;
    auto* op_desc = op->Op();
D
dzhwinter 已提交
218 219
    // NOTE(dzhwinter):
    // current block can not reuse next level block vars.
D
dzhwinter 已提交
220
    if (OpHasSubBlock(op_desc)) update_skip_set(op_desc);
D
dzhwinter 已提交
221 222 223
    // NOTE(dzhwinter):
    // distributed ops input/output name need to
    // keep same bettwen trainer/pserver
D
dzhwinter 已提交
224 225
    if (op_desc->Type() == "send") update_skip_set(op_desc);
    if (op_desc->Type() == "recv") update_skip_set(op_desc);
D
dzhwinter 已提交
226
    if (op_desc->Type() == "prefetch") update_skip_set(op_desc);
D
dzhwinter 已提交
227 228 229
  }
}

D
dzhwinter 已提交
230 231 232
void MemoryOptimizePass::RenameVarInGraphDesc(const std::string& var,
                                              const std::string& cache_var,
                                              size_t idx) const {
D
dzhwinter 已提交
233 234 235 236 237 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);
    if (op_desc->Block()->HasVar(var)) op_desc->Block()->RemoveVar(var);
    op_desc->Flush();
  }
}

D
dzhwinter 已提交
244
void MemoryOptimizePass::InitSSAGraphNodes() const {
D
dzhwinter 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  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 已提交
264 265 266 267
void MemoryOptimizePass::RenameVarInGraphNode(const std::string& var,
                                              const std::string& cache_var,
                                              size_t idx,
                                              ir::Graph* graph) const {
D
dzhwinter 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280
  // 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) {
281
        ir::Node* cache_node = var_nodes_[cache_var].back();
D
dzhwinter 已提交
282 283 284 285 286 287 288 289 290 291 292 293

        // 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);
        }
294 295 296 297 298

        // 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 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
      }
    }

    // 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);
        }
318 319 320 321 322

        // 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 已提交
323 324 325 326 327
      }
    }
  }
}

328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
void MemoryOptimizePass::ClearControlDepVars(ir::Graph* graph) const {
  for (auto& op : graph->Nodes()) {
    if (!op->IsOp()) continue;
    {
      auto& nodes = op->inputs;
      nodes.erase(
          std::remove_if(nodes.begin(), nodes.end(),
                         [&](ir::Node* var) { return var->IsCtrlVar(); }),
          nodes.end());
    }
    {
      auto& nodes = op->outputs;
      nodes.erase(
          std::remove_if(nodes.begin(), nodes.end(),
                         [&](ir::Node* var) { return var->IsCtrlVar(); }),
          nodes.end());
    }
  }

  for (auto& node : graph->Nodes()) {
    if (node->IsCtrlVar()) {
      graph->RemoveNode(node);
    }
  }
}

D
dzhwinter 已提交
354 355 356 357
}  // namespace details
}  // namespace framework
}  // namespace paddle

D
dzhwinter 已提交
358 359
REGISTER_PASS(memory_optimize_pass,
              paddle::framework::details::MemoryOptimizePass)
D
dzhwinter 已提交
360
    .RequireGraphAttr(paddle::framework::details::kAllOpDescs);