while_op.cc 22.8 KB
Newer Older
C
chengduo 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
// 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.
Y
Yang Yang(Tony) 已提交
14

Y
Yi Wang 已提交
15 16 17
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
S
sneaxiy 已提交
18
#include "paddle/fluid/operators/controlflow/while_op_helper.h"
Y
Yang Yang(Tony) 已提交
19

20 21 22
#ifdef PADDLE_WITH_MKLDNN
#include "paddle/fluid/platform/mkldnn_helper.h"
#endif
W
wanghuancoder 已提交
23 24 25 26 27 28 29 30
namespace paddle {
namespace framework {
class InferShapeContext;
class OpDesc;
class VarDesc;
}  // namespace framework
}  // namespace paddle

Y
Yang Yang(Tony) 已提交
31 32 33 34 35 36
namespace paddle {
namespace operators {

using StepScopeVar = std::vector<framework::Scope *>;
using LoDTensor = framework::LoDTensor;

S
sneaxiy 已提交
37 38 39 40 41 42 43 44 45 46 47
namespace {  // NOLINT
static std::string GetSkipEagerDeletionVarsDebugString(
    const std::vector<std::string> &vars) {
  std::string str = "Skip " + std::to_string(vars.size()) +
                    " var(s) in eager deletion mode: ";
  for (auto &var : vars) {
    str.append(var);
    str.push_back(' ');
  }
  return str;
}
48
}  // namespace
Y
Yang Yang(Tony) 已提交
49 50 51

class WhileOp : public framework::OperatorBase {
 public:
52 53
  WhileOp(const std::string &type,
          const framework::VariableNameMap &inputs,
Y
Yang Yang(Tony) 已提交
54 55 56 57
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : framework::OperatorBase(type, inputs, outputs, attrs) {}

58 59 60
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
61 62 63
    PADDLE_ENFORCE_NOT_NULL(scope.FindVar(Input(kCondition)),
                            platform::errors::NotFound(
                                "Input(Condition) of WhileOp is not found."));
64

Y
Yang Yang(Tony) 已提交
65
    auto &cond = scope.FindVar(Input(kCondition))->Get<LoDTensor>();
66
    PADDLE_ENFORCE_EQ(
67 68
        cond.dims(),
        phi::make_ddim({1}),
69 70 71
        platform::errors::InvalidArgument(
            "The shape of Input(Condition) of WhileOp must be 1. But now "
            "the Condition's shape is ",
72 73
            cond.dims().to_str(),
            ".\n"));
Y
Yang Yang(Tony) 已提交
74

75 76 77 78 79 80
#ifdef PADDLE_WITH_MKLDNN
    // (jczaja) Executor on being destroyed clears oneDNN cache and
    // resets registered model data layout. This is unwanted for nested
    // Executors (executors declared inside control ops)
    platform::DontClearMKLDNNCache(dev_place);
#endif
D
dzhwinter 已提交
81
    framework::Executor executor(dev_place);
Y
Yu Yang 已提交
82
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
D
dzhwinter 已提交
83

Y
Yang Yang(Tony) 已提交
84
    auto *program = block->Program();
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    bool is_test = Attr<bool>("is_test");

    std::set<std::string> no_copy_var_names;
    if (!is_test) {
      const std::vector<framework::OpDesc *> &all_ops = block->AllOps();
      for (const framework::OpDesc *op : all_ops) {
        const framework::VariableNameMap &input_var_names = op->Inputs();
        const framework::VariableNameMap &output_var_names = op->Outputs();
        for (auto &ipt : input_var_names) {
          for (const std::string &var_name : ipt.second) {
            if (StrInVaraiableNameMap(var_name, output_var_names)) {
              no_copy_var_names.insert(var_name);
            }
          }
        }
      }
    }
Y
Yang Yang(Tony) 已提交
102 103 104

    auto step_scopes =
        scope.FindVar(Output(kStepScopes))->GetMutable<StepScopeVar>();
105 106 107 108 109 110 111 112 113 114 115

    if (step_scopes->size() > 0) {
      platform::DeviceContextPool::Instance().Get(dev_place)->Wait();
      for (auto &s : *step_scopes) {
        if (scope.HasKid(s)) {
          scope.DeleteScope(s);
        }
      }
      step_scopes->clear();
    }

116 117
    PADDLE_ENFORCE_EQ(step_scopes->size(),
                      0,
118 119
                      platform::errors::PreconditionNotMet(
                          "The Output(StepScope) of WhileOp should be empty."));
X
Xin Pan 已提交
120

121
    bool cond_data = GetCondData(cond);
S
sneaxiy 已提交
122
    auto &skip_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);
S
sneaxiy 已提交
123
    VLOG(2) << GetSkipEagerDeletionVarsDebugString(skip_vars);
S
fix bug  
sneaxiy 已提交
124

S
sneaxiy 已提交
125
    auto ctx = executor.Prepare(*program, block->ID(), skip_vars);
126
    if (!is_test) {
127
      while (cond_data) {
128 129
        auto &current_scope = scope.NewScope();
        step_scopes->push_back(&current_scope);
130 131 132 133 134 135 136 137 138 139 140 141

        std::vector<std::string> rename_vars;
        for (const std::string &input_var_name : Inputs(kX)) {
          if (no_copy_var_names.find(input_var_name) ==
              no_copy_var_names.end()) {
            std::string input_var_rename = input_var_name + kSuffix;
            framework::Variable *input_var = scope.FindVar(input_var_name);
            if (input_var->IsType<framework::LoDTensor>()) {
              rename_vars.push_back(input_var_rename);
              auto input_var_tensor = input_var->Get<LoDTensor>();
              auto *rename_input_var_tensor =
                  current_scope.Var(input_var_rename)->GetMutable<LoDTensor>();
142 143
              framework::TensorCopy(
                  input_var_tensor, dev_place, rename_input_var_tensor);
144 145 146 147
              rename_input_var_tensor->set_lod(input_var_tensor.lod());
            }
          }
        }
148 149
        executor.RunPreparedContext(
            ctx.get(), &current_scope, false, true, true);
150 151 152 153 154 155

        for (auto &var_rename : rename_vars) {
          std::string input_var_name =
              var_rename.substr(0, var_rename.size() - strlen(kSuffix));
          current_scope.Rename(var_rename, input_var_name);
        }
156 157
        cond_data =
            GetCondData(scope.FindVar(Input(kCondition))->Get<LoDTensor>());
158 159
      }
    } else {
Y
Yang Yang(Tony) 已提交
160
      auto &current_scope = scope.NewScope();
161
      executor.CreateVariables(*program, &current_scope, block->ID());
162
      while (cond_data) {
163 164 165 166 167 168 169 170 171 172 173 174 175
        for (auto &name : current_scope.LocalVarNames()) {
          auto *var = current_scope.Var(name);
          if (var->IsType<framework::LoDTensor>()) {
            // Clear all lod information for all lod_tensors.
            auto *t = var->GetMutable<framework::LoDTensor>();
            framework::LoD empty_lod;
            t->set_lod(empty_lod);
          } else if (var->IsType<framework::LoDTensorArray>()) {
            // Clear elements of all tensor arrays.
            auto *t = var->GetMutable<framework::LoDTensorArray>();
            t->clear();
          }
        }
176 177
        executor.RunPreparedContext(
            ctx.get(), &current_scope, false, false, false);
178 179
        cond_data =
            GetCondData(scope.FindVar(Input(kCondition))->Get<LoDTensor>());
C
chengduo 已提交
180
      }
181
      scope.DeleteScope(&current_scope);
Y
Yang Yang(Tony) 已提交
182 183 184 185 186 187
    }
  }
};

class WhileOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
188
  void Make() override {
Y
Yang Yu 已提交
189
    AddInput(kX,
Y
Yang Yang(Tony) 已提交
190 191 192 193 194 195 196
             "A set of variables, which are required by operators inside the "
             "block of While Op.")
        .AsDuplicable();
    AddInput(
        kCondition,
        "(Bool) An scalar. When it's False, the While Op will be terminated.")
        .AsDuplicable();
Y
Yang Yang(Tony) 已提交
197
    AddOutput(kOutputs,
Y
Yang Yang(Tony) 已提交
198
              "A set of variables, which will be assigned with values "
Y
Yang Yang(Tony) 已提交
199
              "generated by the operators inside the block of While Op.")
Y
Yang Yang(Tony) 已提交
200 201 202 203 204
        .AsDuplicable();
    AddOutput(kStepScopes,
              "(StepScopeVar) A vector of local scope, which size equals the "
              "step number of While Op. The i'th scope storages temporary "
              "variables generated in the i'th step.");
Y
Yu Yang 已提交
205 206
    AddAttr<framework::BlockDesc *>(kStepBlock,
                                    "The step block inside WhileOp");
207 208 209 210
    AddAttr<bool>("is_test",
                  "(bool, default false) Set to true for inference only, false "
                  "for training. Some layers may run faster when this is true.")
        .SetDefault(false);
S
sneaxiy 已提交
211
    AddAttr<std::vector<std::string>>(kSkipEagerDeletionVars,
S
fix bug  
sneaxiy 已提交
212 213
                                      "Vars that would skip eager deletion."
                                      "Users should not set this manually.")
C
CtfGo 已提交
214 215
        .SetDefault(std::vector<std::string>())
        .AsExtra();
Y
Yang Yang(Tony) 已提交
216 217 218 219 220 221 222
    AddComment(R"DOC(
)DOC");
  }
};

