gru_op.cc 23.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
Luo Tao 已提交
2 3 4 5 6 7 8 9 10 11 12 13

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. */
G
guosheng 已提交
14

Y
Yi Wang 已提交
15
#include "paddle/fluid/operators/gru_op.h"
16

17
#include <memory>
18
#include <string>
19

20
#include "paddle/phi/kernels/funcs/blas/blas.h"
F
Feiyu Chan 已提交
21 22
#include "paddle/phi/kernels/funcs/detail/gru_cpu_kernel.h"
#include "paddle/phi/kernels/funcs/detail/gru_kernel.h"
T
tensor-tang 已提交
23 24

DECLARE_int32(paddle_num_threads);
G
guosheng 已提交
25 26 27 28 29 30 31 32 33

namespace paddle {
namespace operators {

class GRUOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
34 35 36
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "GRU");
    OP_INOUT_CHECK(ctx->HasInput("Weight"), "Input", "Weight", "GRU");
    OP_INOUT_CHECK(ctx->HasOutput("Hidden"), "Output", "Hidden", "GRU");
37 38 39
    bool is_test = ctx->Attrs().Get<bool>("is_test");
    if (!is_test) {
      OP_INOUT_CHECK(ctx->HasOutput("BatchGate"), "Output", "BatchGate", "GRU");
40 41 42
      OP_INOUT_CHECK(ctx->HasOutput("BatchResetHiddenPrev"),
                     "Output",
                     "BatchResetHiddenPrev",
43
                     "GRU");
44 45
      OP_INOUT_CHECK(
          ctx->HasOutput("BatchHidden"), "Output", "BatchHidden", "GRU");
46
    }
G
guosheng 已提交
47 48 49 50
    auto input_dims = ctx->GetInputDim("Input");
    auto weight_dims = ctx->GetInputDim("Weight");
    int input_size = input_dims[1];
    int frame_size = weight_dims[0];
51
    if (ctx->IsRuntime()) {
52 53
      PADDLE_ENFORCE_EQ(input_size,
                        frame_size * 3,
54 55 56 57
                        platform::errors::InvalidArgument(
                            "The second dimension of Input(Input) must be 3 "
                            "times of frame_size in GRUOp, but received %d "
                            "(Input) vs %d (frame_size).",
58 59
                            input_size,
                            frame_size));
60
    }
G
guosheng 已提交
61
    PADDLE_ENFORCE_EQ(
62 63
        weight_dims[1],
        frame_size * 3,
64 65 66
        platform::errors::InvalidArgument(
            "The shape of Input(Weight) matrix must be [frame_size, frame_size "
            "* 3], but received [%d, %d] (Weight) vs [%d, %d] (frame_size).",
67 68 69 70
            weight_dims[0],
            weight_dims[1],
            frame_size,
            frame_size * 3));
71
    if (ctx->HasInput("H0")) {
G
guosheng 已提交
72
      auto h0_dims = ctx->GetInputDim("H0");
73
      PADDLE_ENFORCE_EQ(
74 75
          h0_dims[1],
          frame_size,
76 77 78
          platform::errors::InvalidArgument(
              "The width of Input(H0) must be equal to frame_size, but "
              "received %d (width of H0) vs %d (frame_size).",
79 80
              h0_dims[1],
              frame_size));
G
guosheng 已提交
81
    }
82
    if (ctx->HasInput("Bias")) {
G
guosheng 已提交
83 84 85
      auto bias_dims = ctx->GetInputDim("Bias");
      int bias_height = bias_dims[0];
      int bias_width = bias_dims[1];
86
      PADDLE_ENFORCE_EQ(
87 88
          bias_height,
          1,
89 90 91
          platform::errors::InvalidArgument(
              "The shape of Bias must be [1, frame_size * 3], but received "
              "[%d, %d] (Bias) vs [1, %d] (frame_size * 3).",
92 93 94
              bias_height,
              bias_width,
              frame_size * 3));
95
      PADDLE_ENFORCE_EQ(
96 97
          bias_width,
          frame_size * 3,
98 99 100
          platform::errors::InvalidArgument(
              "The shape of Bias must be [1, frame_size * 3], but received "
              "[%d, %d] (Bias) vs [1, %d] (frame_size * 3).",
101 102 103
              bias_height,
              bias_width,
              frame_size * 3));
G
guosheng 已提交
104
    }
105 106 107 108 109
    if (!is_test) {
      ctx->SetOutputDim("BatchGate", input_dims);
      ctx->SetOutputDim("BatchResetHiddenPrev", {input_dims[0], frame_size});
      ctx->SetOutputDim("BatchHidden", {input_dims[0], frame_size});
    }
G
guosheng 已提交
110 111 112 113 114 115 116
    ctx->SetOutputDim("Hidden", {input_dims[0], frame_size});
    ctx->ShareLoD("Input", "Hidden");
  }
};

class GRUOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
117
  void Make() override {
118 119 120 121 122 123
    AddInput(
        "Input",
        "(phi::DenseTensor) The first input is a LodTensor, which supports "
        "variable-time length input sequence. The underlying tensor in "
        "this phi::DenseTensor is a matrix with shape (T X 3D), where, T is "
        "the total time steps in this mini-batch, D is the hidden size.");
G
guosheng 已提交
124
    AddInput("H0",
125
             "(Tensor, optional) The initial hidden state is an optional "
G
guosheng 已提交
126
             "input. This is a tensor with shape (N x D), where N is the "
127 128
             "batch size, D is the hidden size.")
        .AsDispensable();
G
guosheng 已提交
129 130
    AddInput(
        "Weight",
131 132 133 134 135
        "(Tensor) The learnable hidden-hidden weight matrix with shape "
        "(D x 3D), where D is the hidden size. The elements continuous in "
        "memory can be divided into two parts. The first part are weights of "
        "the update gate and reset gate with shape (D x 2D), and the second "
        "part are weights of output candidate with shape (D x D).");
G
guosheng 已提交
136
    AddInput("Bias",
137 138 139
             "(Tensor, optional) Bias vector with shape (1 x 3D) concating "
             "bias of the update gate, reset gate and output candidate.")
        .AsDispensable();
140 141 142 143 144 145 146 147 148
    AddOutput(
        "BatchGate",
        "(phi::DenseTensor) To compute with batches, sequence data will be "
        "reorganized into several successive batches each containing "
        "data from the same time step. The phi::DenseTensor BatchGate contains "
        "the update gate, reset gate and output candidate values "
        "organized in batches. The LoD size is 2. The first LoD contains "
        "the batch offsets and the second LoD contains the indexes in "
        "the raw sequence data.")
149 150
        .AsIntermediate()
        .AsExtra();
151 152 153 154 155 156
    AddOutput("BatchResetHiddenPrev",
              "(phi::DenseTensor) The reset hidden state phi::DenseTensor "
              "organized in batches. "
              "This phi::DenseTensor is a matrix with shape (T X D) and has "
              "the same LoD "
              "with `BatchGate`.")
157 158
        .AsIntermediate()
        .AsExtra();
159 160 161 162 163 164
    AddOutput("BatchHidden",
              "(phi::DenseTensor) The hidden state phi::DenseTensor organized "
              "in batches.  "
              "This phi::DenseTensor is a matrix with shape (T X D) and has "
              "the same LoD "
              "with `BatchGate`.")
165 166
        .AsIntermediate()
        .AsExtra();
167 168 169 170 171
    AddOutput("Hidden",
              "(phi::DenseTensor) the hidden state phi::DenseTensor organized "
              "in sequences. "
              "This phi::DenseTensor is a matrix with shape (T X D) and has "
              "the same LoD with `BatchGate`.");
G
guosheng 已提交
172 173 174 175 176 177 178 179 180 181
    AddAttr<std::string>("activation",
                         "(string, default tanh) "
                         "The activation type used for output candidate {h}_t.")
        .SetDefault("tanh");
    AddAttr<std::string>(
        "gate_activation",
        "(string, default sigmoid) "
        "The activation type used in update gate and reset gate.")
        .SetDefault("sigmoid");
    AddAttr<bool>("is_reverse",
翟飞跃 已提交
182
                  "(bool, default: False) "
G
guosheng 已提交
183 184
                  "whether to compute reversed GRU.")
        .SetDefault(false);
Q
Qiao Longfei 已提交
185 186 187 188
    AddAttr<bool>("origin_mode",
                  "bool"
                  "use origin mode in article https://arxiv.org/abs/1412.3555")
        .SetDefault(false);
G
guosheng 已提交
189
    AddComment(R"DOC(
190 191
GRU Operator implements part calculations of the complete GRU as following:

K
kavyasrinet 已提交
192 193 194 195
$$
update\_gate: u_t = actGate(xu_t + W_u * h_{t-1} + b_u) \\
reset\_gate: r_t = actGate(xr_t + W_r * h_{t-1} + b_r)  \\
output\_candidate: {h}_t = actNode(xc_t + W_c * dot(r_t, h_{t-1}) + b_c) \\
196
output: h_t = dot((1 - u_t), h_{t-1}) + dot(u_t, {h}_t)
K
kavyasrinet 已提交
197
$$
198

K
kavyasrinet 已提交
199
@note To implement the complete GRU, fully-connected operator must be used
200
before to feed xu, xr and xc as the Input of GRU operator.
G
guosheng 已提交
201 202 203 204 205 206 207 208 209
)DOC");
  }
};

class GRUGradOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

  void InferShape(framework::InferShapeContext* ctx) const override {
210 211
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "GRU@Grad");
    OP_INOUT_CHECK(ctx->HasInput("Weight"), "Input", "Weight", "GRU@Grad");
212 213 214 215 216
    OP_INOUT_CHECK(
        ctx->HasInput("BatchGate"), "Input", "BatchGate", "GRU@Grad");
    OP_INOUT_CHECK(ctx->HasInput("BatchResetHiddenPrev"),
                   "Input",
                   "BatchResetHiddenPrev",
217
                   "GRU@Grad");
218 219
    OP_INOUT_CHECK(
        ctx->HasInput("BatchHidden"), "Input", "BatchHidden", "GRU@Grad");
220
    OP_INOUT_CHECK(ctx->HasInput("Hidden"), "Input", "Hidden", "GRU@Grad");
221 222 223 224
    OP_INOUT_CHECK(ctx->HasInput(framework::GradVarName("Hidden")),
                   "Input",
                   framework::GradVarName("Hidden"),
                   "GRU@Grad");
225

G
guosheng 已提交
226 227 228 229 230 231
    auto input_dims = ctx->GetInputDim("Input");
    auto weight_dims = ctx->GetInputDim("Weight");
    int input_size = input_dims[1];
    int frame_size = weight_dims[0];
    int weight_height = weight_dims[0];
    int weight_width = weight_dims[1];
232
    PADDLE_ENFORCE_EQ(
233 234
        input_size,
        frame_size * 3,
235 236 237
        platform::errors::InvalidArgument(
            "The second dimension of Input(Input) must be 3 times of "
            "frame_size in GRUOp, but received %d (Input) vs %d (frame_size).",
238 239
            input_size,
            frame_size));
G
guosheng 已提交
240
    PADDLE_ENFORCE_EQ(
241 242
        weight_height,
        frame_size,
243 244 245
        platform::errors::InvalidArgument(
            "The shape of Input(Weight) matrix must be [frame_size, frame_size "
            "* 3], but received [%d, %d] (Weight) vs [%d, %d] (frame_size).",
246 247 248 249
            weight_height,
            weight_width,
            frame_size,
            frame_size * 3));
G
guosheng 已提交
250
    PADDLE_ENFORCE_EQ(
251 252
        weight_width,
        frame_size * 3,
253 254 255
        platform::errors::InvalidArgument(
            "The shape of Input(Weight) matrix must be [frame_size, frame_size "
            "* 3], but received [%d, %d] (Weight) vs [%d, %d] (frame_size).",
256 257 258 259
            weight_height,
            weight_width,
            frame_size,
            frame_size * 3));
