cudnn_lstm_op.cc 15.0 KB
Newer Older
P
phlrain 已提交
1
/* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
L
liuhongyu 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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. */

S
sneaxiy 已提交
15
#include <memory>
L
liuhongyu 已提交
16
#include <string>
17

C
chengduozh 已提交
18
#include "paddle/fluid/framework/op_registry.h"
G
GaoWei8 已提交
19
#include "paddle/fluid/framework/op_version_registry.h"
L
liuhongyu 已提交
20 21 22 23 24 25 26 27 28

namespace paddle {
namespace operators {

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

  void InferShape(framework::InferShapeContext* ctx) const override {
G
GaoWei8 已提交
29 30 31 32 33
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "CudnnLSTM");
    OP_INOUT_CHECK(ctx->HasInput("InitH"), "Input", "InitH", "CudnnLSTM");
    OP_INOUT_CHECK(ctx->HasInput("InitC"), "Input", "InitC", "CudnnLSTM");

    OP_INOUT_CHECK(ctx->HasOutput("Reserve"), "Output", "Reserve", "CudnnLSTM");
34 35
    OP_INOUT_CHECK(
        ctx->HasOutput("StateOut"), "Output", "StateOut", "CudnnLSTM");
G
GaoWei8 已提交
36 37 38
    OP_INOUT_CHECK(ctx->HasOutput("Out"), "Output", "Out", "CudnnLSTM");
    OP_INOUT_CHECK(ctx->HasOutput("LastH"), "Output", "LastH", "CudnnLSTM");
    OP_INOUT_CHECK(ctx->HasOutput("LastC"), "Output", "LastC", "CudnnLSTM");
L
liuhongyu 已提交
39 40

    auto in_dims = ctx->GetInputDim("Input");
G
GaoWei8 已提交
41 42 43
    auto init_h_dims = ctx->GetInputDim("InitH");
    auto init_c_dims = ctx->GetInputDim("InitC");

44 45
    PADDLE_ENFORCE_EQ(in_dims.size(),
                      3,
G
GaoWei8 已提交
46 47 48 49
                      platform::errors::InvalidArgument(
                          "The rank of Input in CudnnLSTM  must be 3. But "
                          "received Input's rank is %d.",
                          in_dims.size()));
50 51
    PADDLE_ENFORCE_EQ(init_h_dims.size(),
                      3,
G
GaoWei8 已提交
52 53 54
                      platform::errors::InvalidArgument(
                          "The rank of InitH in CudnnLSTM  must be 3. But "
                          "received InitH's rank is %d.",
G
GaoWei8 已提交
55
                          init_h_dims.size()));
G
GaoWei8 已提交
56

57 58 59
    if (ctx->HasInput("SequenceLength")) {
      auto seq_dims = ctx->GetInputDim("SequenceLength");
      PADDLE_ENFORCE_EQ(
60 61
          in_dims[1],
          seq_dims[0],
62 63 64
          platform::errors::InvalidArgument(
              "The size of SequenceLength has to equal the batch_size. But "
              "received batch_size is %d and the size of SequenceLength is %d.",
65 66
              in_dims[1],
              seq_dims[0]));
67 68
    }

G
GaoWei8 已提交
69
    PADDLE_ENFORCE_EQ(
70 71
        in_dims[1],
        init_h_dims[1],
G
GaoWei8 已提交
72 73 74 75
        platform::errors::InvalidArgument(
            "The in_dims[1] (Input dims) and init_h_dims[1] (InitH "
            "dims) should be equal. But "
            "received in_dims[1] is %d and init_h_dims[1] is %d.",
76 77
            in_dims[1],
            init_h_dims[1]));
G
GaoWei8 已提交
78

79 80
    PADDLE_ENFORCE_EQ(init_c_dims,
                      init_h_dims,
G
GaoWei8 已提交
81
                      platform::errors::InvalidArgument(
G
GaoWei8 已提交
82 83 84
                          "The InitC dims and InitH "
                          "dims should be equal. But "
                          "received init_c_dims is %d and init_h_dims is %d.",
85 86
                          init_c_dims,
                          init_h_dims));
L
liuhongyu 已提交
87

88 89
    auto out_dims = in_dims;
    auto hidden_size = ctx->Attrs().Get<int>("hidden_size");
G
GaoWei8 已提交
90 91
    bool is_bidirec = ctx->Attrs().Get<bool>("is_bidirec");
    out_dims[2] = is_bidirec ? hidden_size * 2 : hidden_size;
92
    ctx->SetOutputDim("Out", out_dims);
G
GaoWei8 已提交
93 94
    ctx->SetOutputDim("LastH", init_c_dims);
    ctx->SetOutputDim("LastC", init_h_dims);
G
GaoWei8 已提交
95 96 97 98 99 100 101 102
  }