class WhileGradOp : public framework::OperatorBase {
 public:
223 224
  WhileGradOp(const std::string &type,
              const framework::VariableNameMap &inputs,
Y
Yang Yang(Tony) 已提交
225 226 227 228
              const framework::VariableNameMap &outputs,
              const framework::AttributeMap &attrs)
      : framework::OperatorBase(type, inputs, outputs, attrs) {}

229 230 231
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
232
    PADDLE_ENFORCE_EQ(
233 234
        Attr<bool>("is_test"),
        false,
235 236
        platform::errors::InvalidArgument(
            "WhileGradOp is only callable when is_test is false."));
237 238 239
    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(dev_place);
D
dzhwinter 已提交
240
    framework::Executor executor(dev_place);
Y
Yu Yang 已提交
241
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
Y
Yang Yang(Tony) 已提交
242
    auto *program = block->Program();
S
sneaxiy 已提交
243 244

    auto &skip_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);
S
sneaxiy 已提交
245
    VLOG(2) << GetSkipEagerDeletionVarsDebugString(skip_vars);
S
sneaxiy 已提交
246
    auto ctx = executor.Prepare(*program, block->ID(), skip_vars);
Y
Yang Yang(Tony) 已提交
247 248 249 250

    auto *step_scopes =
        scope.FindVar(Input(kStepScopes))->GetMutable<StepScopeVar>();