260
    if (ctx->HasInput("H0")) {
G
guosheng 已提交
261
      auto h0_dims = ctx->GetInputDim("H0");
262
      PADDLE_ENFORCE_EQ(
263 264
          h0_dims[1],
          frame_size,
265 266 267
          platform::errors::InvalidArgument(
              "The width of Input(H0) must be equal to frame_size, but "
              "received %d (width of H0) vs %d (frame_size).",
268 269
              h0_dims[1],
              frame_size));
G
guosheng 已提交
270 271 272 273
      auto h0_grad_name = framework::GradVarName("H0");
      if (ctx->HasOutput(h0_grad_name))
        ctx->SetOutputDim(h0_grad_name, h0_dims);
    }
274
    if (ctx->HasInput("Bias")) {
G
guosheng 已提交
275 276 277
      auto bias_dims = ctx->GetInputDim("Bias");
      int bias_height = bias_dims[0];
      int bias_width = bias_dims[1];
278
      PADDLE_ENFORCE_EQ(
279 280
          bias_height,
          1,
281 282 283
          platform::errors::InvalidArgument(
              "The shape of Bias must be [1, frame_size * 3], but received "
              "[%d, %d] (Bias) vs [1, %d] (frame_size * 3).",
284 285 286
              bias_height,
              bias_width,
              frame_size * 3));
287
      PADDLE_ENFORCE_EQ(
288 289
          bias_width,
          frame_size * 3,
290 291 292
          platform::errors::InvalidArgument(
              "The shape of Bias must be [1, frame_size * 3], but received "
              "[%d, %d] (Bias) vs [1, %d] (frame_size * 3).",
293 294 295
              bias_height,
              bias_width,
              frame_size * 3));
G
guosheng 已提交
296 297 298 299 300 301 302 303 304 305 306
      auto bias_grad_name = framework::GradVarName("Bias");
      if (ctx->HasOutput(bias_grad_name))
        ctx->SetOutputDim(bias_grad_name, bias_dims);
    }
    auto input_grad_name = framework::GradVarName("Input");
    if (ctx->HasOutput(input_grad_name))
      ctx->SetOutputDim(input_grad_name, input_dims);
    auto weight_grad_name = framework::GradVarName("Weight");
    if (ctx->HasOutput(weight_grad_name))
      ctx->SetOutputDim(weight_grad_name, weight_dims);
  }
307

308
  phi::KernelKey GetExpectedKernelType(
309
      const framework::ExecutionContext& ctx) const override {
310 311 312
    return phi::KernelKey(OperatorWithKernel::IndicateVarDataType(
                              ctx, framework::GradVarName("Hidden")),
                          ctx.device_context().GetPlace());
313
  }
G
guosheng 已提交
314 315
};

