recurrent_op.cc 25.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Y
Yan Chunwei 已提交
2

L
Luo Tao 已提交
3 4 5
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
Y
Yan Chunwei 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
Y
Yan Chunwei 已提交
8

L
Luo Tao 已提交
9 10 11 12 13
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
Yan Chunwei 已提交
14

Y
Yu Yang 已提交
15
#include <vector>
Y
Yi Wang 已提交
16 17
#include "paddle/fluid/framework/executor.h"
#include "paddle/fluid/framework/op_registry.h"
S
sneaxiy 已提交
18
#include "paddle/fluid/operators/controlflow/loop_op_helper.h"
Y
Yan Chunwei 已提交
19 20 21

namespace paddle {
namespace operators {
S
sneaxiy 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35

using recurrent::kInputs;
using recurrent::kInitialStates;
using recurrent::kParameters;
using recurrent::kOutputs;
using recurrent::kStepScopes;
using recurrent::kExStates;
using recurrent::kStates;
using recurrent::kReverse;
using recurrent::kIsTrain;
using recurrent::kInputGrads;
using recurrent::kOutputGrads;
using recurrent::kParamGrads;
using recurrent::kInitStateGrads;
Y
Yan Chunwei 已提交
36

Y
Yu Yang 已提交
37 38 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
using StepScopeVar = std::vector<framework::Scope *>;

// StepScopes manages scopes inside RNN.
//    StepScopes::CurScope() get the current scope
//    StepScopes::ExScope() get the ex-scope, or scope in previous time step.
//    StepScopes::Next() move to next time step.
//
// if is_train = False, then
//   there are two scopes for the RNN and just support forward.
// else
//   the len(scopes) == seq_len
//
// if is_backward = True, then
//   reversely access scopes
// else
//   access scopes from begin to end.
class StepScopes {
 public:
  StepScopes(const framework::Scope &parent, StepScopeVar *scopes,
             bool is_train, size_t seq_len, bool is_backward = false)
      : counter_(is_backward ? seq_len - 1 : 0UL),
        scopes_(scopes),
        is_train_(is_train),
        is_backward_(is_backward) {
    size_t num_step_scopes = is_train ? seq_len : 2;
    PADDLE_ENFORCE(is_train || !is_backward,
                   "Cannot backward when is not training");
    if (!is_backward_) {
      PADDLE_ENFORCE(scopes->empty());
      scopes->reserve(static_cast<size_t>(num_step_scopes));
      for (size_t i = 0; i < num_step_scopes; ++i) {
        scopes->emplace_back(&parent.NewScope());
      }
Y
Yan Chunwei 已提交
70
    }
Y
Yu Yang 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  }

  framework::Scope &CurScope() { return GetScope(counter_); }

  framework::Scope &ExScope() {
    auto &scope = GetScope(is_backward_ ? counter_ + 1 : counter_ - 1);
    return scope;
  }

  void Next() {
    if (is_backward_) {
      --counter_;
    } else {
      ++counter_;
    }
  }

 private:
  framework::Scope &GetScope(size_t scope_id) const {
    if (!is_train_) {
      scope_id %= 2;
    }
    PADDLE_ENFORCE_LT(scope_id, scopes_->size());
    return *(*scopes_)[scope_id];
  }

  size_t counter_;
  StepScopeVar *scopes_;
  bool is_train_;
  bool is_backward_;
};

// Base class for RecurrentOp/RecurrentGradOp
//    Some common protected functions for RecurrentOp/RecurrentGradOp
class RecurrentBase : public framework::OperatorBase {
 public:
  RecurrentBase(const std::string &type,
                const framework::VariableNameMap &inputs,
                const framework::VariableNameMap &outputs,
                const framework::AttributeMap &attrs)
      : OperatorBase(type, inputs, outputs, attrs) {}

