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

#include "paddle/fluid/framework/details/inplace_op_pass.h"
#include <algorithm>
#include <deque>
#include <iterator>
Z
Zhen Wang 已提交
19
#include <memory>
D
dzhwinter 已提交
20 21 22 23 24 25
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "paddle/fluid/framework/details/memory_optimize_pass.h"
D
dzhwinter 已提交
26
#include "paddle/fluid/framework/ir/graph_helper.h"
D
dzhwinter 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#include "paddle/fluid/framework/op_info.h"

// NOTE(dzhwinter): inplace means one op output variable reuse the input space.
// By our design, one operator only can read its input(const Variable),
// write its output(non-const Variable). If one operator is inplaced, means
// user have chance to write the space before reading happens.
// Especially when some optimize code writing style is applied.
//
//
// /* wrong case in operator */
// /*In this case, a larger allocation is allocated, input content is lost*/
// const Tensor* in = ctx.Input<Tensor>("In")
// Tensor* out = ctx.Output<Tensor>("Out");
// auto* out_ptr = out->mutable_data<T>(ctx.GetPlace());
// out_ptr[0] = 0;  // input contect is overwrited.

D
dzhwinter 已提交
43 44 45
// NOTE(dzhwinter):
// Only for backward compacity and stable. if enable_inplace_whitelist is turn
// on.
D
dzhwinter 已提交
46 47 48
// only the ops in whitelist will be use inplace strategy.
// if not, all the op will be inplaced if it registered with InplaceClass
DEFINE_bool(
D
dzhwinter 已提交
49
    enable_inplace_whitelist, false,
D
dzhwinter 已提交
50 51 52
    "If this option turns on, only these op in whitelist can be inplaced."
    "If it turns off, all of the running op can be candidate of inplaced op."
    "Such as scale, elementwise_add"
D
dzhwinter 已提交
53
    "By default, it's turned off");
D
dzhwinter 已提交
54

D
dzhwinter 已提交
55 56
DECLARE_string(memory_optimize_debug);

D
dzhwinter 已提交
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
// clang-format off
const std::string kInplacedOpWhiteList[] = { // NOLINT
    "sigmoid",
    "exp",
    "relu",
    "tanh",
    "sqrt",
    "ceil",
    "floor",
    "reciprocal",
    "relu6",
    "soft_relu",
    "hard_sigmoid",
    "batch_norm",
    "batch_norm_grad",
    "sum",
    "sum_grad",
    "scale",
    "reshape",
    "elementwise_add",
    "elementwise_add_grad",
};
// clang-format on