Y
Yang Yang(Tony) 已提交
251 252 253 254
    auto outside_og_names = Inputs(framework::GradVarName(kOutputs));
    auto inside_og_names =
        Attr<std::vector<std::string>>("original_output_grad");

255 256
    PADDLE_ENFORCE_EQ(outside_og_names.size(),
                      inside_og_names.size(),
257 258 259 260 261 262
                      platform::errors::InvalidArgument(
                          "The number of original output gradient names "
                          "does not match the number of backward input "
                          "gradient names. The number of Backward input "
                          "names is %d and the numbers of original output "
                          "gradient names is %d.",
263 264
                          outside_og_names.size(),
                          inside_og_names.size()));
Y
Yang Yang(Tony) 已提交
265

Y
Yang Yang(Tony) 已提交
266
    for (auto cur_scope_iter = step_scopes->rbegin();
267 268
         cur_scope_iter != step_scopes->rend();
         ++cur_scope_iter) {
M
minqiyang 已提交
269 270
      VLOG(3) << "Start backward at time_step "
              << cur_scope_iter - step_scopes->rbegin();
Y
Yang Yang(Tony) 已提交
271 272 273 274 275
      framework::Scope &cur_scope = **cur_scope_iter;
      // Link OG from outside to inside
      for (size_t i = 0; i < outside_og_names.size(); ++i) {
        auto outside_og_name = outside_og_names[i];
        auto inside_og_name = inside_og_names[i];
M
minqiyang 已提交
276 277
        VLOG(8) << "Linking outside " << outside_og_name << " --> inside "
                << inside_og_name;
C
chengduo 已提交
278 279 280 281
        if (scope.FindVar(outside_og_name) == nullptr) {
          continue;
        }

282 283
        auto &og_outside = *scope.FindVar(outside_og_name);
        auto &og_inside = *cur_scope.Var(inside_og_name);
S
sneaxiy 已提交
284
        if (og_outside.IsType<framework::LoDTensor>()) {
Y
Yang Yang(Tony) 已提交
285
          auto &outside_tensor = og_outside.Get<framework::LoDTensor>();
286
          auto &inside_tensor = *og_inside.GetMutable<framework::LoDTensor>();
Y
Yang Yang(Tony) 已提交
287 288
          inside_tensor.set_lod(outside_tensor.lod());
          inside_tensor.ShareDataWith(outside_tensor);
S
sneaxiy 已提交
289
        } else if (og_outside.IsType<framework::LoDTensorArray>()) {
290 291
          auto outside_array =
              og_outside.GetMutable<framework::LoDTensorArray>();
Y
Yang Yang(Tony) 已提交
292
          auto &inside_array =
293
              *og_inside.GetMutable<framework::LoDTensorArray>();
294 295 296
          inside_array.clear();
          inside_array.resize(outside_array->size());
          VLOG(8) << outside_og_name << " size = " << outside_array->size();
Y
Yang Yang(Tony) 已提交
297 298

          for (size_t j = 0; j < inside_array.size(); ++j) {
299 300 301 302 303 304 305
            if (!outside_array->at(j).IsInitialized()) {
              outside_array->at(j).Resize({0});
            }
            VLOG(8) << j << " " << outside_array->at(j).numel();
            if (outside_array->at(j).numel() != 0) {
              inside_array[j].set_lod(outside_array->at(j).lod());
              inside_array[j].ShareDataWith(outside_array->at(j));
Y
Yang Yang(Tony) 已提交
306
            } else {
307
              PADDLE_ENFORCE_EQ(
308 309
                  inside_array[j].numel(),
                  0,
310 311 312
                  platform::errors::InvalidArgument(
                      "The numel of %d-th element of var %s (LoDTensorArray) "
                      "in while block must be 0, but received its numel is %d.",
313 314 315
                      j,
                      inside_og_name,
                      inside_array[j].numel()));
Y
Yang Yang(Tony) 已提交
316 317
            }
          }
C
chengduo 已提交
318
        } else {
319 320 321
          PADDLE_THROW(platform::errors::Unimplemented(
              "Currently only support LoDTensor and LoDTensorArray in "
              "WhileGradOp."));
Y
Yang Yang(Tony) 已提交
322 323
        }
      }
324 325
      executor.RunPreparedContext(
          ctx.get(), *cur_scope_iter, false, true, true);
Y
Yang Yang(Tony) 已提交
326

C
chengduo 已提交
327 328 329
      // The Outputs(kXGRAD) contains the names of the gradient of parameters
      // and inputs.
      auto &pg_ig_names = Outputs(kXGRAD);
Y
Yang Yu 已提交
330
      auto &p_names = Inputs(kX);
331 332
      PADDLE_ENFORCE_EQ(pg_ig_names.size(),
                        p_names.size(),
333 334 335 336 337
                        platform::errors::PreconditionNotMet(
                            "The number of names in Outputs(X@GRAD) does not "
                            "match the number of names in Inputs(X). The "
                            "number of names in Outputs(X@GRAD) is %d and "
                            "the number of names in Inputs(X) is %d.",
338 339
                            pg_ig_names.size(),
                            p_names.size()));
C
chengduo 已提交
340 341
      for (size_t param_id = 0; param_id < pg_ig_names.size(); ++param_id) {
        if (pg_ig_names[param_id] == framework::kEmptyVarName) {
342
          continue;  // parameter doesn't have gradient
Y
Yang Yang(Tony) 已提交
343 344
        }
        auto inside_grad_name = framework::GradVarName(p_names[param_id]);
Y
Yang Yang(Tony) 已提交
345

C
chengduo 已提交
346 347 348 349
        // for some grad_op, their input doesn't have gradient,
        // for example lookup_table_grad_op, the input(Idx) doesn't have
        // gradient.
        auto pg_ig_var = cur_scope.FindVar(inside_grad_name);
350
        PADDLE_ENFORCE_NOT_NULL(
351 352 353
            pg_ig_var,
            platform::errors::NotFound("Variable %s is not found.",
                                       inside_grad_name));
C
chengduo 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
        if (pg_ig_var->IsType<framework::LoDTensorArray>()) {
          auto pg_ig_lod_t_arr =
              pg_ig_var->GetMutable<framework::LoDTensorArray>();
          bool empty = true;
          for (auto &each : *pg_ig_lod_t_arr) {
            if (each.numel() != 0) {
              empty = false;
              break;
            }
          }
          if (empty) {
            LOG(WARNING) << pg_ig_names[param_id]
                         << " is not found in cur_scope.";
            continue;
          }
        }

Y
Yang Yang(Tony) 已提交
371
        //  // TODO(tonyyang-svail): Not sure we need the following
Y
Yang Yang(Tony) 已提交
372 373 374 375 376 377 378 379
        //  // If does not compute gradient of that variable inside rnn,
        //  just
        //  // continue
        //  if (local_var_names.find(inside_grad_name) ==
        //  local_var_names.end()) {
        //    continue;
        //  }

380 381 382
        auto var_iter = std::find(outside_og_names.begin(),
                                  outside_og_names.end(),
                                  pg_ig_names[param_id]);
383

Y
Yang Yang(Tony) 已提交
384 385 386
        // zero gradient variable in step 0
        if (cur_scope_iter == step_scopes->rbegin()) {
          auto *var = (*cur_scope_iter)->FindVar(inside_grad_name);
387
          PADDLE_ENFORCE_NOT_NULL(
388 389 390
              var,
              platform::errors::NotFound("Variable %s is not found.",
                                         inside_grad_name));
391
          PADDLE_ENFORCE_EQ(
C
chengduoZH 已提交
392 393
              var->IsType<framework::LoDTensorArray>() ||
                  var->IsType<LoDTensor>(),
394 395 396 397
              true,
              platform::errors::InvalidArgument(
                  "Currently the type of var only can be LoDTensorArray, "
                  "or LoDTensor, but the received var[%s] is %s.",
398 399
                  inside_grad_name,
                  framework::ToTypeName(var->Type())));
C
chengduo 已提交
400

401 402
          if ((var_iter == outside_og_names.end()) &&
              var->IsType<LoDTensor>()) {
Y
Yang Yang(Tony) 已提交
403 404
            auto &inside_tensor = var->Get<framework::LoDTensor>();
            framework::AttributeMap attrs;
405 406
            attrs["dtype"] =
                framework::TransToProtoVarType(inside_tensor.dtype());
407
            attrs["shape"] = phi::vectorize<int>(inside_tensor.dims());
Y
Yang Yang(Tony) 已提交
408 409
            attrs["value"] = 0.0f;

C
chengduo 已提交
410
            auto var_name = pg_ig_names[param_id];
411 412 413 414 415
            auto zero_op =
                framework::OpRegistry::CreateOp("fill_constant",
                                                framework::VariableNameMap{},
                                                {{"Out", {var_name}}},
                                                attrs);
D
dzhwinter 已提交
416
            zero_op->Run(scope, dev_place);
417 418 419
            scope.FindVar(var_name)
                ->GetMutable<framework::LoDTensor>()
                ->set_lod(inside_tensor.lod());
Y
Yang Yang(Tony) 已提交
420 421
          }
        }
422 423 424 425 426 427
        auto var_outside = scope.FindVar(pg_ig_names[param_id]);
        if ((var_iter == outside_og_names.end()) ||
            ((var_iter != outside_og_names.end()) &&
             var_outside->IsType<framework::LoDTensorArray>())) {
          auto new_inside_name = cur_scope.Rename(inside_grad_name);
          auto sum_op = framework::OpRegistry::CreateOp(
428 429
              "sum",
              {{"X", {pg_ig_names[param_id], new_inside_name}}},
430 431 432 433 434
              {{"Out", {pg_ig_names[param_id]}}},
              framework::AttributeMap{{"use_mkldnn", {false}}});
          sum_op->Run(cur_scope, dev_place);
          cur_scope.Rename(new_inside_name, inside_grad_name);
        }
Y
Yang Yang(Tony) 已提交
435
      }
436 437
      dev_ctx.Wait();
      const_cast<framework::Scope &>(scope).DeleteScope(&cur_scope);
Y
Yang Yang(Tony) 已提交
438
    }