 protected:
  // Get SequenceLength from Scope
  //   The sequence length is got from input tensor. The input tensor's
  //   dimension should be [SEQ_LEN, ..., ...]. The first of the tensor's shape
  //   is SEQ_LEN. The second of the tensor's shape could be the batch size or
  //   nested sequence length.
  int64_t GetSequenceLength(const framework::Scope &scope) const {
    // Dim format SEQ_LEN, BATCH_SIZE, ...
    int64_t seq_len = -1;
    auto &all_inputs = Inputs(kInputs);
    PADDLE_ENFORCE(!all_inputs.empty());
    for (auto &iname : all_inputs) {
      auto *var = scope.FindVar(iname);
      PADDLE_ENFORCE(var != nullptr);
      PADDLE_ENFORCE(var->IsType<framework::LoDTensor>());
      auto &dim = var->Get<framework::LoDTensor>().dims();
      if (seq_len == -1) {
        seq_len = dim[0];
      } else {
        PADDLE_ENFORCE_EQ(seq_len, dim[0]);
      }
    }
    return seq_len;
  }

  // for src_tensor, dst_tensor in zip(map(src_scope.FindVar, src_vars),
  //                                   map(dst_scope.Var, dst_vars)):
  //   dst_tensor.ShareDataWith(src_tensor)
  static void LinkTensor(const framework::Scope &src_scope,
                         const std::vector<std::string> &src_vars,
                         framework::Scope *dst_scope,
                         const std::vector<std::string> &dst_vars) {
    LinkTensorWithCallback(
        src_scope, src_vars, dst_scope, dst_vars,
        [&](const framework::Tensor &src, framework::Tensor *dst) {
          dst->ShareDataWith(src);
        });
  }

  // for src_tensor, dst_tensor in zip(map(src_scope.FindVar, src_vars),
  //                                   map(dst_scope.Var, dst_vars)):
  //   callback(src_tensor, &dst_tensor)
  template <typename Callback>
  static void LinkTensorWithCallback(const framework::Scope &src_scope,
                                     const std::vector<std::string> &src_vars,
                                     framework::Scope *dst_scope,
                                     const std::vector<std::string> &dst_vars,
C
chengduo 已提交
160 161
                                     Callback callback,
                                     bool is_backward = false) {
Y
Yu Yang 已提交
162 163
    PADDLE_ENFORCE_EQ(src_vars.size(), dst_vars.size());
    for (size_t i = 0; i < dst_vars.size(); ++i) {
M
minqiyang 已提交
164
      VLOG(10) << "Link " << src_vars[i] << " to " << dst_vars[i];
C
chengduo 已提交
165 166
      AccessTensor(src_scope, src_vars[i], dst_scope, dst_vars[i], callback,
                   is_backward);
Y
Yu Yang 已提交
167 168 169 170 171 172 173 174 175 176 177
    }
  }

  // for src_tensor, dst_tensor in zip(map(src_scope.FindVar, src_vars),
  //                                   map(dst_scope.FindVar, dst_vars)):
  //   callback(src_tensor, &dst_tensor)
  template <typename Callback>
  static void LinkTensorWithCallback(const framework::Scope &src_scope,
                                     const std::vector<std::string> &src_vars,
                                     const framework::Scope &dst_scope,
                                     const std::vector<std::string> &dst_vars,
C
chengduo 已提交
178 179
                                     Callback callback,
                                     bool is_backward = false) {
Y
Yu Yang 已提交
180 181
    PADDLE_ENFORCE_EQ(src_vars.size(), dst_vars.size());
    for (size_t i = 0; i < dst_vars.size(); ++i) {
M
minqiyang 已提交
182
      VLOG(10) << "Link " << src_vars[i] << " to " << dst_vars[i];
C
chengduo 已提交
183 184
      AccessTensor(src_scope, src_vars[i], dst_scope, dst_vars[i], callback,
                   is_backward);
Y
Yu Yang 已提交
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    }
  }

  // (seq_len, shape) -> return [seq_len] + list(shape)
  static framework::DDim PrependDims(size_t seq_len,
                                     const framework::DDim &src) {
    auto dims = framework::vectorize(src);
    dims.insert(dims.begin(), static_cast<int64_t>(seq_len));
    return framework::make_ddim(dims);
  }

