gru_unit_op.h 11.2 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 16

#pragma once

Y
Yi Wang 已提交
17 18
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
Y
Yu Yang 已提交
19 20
#include "paddle/fluid/operators/activation_op.h"
#include "paddle/fluid/operators/math/blas.h"
21
#include "paddle/fluid/platform/place.h"
G
guosheng 已提交
22 23 24 25 26 27 28 29 30

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>;

D
dzhwinter 已提交
31 32 33 34
template <typename T, int MajorType = Eigen::RowMajor,
          typename IndexType = Eigen::DenseIndex>
using EigenVector = framework::EigenVector<T, MajorType, IndexType>;

35 36
enum GRUActivationType { identity = 0, sigmoid = 1, tanh = 2, relu = 3 };

Q
QI JUN 已提交
37
template <typename DeviceContext, typename T>
38
class GRUUnitKernel : public framework::OpKernel<T> {
G
guosheng 已提交
39
 public:
40
  template <typename Device, typename X, typename Y>
41 42 43
  void ActCompute(const int act_type, const Device& d, X x, Y y,
                  platform::Place place) const {
    if (act_type == identity) {
44
      y.device(d) = x;
45
    } else if (act_type == sigmoid) {
46
      SigmoidFunctor<T>()(d, x, y);
47
    } else if (act_type == tanh) {
48
      TanhFunctor<T>()(d, x, y);
49 50 51 52 53 54
    } else if (act_type == relu) {
      if (place == platform::CPUPlace())
        ReluCPUFunctor<T>()(d, x, y);
      else
        ReluCUDAFunctor<T>()(d, x, y);
    } else {
55 56 57
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported activation type, only supports identity, sigmoid, tanh "
          "and relu."));
58
    }
59 60
  }

G
guosheng 已提交
61
  void Compute(const framework::ExecutionContext& context) const override {
62 63 64 65 66
    auto* input = context.Input<Tensor>("Input");
    auto* hidden_prev = context.Input<Tensor>("HiddenPrev");
    auto* weight = context.Input<Tensor>("Weight");
    auto* bias = context.Input<Tensor>("Bias");
    auto* gate = context.Output<Tensor>("Gate");
G
guosheng 已提交
67
    gate->mutable_data<T>(context.GetPlace());
68
    auto* reset_hidden_prev = context.Output<Tensor>("ResetHiddenPrev");
G
guosheng 已提交
69
    reset_hidden_prev->mutable_data<T>(context.GetPlace());
70
    auto* hidden = context.Output<Tensor>("Hidden");
G
guosheng 已提交
71 72 73 74 75 76 77 78 79 80
    hidden->mutable_data<T>(context.GetPlace());

    int batch_size = input->dims()[0];
    int frame_size = hidden_prev->dims()[1];

    auto x = EigenMatrix<T>::From(*input);
    auto h_p = EigenMatrix<T>::From(*hidden_prev);
    auto g = EigenMatrix<T>::From(*gate);
    auto r_h_p = EigenMatrix<T>::From(*reset_hidden_prev);
    auto h = EigenMatrix<T>::From(*hidden);
Q
QI JUN 已提交
81 82
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
G
guosheng 已提交
83 84

    // calculate unactivated gate outputs
G
guosheng 已提交
85 86 87 88 89 90 91 92
    if (bias) {
      auto b = EigenMatrix<T>::From(*bias);
      g.device(place) = x +
                        b.reshape(Eigen::array<int, 2>({{1, frame_size * 3}}))
                            .broadcast(Eigen::array<int, 2>({{batch_size, 1}}));
    } else {
      g.device(place) = x;
    }
G
guosheng 已提交
93 94 95 96
    const T* hidden_prev_data = hidden_prev->data<T>();
    const T* weight_data = weight->data<T>();
    T* gate_data = gate->data<T>();
    T* reset_hidden_prev_data = reset_hidden_prev->data<T>();
Y
Yu Yang 已提交
97 98 99 100
    auto blas = math::GetBlas<DeviceContext, T>(context);
    blas.GEMM(false, false, batch_size, 2 * frame_size, frame_size, 1,
              hidden_prev_data, frame_size, weight_data, frame_size * 2, 1,
              gate_data, frame_size * 3);
G
guosheng 已提交
101 102

    // calculate activited gate
103 104
    Eigen::array<int, 2> extents{{batch_size, frame_size}};
    Eigen::array<int, 2> u_offsets{{0, 0}};
105
    ActCompute(context.Attr<int>("gate_activation"), place,
106 107
               g.slice(u_offsets, extents), g.slice(u_offsets, extents),
               context.GetPlace());
G
guosheng 已提交
108
    auto u = g.slice(u_offsets, extents);  // update gate
109
    Eigen::array<int, 2> r_offsets{{0, frame_size}};
110
    ActCompute(context.Attr<int>("gate_activation"), place,
111 112
               g.slice(r_offsets, extents), g.slice(r_offsets, extents),
               context.GetPlace());
G
guosheng 已提交
113 114
    auto r = g.slice(r_offsets, extents);  // reset gate
    r_h_p.device(place) = r * h_p;         // reset previous hidden state
Y
Yu Yang 已提交
115 116 117 118
    blas.GEMM(false, false, batch_size, frame_size, frame_size, 1,
              reset_hidden_prev_data, frame_size,
              weight_data + frame_size * frame_size * 2, frame_size, 1,
              gate_data + frame_size * 2, frame_size * 3);
G
guosheng 已提交
119

120
    Eigen::array<int, 2> c_offsets{{0, frame_size * 2}};
121
    ActCompute(context.Attr<int>("activation"), place,
122 123
               g.slice(c_offsets, extents), g.slice(c_offsets, extents),
               context.GetPlace());
G
guosheng 已提交
124 125 126
    auto c = g.slice(c_offsets, extents);  // output candidate

    // calculate final output
Q
Qiao Longfei 已提交
127
    if (context.Attr<bool>("origin_mode")) {
Q
Qiao Longfei 已提交
128 129 130 131
      h.device(place) = c + u * (h_p - c);  // (1 - u) * c + u * h_p
    } else {
      h.device(place) = u * (c - h_p) + h_p;  // u * c + (1 - u) * h_p
    }
G
guosheng 已提交
132 133 134
  }
};

