while_op.cc 18.9 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 15

#include <vector>
Y
Yi Wang 已提交
16 17 18 19
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/lod_tensor_array.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
S
sneaxiy 已提交
20
#include "paddle/fluid/framework/var_type.h"
S
sneaxiy 已提交
21
#include "paddle/fluid/operators/controlflow/while_op_helper.h"
Y
Yi Wang 已提交
22
#include "paddle/fluid/operators/detail/safe_ref.h"
Y
Yang Yang(Tony) 已提交
23 24 25 26 27 28 29

namespace paddle {
namespace operators {

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

S
sneaxiy 已提交
30 31 32 33 34 35 36 37 38 39 40 41
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;
}
}  // NOLINT
Y
Yang Yang(Tony) 已提交
42 43 44 45 46 47 48 49

class WhileOp : public framework::OperatorBase {
 public:
  WhileOp(const std::string &type, const framework::VariableNameMap &inputs,
          const framework::VariableNameMap &outputs,
          const framework::AttributeMap &attrs)
      : framework::OperatorBase(type, inputs, outputs, attrs) {}

50 51 52
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
Y
Yang Yang(Tony) 已提交
53
    PADDLE_ENFORCE_NOT_NULL(scope.FindVar(Input(kCondition)));
54

Y
Yang Yang(Tony) 已提交
55 56 57
    auto &cond = scope.FindVar(Input(kCondition))->Get<LoDTensor>();
    PADDLE_ENFORCE_EQ(cond.dims(), paddle::framework::make_ddim({1}));

D
dzhwinter 已提交
58
    framework::Executor executor(dev_place);
Y
Yu Yang 已提交
59
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
D
dzhwinter 已提交
60

Y
Yang Yang(Tony) 已提交
61 62 63 64
    auto *program = block->Program();

    auto step_scopes =
        scope.FindVar(Output(kStepScopes))->GetMutable<StepScopeVar>();
65 66 67 68 69 70 71 72 73 74 75

    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();
    }

76
    PADDLE_ENFORCE_EQ(step_scopes->size(), 0, "The StepScope should be empty.");
X
Xin Pan 已提交
77

78
    bool cond_data = GetCondData(cond);
C
chengduo 已提交
79
    bool is_test = Attr<bool>("is_test");
S
sneaxiy 已提交
80
    auto &skip_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);
S
sneaxiy 已提交
81
    VLOG(2) << GetSkipEagerDeletionVarsDebugString(skip_vars);
S
fix bug  
sneaxiy 已提交
82

S
sneaxiy 已提交
83
    auto ctx = executor.Prepare(*program, block->ID(), skip_vars);
84
    if (!is_test) {
85
      while (cond_data) {
86 87 88 89
        auto &current_scope = scope.NewScope();
        step_scopes->push_back(&current_scope);
        executor.RunPreparedContext(ctx.get(), &current_scope, false, true,
                                    true);
90 91
        cond_data =
            GetCondData(scope.FindVar(Input(kCondition))->Get<LoDTensor>());
92 93
      }
    } else {
Y
Yang Yang(Tony) 已提交
94
      auto &current_scope = scope.NewScope();
95
      executor.CreateVariables(*program, &current_scope, block->ID());
96
      while (cond_data) {
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
        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();
          }
        }
        executor.RunPreparedContext(ctx.get(), &current_scope, false, false,
                                    false);
112 113
        cond_data =
            GetCondData(scope.FindVar(Input(kCondition))->Get<LoDTensor>());
C
chengduo 已提交
114
      }
115
      scope.DeleteScope(&current_scope);
Y
Yang Yang(Tony) 已提交
116 117 118 119 120 121
    }
  }
};

class WhileOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
122
  void Make() override {
Y
Yang Yu 已提交
123
    AddInput(kX,
Y
Yang Yang(Tony) 已提交
124 125 126 127 128 129 130
             "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) 已提交
131
    AddOutput(kOutputs,
Y
Yang Yang(Tony) 已提交
132
              "A set of variables, which will be assigned with values "
Y
Yang Yang(Tony) 已提交
133
              "generated by the operators inside the block of While Op.")
Y
Yang Yang(Tony) 已提交
134 135 136 137 138
        .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 已提交
139 140
    AddAttr<framework::BlockDesc *>(kStepBlock,
                                    "The step block inside WhileOp");
141 142 143 144
    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 已提交
145
    AddAttr<std::vector<std::string>>(kSkipEagerDeletionVars,
S
fix bug  
sneaxiy 已提交
146 147 148
                                      "Vars that would skip eager deletion."
                                      "Users should not set this manually.")
        .SetDefault(std::vector<std::string>());
Y
Yang Yang(Tony) 已提交
149 150 151 152 153 154 155 156 157 158 159 160
    AddComment(R"DOC(
)DOC");
  }
};

class WhileGradOp : public framework::OperatorBase {
 public:
  WhileGradOp(const std::string &type, const framework::VariableNameMap &inputs,
              const framework::VariableNameMap &outputs,
              const framework::AttributeMap &attrs)
      : framework::OperatorBase(type, inputs, outputs, attrs) {}

161 162 163
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &dev_place) const override {
C
chengduo 已提交
164 165
    PADDLE_ENFORCE(!Attr<bool>("is_test"),
                   "GradOp is only callable when is_test is false");
166 167 168
    // get device context from pool
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(dev_place);
D
dzhwinter 已提交
169
    framework::Executor executor(dev_place);
Y
Yu Yang 已提交
170
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
Y
Yang Yang(Tony) 已提交
171
    auto *program = block->Program();
S
sneaxiy 已提交
172 173

    auto &skip_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);
S
sneaxiy 已提交
174
    VLOG(2) << GetSkipEagerDeletionVarsDebugString(skip_vars);
S
sneaxiy 已提交
175
    auto ctx = executor.Prepare(*program, block->ID(), skip_vars);
Y
Yang Yang(Tony) 已提交
176 177 178 179

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

Y
Yang Yang(Tony) 已提交
180 181 182 183 184 185
    auto outside_og_names = Inputs(framework::GradVarName(kOutputs));
    auto inside_og_names =
        Attr<std::vector<std::string>>("original_output_grad");

    PADDLE_ENFORCE_EQ(outside_og_names.size(), inside_og_names.size());

Y
Yang Yang(Tony) 已提交
186 187
    for (auto cur_scope_iter = step_scopes->rbegin();
         cur_scope_iter != step_scopes->rend(); ++cur_scope_iter) {
M
minqiyang 已提交
188 189
      VLOG(3) << "Start backward at time_step "
              << cur_scope_iter - step_scopes->rbegin();
Y
Yang Yang(Tony) 已提交
190 191 192 193 194
      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 已提交
195 196
        VLOG(8) << "Linking outside " << outside_og_name << " --> inside "
                << inside_og_name;
C
chengduo 已提交
197 198 199 200
        if (scope.FindVar(outside_og_name) == nullptr) {
          continue;
        }

201 202 203 204 205 206
        auto &og_outside =
            detail::Ref(scope.FindVar(outside_og_name),
                        "Cannot find Outside Gradient %s", outside_og_name);
        auto &og_inside =
            detail::Ref(cur_scope.Var(inside_og_name),
                        "Cannot find inside gradient %s", inside_og_name);
S
sneaxiy 已提交
207
        if (og_outside.IsType<framework::LoDTensor>()) {
Y
Yang Yang(Tony) 已提交
208 209 210 211 212
          auto &outside_tensor = og_outside.Get<framework::LoDTensor>();
          auto &inside_tensor =
              detail::Ref(og_inside.GetMutable<framework::LoDTensor>());
          inside_tensor.set_lod(outside_tensor.lod());
          inside_tensor.ShareDataWith(outside_tensor);
S
sneaxiy 已提交
213
        } else if (og_outside.IsType<framework::LoDTensorArray>()) {
214 215
          auto outside_array =
              og_outside.GetMutable<framework::LoDTensorArray>();
Y
Yang Yang(Tony) 已提交
216 217
          auto &inside_array =
              detail::Ref(og_inside.GetMutable<framework::LoDTensorArray>());
218 219 220
          inside_array.clear();
          inside_array.resize(outside_array->size());
          VLOG(8) << outside_og_name << " size = " << outside_array->size();
Y
Yang Yang(Tony) 已提交
221 222

          for (size_t j = 0; j < inside_array.size(); ++j) {
223 224 225 226 227 228 229
            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) 已提交
230 231 232 233
            } else {
              PADDLE_ENFORCE_EQ(inside_array[j].numel(), 0);
            }
          }