H
huangjiyi 已提交
316
template <typename T, typename DeviceContext>
317 318 319
class GRUCPUKernel : public framework::OpKernel<T> {
 public:
  void BatchCompute(const framework::ExecutionContext& context) const {
320
    using LodTensorPtr = phi::DenseTensor*;
321 322
    bool is_test = context.Attr<bool>("is_test");

Q
Qiao Longfei 已提交
323
    bool origin_mode = context.Attr<bool>("origin_mode");
324
    auto* input = context.Input<phi::DenseTensor>("Input");
325 326
    auto* h0 = context.Input<phi::DenseTensor>("H0");
    auto* weight = context.Input<phi::DenseTensor>("Weight");
327
    const T* weight_data = weight->data<T>();
328
    auto* bias = context.Input<phi::DenseTensor>("Bias");
329
    auto* hidden = context.Output<phi::DenseTensor>("Hidden");
330 331
    hidden->mutable_data<T>(context.GetPlace());

332
    auto input_dims = input->dims();
333 334
    auto hidden_dims = hidden->dims();

335
    LodTensorPtr batch_gate, batch_reset_hidden_prev, batch_hidden;
336 337
    phi::DenseTensor batch_gate_tmp, batch_reset_hidden_prev_tmp,
        batch_hidden_tmp;
338 339 340 341 342 343 344 345 346 347
    if (is_test) {
      batch_gate = &batch_gate_tmp;
      batch_gate->Resize(input_dims);

      batch_reset_hidden_prev = &batch_reset_hidden_prev_tmp;
      batch_reset_hidden_prev->Resize(hidden_dims);

      batch_hidden = &batch_hidden_tmp;
      batch_hidden->Resize(hidden_dims);
    } else {
348 349
      batch_gate = context.Output<phi::DenseTensor>("BatchGate");
      batch_hidden = context.Output<phi::DenseTensor>("BatchHidden");
350
      batch_reset_hidden_prev =
351
          context.Output<phi::DenseTensor>("BatchResetHiddenPrev");
352 353 354 355 356
    }
    batch_gate->mutable_data<T>(context.GetPlace());
    batch_reset_hidden_prev->mutable_data<T>(context.GetPlace());
    batch_hidden->mutable_data<T>(context.GetPlace());

357
    bool is_reverse = context.Attr<bool>("is_reverse");
F
Feiyu Chan 已提交
358
    phi::funcs::LoDTensor2BatchFunctor<DeviceContext, T> to_batch;
359 360 361 362
    auto& dev_ctx = context.template device_context<DeviceContext>();
    to_batch(dev_ctx, *input, batch_gate, true, is_reverse);

    if (bias) {
363
      phi::funcs::RowwiseAdd<DeviceContext, T> add_bias;
364 365 366 367
      add_bias(dev_ctx, *batch_gate, *bias, batch_gate);
    }

    int frame_size = hidden_dims[1];
F
Feiyu Chan 已提交
368
    phi::funcs::GRUMetaValue<T> gru_value;
369 370 371
    gru_value.gate_weight = const_cast<T*>(weight_data);
    gru_value.state_weight =
        const_cast<T*>(weight_data + 2 * frame_size * frame_size);
372
    phi::DenseTensor ordered_h0;
373

H
Huang Jiyi 已提交
374
    phi::Vector<size_t> order(batch_gate->lod()[2]);
375 376 377 378 379 380

    if (h0) {
      // Since the batch computing for GRU reorders the input sequences
      // according to their length. The initialized cell state also needs
      // to reorder.
      ReorderInitState<DeviceContext, T>(
381 382 383 384 385
          context.template device_context<DeviceContext>(),
          *h0,
          order,
          &ordered_h0,
          true);
386 387 388 389 390
      gru_value.prev_out_value = ordered_h0.data<T>();
    } else {
      gru_value.prev_out_value = nullptr;
    }
    auto batch_starts = batch_gate->lod()[0];
T
tensor-tang 已提交
391
    size_t seq_len = batch_starts.size() - 1;
F
Feiyu Chan 已提交
392
    auto active_node = phi::funcs::detail::GetActivationType(
393
        context.Attr<std::string>("activation"));
F
Feiyu Chan 已提交
394
    auto active_gate = phi::funcs::detail::GetActivationType(
395 396 397
        context.Attr<std::string>("gate_activation"));

#ifdef PADDLE_WITH_MKLML
T
tensor-tang 已提交
398
    // use MKL packed to speedup GEMM
T
tensor-tang 已提交
399
    if (FLAGS_paddle_num_threads >= 4) {
400
      auto blas = phi::funcs::GetBlas<DeviceContext, T>(dev_ctx);
401 402
      T* packed_gate = blas.GEMM_ALLOC(CblasBMatrix,
                                       1 /*height of C*/,
T
tensor-tang 已提交
403 404
                                       frame_size * 2 /*width of weight*/,
                                       frame_size /*height of height*/);
405
      PADDLE_ENFORCE_NOT_NULL(
406 407 408 409 410 411 412 413 414 415 416 417
          packed_gate,
          platform::errors::NotFound(
              "The caculation result of packed_gate by "
              "GEMM_ALLOC should not be null when using MKL."));
      blas.GEMM_PACK(CblasBMatrix,
                     CblasNoTrans,
                     1 /*cur bs?*/,
                     frame_size * 2,
                     frame_size,
                     T(1.0),
                     gru_value.gate_weight,
                     frame_size * 2,
T
tensor-tang 已提交
418
                     packed_gate);
419 420
      T* packed_state = blas.GEMM_ALLOC(CblasBMatrix,
                                        1 /*height of C*/,
T
tensor-tang 已提交
421 422
                                        frame_size /*width of weight*/,
                                        frame_size /*height of height*/);
423
      PADDLE_ENFORCE_NOT_NULL(
424 425 426 427 428 429 430 431 432 433 434 435
          packed_state,
          platform::errors::NotFound(
              "The caculation result of packed_state by "
              "GEMM_ALLOC should not be null when using MKL."));
      blas.GEMM_PACK(CblasBMatrix,
                     CblasNoTrans,
                     1 /*cur bs?*/,
                     frame_size,
                     frame_size,
                     T(1.0),
                     gru_value.state_weight,
                     frame_size,
T
tensor-tang 已提交
436 437 438 439 440
                     packed_state);
      for (size_t n = 0; n < seq_len; n++) {
        int bstart = static_cast<int>(batch_starts[n]);
        int bend = static_cast<int>(batch_starts[n + 1]);
        int cur_batch_size = bend - bstart;
441

442 443
        phi::DenseTensor gate_t = batch_gate->Slice(bstart, bend);
        phi::DenseTensor reset_hidden_prev_t =
T
tensor-tang 已提交
444
            batch_reset_hidden_prev->Slice(bstart, bend);
445
        phi::DenseTensor hidden_t = batch_hidden->Slice(bstart, bend);
T
tensor-tang 已提交
446 447 448
        gru_value.output_value = hidden_t.data<T>();
        gru_value.gate_value = gate_t.data<T>();
        gru_value.reset_output_value = reset_hidden_prev_t.data<T>();
449

T
tensor-tang 已提交
450
        if (gru_value.prev_out_value) {
451 452 453 454 455 456 457 458 459 460 461 462
          blas.GEMM_COMPUTE(CblasNoTrans,
                            CblasPacked,
                            cur_batch_size,
                            frame_size * 2,
                            frame_size,
                            gru_value.prev_out_value,
                            frame_size,
                            packed_gate,
                            frame_size * 2,
                            T(1),
                            gru_value.gate_value,
                            frame_size * 3);
T
tensor-tang 已提交
463
        }
464

465
        phi::funcs::detail::forward_reset_output<DeviceContext>(
466 467 468 469 470
            phi::funcs::detail::forward::gru_resetOutput<T>(),
            gru_value,
            frame_size,
            cur_batch_size,
            active_gate);
T
tensor-tang 已提交
471 472

        if (gru_value.prev_out_value) {
473 474 475 476 477 478 479 480 481 482 483 484
          blas.GEMM_COMPUTE(CblasNoTrans,
                            CblasPacked,
                            cur_batch_size,
                            frame_size,
                            frame_size,
                            gru_value.reset_output_value,
                            frame_size,
                            packed_state,
                            frame_size,
                            T(1),
                            gru_value.gate_value + frame_size * 2,
                            frame_size * 3);
T
tensor-tang 已提交
485 486
        }

487
        phi::funcs::detail::forward_final_output<DeviceContext>(
488 489 490 491 492 493
            phi::funcs::detail::forward::gru_finalOutput<T>(),
            gru_value,
            frame_size,
            cur_batch_size,
            active_node,
            origin_mode);
T
tensor-tang 已提交
494 495

        gru_value.prev_out_value = gru_value.output_value;
496 497
      }

T
tensor-tang 已提交
498 499 500
      blas.GEMM_FREE(packed_gate);
      blas.GEMM_FREE(packed_state);
    } else {
501
#endif
T
tensor-tang 已提交
502 503 504 505 506
      for (size_t n = 0; n < seq_len; n++) {
        int bstart = static_cast<int>(batch_starts[n]);
        int bend = static_cast<int>(batch_starts[n + 1]);
        int cur_batch_size = bend - bstart;

507 508
        phi::DenseTensor gate_t = batch_gate->Slice(bstart, bend);
        phi::DenseTensor reset_hidden_prev_t =
T
tensor-tang 已提交
509
            batch_reset_hidden_prev->Slice(bstart, bend);
510
        phi::DenseTensor hidden_t = batch_hidden->Slice(bstart, bend);
T
tensor-tang 已提交
511 512 513 514
        gru_value.output_value = hidden_t.data<T>();
        gru_value.gate_value = gate_t.data<T>();
        gru_value.reset_output_value = reset_hidden_prev_t.data<T>();

515 516 517 518 519 520 521
        phi::funcs::GRUUnitFunctor<DeviceContext, T>::compute(dev_ctx,
                                                              gru_value,
                                                              frame_size,
                                                              cur_batch_size,
                                                              active_node,
                                                              active_gate,
                                                              origin_mode);
T
tensor-tang 已提交
522 523 524

        gru_value.prev_out_value = gru_value.output_value;
      }
525
#ifdef PADDLE_WITH_MKLML
T
tensor-tang 已提交
526
    }
527
#endif
F
Feiyu Chan 已提交
528
    phi::funcs::Batch2LoDTensorFunctor<DeviceContext, T> to_seq;
529 530 531 532 533 534 535 536 537
    batch_hidden->set_lod(batch_gate->lod());
    to_seq(dev_ctx, *batch_hidden, hidden);
  }