 protected:
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(
        OperatorWithKernel::IndicateVarDataType(ctx, "Input"),
        ctx.device_context());
L
liuhongyu 已提交
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  }
};

class CudnnLSTMOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override {
    AddInput(
        "Input",
        "(Tensor) RNN input tensor, which support variable-time length input "
        "sequence."
        "The shape of the Tensor MUST be ( seq_len * batch_size * input_size)"
        "seq_len is the total time step in this mini-batch (CAN be change in "
        "different batch)"
        "batch_size is the instance number of this batch"
        "input_size is the hidden size of the input."
G
GaoWei8 已提交
118
        "input_size and the hidden_size in the next may not be same");
L
liuhongyu 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    AddInput("InitH",
             "(Tensor) the initial hidden state of the LSTM"
             "input. This is a tensor with shape (num_layers x batch_size x "
             "hidden_size)"
             "and When is_bidirec is True, the shape will be (num_layers*2 x "
             "batch_size x hidden_size)");
    AddInput("InitC",
             "(Tensor) the initial cell state of the LSTm "
             "input. This is a tensor with shape (num_layers x batch_size x "
             "hidden_size)"
             "and When is_bidirec is True, the shape will be (num_layers*2 x "
             "batch_size x hidden_size)");
    AddInput("W",
             "(Tensor) the learnable hidden-hidden weights."
             " The shape is (N), where N is total weight size of the LSTM. "
G
GaoWei8 已提交
134 135 136 137 138 139 140
             " cudnn concatenate all the weight to one Tensor")
        .AsDispensable();
    AddInput("WeightList",
             "(vector<Tensor>), stores weight and bias data when the weight "
             "use the list format. ")
        .AsDispensable()
        .AsDuplicable();
141 142 143 144 145 146
    AddInput("SequenceLength",
             "(Tensor) When the input data is padding, "
             "set this parameter. This parameter represents "
             "the variable sequence lengths in a batch. "
             "The size of the vector has to equal the batch_size.")
        .AsDispensable();
G
GaoWei8 已提交
147 148 149 150 151 152 153
    AddOutput("Reserve",
              "(Tensor, a temporary output Tensor to store the reserve_data "
              "of cudnn kernel.")
        .AsIntermediate();
    AddOutput("StateOut",
              "Share memory with State. "
              "Store the global drop state when training");
L
liuhongyu 已提交
154 155 156 157 158 159
    AddOutput("Out",
              "(Tensor) the hidden state of LSTM operator. "
              "The shape is ( seq_len x batch_size x hidden_size) if "
              "is_bidirec is False"
              "and When is_bidirec is True, the shape will be ( seq_len x "
              "batch_size x hidden_size * 2) ");
G
GaoWei8 已提交
160
    AddOutput("LastH",
L
liuhongyu 已提交
161 162 163 164 165
              "(Tensor) the hidden state of the last step. "
              "The shape is ( num_layers x batch_size x hidden_size) if "
              "is_bidirec is False"
              "and When is_bidirec is True, the shape will be (num_layers*2 x "
              "batch_size x hidden_size)");
G
GaoWei8 已提交
166
    AddOutput("LastC",
L
liuhongyu 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179
              "(Tensor) the cell state of the last step"
              "The shape is ( num_layers x batch_size x hidden_size) if "
              "is_bidirec is False"
              "and When is_bidirect is True, the shape will be (num_layers*2 x "
              "batch_size x hidden_size*2)");
    AddAttr<float>(
        "dropout_prob",
        "dropout prob of the dropout op"
        "the dropout ONLY work between lstm layers, not between time steps"
        "There is no dropout work on the Out tensor")
        .SetDefault(0.0);
    AddAttr<bool>("is_bidirec",
                  "is_bidirec"
T
tianshuo78520a 已提交
180
                  "if it is bidirectional rnn"
G
GaoWei8 已提交
181
                  "The will affect the shape of the Out, LastH, and LastC")
L
liuhongyu 已提交
182 183 184 185 186 187
        .SetDefault(false);
    AddAttr<int>("input_size", "input size ot the Input Tensor").SetDefault(10);
    AddAttr<int>("hidden_size", "hidden size of the LSTM").SetDefault(100);
    AddAttr<int>("num_layers", "the total layer number of the LSTM")
        .SetDefault(1);
    AddAttr<bool>("is_test", "True if in test phase.").SetDefault(false);
G
GaoWei8 已提交
188
    AddAttr<int>("seed", "seed to used if fix_seed is True").SetDefault(0);
L
liuhongyu 已提交
189 190 191 192 193 194 195
    AddComment(R"DOC(
CUDNN LSTM implementation

A four-gate Long Short-Term Memory network with no peephole connections.
In the forward pass the output ht and cell output ct for a given iteration can be computed from the recurrent input ht-1, 
the cell input ct-1 and the previous layer input xt given matrices W, R and biases bW, bR from the following equations:

P
phlrain 已提交
196
$$ i_t = sigmoid(W_{ix}x_{t} + W_{ih}h_{t-1} + bx_i + bh_i) $$
L
liuhongyu 已提交
197

P
phlrain 已提交
198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220
$$ f_t = sigmoid(W_{fx}x_{t} + W_{fh}h_{t-1} + bx_f + bh_f) $$

$$ o_t = sigmoid(W_{ox}x_{t} + W_{oh}h_{t-1} + bx_o + bh_o) $$

$$ \\tilde{c_t} = tanh(W_{cx}x_t + W_{ch}h_{t-1} + bx_c + bh_c) $$

$$ c_t = f_t \\odot c_{t-1} + i_t \\odot \\tilde{c_t} $$

$$ h_t = o_t \\odot tanh(c_t) $$

- W terms denote weight matrices (e.g. $W_{ix}$ is the matrix
  of weights from the input gate to the input)
- The b terms denote bias vectors ($bx_i$ and $bh_i$ are the input gate bias vector).
- sigmoid is the logistic sigmoid function.
- $i, f, o$ and $c$ are the input gate, forget gate, output gate,
  and cell activation vectors, respectively, all of which have the same size as
  the cell output activation vector $h$.
- The $\odot$ is the element-wise product of the vectors.
- `tanh` is the activation functions.
- $\tilde{c_t}$ is also called candidate hidden state,
  which is computed based on the current input and the previous hidden state.

Where sigmoid is the sigmoid operator: sigmoid(x) = 1 / (1 + e^-x), * represents a point-wise multiplication, 
L
liuhongyu 已提交
221 222 223 224 225 226 227 228 229 230 231 232
X represensts a matrix multiplication


)DOC");
  }
};

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

  void InferShape(framework::InferShapeContext* ctx) const override {
G
GaoWei8 已提交
233 234 235
    OP_INOUT_CHECK(ctx->HasInput("Input"), "Input", "Input", "CudnnLSTMGrad");
    OP_INOUT_CHECK(ctx->HasInput("InitH"), "Input", "InitH", "CudnnLSTMGrad");
    OP_INOUT_CHECK(ctx->HasInput("InitC"), "Input", "InitC", "CudnnLSTMGrad");
L
liuhongyu 已提交
236 237 238 239 240 241 242 243 244

    auto SetOutGradDim = [&ctx](const std::string& name) {
      auto g_name = framework::GradVarName(name);
      if (ctx->HasOutput(g_name)) {
        ctx->SetOutputDim(g_name, ctx->GetInputDim(name));
      }
    };

    SetOutGradDim("Input");
G
GaoWei8 已提交
245 246 247 248
    if (ctx->HasInputs("WeightList")) {
      ctx->SetOutputsDim(framework::GradVarName("WeightList"),
                         ctx->GetInputsDim("WeightList"));
    }
L
liuhongyu 已提交
249 250 251
    SetOutGradDim("InitH");
    SetOutGradDim("InitC");
  }
