inplace_op_pass.cc 15.3 KB
Newer Older
1
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14
//
// 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.

15
#include <map>
L
liuwei1031 已提交
16
#include <queue>
D
dzhwinter 已提交
17 18
#include <string>
#include <unordered_set>
19
#include "paddle/fluid/framework/ir/graph.h"
D
dzhwinter 已提交
20
#include "paddle/fluid/framework/ir/graph_helper.h"
21
#include "paddle/fluid/framework/ir/memory_optimize_pass/memory_optimize_pass.h"
22
#include "paddle/fluid/framework/ir/pass.h"
D
dzhwinter 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#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 已提交
39 40 41
// NOTE(dzhwinter):
// Only for backward compacity and stable. if enable_inplace_whitelist is turn
// on.
D
dzhwinter 已提交
42 43 44
// 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 已提交
45
    enable_inplace_whitelist, false,
D
dzhwinter 已提交
46 47 48
    "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 已提交
49
    "By default, it's turned off");
D
dzhwinter 已提交
50

51 52
namespace paddle {
namespace framework {
53
namespace ir {
54

D
dzhwinter 已提交
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
// 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",
};
Z
Zeng Jinle 已提交
77 78 79 80 81

// FIXME(zjl): Shapes of in-out of some ops are exactly the same,
// but the static size during compiling time would be wrong.
// Use a flag to indicate such ops. Please fix me when found a better way.
static const std::unordered_set<std::string> kSameShapeOpWhiteSet{ // NOLINT
82
    "reshape2", "reshape2_grad"
Z
Zeng Jinle 已提交
83
};
D
dzhwinter 已提交
84 85
// clang-format on

86 87 88
class InplacePass : public ir::Pass {
 public:
  InplacePass();
D
dzhwinter 已提交
89

90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
 protected:
  void ApplyImpl(ir::Graph *graph) const override;

 private:
  // Collect vars that cannot be reused
  // e.g.: subblock ops in/out, distributed ops in/out, op_role_var
  void CollectSkipVars(ir::Graph *graph,
                       const std::vector<ir::Node *> &ops) const;

  // Check whether var_name should be skipped
  bool IsSkipVar(const std::string &var_name) const;

  // Rename out with name of in, and guarantee that the graph is
  // still a SSA graph
  void RenameInOut(ir::Node *op, ir::Node *in, ir::Node *out) const;

  // Check whether var is the last version one in SSA graph
  bool IsLastVersionVar(ir::Node *var) const;

  // Check whether all `ops` is the preceding ops of `op`
  bool CheckOpDeps(ir::Node *op, const std::vector<ir::Node *> &ops) const;

112
  // Find nodes whose names are equal to the given name
113 114
  static std::unordered_set<ir::Node *> FindNodesByName(
      const std::string &name, const std::vector<ir::Node *> &nodes);
115

116 117 118 119
  // Collect inputs and outputs of op_desc
  static void CollectInputArgsOfOpDesc(
      const OpDesc *op_desc, std::unordered_multiset<std::string> *in_args);

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  // Get all versions vars named var_name
  std::vector<ir::Node *> *AllVersionVars(const std::string &var_name) const;

 private:
  // SSA graph. var_name -> each version of vars
  mutable std::map<std::string, std::vector<ir::Node *>> ssa_map_;

  // Skip vars, including subblock ops in/out, distributed ops in/out,
  // op_role_var
  mutable std::unordered_set<std::string> skip_vars_;