  void Compute(const framework::ExecutionContext& context) const override {
    BatchCompute(context);
  }
};

538 539 540 541 542 543
template <typename T>
class GRUGradOpMaker : public framework::SingleGradOpMaker<T> {
 public:
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;

 protected:
544
  void Apply(GradOpPtr<T> grad_op) const override {
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
    grad_op->SetType("gru_grad");
    grad_op->SetInput("Input", this->Input("Input"));
    grad_op->SetInput("H0", this->Input("H0"));
    grad_op->SetInput("Bias", this->Input("Bias"));
    grad_op->SetInput("Weight", this->Input("Weight"));

    grad_op->SetInput("BatchGate", this->Output("BatchGate"));
    grad_op->SetInput("BatchResetHiddenPrev",
                      this->Output("BatchResetHiddenPrev"));
    grad_op->SetInput("BatchHidden", this->Output("BatchHidden"));
    grad_op->SetInput("Hidden", this->Output("Hidden"));

    grad_op->SetInput(framework::GradVarName("Hidden"),
                      this->OutputGrad("Hidden"));

    grad_op->SetOutput(framework::GradVarName("H0"), this->InputGrad("H0"));
    grad_op->SetOutput(framework::GradVarName("Input"),
                       this->InputGrad("Input"));
    grad_op->SetOutput(framework::GradVarName("Weight"),
                       this->InputGrad("Weight"));
    grad_op->SetOutput(framework::GradVarName("Bias"), this->InputGrad("Bias"));

    grad_op->SetAttrMap(this->Attrs());
  }
};

571 572
DECLARE_NO_NEED_BUFFER_VARS_INFERER(GRUGradOpNoNeedBufferVarInferer,
                                    "Input",
573
                                    "Bias");
574

G
guosheng 已提交
575 576 577 578
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
579 580 581
REGISTER_OPERATOR(gru,
                  ops::GRUOp,
                  ops::GRUOpMaker,
582 583
                  ops::GRUGradOpMaker<paddle::framework::OpDesc>,
                  ops::GRUGradOpMaker<paddle::imperative::OpBase>);
584 585
REGISTER_OPERATOR(gru_grad,
                  ops::GRUGradOp,
586
                  ops::GRUGradOpNoNeedBufferVarInferer);
H
huangjiyi 已提交
587 588 589 590 591

PD_REGISTER_STRUCT_KERNEL(
    gru, CPU, ALL_LAYOUT, ops::GRUCPUKernel, float, double) {}
PD_REGISTER_STRUCT_KERNEL(
    gru_grad, CPU, ALL_LAYOUT, ops::GRUGradKernel, float, double) {}