namespace paddle {
namespace framework {
namespace details {

85
static inline ir::Node* GetNextCascadeInplacedVar(ir::Node* var) {
D
dzhwinter 已提交
86 87 88 89
  // if next op is inplaced, then return the output var
  // otherwise return nullptr
  PADDLE_ENFORCE(var && var->IsVar() && !var->IsCtrlVar());
  ir::Node* inplaced_var = nullptr;
90 91 92 93 94
  for (auto* next_op : var->outputs) {
    for (auto* output : next_op->outputs) {
      if (output->IsVar() && !output->IsCtrlVar() &&
          output->Name() == var->Name()) {
        inplaced_var = output;
D
dzhwinter 已提交
95 96 97 98 99 100
      }
    }
  }
  return inplaced_var;
}

101
static inline ir::Node* GetPrevCascadeInplacedVar(ir::Node* var) {
D
dzhwinter 已提交
102
  PADDLE_ENFORCE(var && var->IsVar() && !var->IsCtrlVar());
D
dzhwinter 已提交
103
  if (var->inputs.empty()) return nullptr;
104 105 106 107 108 109 110 111 112 113 114
  auto* prev_op = var->inputs.at(0);
  auto input_it = std::find_if(prev_op->inputs.begin(), prev_op->inputs.end(),
                               [&](ir::Node* node) {
                                 if (node->IsVar() && !node->IsCtrlVar() &&
                                     node->Name() == var->Name()) {
                                   return true;
                                 } else {
                                   return false;
                                 }
                               });
  return input_it == prev_op->inputs.end() ? nullptr : *input_it;
D
dzhwinter 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 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
}

InplacePass::InplacePass() : Pass() {
  if (FLAGS_enable_inplace_whitelist) {
    for (auto& s : kInplacedOpWhiteList) {
      whitelist_.emplace(s);
    }
  }
}

void InplacePass::InitSSAGraphNodes() const {
  std::unordered_map<std::string, std::unordered_set<ir::Node*>> all_vars;
  for (auto* op : view_.AllOps()) {
    for (auto* node : op->inputs) {
      if (!node->IsVar() || node->IsCtrlVar()) continue;
      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 (!node->IsVar() || node->IsCtrlVar()) continue;
      if (all_vars[node->Name()].count(node) == 0) {
        all_vars[node->Name()].emplace(node);
        var_nodes_[node->Name()].emplace_back(node);
      }
    }
  }
}

std::unique_ptr<ir::Graph> InplacePass::ApplyImpl(
    std::unique_ptr<ir::Graph> graph) const {
  var_nodes_.clear();
  view_.Build(graph.get());
  InitSSAGraphNodes();

  for (auto* op : view_.AllOps()) {
    if (FLAGS_enable_inplace_whitelist && !whitelist_.count(op->Name()))
      continue;
    TryInplaceOpInputOutput(op, graph.get());
  }
  graph->ResolveHazard(var_nodes_);
157

D
dzhwinter 已提交
158 159 160 161 162 163 164
  return graph;
}

void InplacePass::InplaceModifyDesc(const std::string& var,
                                    const std::string& cache_var,
                                    const size_t& idx) const {
  for (size_t i = idx; i < view_.AllOps().size(); ++i) {
165
    ir::Node* op = view_.AllOps()[i];
D
dzhwinter 已提交
166 167 168 169 170 171 172 173 174
    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 已提交
175 176 177
const NodeSwapQueue InplacePass::TryInplaceModifyVar(
    const std::string& var, const std::string& cache_var, const size_t& idx,
    ir::Graph* graph) const {
D
dzhwinter 已提交
178 179 180 181 182
  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);

D
dzhwinter 已提交
183
  NodeSwapQueue swap_nodes;
D
dzhwinter 已提交
184

D
dzhwinter 已提交
185 186 187 188 189 190 191
  for (size_t i = idx; i < view_.AllOps().size(); ++i) {
    auto* op = view_.AllOps()[i];

    // redirect the input to the latest version of cache_var
    for (auto* node : op->inputs) {
      if (node->Name() == var) {
        ir::Node* cache_node = graph->CreateVarNode(var_desc.get());
D
dzhwinter 已提交
192

D
dzhwinter 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205
        // 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);
        cache_node->inputs.emplace_back(prev_op);
        for (auto* next_op : node->outputs) {
          std::replace(next_op->inputs.begin(), next_op->inputs.end(), node,
                       cache_node);
        }

D
dzhwinter 已提交
206
        swap_nodes.emplace_back(std::make_pair(node, cache_node));
D
dzhwinter 已提交
207 208
      }
    }
D
dzhwinter 已提交
209 210 211

    // if we need to rename the output,
    // always create a newer version of cache_var
D
dzhwinter 已提交
212 213 214 215 216 217 218 219 220 221 222 223
    for (auto* node : op->outputs) {
      if (node->Name() == var) {
        ir::Node* cache_node = graph->CreateVarNode(var_desc.get());
        // 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);
        }
D
dzhwinter 已提交
224 225

        swap_nodes.emplace_back(std::make_pair(node, cache_node));
D
dzhwinter 已提交
226 227 228
      }
    }
  }
D
dzhwinter 已提交
229

D
dzhwinter 已提交
230 231 232
  return swap_nodes;
}

D
dzhwinter 已提交
233
void InplacePass::CommitModify(const NodeSwapQueue& swap_nodes,
D
dzhwinter 已提交
234 235
                               ir::Graph* graph) const {
  for (auto& pair : swap_nodes) {
D
dzhwinter 已提交
236 237 238 239
    auto *node = pair.first, *cache_node = pair.second;
    const std::string var = node->Name(), cache_var = cache_node->Name();
    var_nodes_[cache_var].emplace_back(cache_node);
    graph->RemoveNode(node);
D
dzhwinter 已提交
240
    auto& nodes = var_nodes_.at(var);
D
dzhwinter 已提交
241 242 243
    // release unused var in graph. Because python side memory optimize
    // may reused the var in same name, so we only clear the var node
    // after current inplaced index.
D
dzhwinter 已提交
244 245 246 247
    nodes.erase(std::remove(nodes.begin(), nodes.end(), node), nodes.end());
  }
}

D
dzhwinter 已提交
248
void InplacePass::WithdrawModify(const NodeSwapQueue& nodes,
D
dzhwinter 已提交
249 250
                                 ir::Graph* graph) const {
  for (auto& pair : nodes) {
D
dzhwinter 已提交
251 252 253 254 255 256 257
    auto *node = pair.first, *cache_node = pair.second;
    const std::string var = node->Name(), cache_var = cache_node->Name();
    auto* prev_op = node->inputs[0];
    std::replace(prev_op->outputs.begin(), prev_op->outputs.end(), cache_node,
                 node);
    for (auto* next_op : node->outputs) {
      std::replace(next_op->inputs.begin(), next_op->inputs.end(), cache_node,
D
dzhwinter 已提交
258
                   node);
D
dzhwinter 已提交
259
    }
D
dzhwinter 已提交
260
    graph->RemoveNode(cache_node);
D
dzhwinter 已提交
261 262 263 264 265
  }
}

void InplacePass::TryInplaceOpInputOutput(ir::Node* op,
                                          ir::Graph* graph) const {
D
dzhwinter 已提交
266
  VLOG(4) << "Try to inplace op " << op->Name();
Z
Zhen Wang 已提交
267 268 269 270
  // 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 已提交
271 272
  PADDLE_ENFORCE(op->Op() != nullptr && op->Op()->Block() != nullptr,
                 "op_desc is nullptr");
D
dzhwinter 已提交
273 274
  // some pre-requirments need to meet if the op want to inplaced.

D
dzhwinter 已提交
275 276 277
  auto* op_desc = op->Op();
  auto& infer_inplace =
      OpInfoMap::Instance().Get(op_desc->Type()).infer_inplace_;
D
dzhwinter 已提交
278 279

  // 1. infer_inplace_ is registered.
D
dzhwinter 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
  if (!static_cast<bool>(infer_inplace)) return;
  PADDLE_ENFORCE(static_cast<bool>(infer_inplace),
                 "%s's infer_inplace has not been registered", op_desc->Type());

  auto* block = op_desc->Block();
  auto in_to_outs = infer_inplace(*op_desc, block);

  auto& all_ops = view_.AllOps();
  auto cursor = std::find(all_ops.begin(), all_ops.end(), op);
  size_t idx = std::distance(all_ops.begin(), cursor);

  for (auto& pair : in_to_outs) {
    auto& in_var_name = pair.first;
    auto& out_var_name = pair.second;
    auto* in_node = view_.GetNodeByName(in_var_name, op->inputs);
    auto* out_node = view_.GetNodeByName(out_var_name, op->outputs);
D
dzhwinter 已提交
296

D
dzhwinter 已提交
297 298
    // 2. there is no external pending op on the input node
    if (view_.PendingOpsOnVar(in_node).size() > 1) {
D
dzhwinter 已提交
299 300 301 302
      VLOG(4) << string::Sprintf(
          "Skiped pair %s => %s. %s input has external dependency."
          "inplace such pair will overwrite the memory.",
          out_var_name, in_var_name, op->Name());
D
dzhwinter 已提交
303 304
      continue;
    }
D
dzhwinter 已提交
305

306
    // 3. if output has been memory optimize by python(fluid.memory_optmize()).
D
dzhwinter 已提交
307
    // this candidate  can not be inplaced. Will be deprecated in the future.
D
dzhwinter 已提交
308
    if (view_.InSkipSet(out_node->Name())) {
D
dzhwinter 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
      VLOG(4) << string::Sprintf(
          "Skiped %s => %s reused previous memory block in python memory "
          "optmize,"
          "it inplace may generate a circle",
          out_var_name, in_var_name, op->Name());
      continue;
    }

    // Debug Interface. Which would be skipped by the pass.
    if (out_node->Name() == FLAGS_memory_optimize_debug) {
      VLOG(3) << "Skiped var by force. FLAGS_memory_optimize_debug="
              << out_node->Name();
      continue;
    }

D
dzhwinter 已提交
324 325 326 327
    // NOTE(dzhwinter):
    // two stage commit of inplaced process. if after inplace happens generate a
    // circle,
    // then withdraw the changes. Otherwise, safely add the node.
D
dzhwinter 已提交
328 329 330 331 332 333 334
    auto swap_nodes =
        TryInplaceModifyVar(out_var_name, in_var_name, idx, graph);

    if (!ir::HasCircle(*graph)) {
      VLOG(3) << string::Sprintf("!!! %s,  %s => %s inplaced", op->Name(),
                                 out_var_name, in_var_name);
      InplaceModifyDesc(out_var_name, in_var_name, idx);
D
dzhwinter 已提交
335
      CommitModify(swap_nodes, graph);
D
dzhwinter 已提交
336 337 338 339
    } else {
      VLOG(3) << string::Sprintf(
          "Skiped pair %s => %s, inplace will generate a circle. withdraw %s",
          out_var_name, in_var_name, op->Name());
D
dzhwinter 已提交
340
      WithdrawModify(swap_nodes, graph);
D
dzhwinter 已提交
341
    }
D
dzhwinter 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  }
}

ir::Node* GraphView::GetNodeByName(const std::string& name,
                                   const std::vector<ir::Node*>& nodes) const {
  // nodes should be op->inputs/outputs
  // node in same node do have different name.
  std::unordered_set<std::string> nodes_in_op;
  bool has_dup_node =
      std::all_of(nodes.begin(), nodes.end(), [&nodes_in_op](ir::Node* node) {
        if (!node->IsVar() || node->IsCtrlVar() || node->Var() == nullptr) {
          if (nodes_in_op.count(node->Name())) return true;
          nodes_in_op.emplace(node->Name());
        }
        return false;
      });
  PADDLE_ENFORCE(has_dup_node == false, "nodes has same name!");
  ir::Node* node = nullptr;
  for (auto* it : nodes) {
    if (!it->IsVar() || it->IsCtrlVar() || it->Var() == nullptr) continue;
    if (it->Name() == name) {
      node = it;
      break;
    }
  }
  PADDLE_ENFORCE(node != nullptr,
                 string::Sprintf("Not found var %s in nodes!", name));
  return node;
}

std::vector<ir::Node*> GraphView::PendingOpsOnVar(ir::Node* node) {
373 374 375 376 377 378 379 380 381 382
  // get the pending ops depends on same var node.
  // because node also maybe a inplaced variable, so need to backtrack all the
  // previous inplaced vars.
  std::vector<ir::Node*> pending_ops;
  ir::Node* p = node;
  while (p != nullptr) {
    pending_ops.insert(pending_ops.end(), p->outputs.begin(), p->outputs.end());
    p = GetPrevCascadeInplacedVar(p);
  }
  return pending_ops;
D
dzhwinter 已提交
383 384
}

D
dzhwinter 已提交
385 386 387 388 389 390 391
void GraphView::Build(ir::Graph* g) {
  // track the var nodes in correct order.
  // Because we insert some new created node. Which may have data race between
  // nodes.
  // resolve data harzards depends on the var nodes in right order.
  ops_ = SortOpLikeDescOrder(*g);

D
dzhwinter 已提交
392
  // 1. track the nodes which reused previous node in Python memory optimize.
D
dzhwinter 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405
  // these node can not be inplaced, otherwise may generate a circle in graph.
  std::unordered_set<std::string> all_vars;
  for (auto& node : g->Nodes()) {
    if (node->IsVar()) continue;
    for (auto& out : node->outputs) {
      if (out->IsCtrlVar() || out->Var() == nullptr) continue;
      if (all_vars.count(out->Name())) {
        dup_nodes_.emplace(out->Name());
      } else {
        all_vars.emplace(out->Name());
      }
    }
  }
D
dzhwinter 已提交
406 407 408 409

  // 2. track the nodes which used by parameter server.
  // these node can not be inplaced, otherwise trainer
  // pserver can not find each other name.
D
dzhwinter 已提交
410 411 412
  auto update_skip_set = [&](ir::Node* node) {
    for (auto& in : node->inputs) {
      if (in->IsVar() && in->Var() != nullptr) dup_nodes_.emplace(in->Name());
D
dzhwinter 已提交
413
    }
D
dzhwinter 已提交
414
    for (auto& out : node->outputs) {
D
dzhwinter 已提交
415 416
      if (out->IsVar() && out->Var() != nullptr)
        dup_nodes_.emplace(out->Name());
D
dzhwinter 已提交
417
    }
D
dzhwinter 已提交
418 419 420 421 422 423
  };
  for (auto& node : g->Nodes()) {
    if (!node->IsOp()) continue;
    if (node->Name() == "send") update_skip_set(node);
    if (node->Name() == "recv") update_skip_set(node);
    if (node->Name() == "prefetch") update_skip_set(node);
D
dzhwinter 已提交
424
  }
D
dzhwinter 已提交
425
}
D
dzhwinter 已提交
426

D
dzhwinter 已提交
427
const std::vector<ir::Node*>& GraphView::AllOps() { return ops_; }
D
dzhwinter 已提交
428

D
dzhwinter 已提交
429
bool GraphView::InSkipSet(const std::string& var) const {
D
dzhwinter 已提交
430 431 432
  return dup_nodes_.count(var);
}

D
dzhwinter 已提交
433 434 435 436 437
}  // namespace details
}  // namespace framework
}  // namespace paddle

REGISTER_PASS(inplace_pass, paddle::framework::details::InplacePass);