439
    step_scopes->clear();
Y
Yang Yang(Tony) 已提交
440 441 442
  }
};

H
hong 已提交
443 444
template <typename T>
class WhileGradOpMaker : public framework::SingleGradOpMaker<T> {
Y
Yang Yang(Tony) 已提交
445
 public:
H
hong 已提交
446
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Y
Yang Yang(Tony) 已提交
447 448

 protected:
449
  void Apply(GradOpPtr<T> while_grad) const override {
F
Update  
fengjiayi 已提交
450
    while_grad->SetType("while_grad");
H
hong 已提交
451 452 453
    while_grad->SetInput(kX, this->Input(kX));
    while_grad->SetInput(kOutputs, this->Output(kOutputs));
    while_grad->SetInput(kStepScopes, this->Output(kStepScopes));
F
Update  
fengjiayi 已提交
454 455

    auto *grad_block = this->grad_block_[0];
Y
Yu Yang 已提交
456 457
    auto *fwd_block = grad_block->ForwardBlock();
    auto *parent_block = grad_block->ParentBlock();
458 459 460

    // Not all of IGs will be generated by inner gradient operators of while op.
    // Ignore IGs that is not generated by the inside block.
F
Update  
fengjiayi 已提交
461 462 463 464
    std::unordered_set<std::string> inner_op_outputs;
    for (const auto *op : grad_block->AllOps()) {
      for (auto &oname : op->OutputArgumentNames()) {
        inner_op_outputs.insert(oname);
465 466
      }
    }
H
hong 已提交
467 468
    auto igs = this->InputGrad(kX, /*do not drop empty gradient*/ false);

469
    for (auto &each_ig : igs) {
F
Update  
fengjiayi 已提交
470
      if (inner_op_outputs.find(each_ig) == inner_op_outputs.end()) {
M
minqiyang 已提交
471
        VLOG(8) << "Ignore " << each_ig;
472 473 474
        each_ig = framework::kEmptyVarName;
      }
    }
F
Update  
fengjiayi 已提交
475
    while_grad->SetOutput(framework::GradVarName(kX), igs);
Y
Yang Yang(Tony) 已提交
476 477 478 479

    // OG should be re-calculated by step blocks, since many outputs of while op
    // do not need to calculate gradients.
    std::unordered_set<std::string> block_ins;
H
hong 已提交
480 481
    block_ins.reserve(this->Input(kX).size() + this->Output(kOutputs).size());
    for (auto &p : this->Input(kX)) {
F
fengjiayi 已提交
482 483
      block_ins.insert(p);
    }
H
hong 已提交
484
    for (auto &o : this->Output(kOutputs)) {
F
fengjiayi 已提交
485 486
      block_ins.insert(o);
    }
Y
Yu Yang 已提交
487
    std::unordered_set<std::string> output_grads;
F
Update  
fengjiayi 已提交
488 489 490 491
    for (const auto *op : grad_block->AllOps()) {
      for (auto &input_name : op->InputArgumentNames()) {
        // If the input of Op has been recorded or is generated by the forward
        // block, do not make it as input again.
Y
Yu Yang 已提交
492 493 494

        // The input is located in I/O or other op's outputs or the variable is
        // located in grad_block's parents
F
Update  
fengjiayi 已提交
495
        if (block_ins.find(input_name) != block_ins.end() ||
Y
Yu Yang 已提交
496 497
            (fwd_block->FindVarRecursive(input_name) != nullptr ||
             parent_block->FindVarRecursive(input_name) != nullptr)) {
Y
Yang Yang(Tony) 已提交
498 499
          continue;
        }
C
chengduo 已提交
500

Y
Yu Yang 已提交
501
        output_grads.insert(input_name);
Y
Yang Yang(Tony) 已提交
502
      }
F
Update  
fengjiayi 已提交
503
      for (auto &output_name : op->OutputArgumentNames()) {
Y
Yang Yang(Tony) 已提交
504
        block_ins.insert(output_name);
Y
Yang Yang(Tony) 已提交
505 506
      }
    }
Y
Yang Yang(Tony) 已提交
507

Y
Yu Yang 已提交
508 509
    std::vector<std::string> output_grads_list;
    output_grads_list.resize(output_grads.size());
510 511
    std::copy(
        output_grads.begin(), output_grads.end(), output_grads_list.begin());
Y
Yu Yang 已提交
512
    while_grad->SetInput(framework::GradVarName(kOutputs), output_grads_list);
F
Update  
fengjiayi 已提交
513 514

    while_grad->SetAttrMap(this->Attrs());
A
Abhinav Arora 已提交
515
    while_grad->SetBlockAttr(kStepBlock, grad_block);
Y
Yang Yang(Tony) 已提交
516 517
    // record the original output gradient names, since the gradient name of
    // while operator could be renamed.
Y
Yu Yang 已提交
518
    while_grad->SetAttr("original_output_grad", output_grads_list);
Y
Yang Yang(Tony) 已提交
519

S
sneaxiy 已提交
520
    while_grad->SetAttr(kSkipEagerDeletionVars, std::vector<std::string>());
Y
Yang Yang(Tony) 已提交
521 522 523
  }
};