 private:
  template <typename Callback>
  static void AccessTensor(const framework::Scope &src_scope,
                           const std::string &src_var_name,
                           framework::Scope *dst_scope,
C
chengduo 已提交
201 202
                           const std::string &dst_var_name, Callback callback,
                           bool is_backward = false) {
Y
Yu Yang 已提交
203
    auto *src_var = src_scope.FindVar(src_var_name);
C
chengduo 已提交
204 205 206 207
    if (is_backward && src_var == nullptr) {
      return;
    }
    PADDLE_ENFORCE(src_var != nullptr, "%s is not found.", src_var_name);
Y
Yu Yang 已提交
208 209 210 211 212 213 214 215 216 217 218
    auto &src_tensor = src_var->Get<framework::LoDTensor>();

    auto *dst_var = dst_scope->Var(dst_var_name);
    auto *dst_tensor = dst_var->GetMutable<framework::LoDTensor>();
    callback(src_tensor, dst_tensor);
  }

  template <typename Callback>
  static void AccessTensor(const framework::Scope &src_scope,
                           const std::string &src_var_name,
                           const framework::Scope &dst_scope,
C
chengduo 已提交
219 220 221 222 223 224
                           const std::string &dst_var_name, Callback callback,
                           bool is_backward = false) {
    auto *dst_var = dst_scope.FindVar(dst_var_name);
    if (is_backward && dst_var == nullptr) {
      return;
    }
Y
Yu Yang 已提交
225
    auto *src_var = src_scope.FindVar(src_var_name);
C
chengduo 已提交
226
    PADDLE_ENFORCE(src_var != nullptr, "%s is not found.", src_var_name);
Y
Yu Yang 已提交
227
    auto &src_tensor = src_var->Get<framework::LoDTensor>();
C
chengduo 已提交
228
    PADDLE_ENFORCE(dst_var != nullptr, "%s is not found.", dst_var_name);
Y
Yu Yang 已提交
229 230 231 232 233 234 235 236 237 238 239 240
    auto *dst_tensor = dst_var->GetMutable<framework::LoDTensor>();
    callback(src_tensor, dst_tensor);
  }
};

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

241 242 243
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
Y
Yu Yang 已提交
244
    auto seq_len = static_cast<size_t>(this->GetSequenceLength(scope));
M
minqiyang 已提交
245
    VLOG(3) << "Static RNN input sequence length = " << seq_len;
Y
Yu Yang 已提交
246 247 248
    StepScopes scopes = CreateStepScopes(scope, seq_len);
    auto reverse = Attr<bool>(kReverse);

D
dzhwinter 已提交
249
    framework::Executor executor(place);
Y
Yu Yang 已提交
250
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
D
dzhwinter 已提交
251

S
sneaxiy 已提交
252 253 254
    auto &keep_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);
    VLOG(2) << GetSkipEagerDeletionVarsDebugString(keep_vars);

Y
Yu Yang 已提交
255 256 257 258
    auto *program = block->Program();