G
GaoWei8 已提交
252 253 254 255 256 257
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
    return framework::OpKernelType(OperatorWithKernel::IndicateVarDataType(
                                       ctx, framework::GradVarName("Out")),
                                   ctx.device_context());
  }
L
liuhongyu 已提交
258 259
};

H
hong 已提交
260 261
template <typename T>
class CudnnLSTMGradOpMaker : public framework::SingleGradOpMaker<T> {
S
sneaxiy 已提交
262
 public:
H
hong 已提交
263
  using framework::SingleGradOpMaker<T>::SingleGradOpMaker;
S
sneaxiy 已提交
264 265

 protected:
266
  void Apply(GradOpPtr<T> op) const override {
S
sneaxiy 已提交
267
    op->SetType("cudnn_lstm_grad");
H
hong 已提交
268 269 270
    op->SetInput("Input", this->Input("Input"));
    op->SetInput("InitH", this->Input("InitH"));
    op->SetInput("InitC", this->Input("InitC"));
G
GaoWei8 已提交
271 272 273
    if (this->HasInput("WeightList")) {
      op->SetInput("WeightList", this->Input("WeightList"));
    }
274 275 276
    if (this->HasInput("SequenceLength")) {
      op->SetInput("SequenceLength", this->Input("SequenceLength"));
    }
G
GaoWei8 已提交
277 278
    op->SetInput("Reserve", this->Output("Reserve"));
    op->SetInput("StateOut", this->Output("StateOut"));
H
hong 已提交
279 280
    op->SetInput("Out", this->Output("Out"));
    op->SetInput(framework::GradVarName("Out"), this->OutputGrad("Out"));
G
GaoWei8 已提交
281 282
    op->SetInput(framework::GradVarName("LastC"), this->OutputGrad("LastC"));
    op->SetInput(framework::GradVarName("LastH"), this->OutputGrad("LastH"));
H
hong 已提交
283

G
GaoWei8 已提交
284 285 286 287 288
    if (this->HasInput("WeightList")) {
      op->SetOutput(framework::GradVarName("WeightList"),
                    this->InputGrad("WeightList", false));
    }

H
hong 已提交
289 290 291 292
    op->SetOutput(framework::GradVarName("Input"), this->InputGrad("Input"));
    op->SetOutput(framework::GradVarName("InitH"), this->InputGrad("InitH"));
    op->SetOutput(framework::GradVarName("InitC"), this->InputGrad("InitC"));
    op->SetAttrMap(this->Attrs());
S
sneaxiy 已提交
293 294 295
  }
};

