prune.cc 18.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yang Yang 已提交
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. */

Y
Yi Wang 已提交
15
#include "paddle/fluid/framework/prune.h"
Y
Yang Yang 已提交
16

17 18
#include <glog/logging.h>

19
#include <queue>
20 21
#include "paddle/fluid/framework/op_proto_maker.h"

Y
Yang Yang 已提交
22 23 24
namespace paddle {
namespace framework {

25 26
const char kFeedOpType[] = "feed";
const char kFetchOpType[] = "fetch";
Y
Yang Yang 已提交
27

28 29 30 31
const char kRecurrent[] = "recurrent";
const char kStates[] = "states";
const char kExStates[] = "ex_states";

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
bool HasDependentInputVar(
    const proto::OpDesc& op_desc,
    const std::unordered_set<std::string>& dependent_vars) {
  for (auto& var : op_desc.inputs()) {
    for (auto& argu : var.arguments()) {
      if (dependent_vars.count(argu) != 0) {
        return true;
      }
    }
  }
  return false;
}

bool HasDependentOutputVar(
    const proto::OpDesc& op_desc,
    const std::unordered_set<std::string>& dependent_vars) {
Y
Yang Yang 已提交
48 49 50 51 52 53 54 55 56 57
  for (auto& var : op_desc.outputs()) {
    for (auto& argu : var.arguments()) {
      if (dependent_vars.count(argu) != 0) {
        return true;
      }
    }
  }
  return false;
}

58
bool IsTarget(const proto::OpDesc& op_desc) {
Y
Yang Yang 已提交
59 60 61 62 63 64
  if (op_desc.has_is_target()) {
    return op_desc.is_target();
  }
  return false;
}

65 66 67 68 69 70 71 72
bool HasTrueTarget(const proto::OpDesc& op_desc) {
  return op_desc.has_is_target() && op_desc.is_target();
}

bool HasFalseTarget(const proto::OpDesc& op_desc) {
  return op_desc.has_is_target() && !op_desc.is_target();
}

K
Kexin Zhao 已提交
73
int GetSubBlockIndex(const proto::OpDesc& op_desc) {
74
  // The block index >= 0, so -1 is used to indicate "NotFound".
K
Kexin Zhao 已提交
75 76
  for (auto& attr : op_desc.attrs()) {
    if (attr.type() == proto::AttrType::BLOCK) {
77 78 79 80
      PADDLE_ENFORCE_EQ(attr.has_block_idx(), true,
                        platform::errors::NotFound(
                            "Attribute sub_block is not found in operator %s",
                            op_desc.type()));
K
Kexin Zhao 已提交
81 82 83 84 85
      return attr.block_idx();
    }
  }
  return -1;
}
Y
Yang Yang 已提交
86

87 88 89 90 91 92 93 94 95 96 97 98
void SetSubBlockIndex(proto::OpDesc* op_desc, int sub_idx) {
  for (auto& attr : *op_desc->mutable_attrs()) {
    if (attr.type() == proto::AttrType::BLOCK) {
      PADDLE_ENFORCE_EQ(attr.has_block_idx(), true,
                        platform::errors::NotFound(
                            "Attribute sub_block is not found in operator %s",
                            op_desc->type()));
      attr.set_block_idx(sub_idx);
    }
  }
}

K
Kexin Zhao 已提交
99 100 101 102
bool HasSubBlock(const proto::OpDesc& op_desc) {
  return GetSubBlockIndex(op_desc) > 0;
}

103 104 105 106 107 108 109 110 111 112 113
int GetOpRole(const proto::OpDesc& op_desc) {
  for (auto& attr : op_desc.attrs()) {
    if (attr.name() == OpProtoAndCheckerMaker::OpRoleAttrName()) {
      PADDLE_ENFORCE_EQ(
          attr.has_i(), true,
          platform::errors::NotFound("Attribute %s is empty in operator %s",
                                     OpProtoAndCheckerMaker::OpRoleAttrName(),
                                     op_desc.type()));
      return attr.i();
    }
  }
114 115 116 117
  // If attr op_role is not found, it may be operator created in c++ test, like
  // prune_test.cc. In that case, the op_role should be defaut value, which is
  // kNotSpecified.
  return static_cast<int>(OpRole::kNotSpecified);
118 119
}

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
void AppendOpInputVarNames(const proto::OpDesc& op_desc,
                           std::unordered_set<std::string>* vars_set) {
  for (auto& var : op_desc.inputs()) {
    for (auto& arg : var.arguments()) {
      vars_set->emplace(arg);
    }
  }
}

void AppendOpOutputVarNames(const proto::OpDesc& op_desc,
                            std::unordered_set<std::string>* vars_set) {
  for (auto& var : op_desc.outputs()) {
    for (auto& arg : var.arguments()) {
      vars_set->emplace(arg);
    }
  }
}

138 139 140 141 142 143 144 145 146 147
int FindMapByValue(const std::map<int, int>& m, int val) {
  // The content in map should be >= 0, so -1 is used to indicate "NotFound".
  for (auto& pair : m) {
    if (pair.second == val) {
      return pair.first;
    }
  }
  return -1;
}

K
Kexin Zhao 已提交
148 149 150 151 152 153 154
// block_id is the idx of the current block in the input desc
// parent_block_id is the idx of the parent of the current block
// in the output desc, -1 means the current block is global block
// dependent_vars is passed recursively from the parent block to
// the child block to help pruning
void prune_impl(const proto::ProgramDesc& input, proto::ProgramDesc* output,
                int block_id, int parent_block_id,
155
                std::unordered_set<std::string>* dependent_vars,
156 157
                const std::set<std::string> feed_var_names,
                std::map<int, int>* pruned_origin_block_id_map) {
Y
Yang Yang 已提交
158
  auto& block = input.blocks(block_id);
Y
Yang Yang 已提交
159 160 161 162
  auto& ops = block.ops();

  bool expect_feed = true;
  for (auto& op_desc : ops) {
163 164 165 166
    PADDLE_ENFORCE_EQ(
        op_desc.type() != kFeedOpType || expect_feed, true,
        platform::errors::PreconditionNotMet(
            "All FeedOps are at the beginning of the ProgramDesc"));
Y
Yang Yang 已提交
167 168 169 170 171 172
    expect_feed = (op_desc.type() == kFeedOpType);
  }

  bool expect_fetch = true;
  for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) {
    auto& op_desc = *op_iter;
173 174 175
    PADDLE_ENFORCE_EQ(op_desc.type() != kFetchOpType || expect_fetch, true,
                      platform::errors::PreconditionNotMet(
                          "All FetchOps must at the end of the ProgramDesc"));
Y
Yang Yang 已提交
176 177 178 179 180 181
    expect_fetch = (op_desc.type() == kFetchOpType);
  }