    for (size_t i = 0; i < seq_len; ++i) {
      size_t seq_offset = reverse ? seq_len - i - 1 : i;
M
minqiyang 已提交
259
      VLOG(3) << "Recurrent operate at the time step " << seq_offset;
Y
Yu Yang 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287

      auto &cur_scope = scopes.CurScope();

      // Link outside::input --> inside::input
      //   inside::input = outside::input[seq_offset: seq_offset+1]
      LinkTensorWithCallback(
          scope, Inputs(kInputs), &cur_scope, Inputs(kInputs),
          [&seq_offset](const framework::Tensor &outside,
                        framework::Tensor *inside) {
            inside->ShareDataWith(outside.Slice(seq_offset, seq_offset + 1));
            auto dims = framework::vectorize(inside->dims());
            dims.erase(dims.begin());
            inside->Resize(framework::make_ddim(dims));
          });

      if (i == 0) {
        // Link initial states  --> ex_states
        LinkTensor(scope, Inputs(kInitialStates), &cur_scope,
                   Attr<std::vector<std::string>>(kExStates));
      } else {
        auto &ex_scope = scopes.ExScope();
        // Link ex_scope::state --> cur_scope::ex_state
        LinkTensor(ex_scope, Attr<std::vector<std::string>>(kStates),
                   &cur_scope, Attr<std::vector<std::string>>(kExStates));
      }

      // Every inputs are linked now, execute!
      executor.Run(*program, &cur_scope, block->ID(),
S
sneaxiy 已提交
288
                   false /*create_local_scope*/, true /*create_vars*/,
S
sneaxiy 已提交
289
                   keep_vars);
Y
Yu Yang 已提交
290

D
dzhwinter 已提交
291
      // get device context from pool
Y
Yu Yang 已提交
292 293 294
      platform::DeviceContextPool &pool =
          platform::DeviceContextPool::Instance();
      auto &dev_ctx = *pool.Get(place);
D
dzhwinter 已提交
295

Y
Yu Yang 已提交
296 297 298 299 300 301 302 303
      // Copy inside::output -> outside::output
      //    outside::output[seq_offset: seq_offset + 1] = inside::output
      this->LinkTensorWithCallback(
          cur_scope, Outputs(kOutputs), scope, Outputs(kOutputs),
          [&](const framework::LoDTensor &src_tensor,
              framework::LoDTensor *dst_tensor) {
            if (i == 0) {  // create output tensor at begin
              dst_tensor->Resize(PrependDims(seq_len, src_tensor.dims()));
D
dzhwinter 已提交
304
              dst_tensor->mutable_data(place, src_tensor.type());
Y
Yu Yang 已提交
305 306 307 308 309
            }

            auto dst_out = dst_tensor->Slice(seq_offset, seq_offset + 1);
            // Explicit copy output since the local RNN scope can be destroyed
            // early.
Y
Yi Wang 已提交
310
            framework::TensorCopy(src_tensor, place, dev_ctx, &dst_out);
Y
Yu Yang 已提交
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
          });

      scopes.Next();
    }
  }

 private:
  StepScopes CreateStepScopes(const framework::Scope &scope,
                              size_t seq_len) const {
    auto *var = scope.FindVar(Output(kStepScopes));
    PADDLE_ENFORCE(var != nullptr);
    return StepScopes(scope, var->GetMutable<StepScopeVar>(),
                      Attr<bool>(kIsTrain), seq_len);
  }
};

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

