cudnn_lstm_op.cu.cc 8.9 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. */

C
chengduozh 已提交
15
#include "paddle/fluid/framework/op_registry.h"
S
sneaxiy 已提交
16
#include "paddle/fluid/operators/cudnn_rnn_cache.h"
C
chengduozh 已提交
17
#include "paddle/fluid/operators/math/math_function.h"
G
GaoWei8 已提交
18
#include "paddle/fluid/platform/cudnn_desc.h"
L
liuhongyu 已提交
19 20 21 22 23 24 25

namespace paddle {
namespace operators {

using LoDTensor = framework::LoDTensor;
using Tensor = framework::Tensor;

C
chengduozh 已提交
26
template <typename T>
L
liuhongyu 已提交
27 28 29 30 31 32 33 34 35 36
class CudnnLSTMGPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    const Tensor *x = ctx.Input<Tensor>("Input");
    const Tensor *init_h = ctx.Input<Tensor>("InitH");
    const Tensor *init_c = ctx.Input<Tensor>("InitC");

    auto w = ctx.Input<Tensor>("W");

    Tensor *out = ctx.Output<Tensor>("Out");
G
GaoWei8 已提交
37 38 39 40
    Tensor *last_h = ctx.Output<Tensor>("LastH");
    Tensor *last_c = ctx.Output<Tensor>("LastC");
    Tensor *reserve = ctx.Output<Tensor>("Reserve");
    Tensor *state_out = ctx.Output<Tensor>("StateOut");
L
liuhongyu 已提交
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

    const T *x_data = x->data<T>();
    const T *init_h_data = init_h->data<T>();
    const T *init_c_data = init_c->data<T>();

    const T *w_data = w->data<T>();

    T *out_data = out->mutable_data<T>(ctx.GetPlace());
    T *last_h_data = last_h->mutable_data<T>(ctx.GetPlace());
    T *last_c_data = last_c->mutable_data<T>(ctx.GetPlace());

    float dropout_prob = ctx.Attr<float>("dropout_prob");
    bool is_bidirec = ctx.Attr<bool>("is_bidirec");
    int hidden_size = ctx.Attr<int>("hidden_size");
    int num_layers = ctx.Attr<int>("num_layers");
    bool is_test = ctx.Attr<bool>("is_test");
G
GaoWei8 已提交
57
    int seed = ctx.Attr<int>("seed");
L
liuhongyu 已提交
58 59 60 61

    auto &dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
    auto handle = dev_ctx.cudnn_handle();

G
GaoWei8 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    CudnnRNNCache *cudnn_rnn_cache = new CudnnRNNCache();

    auto input_w_numel = w->numel();
    auto seq_len = x->dims()[0];
    auto batch_size = x->dims()[1];
    auto input_dim = x->dims()[2];
    size_t reserve_size;
    bool state_initialized = state_out->IsInitialized() ? true : false;
    cudnnDataType_t cudnn_type = platform::ToCudnnDataType(
        framework::ToDataType(std::type_index(typeid(T))));
    cudnn_rnn_cache->init(handle, ctx.GetPlace(), seq_len, batch_size,
                          input_dim, hidden_size, num_layers, dropout_prob,
                          is_bidirec, seed, input_w_numel, &reserve_size,
                          state_out, state_initialized, cudnn_type);

    auto *reserve_data = reserve->mutable_data<uint8_t>(
        {static_cast<int64_t>(reserve_size)}, ctx.GetPlace());
L
liuhongyu 已提交
79 80 81