  std::vector<bool> should_run;
  for (auto op_iter = ops.rbegin(); op_iter != ops.rend(); ++op_iter) {
    auto& op_desc = *op_iter;
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    // TODO(wanghaipeng03) reconstruct the follwing if/else block
    //                     to extract common code
    //
    // bool should_run_flag = false;
    // if (IsTarget........) {
    //   should_run_flag = true;
    // } else {
    //   if (parent......) {
    //     for (....) {
    //       for (.....) {
    //         if (.....) {
    //           should_run_flag = true;
    //         }
    //       }
    //     }
    //   }
    // }
    //
    // should_run.push_back(should_run_flag);
    // if (should_run_flag) {
    //   for (auto & var: op_desc.iputs()) {
    //     for (....) {
    //       if (.....) {
    //         dependent_vars->insert(argu);
    //       }
    //     }
    //   }
    // }

212 213 214 215 216 217 218 219
    if (IsTarget(op_desc) ||
        (HasDependentOutputVar(op_desc, *dependent_vars) &&
         (GetOpRole(op_desc) & static_cast<int>(OpRole::kOptimize)) == 0)) {
      // NOTE(zhiqiu): since optimize op takes the trainable parameters as
      // inputs and output, it may introduce wrong dependency graph.
      // For train mode, the optimize op should be in targets, so is not need
      // and not right to mark optimize op by its outputs.
      // For eval / infer mode, there is no optimize op in program.
Y
Yang Yang 已提交
220 221
      for (auto& var : op_desc.inputs()) {
        for (auto& argu : var.arguments()) {
222 223 224
          if (feed_var_names.count(argu) == 0) {
            dependent_vars->insert(argu);
          }
Y
Yang Yang 已提交
225 226 227 228 229
        }
      }
      should_run.push_back(true);
    } else {
      should_run.push_back(false);
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
      // If the output of an op modifies feed vars, the op should not clip.
      // For example, in the transformer structure, the third parameter returned
      // by beam_search op is generally assigned to a feed var. Cutting the
      // assign op will cause an error.
      if (parent_block_id != -1) {
        bool flag = false;
        for (auto& var : op_desc.outputs()) {
          for (auto& argu : var.arguments()) {
            if (feed_var_names.count(argu)) {
              flag = true;
            }
          }
        }
        if (flag) {
          should_run.back() = true;
245 246 247 248 249 250 251

          // If any op should run, then there inputs are dependent_vars
          for (auto& var : op_desc.inputs()) {
            for (auto& argu : var.arguments()) {
              dependent_vars->insert(argu);
            }
          }
252 253
        }
      }
Y
Yang Yang 已提交
254 255 256 257 258 259 260
    }
  }