335 336 337
 private:
  void RunImpl(const framework::Scope &scope,
               const platform::Place &place) const override {
Y
Yu Yang 已提交
338 339 340 341
    auto seq_len = static_cast<size_t>(GetSequenceLength(scope));
    StepScopes scopes = CreateStepScopes(scope, seq_len);
    auto reverse = Attr<bool>(kReverse);

D
dzhwinter 已提交
342
    framework::Executor executor(place);
Y
Yu Yang 已提交
343
    auto *block = Attr<framework::BlockDesc *>(kStepBlock);
D
dzhwinter 已提交
344

Y
Yu Yang 已提交
345
    auto *program = block->Program();
S
sneaxiy 已提交
346 347 348
    auto &keep_vars = Attr<std::vector<std::string>>(kSkipEagerDeletionVars);

    VLOG(2) << GetSkipEagerDeletionVarsDebugString(keep_vars);
Y
Yu Yang 已提交
349

D
dzhwinter 已提交
350
    // get device context from pool
Y
Yu Yang 已提交
351 352
    platform::DeviceContextPool &pool = platform::DeviceContextPool::Instance();
    auto &dev_ctx = *pool.Get(place);
D
dzhwinter 已提交
353

Y
Yu Yang 已提交
354 355
    for (size_t step_id = 0; step_id < seq_len; ++step_id) {
      size_t seq_offset = reverse ? step_id : seq_len - step_id - 1;
M
minqiyang 已提交
356
      VLOG(3) << "Recurrent backward operate at the time step " << seq_offset;
Y
Yu Yang 已提交
357 358 359 360 361 362 363 364 365 366
      auto &cur_scope = scopes.CurScope();
      // Link outside::output_grads --> inside::output_grads
      //   inside::output_grad = outside::output_grad[seq_offset:seq_offset+1]
      LinkTensorWithCallback(
          scope, Inputs(kOutputGrads), &cur_scope, Inputs(kOutputGrads),
          [&](const framework::Tensor &outside, framework::Tensor *inside) {
            inside->ShareDataWith(outside.Slice(seq_offset, seq_offset + 1));
            auto dims = framework::vectorize(inside->dims());
            dims.erase(dims.begin());
            inside->Resize(framework::make_ddim(dims));
C
chengduo 已提交
367 368
          },
          true /*is_backward*/);
Y
Yu Yang 已提交
369 370
      auto og_set = List2Set(Inputs(kOutputGrads));

M
minqiyang 已提交
371
      if (VLOG_IS_ON(10)) {
Y
Yu Yang 已提交
372 373 374
        std::ostringstream sout;
        std::copy(og_set.begin(), og_set.end(),
                  std::ostream_iterator<std::string>(sout, ","));
M
minqiyang 已提交
375
        VLOG(10) << " RNN output gradients = [" << sout.str() << "]";
Y
Yu Yang 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
      }

      // Link states
      //   if cur_scope::cur_state_grad in out_grads:
      //     cur_scope::cur_state_grad += ex_scope::ex_state_grad
      //   else:
      //     ex_scope::ex_state_grad --> cur_scope::cur_state_grad
      if (step_id != 0) {  // not at beginning
        auto &ex_scope = scopes.ExScope();
        auto ex_state_grads =
            GradVarLists(Attr<std::vector<std::string>>(kExStates));
        auto cur_state_grads =
            GradVarLists(Attr<std::vector<std::string>>(kStates));

        PADDLE_ENFORCE_EQ(ex_state_grads.size(), cur_state_grads.size());
        for (size_t i = 0; i < ex_state_grads.size(); ++i) {
          auto &cur_grad = cur_state_grads[i];
          auto &ex_grad = ex_state_grads[i];
          auto &ex_tensor =
              ex_scope.FindVar(ex_grad)->Get<framework::LoDTensor>();

M
minqiyang 已提交
397
          VLOG(10) << " RNN link " << cur_grad << " from " << ex_grad;
Y
Yu Yang 已提交
398 399 400
          auto *cur_grad_var = cur_scope.Var(cur_grad);
          auto cur_grad_tensor =
              cur_grad_var->GetMutable<framework::LoDTensor>();
Y
Yi Wang 已提交
401
          framework::TensorCopy(ex_tensor, place, dev_ctx, cur_grad_tensor);
Y
Yu Yang 已提交
402
        }
Y
Yan Chunwei 已提交
403
      }
Y
Yu Yang 已提交
404

M
minqiyang 已提交
405
      VLOG(5) << "Recurrent memory linking finished ";
Y
Yu Yang 已提交
406 407
      // Run step block with cur_scope
      executor.Run(*program, &cur_scope, block->ID(),
S
sneaxiy 已提交
408
                   false /*create_local_scope*/, true /*create_vars*/,
S
sneaxiy 已提交
409
                   keep_vars);
Y
Yu Yang 已提交
410

M
minqiyang 已提交
411
      VLOG(5) << "executor.Run finished ";
Y
Yu Yang 已提交
412 413 414 415 416 417 418 419 420 421 422 423

      auto local_var_names = LocalVarNames(cur_scope);

      // Accumulate params
      //   if (step == 0):
      //      outside::param_grad = 0.0
      //   outside::param_grad += inside::param_grad
      {
        auto &pg_names = Outputs(kParamGrads);
        auto &p_names = Inputs(kParameters);
        PADDLE_ENFORCE_EQ(pg_names.size(), p_names.size());

Y
Yu Yang 已提交
424 425
        for (size_t param_id = 0; param_id < pg_names.size(); ++param_id) {
          auto inside_grad_name = framework::GradVarName(p_names[param_id]);
Y
Yu Yang 已提交
426 427 428 429 430 431 432 433 434 435 436 437

          // 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 (step_id == 0) {
            auto &inside_tensor = cur_scope.FindVar(inside_grad_name)
                                      ->Get<framework::LoDTensor>();
            framework::AttributeMap attrs;
Y
Yu Yang 已提交
438
            attrs["dtype"] = inside_tensor.type();
Y
Yu Yang 已提交
439 440 441 442
            attrs["shape"] = framework::vectorize2int(inside_tensor.dims());
            attrs["value"] = 0.0f;

            auto zero_op = framework::OpRegistry::CreateOp(
Y
Yiqun Liu 已提交
443 444
                "fill_constant", framework::VariableNameMap{},
                {{"Out", {pg_names[param_id]}}}, attrs);
D
dzhwinter 已提交
445
            zero_op->Run(scope, place);
Y
Yu Yang 已提交
446 447
          }

Y
Yu Yang 已提交
448
          auto new_inside_name = cur_scope.Rename(inside_grad_name);
Y
Yu Yang 已提交
449 450 451
          // sum gradient

          auto sum_op = framework::OpRegistry::CreateOp(
Y
Yu Yang 已提交
452
              "sum", {{"X", {pg_names[param_id], new_inside_name}}},
453 454
              {{"Out", {pg_names[param_id]}}},
              framework::AttributeMap{{"use_mkldnn", {false}}});
D
dzhwinter 已提交
455
          sum_op->Run(cur_scope, place);
Y
Yu Yang 已提交
456 457

          cur_scope.Rename(new_inside_name, inside_grad_name);
Y
Yu Yang 已提交
458
        }
Y
Yan Chunwei 已提交
459
      }
M
minqiyang 已提交
460
      VLOG(5) << "Accumulate Parameter finished ";
Y
Yu Yang 已提交
461 462 463 464 465 466 467 468 469 470 471 472

      // Copy input gradient from inside to outside
      //   outside::input_grad[seq_offset: seq_offset + 1] = inside::input_grad
      LinkTensorWithCallback(
          cur_scope, GradVarLists(Inputs(kInputs)), scope, Outputs(kInputGrads),
          [&](const framework::LoDTensor &inside,
              framework::LoDTensor *outside) {
            if (inside.memory_size() == 0) {  // IG is not created.
              return;
            }
            if (step_id == 0) {  // alloc memory
              outside->Resize(PrependDims(seq_len, inside.dims()));
D
dzhwinter 已提交
473
              outside->mutable_data(place, inside.type());
Y
Yu Yang 已提交
474 475 476
            }

            auto dst = outside->Slice(seq_offset, seq_offset + 1);
Y
Yi Wang 已提交
477
            framework::TensorCopy(inside, place, dev_ctx, &dst);
C
chengduo 已提交
478 479
          },
          true /*is_backward*/);
M
minqiyang 已提交
480
      VLOG(5) << "Link outside gradient finished ";
Y
Yu Yang 已提交
481 482 483 484 485 486 487 488 489

      if (step_id + 1 == seq_len) {  // at_end
        // copy initialize states gradient from inside to outside
        LinkTensorWithCallback(
            cur_scope, GradVarLists(Attr<std::vector<std::string>>(kExStates)),
            scope, Outputs(kInitStateGrads),
            [&](const framework::LoDTensor &inside,
                framework::LoDTensor *outside) {
              outside->Resize(inside.dims());
D
dzhwinter 已提交
490
              outside->mutable_data(place, inside.type());
Y
Yi Wang 已提交
491
              framework::TensorCopy(inside, place, dev_ctx, outside);
C
chengduo 已提交
492 493
            },
            true /*is_backward*/);
M
minqiyang 已提交
494
        VLOG(5) << "Link initialize state gradient finished ";
Y
Yu Yang 已提交
495 496
      }
      scopes.Next();
Y
Yan Chunwei 已提交
497 498
    }
  }