    if (is_test) {
      // for inference
82
      PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::cudnnRNNForwardInference(
G
GaoWei8 已提交
83 84 85 86 87 88
          handle, cudnn_rnn_cache->rnn_desc_, seq_len, cudnn_rnn_cache->x_desc_,
          x_data, cudnn_rnn_cache->hx_desc_, init_h_data,
          cudnn_rnn_cache->cx_desc_, init_c_data, cudnn_rnn_cache->w_desc_,
          w_data, cudnn_rnn_cache->y_desc_, out_data, cudnn_rnn_cache->hy_desc_,
          last_h_data, cudnn_rnn_cache->cy_desc_, last_c_data,
          cudnn_rnn_cache->workspace_data_.data<uint8_t>(),
L
liuhongyu 已提交
89 90 91
          cudnn_rnn_cache->workspace_size_));
    } else {
      // for train
92
      PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::cudnnRNNForwardTraining(
G
GaoWei8 已提交
93 94 95 96 97 98 99
          handle, cudnn_rnn_cache->rnn_desc_, seq_len, cudnn_rnn_cache->x_desc_,
          x_data, cudnn_rnn_cache->hx_desc_, init_h_data,
          cudnn_rnn_cache->cx_desc_, init_c_data, cudnn_rnn_cache->w_desc_,
          w_data, cudnn_rnn_cache->y_desc_, out_data, cudnn_rnn_cache->hy_desc_,
          last_h_data, cudnn_rnn_cache->cy_desc_, last_c_data,
          cudnn_rnn_cache->workspace_data_.data<uint8_t>(),
          cudnn_rnn_cache->workspace_size_, reserve_data, reserve_size));
L
liuhongyu 已提交
100
    }
G
GaoWei8 已提交
101
    delete cudnn_rnn_cache;
L
liuhongyu 已提交
102 103 104
  }
};

C
chengduozh 已提交
105
template <typename T>
L
liuhongyu 已提交
106 107 108 109 110 111 112
class CudnnLSTMGPUGradKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext &ctx) const override {
    auto *input = ctx.Input<Tensor>("Input");
    auto *weight = ctx.Input<Tensor>("W");
    auto *init_h = ctx.Input<Tensor>("InitH");
    auto *init_c = ctx.Input<Tensor>("InitC");
G
GaoWei8 已提交
113 114 115
    auto *reserve = ctx.Input<Tensor>("Reserve");
    auto *state_out = ctx.Input<Tensor>("StateOut");

L
liuhongyu 已提交
116 117
    auto *out = ctx.Input<Tensor>("Out");
    auto *out_grad = ctx.Input<Tensor>(framework::GradVarName("Out"));
G
GaoWei8 已提交
118 119
    auto *last_h_grad = ctx.Input<Tensor>(framework::GradVarName("LastH"));
    auto *last_c_grad = ctx.Input<Tensor>(framework::GradVarName("LastC"));
L
liuhongyu 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132

    auto *in_grad = ctx.Output<Tensor>(framework::GradVarName("Input"));
    auto *weight_grad = ctx.Output<Tensor>(framework::GradVarName("W"));
    auto *init_h_grad = ctx.Output<Tensor>(framework::GradVarName("InitH"));
    auto *init_c_grad = ctx.Output<Tensor>(framework::GradVarName("InitC"));

    auto &dev_ctx = ctx.template device_context<platform::CUDADeviceContext>();
    auto handle = dev_ctx.cudnn_handle();

    auto input_dims = input->dims();
    auto init_h_dims = init_h->dims();
    auto init_c_dims = init_c->dims();

G
GaoWei8 已提交
133 134 135 136 137 138 139
    auto *weight_data = weight->data<T>();
    auto *init_h_data = init_h->data<T>();
    auto *init_c_data = init_c->data<T>();
    auto *out_data = out->data<T>();
    auto *out_grad_data = out_grad->data<T>();
    auto *last_h_grad_data = last_h_grad->data<T>();
    auto *last_c_grad_data = last_c_grad->data<T>();
L
liuhongyu 已提交
140

G
GaoWei8 已提交
141 142 143
    math::SetConstant<paddle::platform::CUDADeviceContext, T> zero;
    weight_grad->mutable_data<T>(ctx.GetPlace());
    zero(dev_ctx, weight_grad, static_cast<T>(0.0));
L
liuhongyu 已提交
144

G
GaoWei8 已提交
145 146
    in_grad->mutable_data<T>(input_dims, ctx.GetPlace());
    auto *in_grad_data = in_grad->data<T>();
L
liuhongyu 已提交
147

G
GaoWei8 已提交
148 149
    init_h_grad->mutable_data<T>(init_h_dims, ctx.GetPlace());
    auto *init_h_grad_data = init_h_grad->data<T>();
L
liuhongyu 已提交
150

G
GaoWei8 已提交
151 152
    init_c_grad->mutable_data<T>(init_c_dims, ctx.GetPlace());
    auto *init_c_grad_data = init_c_grad->data<T>();
L
liuhongyu 已提交
153

G
GaoWei8 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
    float dropout_prob = ctx.Attr<float>("dropout_prob");
    bool is_bidirec = ctx.Attr<bool>("is_bidirec");
    int hidden_size = ctx.Attr<int>("hidden_size");
    int num_layers = ctx.Attr<int>("num_layers");
    int seed = ctx.Attr<int>("seed");

