row_conv_op.cc 12.4 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
L
Luo Tao 已提交
2 3 4
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
S
Siddharth Goyal 已提交
5

L
Luo Tao 已提交
6
    http://www.apache.org/licenses/LICENSE-2.0
S
Siddharth Goyal 已提交
7

L
Luo Tao 已提交
8 9 10 11 12
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
Siddharth Goyal 已提交
13

Y
Yi Wang 已提交
14
#include "paddle/fluid/operators/row_conv_op.h"
15 16 17 18
#include <memory>
#include <string>
#include <vector>

Y
Yi Wang 已提交
19
#include "paddle/fluid/framework/eigen.h"
S
Siddharth Goyal 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

namespace paddle {
namespace operators {

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

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

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("X"),
                   "Input(X) of RowConvOp should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Filter"),
                   "Input(Filter) of RowConvOp should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("Out"),
                   "Output(Out) of RowConvOp should not be null.");

    auto x_dims = ctx->GetInputDim("X");
    auto filter_dims = ctx->GetInputDim("Filter");
    PADDLE_ENFORCE_EQ(filter_dims.size(), 2, "Input(Y)'s rank should be 2.");
T
tink2123 已提交
46

S
Siddharth Goyal 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
    ctx->SetOutputDim("Out", x_dims);
    ctx->ShareLoD("X", "Out");
  }
};

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

  void InferShape(framework::InferShapeContext *ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Filter"),
                   "Input(Filter) should not be null.");
    PADDLE_ENFORCE(ctx->HasInput(framework::GradVarName("Out")),
                   "Gradient of output(Out) should not be null.");

    auto x_grad_name = framework::GradVarName("X");
    if (ctx->HasOutput(x_grad_name)) {
64 65
      auto dout_dims = ctx->GetInputDim(framework::GradVarName("Out"));
      ctx->SetOutputDim(x_grad_name, dout_dims);
S
Siddharth Goyal 已提交
66 67 68 69 70 71 72 73 74 75 76 77
    }

    auto filter_grad_name = framework::GradVarName("Filter");
    if (ctx->HasOutput(filter_grad_name)) {
      auto filter_dims = ctx->GetInputDim("Filter");
      ctx->SetOutputDim(filter_grad_name, filter_dims);
    }
  }
};

class RowConvOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
Y
Yu Yang 已提交
78
  void Make() override {
S
Siddharth Goyal 已提交
79
    AddInput("X",
80
             "the input(X) is a LodTensor or tensor, LodTensor(X) supports "
S
Siddharth Goyal 已提交
81 82 83
             "variable time-length input sequences. The underlying tensor "
             "in this LoDTensor is a matrix with shape (T x N), where T "
             "is the total time steps in this mini-batch and N is the input "
84 85
             "data dimension. the shape of Tensor input(X) has shape "
             "(B x T x N), B is batch size;");
S
Siddharth Goyal 已提交
86
    AddInput("Filter",
Y
yuyang18 已提交
87
             "the input(Filter) is a learnable parameter. It "
S
Siddharth Goyal 已提交
88 89 90 91
             "is a 2-D tensor with shape (future_context x N), where, "
             "future_context is the future context length and N is the data "
             "dimension.");
    AddOutput("Out",
92 93
              "the output(Out) is a LodTensor or Tensor, which has same type"
              " and same shape as X.");
S
Siddharth Goyal 已提交
94
    AddComment(R"DOC(
Y
yuyang18 已提交
95
:strong:`Row-convolution operator`
S
Siddharth Goyal 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109

The row convolution is called lookahead convolution.  This operator was 
introduced in the following paper for DeepSpeech2:
http://www.cs.cmu.edu/~dyogatam/papers/wang+etal.iclrworkshop2016.pdf 

The main motivation is that a bidirectional RNN, useful in DeepSpeech 
like speech models, learns representation for a sequence by performing a 
forward and a backward pass through the entire sequence. However, unlike 
unidirectional RNNs, bidirectional RNNs are challenging to deploy in an online
and low-latency setting. The lookahead convolution incorporates information 
from future subsequences in a computationally efficient manner to improve 
unidirectional recurrent neural networks. The row convolution operator is 
different from the 1D sequence convolution, and is computed as follows:

D
Dang Qingqing 已提交
110 111
Given an input sequence $X$ of length $t$ and input dimension $D$, 
and a filter ($W$) of size $context \times D$,
S
Siddharth Goyal 已提交
112 113 114
the output sequence is convolved as:

$$
D
Dang Qingqing 已提交
115
out_{i} = \\sum_{j=i}^{i + context - 1} X_{j} \\cdot W_{j-i}
S
Siddharth Goyal 已提交
116 117
$$

Y
yuyang18 已提交
118 119 120 121
In the above equation:

* $Out_{i}$: The i-th row of output variable with shape [1, D].

D
Dang Qingqing 已提交
122
* $context$: Future context size.
Y
yuyang18 已提交
123 124 125

* $X_{j}$: The j-th row of input variable with shape [1, D].

D
Dang Qingqing 已提交
126
* $W_{j-i}$: The (j-i)-th row of parameters with shape [1, D].
Y
yuyang18 已提交
127 128 129 130 131

More details about row_conv please refer to
the design document
https://github.com/PaddlePaddle/Paddle/issues/2228#issuecomment-303903645 .

S
Siddharth Goyal 已提交
132 133 134 135 136
)DOC");
  }
};