Y
Yu Yang 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520

 private:
  StepScopes CreateStepScopes(const framework::Scope &scope,
                              size_t seq_len) const {
    auto *var = scope.FindVar(Input(kStepScopes));
    PADDLE_ENFORCE(var != nullptr);
    return StepScopes(scope, var->GetMutable<StepScopeVar>(),
                      Attr<bool>(kIsTrain), seq_len, true /*is_backward*/);
  }

  std::unordered_set<std::string> List2Set(
      const std::vector<std::string> &list) const {
    std::unordered_set<std::string> local_var_name_set;
    local_var_name_set.reserve(list.size());
    for (auto &each : list) {
      local_var_name_set.insert(each);
    }
    return local_var_name_set;
  }

  std::unordered_set<std::string> LocalVarNames(
      const framework::Scope &scope) const {
Y
Yang Yu 已提交
521
    return this->List2Set(scope.LocalVarNames());
Y
Yu Yang 已提交
522 523 524 525 526 527 528 529 530 531 532 533
  }
  static std::vector<std::string> GradVarLists(
      const std::vector<std::string> &var_names) {
    std::vector<std::string> retv;
    retv.reserve(var_names.size());
    std::transform(var_names.begin(), var_names.end(), std::back_inserter(retv),
                   framework::GradVarName);
    return retv;
  }
};