C
chengduo 已提交
234 235
        } else {
          PADDLE_THROW("Currently only support LoDTensor and LoDTensorArray.");
Y
Yang Yang(Tony) 已提交
236 237
        }
      }
C
chengduoZH 已提交
238 239
      executor.RunPreparedContext(ctx.get(), *cur_scope_iter, false, true,
                                  true);
Y
Yang Yang(Tony) 已提交
240

C
chengduo 已提交
241 242 243
      // The Outputs(kXGRAD) contains the names of the gradient of parameters
      // and inputs.
      auto &pg_ig_names = Outputs(kXGRAD);
Y
Yang Yu 已提交
244
      auto &p_names = Inputs(kX);
C
chengduo 已提交
245 246 247
      PADDLE_ENFORCE_EQ(pg_ig_names.size(), p_names.size());
      for (size_t param_id = 0; param_id < pg_ig_names.size(); ++param_id) {
        if (pg_ig_names[param_id] == framework::kEmptyVarName) {
248
          continue;  // parameter doesn't have gradient
Y
Yang Yang(Tony) 已提交
249 250
        }
        auto inside_grad_name = framework::GradVarName(p_names[param_id]);
Y
Yang Yang(Tony) 已提交
251

C
chengduo 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        // 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);
        PADDLE_ENFORCE(pg_ig_var != nullptr);
        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) 已提交
274
        //  // TODO(tonyyang-svail): Not sure we need the following
Y
Yang Yang(Tony) 已提交
275 276 277 278 279 280 281 282 283 284 285
        //  // 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;
        //  }

        // zero gradient variable in step 0
        if (cur_scope_iter == step_scopes->rbegin()) {
          auto *var = (*cur_scope_iter)->FindVar(inside_grad_name);
Y
Yang Yang(Tony) 已提交
286
          PADDLE_ENFORCE_NOT_NULL(var, "Can not find var %s", inside_grad_name);
C
chengduoZH 已提交
287 288 289 290 291
          PADDLE_ENFORCE(
              var->IsType<framework::LoDTensorArray>() ||
                  var->IsType<LoDTensor>(),
              "Currently the type of var only can be LoDTensorArray, "
              "or LoDTensor, but the received var[%s] is %s.",
S
sneaxiy 已提交
292
              inside_grad_name, framework::ToTypeName(var->Type()));
C
chengduo 已提交
293

Y
Yang Yang(Tony) 已提交
294 295 296
          if (var->IsType<LoDTensor>()) {
            auto &inside_tensor = var->Get<framework::LoDTensor>();
            framework::AttributeMap attrs;
Y
Yu Yang 已提交
297
            attrs["dtype"] = inside_tensor.type();
298
            attrs["shape"] = framework::vectorize<int>(inside_tensor.dims());
Y
Yang Yang(Tony) 已提交
299 300
            attrs["value"] = 0.0f;

C
chengduo 已提交
301
            auto var_name = pg_ig_names[param_id];
Y
Yang Yang(Tony) 已提交
302
            auto zero_op = framework::OpRegistry::CreateOp(
Y
Yiqun Liu 已提交
303
                "fill_constant", framework::VariableNameMap{},
304
                {{"Out", {var_name}}}, attrs);
D
dzhwinter 已提交
305
            zero_op->Run(scope, dev_place);
306 307 308
            scope.FindVar(var_name)
                ->GetMutable<framework::LoDTensor>()
                ->set_lod(inside_tensor.lod());
Y
Yang Yang(Tony) 已提交
309 310
          }
        }
Y
Yang Yang(Tony) 已提交
311
        auto new_inside_name = cur_scope.Rename(inside_grad_name);
Y
Yang Yang(Tony) 已提交
312
        auto sum_op = framework::OpRegistry::CreateOp(
C
chengduo 已提交
313 314
            "sum", {{"X", {pg_ig_names[param_id], new_inside_name}}},
            {{"Out", {pg_ig_names[param_id]}}},
315
            framework::AttributeMap{{"use_mkldnn", {false}}});
