while_op_helper.cc 9.3 KB
Newer Older
S
sneaxiy 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// Copyright (c) 2019 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/operators/controlflow/while_op_helper.h"
16

S
sneaxiy 已提交
17
#include <string>
18

19
#include "paddle/fluid/string/string_helper.h"
S
sneaxiy 已提交
20

21 22 23 24 25 26
namespace paddle {
namespace framework {
class BlockDesc;
}  // namespace framework
}  // namespace paddle

S
sneaxiy 已提交
27 28 29 30 31 32 33 34 35 36 37
namespace paddle {
namespace operators {

// Set skip variables of while_op and while_grad_op
// These variables should be skipped when eager deletion enables.
// It is because:
//  1. while_grad_op needs some variables defined in while_op.
//  2. while_grad_op needs variables from the previous time step.
static void SetSkipVars(const OpVariant &op, std::vector<std::string> attr) {
  auto &attrs = const_cast<framework::AttributeMap &>(op.Attrs());
  VLOG(2) << "Prepare to skip " << attr.size()
38
          << " var(s): " << string::join_strings(attr, ' ');
S
sneaxiy 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  attrs[kSkipEagerDeletionVars] = std::move(attr);
}

// Check whether the forward while_op and while_grad_op match
// The program may have many while_ops.
static bool IsMatchedWhileOpAndWhileGradOp(const OpVariant &fwd_op,
                                           const OpVariant &grad_op) {
  return fwd_op.Inputs().at(kX) == grad_op.Inputs().at(kX) &&
         fwd_op.Outputs().at(kOutputs) == grad_op.Inputs().at(kOutputs);
}

// Test whether the variable is skippable in forward while_op
// The variable is skippable in while_op when the variable used in while_grad
// is not from grad_block.
static bool IsSkippableVar(const std::string &name,
                           framework::BlockDesc *grad_block) {
  return name != framework::kEmptyVarName && !grad_block->HasVar(name);
}

static void ModifyWhileOpAndWhileGradOpAttr(const OpVariant &fwd_op,
                                            const OpVariant &bwd_op) {
  auto *grad_block = bwd_op.Attr<framework::BlockDesc *>(kStepBlock);

  // Find all skippable variables in forward while_op
  std::unordered_set<std::string> forward_skip_vars;
  for (auto *op_desc : grad_block->AllOps()) {
    for (auto &in_arg_name : op_desc->InputArgumentNames()) {
      if (IsSkippableVar(in_arg_name, grad_block)) {
        forward_skip_vars.insert(in_arg_name);
      }
    }

    for (auto &out_arg_name : op_desc->OutputArgumentNames()) {
      if (IsSkippableVar(out_arg_name, grad_block)) {
        forward_skip_vars.insert(out_arg_name);
      }
    }
  }

78 79 80
  SetSkipVars(fwd_op,
              std::vector<std::string>(forward_skip_vars.begin(),
                                       forward_skip_vars.end()));
S
sneaxiy 已提交
81 82 83 84 85 86

  // Find all skippable variables in while_grad_op
  // The skipped variables are those which would be used across time steps.
  auto &fwd_input = fwd_op.Inputs().at(kX);
  auto &in_grads = bwd_op.Outputs().at(framework::GradVarName(kX));
  PADDLE_ENFORCE_EQ(
87 88
      fwd_input.size(),
      in_grads.size(),
89 90 91 92
      platform::errors::PreconditionNotMet(
          "Backward output gradient number does not match forward input number."
          "The number of forward input number is %d and the number of backward "
          "output geadient number is %d.",
93 94
          fwd_input.size(),
          in_grads.size()));
S
sneaxiy 已提交
95 96 97 98 99 100 101 102 103 104

  std::unordered_set<std::string> backward_skip_vars;
  for (size_t i = 0; i < in_grads.size(); ++i) {
    if (in_grads[i] == framework::kEmptyVarName) {
      continue;
    }
    backward_skip_vars.insert(in_grads[i]);
    backward_skip_vars.insert(framework::GradVarName(fwd_input[i]));
  }

105 106 107
  SetSkipVars(bwd_op,
              std::vector<std::string>(backward_skip_vars.begin(),
                                       backward_skip_vars.end()));
S
sneaxiy 已提交
108 109 110 111 112
}

// Find all while_ops and while_grad_ops in the graph or program
// The while_grad_op and while_op may located in different blocks
// So we should traverse all blocks in the program and find them out.
113 114
static void FindAllWhileAndWhileGradOp(const framework::ProgramDesc &program,
                                       std::vector<OpVariant> *while_ops,
S
sneaxiy 已提交
115
                                       std::vector<OpVariant> *while_grad_ops) {
116
  PADDLE_ENFORCE_GE(
117 118
      while_ops->size(),
      while_grad_ops->size(),
119 120 121 122
      platform::errors::PreconditionNotMet(
          "There are more while_grad_ops than forward while_ops in the graph "
          "or program, the number of while_ops is %d and the number of "
          "while_grad_ops is %d.",
123 124
          while_ops->size(),
          while_grad_ops->size()));
125 126
  for (size_t i = 1; i < program.Size(); ++i) {
    auto &block = program.Block(i);
S
sneaxiy 已提交
127 128 129 130 131 132 133 134 135 136
    for (size_t j = 0; j < block.OpSize(); ++j) {
      auto *op = block.Op(j);
      if (op->Type() == "while") {
        while_ops->emplace_back(op);
      } else if (op->Type() == "while_grad") {
        while_grad_ops->emplace_back(op);
      }
    }
  }

137
  PADDLE_ENFORCE_GE(
138 139
      while_ops->size(),
      while_grad_ops->size(),
140 141 142 143
      platform::errors::InvalidArgument(
          "There are more while_grad_ops than forward while_ops in the graph "
          "or program, the number of while_ops is %d and the number of "
          "while_grad_ops is %d.",
144 145
          while_ops->size(),
          while_grad_ops->size()));
S
sneaxiy 已提交
146 147 148
}

static void PrepareSafeEagerDeletionOnWhileOpAndWhileGradOpImpl(
149 150
    const framework::ProgramDesc &program,
    std::vector<OpVariant> *while_ops,
151 152
    std::vector<OpVariant> *while_grad_ops) {
  FindAllWhileAndWhileGradOp(program, while_ops, while_grad_ops);
S
sneaxiy 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167

  VLOG(2) << "Found while op num: " << while_ops->size()
          << ", while grad op num: " << while_grad_ops->size();

  if (while_grad_ops->empty()) {
    return;
  }

  std::unordered_set<OpVariant, OpVariant::Hasher> while_op_set(
      while_ops->begin(), while_ops->end());

  for (auto &bwd_op : *while_grad_ops) {
    const OpVariant *matched_fwd_op = nullptr;
    for (auto &fwd_op : while_op_set) {
      if (IsMatchedWhileOpAndWhileGradOp(fwd_op, bwd_op)) {
168 169
        PADDLE_ENFORCE_EQ(matched_fwd_op,
                          nullptr,
170 171 172
                          platform::errors::PreconditionNotMet(
                              "Found multiple while forward ops match while "
                              "grad ops."));
S
sneaxiy 已提交
173 174 175 176
        matched_fwd_op = &fwd_op;
      }
    }
    PADDLE_ENFORCE_NOT_NULL(matched_fwd_op,
177 178
                            platform::errors::PreconditionNotMet(
                                "Cannot find matched forward while op."));
S
sneaxiy 已提交
179 180 181 182 183 184
    ModifyWhileOpAndWhileGradOpAttr(*matched_fwd_op, bwd_op);
    while_op_set.erase(*matched_fwd_op);
  }
}

void PrepareSafeEagerDeletionOnWhileOpAndWhileGradOp(
185 186
    const framework::ProgramDesc &program,
    int block_id,
S
sneaxiy 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    const std::vector<std::unique_ptr<framework::OperatorBase>> &all_ops) {
  // If block_id is not 0, returns
  // This is because all while_ops and while_grad_ops in the whole program
  // would be processed when block_id is 0 (i.e. when Executor::Run() or
  // ParallelExecutor constructs).

  // What's more, all while_ops and while_grad_ops must be processed when
  // block_id is zero. If not, while_op may run first and erase variables
  // used in while_grad_op, and in this moment, while_grad_ops may be not
  // constructed yet.
  if (block_id != 0) return;

  std::vector<OpVariant> fwd_ops, bwd_ops;
  for (auto &op : all_ops) {
    if (op->Type() == "while") {
      fwd_ops.emplace_back(op.get());
    } else if (op->Type() == "while_grad") {
      bwd_ops.emplace_back(op.get());
    }
  }
207 208
  PrepareSafeEagerDeletionOnWhileOpAndWhileGradOpImpl(
      program, &fwd_ops, &bwd_ops);
S
sneaxiy 已提交
209 210 211
}

void PrepareSafeEagerDeletionOnWhileOpAndWhileGradOp(
212
    const framework::ProgramDesc &program,
213 214 215 216
    const std::vector<OpVariant> &while_ops,
    const std::vector<OpVariant> &while_grad_ops) {
  std::vector<OpVariant> fwd_ops = while_ops;
  std::vector<OpVariant> bwd_ops = while_grad_ops;
S
sneaxiy 已提交
217

218 219
  PrepareSafeEagerDeletionOnWhileOpAndWhileGradOpImpl(
      program, &fwd_ops, &bwd_ops);
S
sneaxiy 已提交
220 221
}

222 223 224 225 226
// Make while_op could run on GPU place
bool GetCondData(const framework::LoDTensor &cond) {
  if (platform::is_cpu_place(cond.place())) {
    return cond.data<bool>()[0];
  }
227 228
  // when platform::is_gpu_place(cond.place()) or
  // platform::is_npu_place(cond.place()) is true
229
  std::unique_ptr<framework::LoDTensor> cpu_cond{new framework::LoDTensor()};
230 231
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) || \
    defined(PADDLE_WITH_ASCEND_CL)
232 233 234
  framework::TensorCopySync(cond, platform::CPUPlace(), cpu_cond.get());
#else
  PADDLE_THROW(platform::errors::PreconditionNotMet(
235 236 237
      "This version of PaddlePaddle does NOT support GPU/NPU but got GPU/NPU "
      "tensor "
      "Cond in WhileOp. Please compile WITH_GPU or WITH_ASCEND_CL option."));
238 239 240 241
#endif
  return cpu_cond->data<bool>()[0];
}

242 243 244 245 246 247 248 249 250 251 252
bool StrInVaraiableNameMap(const std::string &name,
                           const framework::VariableNameMap &var_names) {
  for (auto &ipt : var_names) {
    if (std::find(ipt.second.begin(), ipt.second.end(), name) !=
        ipt.second.end()) {
      return true;
    }
  }
  return false;
}

S
sneaxiy 已提交
253 254
}  // namespace operators
}  // namespace paddle