class RecurrentOpProtoMaker : public framework::OpProtoAndCheckerMaker {
534
 public:
Y
Yu Yang 已提交
535
  void Make() override {
Y
Yu Yang 已提交
536 537 538 539
    AddInput(kInputs, "rnn inputs").AsDuplicable();
    AddInput(kInitialStates, "rnn initial states").AsDuplicable();
    AddInput(kParameters,
             "Parameters are used by step block as its input. However, the "
K
kexinzhao 已提交
540 541
             "input is not a sequence tensor. Every time step, each operator "
             "in step block just use the parameter directly.")
Y
Yu Yang 已提交
542
        .AsDuplicable();
Y
Yu Yang 已提交
543
    AddOutput(kOutputs,
K
kexinzhao 已提交
544
              "The output sequence of RNN. The sequence length must be same.")
Y
Yu Yang 已提交
545
        .AsDuplicable();
Y
Yu Yang 已提交
546
    AddOutput(kStepScopes,
K
kexinzhao 已提交
547
              "StepScopes contain all local variables in each time step.");
Y
Yu Yang 已提交
548 549 550 551 552 553 554 555 556 557 558
    AddAttr<std::vector<std::string>>(kExStates,
                                      string::Sprintf(
                                          R"DOC(The ex-state variable names.
The ex-state means the state value in the ex-timestep or the previous time step
[%s, %s, %s] must be the same order)DOC",
                                          kExStates, kStates, kInitStateGrads));
    AddAttr<std::vector<std::string>>(
        kStates,
        string::Sprintf(
            "The state variable names. [%s, %s, %s] must be the same order",
            kExStates, kStates, kInitStateGrads));
Y
Yu Yang 已提交
559
    AddAttr<framework::BlockDesc *>(kStepBlock, "The step block inside RNN");
Y
Yu Yang 已提交
560 561
    AddAttr<bool>(kReverse, R"DOC(Calculate RNN reversely or not.
By default reverse=False
Y
Yan Chunwei 已提交
562

Y
Yu Yang 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
Assume the input data is [A, B, C, D]

if reverse is False:
  the computation of RNN is like
      A          B          C         D
      |          |          |         |
      v          v          v         v
     rnn -----> rnn -----> rnn ----> rnn
      |          |          |         |
      v          v          v         v
      o          o          o         o

if reverse is True
  the computation of RNN is like
      A          B          C         D
      |          |          |         |
      v          v          v         v
     rnn <----- rnn <----- rnn <---- rnn
      |          |          |         |
      v          v          v         v
      o          o          o         o
)DOC").SetDefault(false);
    AddAttr<bool>(kIsTrain, "").SetDefault(true);
S
sneaxiy 已提交
586 587 588 589
    AddAttr<std::vector<std::string>>(kSkipEagerDeletionVars,
                                      "Skip vars that would "
                                      "be used in backward ops")
        .SetDefault(std::vector<std::string>());
K
kexinzhao 已提交
590 591 592 593 594
    AddComment(R"DOC(
Static Length Recurrent Operator.

The static length recurrent operator can only operate on fixed size sequence
data, i.e. in each mini-batch, the sequence length of all inputs are the same.
Y
Yu Yang 已提交
595 596 597 598 599 600 601 602

)DOC");
  }
};

class RecurrentGradOpDescMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;
Y
Yan Chunwei 已提交
603

Y
Yu Yang 已提交
604
 protected:
Y
Yu Yang 已提交
605 606
  virtual std::unique_ptr<framework::OpDesc> Apply() const {
    auto *grad = new framework::OpDesc();
Y
Yu Yang 已提交
607 608 609 610
    grad->SetType("recurrent_grad");
    for (auto &input_param : this->InputNames()) {
      grad->SetInput(input_param, this->Input(input_param));
      grad->SetOutput(framework::GradVarName(input_param),
611
                      this->InputGrad(input_param, false));
Y
Yu Yang 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624
    }

    for (auto &output_param : this->OutputNames()) {
      if (output_param == kStepScopes) {
        grad->SetInput(output_param, this->Output(output_param));
        grad->SetInput(framework::GradVarName(output_param),
                       this->Output(output_param));
      } else {
        grad->SetInput(output_param, this->Output(output_param));
        grad->SetInput(framework::GradVarName(output_param),
                       this->OutputGrad(output_param));
      }
    }
S
sneaxiy 已提交
625 626 627 628 629

    auto attrs = this->Attrs();
    attrs.insert({kSkipEagerDeletionVars, std::vector<std::string>()});
    grad->SetAttrMap(attrs);

A
Abhinav Arora 已提交
630
    grad->SetBlockAttr(kStepBlock, grad_block_[0]);
Y
Yan Chunwei 已提交
631

Y
Yu Yang 已提交
632
    return std::unique_ptr<framework::OpDesc>(grad);
Y
Yan Chunwei 已提交
633 634 635
  }
};

Y
Yu Yang 已提交
636 637 638 639 640 641
class RecurrentGradOpShapeInference : public framework::InferShapeBase {
 public:
  void operator()(framework::InferShapeContext *ctx) const override {
    std::vector<std::string> input{kInputs, kInitialStates};
    std::vector<std::string> output{kOutputs};
    for (auto &s : input) {
C
chengduo 已提交
642
      // NOTE(zcd): In some case, some of kInputs doesn't have gradient.
Y
Yu Yang 已提交
643 644 645 646 647 648 649
      PADDLE_ENFORCE(ctx->HasInputs(s));
    }
    for (auto &s : output) {
      PADDLE_ENFORCE(ctx->HasInputs(s));
    }
    for (auto &s : input) {
      ctx->SetOutputsDim(framework::GradVarName(s), ctx->GetInputsDim(s));
Y
Yan Chunwei 已提交
650
    }
Y
Yu Yang 已提交
651 652 653 654 655 656 657
    if (ctx->HasInputs(kParameters)) {
      PADDLE_ENFORCE(ctx->HasOutputs(framework::GradVarName(kParameters)));
      ctx->SetOutputsDim(framework::GradVarName(kParameters),
                         ctx->GetInputsDim(kParameters));
    }
  }
};
Y
Yan Chunwei 已提交
658 659 660 661

}  // namespace operators
}  // namespace paddle

Y
Yu Yang 已提交
662 663 664 665 666
REGISTER_OPERATOR(recurrent, paddle::operators::RecurrentOp,
                  paddle::operators::RecurrentOpProtoMaker,
                  paddle::operators::RecurrentGradOpDescMaker);
REGISTER_OPERATOR(recurrent_grad, paddle::operators::RecurrentGradOp,
                  paddle::operators::RecurrentGradOpShapeInference);