D
dzhwinter 已提交
316
        sum_op->Run(cur_scope, dev_place);
Y
Yang Yang(Tony) 已提交
317
        cur_scope.Rename(new_inside_name, inside_grad_name);
Y
Yang Yang(Tony) 已提交
318
      }
319 320
      dev_ctx.Wait();
      const_cast<framework::Scope &>(scope).DeleteScope(&cur_scope);
Y
Yang Yang(Tony) 已提交
321
    }
322
    step_scopes->clear();
Y
Yang Yang(Tony) 已提交
323 324 325
  }
};

H
hong 已提交
326 327
template <typename T>
class WhileGradOpMaker : public framework::SingleGradOpMaker<T> {
Y
Yang Yang(Tony) 已提交
328
 public:
H
hong 已提交
329
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
Y
Yang Yang(Tony) 已提交
330 331

 protected:
332
  void Apply(GradOpPtr<T> while_grad) const override {
F
Update  
fengjiayi 已提交
333
    while_grad->SetType("while_grad");
H
hong 已提交
334 335 336
    while_grad->SetInput(kX, this->Input(kX));
    while_grad->SetInput(kOutputs, this->Output(kOutputs));
    while_grad->SetInput(kStepScopes, this->Output(kStepScopes));
F
Update  
fengjiayi 已提交
337 338

    auto *grad_block = this->grad_block_[0];
Y
Yu Yang 已提交
339 340
    auto *fwd_block = grad_block->ForwardBlock();
    auto *parent_block = grad_block->ParentBlock();
341 342 343

    // 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 已提交
344 345 346 347
    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);
348 349
      }
    }
H
hong 已提交
350 351
    auto igs = this->InputGrad(kX, /*do not drop empty gradient*/ false);

352
    for (auto &each_ig : igs) {
F
Update  
fengjiayi 已提交
353
      if (inner_op_outputs.find(each_ig) == inner_op_outputs.end()) {
M
minqiyang 已提交
354
        VLOG(8) << "Ignore " << each_ig;
355 356 357
        each_ig = framework::kEmptyVarName;
      }
    }
F
Update  
fengjiayi 已提交
358
    while_grad->SetOutput(framework::GradVarName(kX), igs);
Y
Yang Yang(Tony) 已提交
359 360 361 362

    // 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 已提交
363 364
    block_ins.reserve(this->Input(kX).size() + this->Output(kOutputs).size());
    for (auto &p : this->Input(kX)) {
F
fengjiayi 已提交
365 366
      block_ins.insert(p);
    }
H
hong 已提交
367
    for (auto &o : this->Output(kOutputs)) {
F
fengjiayi 已提交
368 369
      block_ins.insert(o);
    }
Y
Yu Yang 已提交
370
    std::unordered_set<std::string> output_grads;
F
Update  
fengjiayi 已提交
371 372 373 374
    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 已提交
375 376 377

        // 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 已提交
378
        if (block_ins.find(input_name) != block_ins.end() ||
Y
Yu Yang 已提交
379 380
            (fwd_block->FindVarRecursive(input_name) != nullptr ||
             parent_block->FindVarRecursive(input_name) != nullptr)) {
Y
Yang Yang(Tony) 已提交
381 382
          continue;
        }
C
chengduo 已提交
383

Y
Yu Yang 已提交
384
        output_grads.insert(input_name);
Y
Yang Yang(Tony) 已提交
385
      }
F
Update  
fengjiayi 已提交
386
      for (auto &output_name : op->OutputArgumentNames()) {
Y
Yang Yang(Tony) 已提交
387
        block_ins.insert(output_name);
Y
Yang Yang(Tony) 已提交
388 389
      }
    }
Y
Yang Yang(Tony) 已提交
390

Y
Yu Yang 已提交
391 392 393 394 395
    std::vector<std::string> output_grads_list;
    output_grads_list.resize(output_grads.size());
    std::copy(output_grads.begin(), output_grads.end(),
              output_grads_list.begin());
    while_grad->SetInput(framework::GradVarName(kOutputs), output_grads_list);
F
Update  
fengjiayi 已提交
396 397

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

S
sneaxiy 已提交
403
    while_grad->SetAttr(kSkipEagerDeletionVars, std::vector<std::string>());