  // since we are traversing the ProgramDesc in reverse order
  // we reverse the should_run vector
  std::reverse(should_run.begin(), should_run.end());

K
Kexin Zhao 已提交
261 262 263 264 265 266
  // copy the current block from input to output
  auto* block_field = output->mutable_blocks();
  *block_field->Add() = input.blocks(block_id);

  int output_block_id = output->blocks_size() - 1;
  auto* output_block = output->mutable_blocks(output_block_id);
267 268
  output_block->set_idx(output_block_id);
  output_block->set_parent_idx(parent_block_id);
K
Kexin Zhao 已提交
269

270 271
  (*pruned_origin_block_id_map)[output_block_id] = block_id;

K
Kexin Zhao 已提交
272
  auto* op_field = output_block->mutable_ops();
Y
Yang Yang 已提交
273 274 275
  op_field->Clear();
  for (size_t i = 0; i < should_run.size(); ++i) {
    if (should_run[i]) {
K
Kexin Zhao 已提交
276 277 278
      auto* op = op_field->Add();
      *op = input.blocks(block_id).ops(i);
      if (HasSubBlock(*op)) {
279
        VLOG(2) << "Pruning op which has sub block: " << op->type();
K
Kexin Zhao 已提交
280
        // create sub_block_dependent_vars here to help prune the sub block
281
        std::unordered_set<std::string> sub_block_dependent_vars;
282
        for (auto& var : op->inputs()) {
K
Kexin Zhao 已提交
283
          for (auto& argu : var.arguments()) {
284 285 286
            if (feed_var_names.count(argu) == 0) {
              sub_block_dependent_vars.insert(argu);
            }
K
Kexin Zhao 已提交
287 288
          }
        }
289
        for (auto& var : op->outputs()) {
K
Kexin Zhao 已提交
290
          for (auto& argu : var.arguments()) {
291 292 293
            if (feed_var_names.count(argu) == 0) {
              sub_block_dependent_vars.insert(argu);
            }
K
Kexin Zhao 已提交
294 295
          }
        }
296 297 298 299 300 301 302 303 304 305 306 307 308 309

        // Recurrent op's states are also dependent vars
        if (op->type() == kRecurrent) {
          auto& attributes = op->attrs();
          for (auto& attr : attributes) {
            if (attr.name() == kStates || attr.name() == kExStates) {
              for (auto& argu : attr.strings()) {
                if (feed_var_names.count(argu) == 0) {
                  sub_block_dependent_vars.insert(argu);
                }
              }
            }
          }
        }
K
Kexin Zhao 已提交
310 311 312
        // GetSubBlockIndex(*op) is the idx of the sub_block in the input desc
        // output_block_id is the idx of the current block in the output desc
        prune_impl(input, output, GetSubBlockIndex(*op), output_block_id,
313 314
                   &sub_block_dependent_vars, feed_var_names,
                   pruned_origin_block_id_map);
K
Kexin Zhao 已提交
315
      }
Y
Yang Yang 已提交
316 317
    }
  }
K
Kexin Zhao 已提交
318

K
Kexin Zhao 已提交
319 320 321
  // remove the VarDescs in BlockDesc that are not referenced in
  // the pruned OpDescs
  std::unordered_map<std::string, proto::VarDesc> var_map;
K
Kexin Zhao 已提交
322
  auto* var_field = output->mutable_blocks(output_block_id)->mutable_vars();
K
Kexin Zhao 已提交
323 324
  for (const auto& var : *var_field) {
    var_map[var.name()] = var;
K
Kexin Zhao 已提交
325 326
  }

327
  std::set<std::string> var_names;
K
Kexin Zhao 已提交
328 329
  for (const auto& op : *op_field) {
    auto& input_field = op.inputs();
K
Kexin Zhao 已提交
330 331
    for (auto& input_var : input_field) {
      for (auto& arg : input_var.arguments()) {
332 333 334
        if (var_map.count(arg) != 0) {
          var_names.insert(arg);
        }
K
Kexin Zhao 已提交
335 336 337
      }
    }
    auto& output_field = op.outputs();
K
Kexin Zhao 已提交
338 339
    for (auto& output_var : output_field) {
      for (auto& arg : output_var.arguments()) {
340 341 342
        if (var_map.count(arg) != 0) {
          var_names.insert(arg);
        }
K
Kexin Zhao 已提交
343 344 345
      }
    }
  }
346 347 348 349 350