  // Op whitelist which should not peform inplace
  // Only enabled when FLAGS_enable_inplace_whitelist is true.
  mutable std::unordered_set<std::string> whitelist_ops_;
};

InplacePass::InplacePass() {
  if (FLAGS_enable_inplace_whitelist) {
    for (auto &s : kInplacedOpWhiteList) {
      whitelist_ops_.emplace(s);
D
dzhwinter 已提交
140 141 142 143
    }
  }
}

144 145 146 147 148 149 150 151
std::vector<ir::Node *> *InplacePass::AllVersionVars(
    const std::string &var_name) const {
  auto iter = ssa_map_.find(var_name);
  PADDLE_ENFORCE(iter != ssa_map_.end(), "cannot find var %s in ssa graph",
                 var_name);
  PADDLE_ENFORCE(!iter->second.empty(), "var %s is empty in ssa graph",
                 var_name);
  return &(iter->second);
D
dzhwinter 已提交
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 182 183 184 185 186 187 188 189 190 191
bool InplacePass::IsSkipVar(const std::string &var_name) const {
  return skip_vars_.count(var_name) > 0;
}

bool InplacePass::IsLastVersionVar(ir::Node *var) const {
  return AllVersionVars(var->Name())->back() == var;
}

bool InplacePass::CheckOpDeps(ir::Node *op,
                              const std::vector<ir::Node *> &ops) const {
  std::unordered_set<ir::Node *> other_ops(ops.begin(), ops.end());
  other_ops.erase(op);
  if (other_ops.empty()) return true;

  // Traverse all preceding ops of op
  std::queue<ir::Node *> queue;
  std::unordered_set<ir::Node *> visited_ops;
  queue.push(op);
  visited_ops.insert(op);

  // Visit all preceding ops of `op`, and erase it from other_ops if it is
  // inside other_ops. Return true only if other_ops is empty(), which means
  // that all `ops` are preceding ops of `op`.
  while (!queue.empty()) {
    auto *cur_op = queue.front();
    queue.pop();

    for (auto *in_var : cur_op->inputs) {
      for (auto *in_op : in_var->inputs) {
        if (visited_ops.count(in_op) != 0) {
          continue;
        }

        visited_ops.insert(in_op);
        queue.push(in_op);
        other_ops.erase(in_op);
        if (other_ops.empty()) return true;
      }
D
dzhwinter 已提交
192 193
    }
  }
194
  return false;
D
dzhwinter 已提交
195 196
}

197 198 199
void InplacePass::CollectSkipVars(ir::Graph *graph,
                                  const std::vector<ir::Node *> &ops) const {
  // 1. Collect op role vars
200 201
  PADDLE_ENFORCE(graph->Has(kMemOptSkipVars), "Graph should have attr %s",
                 kMemOptSkipVars);
202 203 204 205
  auto &mem_opt_whitelist = graph->Get<MemOptSkipVars>(kMemOptSkipVars);
  for (const auto &var : mem_opt_whitelist) {
    skip_vars_.emplace(var);
  }
D
dzhwinter 已提交
206 207
}

208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
void InplacePass::RenameInOut(ir::Node *op, ir::Node *in_var,
                              ir::Node *out_var) const {
  auto out_var_name = out_var->Name();
  auto in_var_name = in_var->Name();

  auto &all_out_nodes = *AllVersionVars(out_var_name);
  auto &all_in_nodes = *AllVersionVars(in_var_name);

  auto iter = std::find(all_out_nodes.begin(), all_out_nodes.end(), out_var);
  PADDLE_ENFORCE(iter != all_out_nodes.end(), "Cannot find out var %s",
                 out_var_name);

  // The following codes are designed to guarantee that ssa_map_ is still
  // an ssa graph after inplace is performed.
  // Step 1: Rename the following versions of out_var as the name of in_var
  // Step 2: Remove the following versions of out_var and append them to in_var
  // Be careful that the inputs of input op of out_var should not be renamed,
  // but outputs should be renamed.
  auto original_iter = iter;
  while (iter != all_out_nodes.end()) {
    auto *node = *iter;
    /* Step 1 */
    node->RenameVar(in_var_name);
    if (iter != original_iter) {
      for (auto *in : node->inputs) {
        if (in->IsOp() && in->Op()) {
          in->Op()->RenameOutput(out_var_name, in_var_name);
          in->Op()->RenameInput(out_var_name, in_var_name);
          in->Op()->Flush();
D
dzhwinter 已提交
237 238 239
        }
      }
    }
D
dzhwinter 已提交
240

241 242 243 244 245
    for (auto *out : node->outputs) {
      if (out->IsOp() && out->Op()) {
        out->Op()->RenameOutput(out_var_name, in_var_name);
        out->Op()->RenameInput(out_var_name, in_var_name);
        out->Op()->Flush();
D
dzhwinter 已提交
246 247
      }
    }
248 249 250 251

    /* Step 2 */
    all_in_nodes.emplace_back(node);
    ++iter;
D
dzhwinter 已提交
252
  }
D
dzhwinter 已提交
253

254 255
  /* Step 2 */
  all_out_nodes.erase(original_iter, all_out_nodes.end());
D
dzhwinter 已提交
256

257 258
  if (all_out_nodes.empty()) {
    ssa_map_.erase(out_var_name);
D
dzhwinter 已提交
259
  }
260 261
  op->Op()->RenameOutput(out_var_name, in_var_name);
  op->Op()->Flush();
D
dzhwinter 已提交
262 263
}

264 265 266
std::unordered_set<ir::Node *> InplacePass::FindNodesByName(
    const std::string &name, const std::vector<ir::Node *> &nodes) {
  std::unordered_set<ir::Node *> ret;
267 268
  for (auto *node : nodes) {
    if (node->Name() == name) {
269
      ret.insert(node);
D
dzhwinter 已提交
270 271
    }
  }
272
  return ret;
D
dzhwinter 已提交
273 274
}

275 276 277 278 279 280 281 282
void InplacePass::CollectInputArgsOfOpDesc(
    const OpDesc *op_desc, std::unordered_multiset<std::string> *in_args) {
  in_args->clear();
  for (auto &in_name : op_desc->InputArgumentNames()) {
    in_args->insert(in_name);
  }
}

283 284 285 286 287 288 289 290 291 292 293 294 295
void InplacePass::ApplyImpl(ir::Graph *graph) const {
  // Step 1: topo sort ops, collect skip vars
  auto ops = ir::TopologySortOperations(*graph);
  CollectSkipVars(graph, ops);

  // Step 2: build ssa var map
  for (auto *op_node : ops) {
    for (auto *in : op_node->inputs) {
      PADDLE_ENFORCE(in->IsVar());
      // Only create a new var node when var first occurs in input of op.
      if (ssa_map_.count(in->Name()) == 0) {
        ssa_map_[in->Name()].emplace_back(in);
      }
Z
Zeng Jinle 已提交
296
    }
L
liuwei1031 已提交
297

298 299 300 301
    // Always create a new var node for each output of op.
    for (auto *out : op_node->outputs) {
      PADDLE_ENFORCE(out->IsVar());
      ssa_map_[out->Name()].emplace_back(out);
302
    }
303
  }
304

305
  // Step 3: traverse ops and try inplace if possible
306 307 308 309
  bool use_cuda = Get<bool>(kUseCuda);
  VLOG(4) << "Inplace pass is applied when use_cuda = "
          << (use_cuda ? "true" : "false");

310 311
  for (auto *op_node : ops) {
    PADDLE_ENFORCE_NOT_NULL(op_node->Op(), "op_desc is nullptr");
L
liuwei1031 已提交
312

313 314
    auto *op_desc = op_node->Op();
    auto op_type = op_desc->Type();
L
liuwei1031 已提交
315

316 317
    // Skip op inside whitelist
    if (whitelist_ops_.count(op_type) > 0) {
D
dzhwinter 已提交
318 319
      continue;
    }
D
dzhwinter 已提交
320

321 322 323
    auto &infer_inplace = OpInfoMap::Instance().Get(op_type).infer_inplace_;

    if (!infer_inplace) {
D
dzhwinter 已提交
324 325 326
      continue;
    }

327
    auto in_to_outs = infer_inplace(*op_desc, use_cuda);
328 329 330 331 332
    if (in_to_outs.empty()) continue;

    std::unordered_multiset<std::string> all_in_args;
    CollectInputArgsOfOpDesc(op_desc, &all_in_args);

333 334 335
    for (auto &pair : in_to_outs) {
      auto &in_param = pair.first;
      auto &out_param = pair.second;
D
dzhwinter 已提交
336

337 338
      auto &in_args = op_desc->Input(in_param);
      auto &out_args = op_desc->Output(out_param);
L
liuwei1031 已提交
339

340 341 342 343 344
      if (in_args.empty()) {
        VLOG(4) << "Cannot inplace because Input(" << in_param
                << ") is empty in " << op_type;
        continue;
      }
L
liuwei1031 已提交
345

346 347 348 349
      if (out_args.empty()) {
        VLOG(4) << "Cannot inplace because Output(" << out_param
                << ") is empty in " << op_type;
        continue;
L
liuwei1031 已提交
350 351
      }

352 353
      auto &in_arg = in_args[0];
      auto &out_arg = out_args[0];
L
liuwei1031 已提交
354

355 356 357 358 359
      if (IsSkipVar(in_arg)) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is skipped in " << op_type;
        continue;
      }
L
liuwei1031 已提交
360

361 362 363 364
      if (IsSkipVar(out_arg)) {
        VLOG(4) << "Cannot inplace because Output(" << out_param
                << ")=" << out_arg << " is skipped in " << op_type;
        continue;
L
liuwei1031 已提交
365 366
      }

367 368 369 370 371 372
      if (in_arg == out_arg) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is the same with Output(" << out_param << ")=" << out_arg
                << " in " << op_type;
        continue;
      }
L
liuwei1031 已提交
373

374 375 376 377 378 379 380 381
      size_t in_arg_occur_times = all_in_args.count(in_arg);
      if (in_arg_occur_times > 1) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " occurs " << in_arg_occur_times << " times in input of op "
                << op_type;
        continue;
      }

382 383 384 385 386 387 388 389 390 391 392
      auto in_nodes = FindNodesByName(in_arg, op_node->inputs);
      PADDLE_ENFORCE(!in_nodes.empty(), "Input(%s)=%s cannot be found in op %s",
                     in_param, in_arg, op_type);

      if (in_nodes.size() > 1) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " occurs in other inputs of " << op_type;
        continue;
      }