Y
Yang Yang(Tony) 已提交
404 405 406
  }
};

Y
Yang Yang(Tony) 已提交
407 408
class WhileGradOpVarTypeInference : public framework::VarTypeInference {
 public:
M
minqiyang 已提交
409 410 411
  void operator()(framework::InferVarTypeContext *ctx) const override {
    auto p_names = ctx->Input(kX);
    auto pg_ig_names = ctx->Output(framework::GradVarName(kX));
Y
Yang Yang(Tony) 已提交
412 413

    for (size_t i = 0; i < p_names.size(); ++i) {
M
minqiyang 已提交
414
      if (ctx->HasVar(pg_ig_names[i])) {
M
minqiyang 已提交
415
        VLOG(5) << "Setting " << pg_ig_names[i] << " following " << p_names[i]
M
minqiyang 已提交
416 417 418
                << " type: " << ctx->GetType(p_names[i]);
        ctx->SetType(pg_ig_names[i], ctx->GetType(p_names[i]));
        ctx->SetDataType(pg_ig_names[i], ctx->GetDataType(p_names[i]));
Y
Yang Yang(Tony) 已提交
419 420 421 422 423 424 425 426
      }
    }
  }
};

class WhileGradOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {
Y
Yang Yu 已提交
427 428
    ctx->HasInputs(kX);
    ctx->HasOutputs(framework::GradVarName(kX));
Y
Yang Yang(Tony) 已提交
429 430 431
    ctx->HasInputs(kOutputs);
    ctx->HasInputs(framework::GradVarName(kOutputs));

C
chengduo 已提交
432
    auto pg_ig_names = ctx->Outputs(kXGRAD);
X
Xin Pan 已提交
433 434 435 436 437 438 439
    std::vector<framework::InferShapeVarPtr> in_var_ptrs =
        ctx->GetInputVarPtrs(kX);
    std::vector<framework::InferShapeVarPtr> out_var_ptrs =
        ctx->GetOutputVarPtrs(kXGRAD);
    PADDLE_ENFORCE(in_var_ptrs.size() == out_var_ptrs.size());

    for (size_t i = 0; i < in_var_ptrs.size(); ++i) {
C
chengduo 已提交
440
      if (pg_ig_names[i] == framework::kEmptyVarName) {
Y
Yang Yang(Tony) 已提交
441 442
        continue;
      }
X
Xin Pan 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
      if (ctx->IsRuntime()) {
        framework::Variable *in_var =
            boost::get<framework::Variable *>(in_var_ptrs[i]);
        framework::Variable *out_var =
            boost::get<framework::Variable *>(out_var_ptrs[i]);

        auto type = framework::ToVarType(in_var->Type());
        if (type == framework::proto::VarType::LOD_TENSOR) {
          out_var->GetMutable<LoDTensor>()->Resize(
              in_var->Get<framework::LoDTensor>().dims());
        } else if (type == framework::proto::VarType::SELECTED_ROWS) {
          out_var->GetMutable<framework::SelectedRows>()->set_height(
              in_var->Get<framework::SelectedRows>().GetCompleteDims()[0]);
        } else if (type == framework::proto::VarType::LOD_TENSOR_ARRAY) {
          PADDLE_THROW("WhileGradOp doesn't support type %d",
                       static_cast<int>(type));
        }
      } else {
        framework::VarDesc *in_var =
            boost::get<framework::VarDesc *>(in_var_ptrs[i]);
        boost::get<framework::VarDesc *>(out_var_ptrs[i])
            ->SetShape(in_var->GetShape());
Y
Yang Yang(Tony) 已提交
465 466 467 468 469
      }
    }
  }
};

Y
Yang Yang(Tony) 已提交
470 471 472
}  // namespace operators
}  // namespace paddle

H
hong 已提交
473 474 475
REGISTER_OPERATOR(
    while, paddle::operators::WhileOp, paddle::operators::WhileOpMaker,
    paddle::operators::WhileGradOpMaker<paddle::framework::OpDesc>);
Y
Yang Yang(Tony) 已提交
476 477 478
REGISTER_OPERATOR(while_grad, paddle::operators::WhileGradOp,
                  paddle::operators::WhileGradOpShapeInference,
                  paddle::operators::WhileGradOpVarTypeInference);