524 525
class WhileGradOpVarTypeInference
    : public framework::StaticGraphVarTypeInference {
Y
Yang Yang(Tony) 已提交
526
 public:
M
minqiyang 已提交
527
  void operator()(framework::InferVarTypeContext *ctx) const override {
528 529
    auto p_names = Input(ctx, kX);
    auto pg_ig_names = Output(ctx, framework::GradVarName(kX));
Y
Yang Yang(Tony) 已提交
530 531

    for (size_t i = 0; i < p_names.size(); ++i) {
532
      if (HasVar(ctx, pg_ig_names[i])) {
M
minqiyang 已提交
533
        VLOG(5) << "Setting " << pg_ig_names[i] << " following " << p_names[i]
534 535 536
                << " type: " << GetType(ctx, p_names[i]);
        SetType(ctx, pg_ig_names[i], GetType(ctx, p_names[i]));
        SetDataType(ctx, pg_ig_names[i], GetDataType(ctx, p_names[i]));
Y
Yang Yang(Tony) 已提交
537 538 539 540 541 542 543 544
      }
    }
  }
};

class WhileGradOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {
Y
Yang Yu 已提交
545 546
    ctx->HasInputs(kX);
    ctx->HasOutputs(framework::GradVarName(kX));
Y
Yang Yang(Tony) 已提交
547 548
    ctx->HasInputs(kOutputs);
    ctx->HasInputs(framework::GradVarName(kOutputs));
C
chengduo 已提交
549
    auto pg_ig_names = ctx->Outputs(kXGRAD);
550 551
    auto in_var_ptrs = ctx->GetInputVarPtrs(kX);
    auto out_var_ptrs = ctx->GetOutputVarPtrs(kXGRAD);
552 553
    PADDLE_ENFORCE_EQ(in_var_ptrs.size(),
                      out_var_ptrs.size(),
554 555 556
                      platform::errors::InvalidArgument(
                          "The size of Inputs(X) must be the same as "
                          "the size of Outputs(X@GRAD)."));
X
Xin Pan 已提交
557 558