      auto *in_node = *in_nodes.begin();
L
liuwei1031 已提交
393

394 395 396 397 398
      if (!NodeCanReused(in_node)) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is not reusable in " << op_type;
        continue;
      }
L
liuwei1031 已提交
399

400 401 402 403 404
      if (!IsLastVersionVar(in_node)) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is not the last version in " << op_type;
        continue;
      }
L
liuwei1031 已提交
405

406 407 408 409 410 411 412 413
      // If in_node is used as inputs of many ops, check whether all of that ops
      // depends on op_node. If not, in_node cannot be inplaced.
      if (in_node->outputs.size() > 1 &&
          !CheckOpDeps(op_node, in_node->outputs)) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is not lastly used in " << op_type;
        continue;
      }
L
liuwei1031 已提交
414

415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
      auto out_nodes = FindNodesByName(out_arg, op_node->outputs);
      PADDLE_ENFORCE(!out_nodes.empty(),
                     "Output(%s)=%s cannot be found in op %s", out_param,
                     out_arg, op_type);

      PADDLE_ENFORCE_EQ(
          out_nodes.size(), 1,
          "Wrong graph: Output(%s)=%s occurs in other outputs of op %s",
          out_param, out_arg, op_type);

      if (!FindNodesByName(in_arg, op_node->outputs).empty()) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " occurs in output of op " << op_type;
        continue;
      }

      if (!FindNodesByName(out_arg, op_node->inputs).empty()) {
        VLOG(4) << "Cannot inplace because Output(" << in_param
                << ")=" << out_arg << " occurs in input of op " << op_type;
        continue;
      }

      auto *out_node = *out_nodes.begin();