C
chengduozh 已提交
296 297 298 299
template <typename T>
class NotImpleKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
300 301
    PADDLE_THROW(platform::errors::Unimplemented(
        "CPU is not support for this kernel now. Will be add in the future"));
C
chengduozh 已提交
302 303 304
  }
};

L
liuhongyu 已提交
305 306 307 308
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
309 310 311
REGISTER_OPERATOR(cudnn_lstm,
                  ops::CudnnLSTMOp,
                  ops::CudnnLSTMOpMaker,
H
hong 已提交
312 313
                  ops::CudnnLSTMGradOpMaker<paddle::framework::OpDesc>,
                  ops::CudnnLSTMGradOpMaker<paddle::imperative::OpBase>);
C
chengduozh 已提交
314
REGISTER_OPERATOR(cudnn_lstm_grad, ops::CudnnLSTMGradOp);
L
liuhongyu 已提交
315

C
chengduozh 已提交
316 317
REGISTER_OP_CPU_KERNEL(cudnn_lstm, ops::NotImpleKernel<float>);
REGISTER_OP_CPU_KERNEL(cudnn_lstm_grad, ops::NotImpleKernel<float>);
G
GaoWei8 已提交
318 319 320 321 322

// TODO(Shixiaowei02) Add ModifyInput support
REGISTER_OP_VERSION(cudnn_lstm)
    .AddCheckpoint(
        R"ROC(
323 324 325
              Upgrade cudnn_lstm add new inputs [WeightList, SequenceLength], modify the input [W] to dispensable, delete the input [Cache].
              Upgrade cudnn_lstm add new outputs [StateOut, Reserve, LastC, LastH], delete output [last_c, last_h].
              Upgrade cudnn_lstm modify the attr [seed] default value to 0, delete the attr [max_len].)ROC",
G
GaoWei8 已提交
326 327 328 329 330 331 332 333
        paddle::framework::compatible::OpVersionDesc()
            .NewInput(
                "WeightList",
                "The WeightList stores weight and bias data. WeightList is "
                "dispensable.")
            .NewInput("SequenceLength",
                      "When the input data is padding, set this parameter. "
                      "SequenceLength is dispensable.")
334 335 336 337 338 339
            .ModifyInput("W",
                         "The new LSTM use WeightList instead of W. The W "
                         "concatenate all the weight to one Tensor.")
            .DeleteInput("Cache",
                         "The new LSTM use the Reserve Output to store the "
                         "data of dropout.")
G
GaoWei8 已提交
340 341
            .NewOutput("StateOut", "Store the global drop state when training")
            .NewOutput("Reserve",
342 343 344 345 346 347 348 349 350 351
                       "A temporary output Tensor to store the reserve_data")
            .DeleteOutput(
                "last_c",
                "Modify the name of the output from 'last_c' to 'LastC'.")
            .NewOutput("LastC", "The cell state of the last step.")
            .DeleteOutput(
                "last_h",
                "Modify the name of the output from 'last_h' to 'LastH'.")
            .NewOutput("LastH", "The hidden state of the last step.")
            .ModifyAttr("seed",
352 353
                        "Set the default value of seed from '-1' to '0'.",
                        0)
354 355 356 357
            .DeleteAttr("max_len",
                        "The length of Inputs is achieved form the input data "
                        "which is difficult to know the information in "
                        "advance."));