gru_op.h 12.5 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
G
guosheng 已提交
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
G
guosheng 已提交
6

L
Luo Tao 已提交
7
    http://www.apache.org/licenses/LICENSE-2.0
G
guosheng 已提交
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. */
G
guosheng 已提交
14 15

#pragma once
16 17 18
#include <string>
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
T
tensor-tang 已提交
19
#include "paddle/fluid/operators/math/blas.h"
Y
Yi Wang 已提交
20
#include "paddle/fluid/operators/math/detail/activation_functions.h"
T
tensor-tang 已提交
21 22
#include "paddle/fluid/operators/math/detail/gru_cpu_kernel.h"
#include "paddle/fluid/operators/math/detail/gru_kernel.h"
Y
Yi Wang 已提交
23 24 25
#include "paddle/fluid/operators/math/gru_compute.h"
#include "paddle/fluid/operators/math/math_function.h"
#include "paddle/fluid/operators/math/sequence2batch.h"
G
guosheng 已提交
26 27 28 29

namespace paddle {
namespace operators {

G
guosheng 已提交
30 31 32
using LoDTensor = framework::LoDTensor;
using Tensor = framework::Tensor;

Q
QI JUN 已提交
33 34
template <typename DeviceContext, typename T>
inline void ReorderInitState(const DeviceContext& ctx,
D
dzhwinter 已提交
35 36
                             const framework::Tensor& src,
                             framework::Vector<size_t> index_lod,
G
guosheng 已提交
37
                             framework::Tensor* dst, bool indexed_src) {
Q
QI JUN 已提交
38
  math::CopyMatrixRowsFunctor<DeviceContext, T> row_shuffle;
G
guosheng 已提交
39
  dst->mutable_data<T>(src.dims(), ctx.GetPlace());
40
  row_shuffle(ctx, src, index_lod, dst, indexed_src);
G
guosheng 已提交
41 42
}

Q
QI JUN 已提交
43
template <typename DeviceContext, typename T>
G
guosheng 已提交
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
class GRUKernel : public framework::OpKernel<T> {
 public:
  void BatchCompute(const framework::ExecutionContext& context) const {
    auto* input = context.Input<LoDTensor>("Input");
    auto* h0 = context.Input<Tensor>("H0");
    auto* weight = context.Input<Tensor>("Weight");
    const T* weight_data = weight->data<T>();
    auto* bias = context.Input<Tensor>("Bias");
    auto* batch_gate = context.Output<LoDTensor>("BatchGate");
    batch_gate->mutable_data<T>(context.GetPlace());
    auto* batch_reset_hidden_prev =
        context.Output<LoDTensor>("BatchResetHiddenPrev");
    batch_reset_hidden_prev->mutable_data<T>(context.GetPlace());
    auto* batch_hidden = context.Output<LoDTensor>("BatchHidden");
    batch_hidden->mutable_data<T>(context.GetPlace());
    auto* hidden = context.Output<LoDTensor>("Hidden");
    hidden->mutable_data<T>(context.GetPlace());

    auto hidden_dims = hidden->dims();

    bool is_reverse = context.Attr<bool>("is_reverse");
Q
QI JUN 已提交
65 66
    math::LoDTensor2BatchFunctor<DeviceContext, T> to_batch;
    auto& dev_ctx = context.template device_context<DeviceContext>();
67
    to_batch(dev_ctx, *input, batch_gate, true, is_reverse);
G
guosheng 已提交
68 69

    if (bias) {
Q
QI JUN 已提交
70
      math::RowwiseAdd<DeviceContext, T> add_bias;
71
      add_bias(dev_ctx, *batch_gate, *bias, batch_gate);
G
guosheng 已提交
72 73
    }

74
    int frame_size = hidden_dims[1];
75
    math::GRUMetaValue<T> gru_value;
G
guosheng 已提交
76 77
    gru_value.gate_weight = const_cast<T*>(weight_data);
    gru_value.state_weight =
G
guosheng 已提交
78
        const_cast<T*>(weight_data + 2 * frame_size * frame_size);
G
guosheng 已提交
79
    Tensor ordered_h0;
D
dzhwinter 已提交
80 81 82

    framework::Vector<size_t> order(batch_gate->lod()[2]);

G
guosheng 已提交
83 84 85 86
    if (h0) {
      // Since the batch computing for GRU reorders the input sequences
      // according to their length. The initialized cell state also needs
      // to reorder.
Q
QI JUN 已提交
87 88 89
      ReorderInitState<DeviceContext, T>(
          context.template device_context<DeviceContext>(), *h0, order,
          &ordered_h0, true);
G
guosheng 已提交
90
      gru_value.prev_out_value = ordered_h0.data<T>();
G
guosheng 已提交
91
    } else {
G
guosheng 已提交
92
      gru_value.prev_out_value = nullptr;
G
guosheng 已提交
93
    }
G
guosheng 已提交
94 95
    auto batch_starts = batch_gate->lod()[0];
    size_t num_batch = batch_starts.size() - 1;
96 97 98 99
    auto active_node = math::detail::GetActivationType(
        context.Attr<std::string>("activation"));
    auto active_gate = math::detail::GetActivationType(
        context.Attr<std::string>("gate_activation"));
T
tensor-tang 已提交
100
    auto blas = math::GetBlas<DeviceContext, T>(dev_ctx);
T
tensor-tang 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

    // TODO(TJ): make a class, make one pack
    T* packed_gate = blas.GEMM_ALLOC(CblasBMatrix, 1 /*height of C*/,
                                     frame_size * 2 /*width of weight*/,
                                     frame_size /*height of height*/);
    PADDLE_ENFORCE(packed_gate);
    blas.GEMM_PACK(CblasBMatrix, CblasNoTrans, 1 /*cur bs?*/, frame_size * 2,
                   frame_size, T(1.0), gru_value.gate_weight, frame_size * 2,
                   packed_gate);
    T* packed_state = blas.GEMM_ALLOC(CblasBMatrix, 1 /*height of C*/,
                                      frame_size /*width of weight*/,
                                      frame_size /*height of height*/);
    PADDLE_ENFORCE(packed_state);
    blas.GEMM_PACK(CblasBMatrix, CblasNoTrans, 1 /*cur bs?*/, frame_size,
                   frame_size, T(1.0), gru_value.state_weight, frame_size,
                   packed_state);

G
guosheng 已提交
118 119 120 121 122 123 124 125
    for (size_t n = 0; n < num_batch; n++) {
      int bstart = static_cast<int>(batch_starts[n]);
      int bend = static_cast<int>(batch_starts[n + 1]);
      int cur_batch_size = bend - bstart;

      Tensor gate_t = batch_gate->Slice(bstart, bend);
      Tensor reset_hidden_prev_t = batch_reset_hidden_prev->Slice(bstart, bend);
      Tensor hidden_t = batch_hidden->Slice(bstart, bend);
G
guosheng 已提交
126 127 128
      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>();
T
tensor-tang 已提交
129
      if (gru_value.prev_out_value) {
T
tensor-tang 已提交
130 131 132 133
        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 已提交
134 135 136 137 138 139 140
      }

      math::detail::forward_reset_output(
          math::detail::forward::gru_resetOutput<T>(), gru_value, frame_size,
          cur_batch_size, active_gate);

      if (gru_value.prev_out_value) {
T
tensor-tang 已提交
141 142 143 144
        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 已提交
145 146 147 148 149 150
      }

      math::detail::forward_final_output(
          math::detail::forward::gru_finalOutput<T>(), gru_value, frame_size,
          cur_batch_size, active_node);

G
guosheng 已提交
151
      gru_value.prev_out_value = gru_value.output_value;
G
guosheng 已提交
152
    }
T
tensor-tang 已提交
153 154
    blas.GEMM_FREE(packed_gate);
    blas.GEMM_FREE(packed_state);
G
guosheng 已提交
155

Q
QI JUN 已提交
156
    math::Batch2LoDTensorFunctor<DeviceContext, T> to_seq;
G
guosheng 已提交
157
    batch_hidden->set_lod(batch_gate->lod());
158
    to_seq(dev_ctx, *batch_hidden, hidden);
G
guosheng 已提交
159 160 161 162 163 164 165
  }

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

Q
QI JUN 已提交
166
template <typename DeviceContext, typename T>
G
guosheng 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
class GRUGradKernel : public framework::OpKernel<T> {
 public:
  void BatchCompute(const framework::ExecutionContext& context) const {
    auto* h0 = context.Input<Tensor>("H0");
    auto* weight = context.Input<Tensor>("Weight");
    const T* weight_data = weight->data<T>();
    auto* batch_gate = context.Input<LoDTensor>("BatchGate");
    auto* batch_reset_hidden_prev =
        context.Input<LoDTensor>("BatchResetHiddenPrev");
    auto* batch_hidden = context.Input<LoDTensor>("BatchHidden");
    auto* hidden = context.Input<LoDTensor>("Hidden");
    auto* hidden_grad =
        context.Input<LoDTensor>(framework::GradVarName("Hidden"));
    auto* input_grad =
        context.Output<LoDTensor>(framework::GradVarName("Input"));
    auto* h0_grad = context.Output<Tensor>(framework::GradVarName("H0"));
    auto* weight_grad =
        context.Output<Tensor>(framework::GradVarName("Weight"));
    auto* bias_grad = context.Output<Tensor>(framework::GradVarName("Bias"));

    auto gate_dims = batch_gate->dims();
    auto hidden_dims = hidden->dims();
    int frame_size = hidden_dims[1];

Q
QI JUN 已提交
191
    math::LoDTensor2BatchFunctor<DeviceContext, T> to_batch;
G
guosheng 已提交
192 193 194 195 196
    LoDTensor batch_hidden_grad, batch_gate_grad, batch_reset_hidden_prev_grad;
    batch_hidden_grad.mutable_data<T>(hidden_dims, context.GetPlace());
    batch_gate_grad.mutable_data<T>(gate_dims, context.GetPlace());
    batch_reset_hidden_prev_grad.mutable_data<T>(hidden_dims,
                                                 context.GetPlace());
Q
QI JUN 已提交
197 198
    math::SetConstant<DeviceContext, T> zero;
    auto& dev_ctx = context.template device_context<DeviceContext>();
199 200 201
    zero(dev_ctx, &batch_hidden_grad, static_cast<T>(0.0));
    zero(dev_ctx, &batch_gate_grad, static_cast<T>(0.0));
    zero(dev_ctx, &batch_reset_hidden_prev_grad, static_cast<T>(0.0));
G
guosheng 已提交
202

G
guosheng 已提交
203
    Tensor ordered_h0, ordered_h0_grad;
D
dzhwinter 已提交
204 205 206

    framework::Vector<size_t> order(batch_gate->lod()[2]);

G
guosheng 已提交
207
    if (h0) {
Q
QI JUN 已提交
208 209
      ReorderInitState<DeviceContext, T>(dev_ctx, *h0, order, &ordered_h0,
                                         true);
G
guosheng 已提交
210 211 212
    }
    if (h0_grad) {
      ordered_h0_grad.mutable_data<T>(h0_grad->dims(), context.GetPlace());
Q
QI JUN 已提交
213 214
      zero(context.template device_context<DeviceContext>(), &ordered_h0_grad,
           static_cast<T>(0.0));
G
guosheng 已提交
215 216
    }

G
guosheng 已提交
217 218
    bool is_reverse = context.Attr<bool>("is_reverse");
    batch_hidden_grad.set_lod(batch_hidden->lod());
219
    to_batch(dev_ctx, *hidden_grad, &batch_hidden_grad, false, is_reverse);
G
guosheng 已提交
220

221
    math::GRUMetaValue<T> gru_value;
G
guosheng 已提交
222 223
    gru_value.gate_weight = const_cast<T*>(weight_data);
    gru_value.state_weight =
G
guosheng 已提交
224 225
        const_cast<T*>(weight_data + 2 * frame_size * frame_size);

226
    math::GRUMetaGrad<T> gru_grad;
G
guosheng 已提交
227
    if (weight_grad) {
G
guosheng 已提交
228
      gru_grad.gate_weight_grad =
G
guosheng 已提交
229
          weight_grad->mutable_data<T>(context.GetPlace());
230
      zero(dev_ctx, weight_grad, static_cast<T>(0.0));
G
guosheng 已提交
231
      gru_grad.state_weight_grad =
G
guosheng 已提交
232 233
          weight_grad->data<T>() + 2 * frame_size * frame_size;
    } else {
G
guosheng 已提交
234 235
      gru_grad.gate_weight_grad = nullptr;
      gru_grad.state_weight_grad = nullptr;
G
guosheng 已提交
236 237 238 239
    }

    auto batch_starts = batch_hidden_grad.lod()[0];
    size_t num_batch = batch_starts.size() - 1;
240 241 242 243
    auto active_node = math::detail::GetActivationType(
        context.Attr<std::string>("activation"));
    auto active_gate = math::detail::GetActivationType(
        context.Attr<std::string>("gate_activation"));
G
guosheng 已提交
244 245 246 247 248 249
    for (int n = static_cast<int>(num_batch) - 1; n >= 0; n--) {
      int bstart = static_cast<int>(batch_starts[n]);
      int bend = static_cast<int>(batch_starts[n + 1]);
      int cur_batch_size = bend - bstart;

      Tensor gate_t = batch_gate->Slice(bstart, bend);
G
guosheng 已提交
250
      gru_value.gate_value = gate_t.data<T>();
G
guosheng 已提交
251
      Tensor reset_hidden_prev_t = batch_reset_hidden_prev->Slice(bstart, bend);
G
guosheng 已提交
252
      gru_value.reset_output_value = reset_hidden_prev_t.data<T>();
G
guosheng 已提交
253 254

      Tensor hidden_grad_t = batch_hidden_grad.Slice(bstart, bend);
G
guosheng 已提交
255
      gru_grad.output_grad = hidden_grad_t.data<T>();
G
guosheng 已提交
256
      Tensor gate_grad_t = batch_gate_grad.Slice(bstart, bend);
G
guosheng 已提交
257
      gru_grad.gate_grad = gate_grad_t.data<T>();
G
guosheng 已提交
258 259
      Tensor reset_hidden_prev_grad_t =
          batch_reset_hidden_prev_grad.Slice(bstart, bend);
G
guosheng 已提交
260
      gru_grad.reset_output_grad = reset_hidden_prev_grad_t.data<T>();
G
guosheng 已提交
261
      if (n == 0) {
G
guosheng 已提交
262 263
        gru_value.prev_out_value = h0 ? ordered_h0.data<T>() : nullptr;
        gru_grad.prev_out_grad =
G
guosheng 已提交
264
            h0 && h0_grad ? ordered_h0_grad.data<T>() : nullptr;
G
guosheng 已提交
265 266 267
      } else {
        int bstart_pre = static_cast<int>(batch_starts[n - 1]);
        Tensor hidden_prev_t = batch_hidden->Slice(bstart_pre, bstart);
G
guosheng 已提交
268
        gru_value.prev_out_value = hidden_prev_t.data<T>();
G
guosheng 已提交
269
        Tensor hidden_prev_grad_t = batch_hidden_grad.Slice(bstart_pre, bstart);
G
guosheng 已提交
270
        gru_grad.prev_out_grad = hidden_prev_grad_t.data<T>();
G
guosheng 已提交
271 272
      }

Q
QI JUN 已提交
273
      math::GRUUnitGradFunctor<DeviceContext, T>::compute(
274 275
          dev_ctx, gru_value, gru_grad, frame_size, cur_batch_size, active_node,
          active_gate);
G
guosheng 已提交
276 277 278
    }
    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
Q
QI JUN 已提交
279
      math::Batch2LoDTensorFunctor<DeviceContext, T> to_seq;
G
guosheng 已提交
280
      batch_gate_grad.set_lod(batch_gate->lod());
281
      to_seq(dev_ctx, batch_gate_grad, input_grad);
G
guosheng 已提交
282 283 284
    }
    if (bias_grad) {
      bias_grad->mutable_data<T>(context.GetPlace());
Q
QI JUN 已提交
285
      math::ColwiseSum<DeviceContext, T> col_sum;
286
      col_sum(dev_ctx, batch_gate_grad, bias_grad);
G
guosheng 已提交
287
    }
G
guosheng 已提交
288
    if (h0 && h0_grad) {
Q
QI JUN 已提交
289 290
      ReorderInitState<DeviceContext, T>(dev_ctx, ordered_h0_grad, order,
                                         h0_grad, false);
G
guosheng 已提交
291
    }
G
guosheng 已提交
292 293 294 295 296 297 298 299 300
  }

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

}  // namespace operators
}  // namespace paddle