    CudnnRNNCache *cudnn_rnn_cache = new CudnnRNNCache();

    auto input_w_numel = weight->numel();
    auto seq_len = input_dims[0];
    auto batch_size = input->dims()[1];
    auto input_dim = input->dims()[2];
    size_t reserve_size;
    cudnnDataType_t cudnn_type = platform::ToCudnnDataType(
        framework::ToDataType(std::type_index(typeid(T))));
    cudnn_rnn_cache->init(handle, ctx.GetPlace(), seq_len, batch_size,
                          input_dim, hidden_size, num_layers, dropout_prob,
                          is_bidirec, seed, input_w_numel, &reserve_size,
                          const_cast<Tensor *>(state_out), true, cudnn_type);
L
liuhongyu 已提交
173 174

    auto work_data = cudnn_rnn_cache->workspace_data_.data<uint8_t>();
G
GaoWei8 已提交
175
    const uint8_t *reserve_data = reserve->data<uint8_t>();
L
liuhongyu 已提交
176

177
    PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::cudnnRNNBackwardData(
G
GaoWei8 已提交
178 179 180 181 182 183 184 185 186
        handle, cudnn_rnn_cache->rnn_desc_, seq_len, cudnn_rnn_cache->y_desc_,
        out_data, cudnn_rnn_cache->y_desc_, out_grad_data,
        cudnn_rnn_cache->hy_desc_, last_h_grad_data, cudnn_rnn_cache->cy_desc_,
        last_c_grad_data, cudnn_rnn_cache->w_desc_, weight_data,
        cudnn_rnn_cache->hx_desc_, init_h_data, cudnn_rnn_cache->cx_desc_,
        init_c_data, cudnn_rnn_cache->x_desc_, in_grad_data,
        cudnn_rnn_cache->hx_desc_, init_h_grad_data, cudnn_rnn_cache->cx_desc_,
        init_c_grad_data, work_data, cudnn_rnn_cache->workspace_size_,
        const_cast<uint8_t *>(reserve_data), reserve_size));
L
liuhongyu 已提交
187

188
    PADDLE_ENFORCE_CUDA_SUCCESS(platform::dynload::cudnnRNNBackwardWeights(
G
GaoWei8 已提交
189 190 191
        handle, cudnn_rnn_cache->rnn_desc_, seq_len, cudnn_rnn_cache->x_desc_,
        input->data<T>(), cudnn_rnn_cache->hx_desc_, init_h->data<T>(),
        cudnn_rnn_cache->y_desc_, out->data<T>(),
L
liuhongyu 已提交
192
        cudnn_rnn_cache->workspace_data_.data<uint8_t>(),
G
GaoWei8 已提交
193 194 195 196
        cudnn_rnn_cache->workspace_size_, cudnn_rnn_cache->w_desc_,
        weight_grad->data<T>(), const_cast<uint8_t *>(reserve_data),
        reserve_size));
    delete cudnn_rnn_cache;
L
liuhongyu 已提交
197 198 199 200 201 202 203
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
G
GaoWei8 已提交
204 205 206 207
REGISTER_OP_CUDA_KERNEL(cudnn_lstm, ops::CudnnLSTMGPUKernel<float>,
                        ops::CudnnLSTMGPUKernel<double>);
REGISTER_OP_CUDA_KERNEL(cudnn_lstm_grad, ops::CudnnLSTMGPUGradKernel<float>,
                        ops::CudnnLSTMGPUGradKernel<double>);