    for (size_t i = 0; i < in_var_ptrs.size(); ++i) {
C
chengduo 已提交
559
      if (pg_ig_names[i] == framework::kEmptyVarName) {
Y
Yang Yang(Tony) 已提交
560 561
        continue;
      }
562
      framework::VarDesc *in_var =
R
Ruibiao Chen 已提交
563 564
          PADDLE_GET(framework::VarDesc *, in_var_ptrs[i]);
      PADDLE_GET(framework::VarDesc *, out_var_ptrs[i])
565
          ->SetShape(in_var->GetShape());
Y
Yang Yang(Tony) 已提交
566 567 568 569
    }
  }
};

Y
Yang Yang(Tony) 已提交
570 571 572
}  // namespace operators
}  // namespace paddle

H
hong 已提交
573
REGISTER_OPERATOR(
574 575 576
    while,
    paddle::operators::WhileOp,
    paddle::operators::WhileOpMaker,
H
hong 已提交
577
    paddle::operators::WhileGradOpMaker<paddle::framework::OpDesc>);
578 579
REGISTER_OPERATOR(while_grad,
                  paddle::operators::WhileGradOp,
Y
Yang Yang(Tony) 已提交
580 581
                  paddle::operators::WhileGradOpShapeInference,
                  paddle::operators::WhileGradOpVarTypeInference);