Q
QI JUN 已提交
135
template <typename DeviceContext, typename T>
136
class GRUUnitGradKernel : public framework::OpKernel<T> {
G
guosheng 已提交
137
 public:
138 139 140 141 142 143 144 145 146 147 148 149 150
  template <typename Device, typename X, typename Y, typename DX, typename DY>
  void ActGradCompute(const int act_type, const Device& d, X x, Y y, DX dx,
                      DY dy) const {
    // x is dummy and won't be used even in Relu(use y instead)
    if (act_type == identity)
      dx.device(d) = dy;
    else if (act_type == sigmoid)
      SigmoidGradFunctor<T>()(d, x, y, dy, dx);
    else if (act_type == tanh)
      TanhGradFunctor<T>()(d, x, y, dy, dx);
    else if (act_type == relu)
      ReluGradFunctor<T>()(d, x, y, dy, dx);
    else
151 152 153
      PADDLE_THROW(platform::errors::Unimplemented(
          "Unsupported activation type, only supports identity, sigmoid, tanh "
          "and relu."));
154 155
  }

G
guosheng 已提交
156
  void Compute(const framework::ExecutionContext& context) const override {
157 158 159 160 161 162 163
    auto* input = context.Input<Tensor>("Input");
    auto* hidden_prev = context.Input<Tensor>("HiddenPrev");
    auto* weight = context.Input<Tensor>("Weight");
    auto* gate = context.Input<Tensor>("Gate");
    auto* reset_hidden_prev = context.Input<Tensor>("ResetHiddenPrev");
    auto* hidden_grad = context.Input<Tensor>(framework::GradVarName("Hidden"));
    auto* input_grad = context.Output<Tensor>(framework::GradVarName("Input"));
G
guosheng 已提交
164
    auto* hidden_prev_grad =
165
        context.Output<Tensor>(framework::GradVarName("HiddenPrev"));
G
guosheng 已提交
166
    auto* weight_grad =
167 168
        context.Output<Tensor>(framework::GradVarName("Weight"));
    auto* bias_grad = context.Output<Tensor>(framework::GradVarName("Bias"));
G
guosheng 已提交
169 170 171 172 173
    Tensor gate_grad;
    Tensor reset_hidden_prev_grad;

    const T* hidden_prev_data = hidden_prev->data<T>();
    const T* weight_data = weight->data<T>();
174 175
    T* gate_grad_data =
        gate_grad.mutable_data<T>(input->dims(), context.GetPlace());
G
guosheng 已提交
176
    const T* reset_hidden_prev_data = reset_hidden_prev->data<T>();
177 178
    T* reset_hidden_prev_grad_data = reset_hidden_prev_grad.mutable_data<T>(
        reset_hidden_prev->dims(), context.GetPlace());
G
guosheng 已提交
179 180 181 182 183 184

    auto h_p = EigenMatrix<T>::From(*hidden_prev);
    auto g = EigenMatrix<T>::From(*gate);
    auto d_h = EigenMatrix<T>::From(*hidden_grad);
    auto d_g = EigenMatrix<T>::From(gate_grad);
    auto d_r_h_p = EigenMatrix<T>::From(reset_hidden_prev_grad);
Q
QI JUN 已提交
185 186
    auto& place =
        *context.template device_context<DeviceContext>().eigen_device();
G
guosheng 已提交
187

188 189 190
    int batch_size = input->dims()[0];
    int frame_size = hidden_prev->dims()[1];

191 192
    Eigen::array<int, 2> extents{{batch_size, frame_size}};
    Eigen::array<int, 2> u_offsets{{0, 0}};
G
guosheng 已提交
193
    auto u = g.slice(u_offsets, extents);  // update gate
194
    Eigen::array<int, 2> r_offsets{{0, frame_size}};
G
guosheng 已提交
195
    auto r = g.slice(r_offsets, extents);  // reset gate
196
    Eigen::array<int, 2> c_offsets{{0, frame_size * 2}};
G
guosheng 已提交
197 198 199
    auto c = g.slice(c_offsets, extents);  // output candidate

    // backward for unactivated update gate
Q
Qiao Longfei 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212
    if (context.Attr<bool>("origin_mode")) {
      ActGradCompute(context.Attr<int>("gate_activation"), place, u, u,
                     d_g.slice(u_offsets, extents), d_h * (h_p - c));
      // backward for unactivated output candidate
      ActGradCompute(context.Attr<int>("activation"), place, c, c,
                     d_g.slice(c_offsets, extents), d_h * (1 - u));
    } else {
      ActGradCompute(context.Attr<int>("gate_activation"), place, u, u,
                     d_g.slice(u_offsets, extents), d_h * (c - h_p));
      // backward for unactivated output candidate
      ActGradCompute(context.Attr<int>("activation"), place, c, c,
                     d_g.slice(c_offsets, extents), d_h * u);
    }
G
guosheng 已提交
213
    // backward for reset_hidden_prev
Y
Yu Yang 已提交
214 215 216 217 218
    auto blas = math::GetBlas<DeviceContext, T>(context);
    blas.GEMM(false, true, batch_size, frame_size, frame_size, 1,
              gate_grad_data + frame_size * 2, frame_size * 3,
              weight_data + frame_size * frame_size * 2, frame_size, 0,
              reset_hidden_prev_grad_data, frame_size);
G
guosheng 已提交
219
    // backward for unactivated reset gate
220 221
    ActGradCompute(context.Attr<int>("gate_activation"), place, r, r,
                   d_g.slice(r_offsets, extents), d_r_h_p * h_p);
222 223 224 225
    // backward for weight
    if (weight_grad) {
      T* weight_grad_data = weight_grad->mutable_data<T>(context.GetPlace());
      // backward for state_weight
Y
Yu Yang 已提交
226 227 228 229
      blas.GEMM(true, false, frame_size, frame_size, batch_size, 1,
                reset_hidden_prev_data, frame_size,
                gate_grad_data + frame_size * 2, frame_size * 3, 0,
                weight_grad_data + frame_size * frame_size * 2, frame_size);
230 231

      // backward for update_gate_weight and reset_gate_weight
Y
Yu Yang 已提交
232 233 234
      blas.GEMM(true, false, frame_size, frame_size * 2, batch_size, 1,
                hidden_prev_data, frame_size, gate_grad_data, frame_size * 3, 0,
                weight_grad_data, frame_size * 2);
235
    }
G
guosheng 已提交
236
    // backward for hidden_prev
237 238 239 240
    if (hidden_prev_grad) {
      T* hidden_prev_grad_data =
          hidden_prev_grad->mutable_data<T>(context.GetPlace());
      auto d_h_p = EigenMatrix<T>::From(*hidden_prev_grad);
Q
Qiao Longfei 已提交
241
      if (context.Attr<bool>("origin_mode")) {
Q
Qiao Longfei 已提交
242
        d_h_p.device(place) = d_r_h_p * r + d_h * u;
Q
Qiao Longfei 已提交
243
      } else {
Q
Qiao Longfei 已提交
244
        d_h_p.device(place) = d_r_h_p * r + d_h * (1 - u);
Q
Qiao Longfei 已提交
245
      }
Y
Yu Yang 已提交
246 247 248
      blas.GEMM(false, true, batch_size, frame_size, frame_size * 2, 1,
                gate_grad_data, frame_size * 3, weight_data, frame_size * 2, 1,
                hidden_prev_grad_data, frame_size);
249
    }
G
guosheng 已提交
250
    // backward for input
251 252 253 254 255
    if (input_grad) {
      input_grad->mutable_data<T>(context.GetPlace());
      auto d_x = EigenMatrix<T>::From(*input_grad);
      d_x.device(place) = d_g;
    }
G
guosheng 已提交
256
    // backward for bias
G
guosheng 已提交
257 258
    if (bias_grad) {
      bias_grad->mutable_data<T>(context.GetPlace());
D
dzhwinter 已提交
259
      auto d_b = EigenVector<T>::Flatten(*bias_grad);
G
guosheng 已提交
260 261
      d_b.device(place) = d_g.sum(Eigen::array<int, 1>({{0}}));
    }
G
guosheng 已提交
262 263 264 265 266
  }
};

}  // namespace operators
}  // namespace paddle