  var_field->Clear();
  for (const auto& name : var_names) {
    *var_field->Add() = var_map[name];
  }
Y
Yang Yang 已提交
351
}
Y
Yang Yang 已提交
352

353
// TODO(fengjiayi): Prune() could be inplaced to avoid unnecessary copies
354 355 356
std::map<int, int> Prune(const proto::ProgramDesc& input,
                         const std::set<std::string>& feed_var_names,
                         proto::ProgramDesc* output) {
357
  std::unordered_set<std::string> dependent_vars;
K
fix bug  
Kexin Zhao 已提交
358
  output->clear_blocks();
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
  std::map<int, int> pruned_origin_block_id_map;
  prune_impl(input, output, 0, -1, &dependent_vars, feed_var_names,
             &pruned_origin_block_id_map);
  // update subblock idx
  for (int i = 0; i < output->blocks_size(); i++) {
    auto* pruned = output->mutable_blocks(i);
    auto* ops = pruned->mutable_ops();
    for (auto op_iter = ops->rbegin(); op_iter != ops->rend(); ++op_iter) {
      auto& op_desc = *op_iter;
      if (HasSubBlock(op_desc)) {
        int origin_sub_idx = GetSubBlockIndex(op_desc);
        auto sub_idx =
            FindMapByValue(pruned_origin_block_id_map, origin_sub_idx);
        PADDLE_ENFORCE_NE(sub_idx, -1,
                          platform::errors::NotFound(
                              "The origin sub block id should be found in "
                              "pruned_progin_block_id_map"));
        SetSubBlockIndex(&op_desc, sub_idx);
      }
378 379
    }
  }
380
  return pruned_origin_block_id_map;
381 382
}

383
void PruneBackwardImpl(proto::BlockDesc* origin, proto::BlockDesc* pruned) {
384 385 386
  std::unordered_set<std::string> op_input_vars;
  std::unordered_set<std::string> op_output_vars;

387 388
  // Step 1. Mark backward, optimize and lrsched ops in the block
  auto* ops = origin->mutable_ops();
389 390
  for (auto op_iter = ops->begin(); op_iter != ops->end(); ++op_iter) {
    auto& op_desc = *op_iter;
391 392 393 394
    auto op_role = GetOpRole(op_desc);
    if (op_role & static_cast<int>(OpRole::kOptimize) ||
        op_role & static_cast<int>(OpRole::kBackward) ||
        op_role & static_cast<int>(OpRole::kLRSched)) {
395 396 397 398
      op_desc.set_is_target(false);
    }
  }

399 400 401 402 403
  // Step 2. Copy the forward ops which have not been set false target to new
  // ProgramDesc
  // Note: The proto::ProgramDesc doesn't have interface
  //       to remove op and var
  auto* op_field = pruned->mutable_ops();
404 405
  op_field->Clear();
  for (auto op_iter = ops->begin(); op_iter != ops->end(); ++op_iter) {
406
    if (!HasFalseTarget(*op_iter)) {
407
      auto* op = op_field->Add();
408 409
      AppendOpInputVarNames(*op_iter, &op_input_vars);
      AppendOpOutputVarNames(*op_iter, &op_output_vars);
410 411 412 413
      *op = *op_iter;
    }
  }

414
  // Step 3. Copy the forward vars to new ProgramDesc,
415
  // construct all var's map before clear
416 417
  auto* origin_vars = origin->mutable_vars();
  auto* pruned_vars = pruned->mutable_vars();
418
  std::unordered_map<std::string, proto::VarDesc> var_map;
419
  for (const auto& var : *origin_vars) {
420 421
    var_map[var.name()] = var;
  }
422 423
  pruned_vars->Clear();

424 425 426 427
  std::unordered_set<std::string> var_names;
  var_names.insert(op_input_vars.begin(), op_input_vars.end());
  var_names.insert(op_output_vars.begin(), op_output_vars.end());
  for (const auto& name : var_names) {
428
    if (var_map.count(name)) {
429 430
      // NOTE(zhiqiu): For operator in a conditional block, the related vars
      // may not exist in current block, but in its futher block.
431 432
      *pruned_vars->Add() = var_map[name];
    }
433
  }
434
}  // namespace framework
435

436
std::tuple<framework::ProgramDesc, std::map<int, int>> PruneBackward(
437 438 439 440
    const framework::ProgramDesc& origin) {
  // Copy original ProgramDesc, origin can't be change
  framework::ProgramDesc origin_clone(origin);

441 442 443 444 445 446 447 448
  // Step 1. check if the program contains grad loss operator.
  // If not, the program need no pruning.
  bool has_loss_grad_op = false;
  std::queue<int> block_contains_loss;
  std::queue<int> block_contains_loss_grad;
  for (size_t i = 0; i < origin_clone.Size(); i++) {
    auto block_ops = origin_clone.Block(i).AllOps();
    for (auto op : block_ops) {
449 450
      int op_role = BOOST_GET_MUTABLE(
          int, op->GetAttr(OpProtoAndCheckerMaker::OpRoleAttrName()));
451 452 453 454 455 456
      if (op_role == (static_cast<int>(OpRole::kBackward) |
                      static_cast<int>(OpRole::kLoss))) {
        op->SetIsTarget(false);
        has_loss_grad_op = true;
        break;
      }
457 458 459
    }
  }

460 461 462 463 464 465 466 467
  std::map<int, int> pruned_progin_block_id_map;
  if (!has_loss_grad_op) {
    // No pruning, fast return a copy of the origin ProgramDesc with an empty
    // map, means default mapped, i.e.{0:0, 1:1, ..., n:n}.
    return std::make_tuple(framework::ProgramDesc(origin_clone),
                           pruned_progin_block_id_map);
  }

468 469
  proto::ProgramDesc pruned_desc;
  pruned_desc.clear_blocks();
470

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
  // Step 2. Prune backward for each block.
  for (size_t i = 0; i < origin_clone.Size(); i++) {
    auto pruned = proto::BlockDesc();
    auto origin = origin_clone.Proto()->mutable_blocks(i);

    PruneBackwardImpl(origin, &pruned);
    // If pruned block contains no operator, it means the block is a
    // backward block and should be pruned.
    // Else, add the block to pruned_desc and update its id & parent_id.
    if (pruned.ops_size() > 0) {
      auto* block_field = pruned_desc.mutable_blocks();
      *block_field->Add() = pruned;

      auto pruned_block_id = pruned_desc.blocks_size() - 1;
      pruned_progin_block_id_map[pruned_block_id] = origin->idx();
      auto* pruned_block = pruned_desc.mutable_blocks(pruned_block_id);
      pruned_block->set_idx(pruned_block_id);

      if (origin->parent_idx() == -1) {
        pruned_block->set_parent_idx(-1);
      } else {
        auto parent_idx =
            FindMapByValue(pruned_progin_block_id_map, origin->parent_idx());
        PADDLE_ENFORCE_NE(parent_idx, -1,
                          platform::errors::NotFound(
                              "The origin parent block id is not found in "
                              "pruned_progin_block_id_map"));
        pruned_block->set_parent_idx(parent_idx);
      }
    }
  }
502

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  // Step 3. Update subblock attribute for conditional operator.
  // This should be performed after all blocks pruned.
  for (int i = 0; i < pruned_desc.blocks_size(); i++) {
    auto* pruned = pruned_desc.mutable_blocks(i);
    auto* ops = pruned->mutable_ops();
    for (auto op_iter = ops->begin(); op_iter != ops->end(); ++op_iter) {
      auto& op_desc = *op_iter;
      if (HasSubBlock(op_desc)) {
        int origin_sub_idx = GetSubBlockIndex(op_desc);
        auto sub_idx =
            FindMapByValue(pruned_progin_block_id_map, origin_sub_idx);
        PADDLE_ENFORCE_NE(sub_idx, -1,
                          platform::errors::NotFound(
                              "The origin sub block id is not found in "
                              "pruned_progin_block_id_map"));
        SetSubBlockIndex(&op_desc, sub_idx);
      }
    }
  }

  // Step 4. Return a tuple
  return std::make_tuple(framework::ProgramDesc(pruned_desc),
                         pruned_progin_block_id_map);
}  // namespace framework
527

Y
Yang Yang 已提交
528 529
}  // namespace framework
}  // namespace paddle