template <typename T>
Q
QI JUN 已提交
137 138
class RowConvKernel<platform::CPUDeviceContext, T>
    : public framework::OpKernel<T> {
S
Siddharth Goyal 已提交
139 140 141 142 143 144 145 146
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto *x = context.Input<LoDTensor>("X");
    auto *filter = context.Input<Tensor>("Filter");
    auto *out = context.Output<LoDTensor>("Out");

    out->mutable_data<T>(context.GetPlace());

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
    bool is_tensor = x->lod().empty();
    int batch_size = 0;
    if (is_tensor) {
      batch_size = x->dims()[0];
    } else {
      batch_size = x->lod()[0].size() - 1;
    }
    framework::Vector<size_t> batch_indices(batch_size + 1);
    int input_dim = 0;
    int timesteps = 0;
    if (is_tensor) {
      for (int i = 0; i < batch_size + 1; i++) {
        batch_indices[i] = i;
      }
      input_dim = x->dims()[2];
      timesteps = x->dims()[1];
    } else {
      batch_indices = x->lod()[0];
      input_dim = x->dims()[1];
    }
S
Siddharth Goyal 已提交
167 168 169 170 171 172 173 174
    size_t num_sequence = batch_indices.size() - 1;

    auto future_context = filter->dims()[0];
    auto weights = EigenMatrix<T>::From(*filter);

    for (size_t i = 0; i < num_sequence; i++) {
      int start = static_cast<int>(batch_indices[i]);
      int end = static_cast<int>(batch_indices[i + 1]);
175 176 177 178 179 180 181
      int current_timesteps = 0;
      if (is_tensor) {
        current_timesteps = timesteps;
      } else {
        current_timesteps = end - start;
      }
      // int current_timesteps = end - start;
S
Siddharth Goyal 已提交
182 183
      Tensor cur_input_sequence =
          x->Slice(start, end);  // Current input sequence
184 185 186
      cur_input_sequence =
          cur_input_sequence.Resize({current_timesteps, input_dim});

S
Siddharth Goyal 已提交
187 188
      Tensor cur_output_sequence =
          out->Slice(start, end);  // Current output sequence
189 190 191
      cur_output_sequence =
          cur_output_sequence.Resize({current_timesteps, input_dim});

S
Siddharth Goyal 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
      auto cip_seq = EigenMatrix<T>::From(cur_input_sequence);
      auto cot_seq = EigenMatrix<T>::From(cur_output_sequence);

      for (int k = 0; k < current_timesteps;
           k++) {  // For different time steps in the same sequence
        for (int w = 0; (w < future_context) && ((k + w) < current_timesteps);
             w++) {
          for (int d = 0; d < input_dim; d++) {
            if (w == 0) {
              cot_seq(k, d) = weights(w, d) * cip_seq(k + w, d);
            } else {
              cot_seq(k, d) += weights(w, d) * cip_seq(k + w, d);
            }
          }
        }
      }
    }
  }
};