D
dzhwinter 已提交
438

439 440 441 442 443
      if (!NodeCanReused(out_node)) {
        VLOG(4) << "Cannot inplace because Output(" << out_param
                << ")=" << out_arg << " is not reusable in " << op_type;
        continue;
      }
D
dzhwinter 已提交
444

445 446 447 448 449 450 451
      if (in_node->Var()->GetType() != out_node->Var()->GetType()) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is not the same type with "
                << "Output(" << out_param << ")=" << out_arg << " in "
                << op_type;
        continue;
      }
D
dzhwinter 已提交
452

453
      if (NodeSize(*in_node->Var()) != NodeSize(*out_node->Var()) &&
454 455 456 457 458 459 460
          kSameShapeOpWhiteSet.count(op_desc->Type()) == 0) {
        VLOG(4) << "Cannot inplace because Input(" << in_param << ")=" << in_arg
                << " is not the same size with "
                << "Output(" << out_param << ")=" << out_arg << " in "
                << op_type;
        continue;
      }
Z
Zeng Jinle 已提交
461

462 463 464 465
      VLOG(4) << "Rename " << out_node->Name() << " with " << in_node->Name()
              << " in " << op_type;
      RenameInOut(op_node, in_node, out_node);
    }
D
dzhwinter 已提交
466
  }
D
dzhwinter 已提交
467
}
D
dzhwinter 已提交
468

469
}  // namespace ir
D
dzhwinter 已提交
470 471 472
}  // namespace framework
}  // namespace paddle

473 474
REGISTER_PASS(inplace_pass, paddle::framework::ir::InplacePass)
    .RequirePassAttr(paddle::framework::ir::kUseCuda);