template <typename T>
Q
QI JUN 已提交
213 214
class RowConvGradKernel<platform::CPUDeviceContext, T>
    : public framework::OpKernel<T> {
S
Siddharth Goyal 已提交
215 216 217 218 219 220 221 222
 public:
  void Compute(const framework::ExecutionContext &context) const override {
    auto *x = context.Input<LoDTensor>("X");
    auto *filter = context.Input<Tensor>("Filter");
    auto *d_out = context.Input<LoDTensor>(framework::GradVarName("Out"));
    auto *dx = context.Output<LoDTensor>(framework::GradVarName("X"));
    auto *d_filter = context.Output<Tensor>(framework::GradVarName("Filter"));

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    auto &x_lod = x->lod();
    bool is_tensor = x_lod.empty();
    int batch_size = 0;
    if (is_tensor) {
      batch_size = x->dims()[0];
    } else {
      batch_size = x->lod()[0].size() - 1;
    }
    framework::Vector<size_t> batch_indices(batch_size + 1);
    int timesteps = 0;
    int input_dim = 0;
    if (is_tensor) {
      for (int i = 0; i < batch_size + 1; i++) {
        batch_indices[i] = i;
      }
      input_dim = x->dims()[2];
      timesteps = x->dims()[1];
    } else {
      batch_indices = x->lod()[0];
      input_dim = x->dims()[1];
    }

S
Siddharth Goyal 已提交
245 246 247 248 249 250 251 252 253 254 255 256
    size_t num_sequence = batch_indices.size() - 1;
    auto future_context = filter->dims()[0];
    if (d_filter) {
      d_filter->mutable_data<T>(context.GetPlace());
      auto dweights =
          EigenMatrix<T>::From(*d_filter);  // Gradient of weight matrix
      dweights.setZero();

      for (size_t i = 0; i < num_sequence; i++) {  // For different sequences
        int start = static_cast<int>(batch_indices[i]);
        int end = static_cast<int>(batch_indices[i + 1]);

257 258 259 260 261 262
        int current_timesteps = 0;
        if (is_tensor) {
          current_timesteps = timesteps;
        } else {
          current_timesteps = end - start;
        }
S
Siddharth Goyal 已提交
263
        Tensor cur_input = x->Slice(start, end);  // Current input sequence
264
        cur_input = cur_input.Resize({current_timesteps, input_dim});
S
Siddharth Goyal 已提交
265 266
        Tensor cur_doutput =
            d_out->Slice(start, end);  // Current output grad sequence
267
        cur_doutput = cur_doutput.Resize({current_timesteps, input_dim});
S
Siddharth Goyal 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
        auto cur_ip = EigenMatrix<T>::From(cur_input);
        auto cur_dout = EigenMatrix<T>::From(cur_doutput);
        for (int k = 0; k < current_timesteps;
             k++) {  // For different time steps in the same sequence
          for (int w = 0; (w < future_context) && ((k + w) < current_timesteps);
               w++) {
            // For dweights (Updating the gradient of weight matrix)
            for (int d = 0; d < input_dim; d++) {
              dweights(w, d) += cur_ip(k + w, d) * cur_dout(k, d);
            }
          }
        }
      }
    }

    if (dx) {
      dx->mutable_data<T>(context.GetPlace());
      auto weights = EigenMatrix<T>::From(*filter);
      for (size_t i = 0; i < num_sequence; i++) {  // For different sequences
        int start = static_cast<int>(batch_indices[i]);
        int end = static_cast<int>(batch_indices[i + 1]);

290 291 292 293 294 295 296
        int current_timesteps = 0;
        if (is_tensor) {
          current_timesteps = timesteps;
        } else {
          current_timesteps = end - start;
        }

S
Siddharth Goyal 已提交
297 298
        Tensor cur_doutput =
            d_out->Slice(start, end);  // Current output grad sequence
299
        cur_doutput = cur_doutput.Resize({current_timesteps, input_dim});
S
Siddharth Goyal 已提交
300 301
        Tensor cur_dinput =
            dx->Slice(start, end);  // Current input grad sequence
302
        cur_dinput = cur_dinput.Resize({current_timesteps, input_dim});
S
Siddharth Goyal 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

        auto cur_dout = EigenMatrix<T>::From(cur_doutput);
        auto cur_dip = EigenMatrix<T>::From(cur_dinput);
        cur_dip.setZero();

        for (int k = 0; k < current_timesteps;
             k++) {  // For different time steps in the same sequence
          for (int w = 0; (w < future_context) && ((k + w) < current_timesteps);
               w++) {
            // For dinput (Updating the gradient wrt input)
            for (int d = 0; d < input_dim; d++) {
              cur_dip(k + w, d) += weights(w, d) * cur_dout(k, d);
            }
          }
        }
      }
    }
  }
};
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340

class RowConvGradOpDescMaker : public framework::SingleGradOpDescMaker {
 public:
  using framework::SingleGradOpDescMaker::SingleGradOpDescMaker;

 protected:
  std::unique_ptr<framework::OpDesc> Apply() const override {
    std::unique_ptr<framework::OpDesc> op(new framework::OpDesc());
    op->SetType("row_conv_grad");
    op->SetAttrMap(Attrs());
    op->SetInput("X", Input("X"));
    op->SetInput("Filter", Input("Filter"));
    op->SetInput(framework::GradVarName("Out"), OutputGrad("Out"));
    op->SetOutput(framework::GradVarName("X"), InputGrad("X"));
    op->SetOutput(framework::GradVarName("Filter"), InputGrad("Filter"));
    return op;
  }
};

S
Siddharth Goyal 已提交
341 342 343 344
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
Y
Yang Yang 已提交
345
REGISTER_OPERATOR(row_conv, ops::RowConvOp, ops::RowConvOpMaker,
346
                  ops::RowConvGradOpDescMaker);
347
REGISTER_OPERATOR(row_conv_grad, ops::RowConvGradOp);
S
Siddharth Goyal 已提交
348
REGISTER_OP_CPU_KERNEL(
Q
QI JUN 已提交
349 350 351 352
    row_conv, ops::RowConvKernel<paddle::platform::CPUDeviceContext, float>);
REGISTER_OP_CPU_KERNEL(
    row_conv_grad,
    ops::RowConvGradKernel<paddle::platform::CPUDeviceContext, float>);