ContextProjectionOp.cpp 11.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

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

15
#include "ContextProjectionOp.h"
16 17 18 19 20
#include "paddle/math/Matrix.h"
#include "paddle/math/Vector.h"

namespace paddle {

X
xutianbing 已提交
21 22 23 24
/**
 * Context Projection Forward with CPU Matrix Device.
 *
 */
25
template <>
26 27 28
void ContextProjectionForward<DEVICE_TYPE_CPU>(CpuMatrix& out_mat,
                                               const CpuMatrix& input_mat,
                                               const CpuMatrix& weight_mat,
29
                                               const CpuIVector& seq_vec,
30 31
                                               size_t context_length,
                                               int context_start,
32
                                               size_t begin_pad) {
33 34 35 36 37 38 39 40 41 42 43
  const int* starts = seq_vec.getData();
  const size_t num_sequences = seq_vec.getSize() - 1;
  for (size_t i = 0; i < num_sequences; ++i) {
    for (size_t j = 0; j < context_length; ++j) {
      int begin = starts[i] + context_start + j;
      int end = starts[i + 1] + context_start + j;
      int dst_begin = starts[i];
      int dst_end = starts[i + 1];
      if (begin < starts[i]) {
        int64_t pad_size =
            std::min(starts[i] - begin, starts[i + 1] - starts[i]);
44 45 46 47 48
        MatrixPtr mat = out_mat.subMatrix(starts[i], pad_size);
        if (weight_mat) {
          MatrixPtr sub =
              const_cast<CpuMatrix&>(weight_mat).subMatrix(j, pad_size);
          mat->addAtOffset(*sub, j * input_mat.getWidth());
49 50 51 52 53 54 55
        }
        dst_begin = starts[i] + pad_size;
        begin = starts[i];
      }
      if (end > starts[i + 1]) {
        int64_t pad_size =
            std::min(end - starts[i + 1], starts[i + 1] - starts[i]);
56 57 58 59 60 61 62
        MatrixPtr mat = out_mat.subMatrix(starts[i + 1] - pad_size, pad_size);
        if (weight_mat) {
          MatrixPtr sub =
              const_cast<CpuMatrix&>(weight_mat)
                  .subMatrix(begin_pad + context_start + j - pad_size,
                             pad_size);
          mat->addAtOffset(*sub, j * input_mat.getWidth());
63 64 65 66 67
        }
        dst_end = starts[i + 1] - pad_size;
        end = starts[i + 1];
      }
      if (end <= begin) continue;
68 69 70 71
      MatrixPtr src =
          const_cast<CpuMatrix&>(input_mat).subMatrix(begin, end - begin);
      MatrixPtr dst = out_mat.subMatrix(dst_begin, dst_end - dst_begin);
      dst->addAtOffset(*src, j * input_mat.getWidth());
72 73 74 75 76
    }
  }
}

/**
X
xutianbing 已提交
77 78 79 80 81 82 83
 * Paddle Function for Context Projection Forward.
 * Calculate the value for the output layer with context projection.
 *
 * What is Context Projection?
 * For example, assumed input (x) has 4 words and the dimension of each word
 * representation is 2. If we use zero to pad instead of learned weight to pad,
 * and the context_lenth is 3, the output (y) is:
84
 *
X
xutianbing 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
 * @code
 *  x = [a1, a2;
 *       b1, b2;
 *       c1, c2;
 *       d1, d2]
 *  y = [0,  0,  a1, a2, b1, b2;
 *       a1, a2, b1, b2, c1, c2;
 *       b1, b2, c1, c2, d1, d2;
 *       c1, c2, d1, d2, 0,  0]
 * @endcode
 *
 * \param outputs[0] output value.
 * \param inputs[0]  input value.
 * \param inputs[1]  input weight.
 * \param inputs[2]  input sequence.
100 101 102 103 104 105 106 107 108 109
 */
template <DeviceType Device>
class ContextProjectionForwardFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
    context_length_ = config.get<size_t>("context_length");
    context_start_ = config.get<int>("context_start");
    begin_pad_ = config.get<size_t>("begin_pad");
  }

110
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
H
hedaoyuan 已提交
111 112
    CHECK_EQ((size_t)3, inputs.size());
    CHECK_EQ((size_t)1, outputs.size());
113

114
    CHECK(outputs[0].data() && inputs[0].data() && inputs[2].data());
115 116 117 118
    CHECK_EQ(outputs[0].shape().ndims(), (size_t)2);
    CHECK_EQ(inputs[0].shape().ndims(), (size_t)2);
    CHECK_EQ(inputs[1].shape().ndims(), (size_t)2);
    CHECK_EQ(inputs[2].shape().ndims(), (size_t)1);
119
    /// dim of output = dim of input * context_length
120
    CHECK_EQ(outputs[0].shape()[1], inputs[0].shape()[1] * context_length_);
121
    /// dim of input == dim of weight
122
    CHECK_EQ(inputs[0].shape()[1], inputs[1].shape()[1]);
123
    /// input and output has the same batch_size
124 125
    CHECK_EQ(inputs[0].shape()[0], outputs[0].shape()[0]);

126
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
127
    auto out_mat = outputs[0].matrix<Device>();
128 129 130 131 132
    const auto in_mat = inputs[0].matrix<Device>();
    const auto w_mat =
        !inputs[1].data() ? typename Tensor<real, Device>::Matrix(nullptr, 0, 0)
                          : inputs[1].matrix<Device>();
    const auto seq_vec = inputs[2].vector<int, Device>();
133 134 135
    ContextProjectionForward<Device>(out_mat,
                                     in_mat,
                                     w_mat,
136
                                     seq_vec,
137 138
                                     context_length_,
                                     context_start_,
139
                                     begin_pad_);
140 141 142 143 144 145 146 147
  }

private:
  size_t context_length_;
  int context_start_;
  size_t begin_pad_;
};

X
xutianbing 已提交
148 149 150 151
/**
 * Context Projection Backward with CPU Matrix Device.
 *
 */
152
template <>
153
void ContextProjectionBackward<DEVICE_TYPE_CPU>(const CpuMatrix& out_grad_mat,
154 155
                                                CpuMatrix& in_grad_mat,
                                                CpuMatrix& w_grad_mat,
156
                                                const CpuIVector& seq_vec,
157 158 159
                                                size_t context_length,
                                                int context_start,
                                                size_t begin_pad,
160 161
                                                bool is_padding,
                                                size_t total_pad) {
162 163
  size_t input_dim = in_grad_mat ? in_grad_mat.getWidth()
                                 : w_grad_mat ? w_grad_mat.getWidth() : 0;
164 165 166 167 168 169 170 171 172 173 174 175
  const int* starts = seq_vec.getData();
  size_t num_sequences = seq_vec.getSize() - 1;
  for (size_t i = 0; i < num_sequences; ++i) {
    for (size_t j = 0; j < context_length; ++j) {
      int begin = starts[i] + context_start + j;
      int end = starts[i + 1] + context_start + j;
      int dst_begin = starts[i];
      int dst_end = starts[i + 1];
      if (begin < starts[i]) {
        int64_t pad_size =
            std::min(starts[i] - begin, starts[i + 1] - starts[i]);
        if (is_padding && w_grad_mat) {
176 177
          MatrixPtr mat = const_cast<CpuMatrix&>(out_grad_mat)
                              .subMatrix(starts[i], pad_size);
178
          MatrixPtr sub = w_grad_mat.subMatrix(j, pad_size);
179 180 181 182 183 184 185 186 187
          sub->addAtOffset(*mat, j * input_dim);
        }
        dst_begin = starts[i] + pad_size;
        begin = starts[i];
      }
      if (end > starts[i + 1]) {
        int64_t pad_size =
            std::min(end - starts[i + 1], starts[i + 1] - starts[i]);
        if (is_padding && w_grad_mat) {
188 189
          MatrixPtr mat = const_cast<CpuMatrix&>(out_grad_mat)
                              .subMatrix(starts[i + 1] - pad_size, pad_size);
190
          MatrixPtr sub = w_grad_mat.subMatrix(
191 192 193 194 195 196 197 198
              begin_pad + context_start + j - pad_size, pad_size);
          sub->addAtOffset(*mat, j * input_dim);
        }
        dst_end = starts[i + 1] - pad_size;
        end = starts[i + 1];
      }
      if (end <= begin) continue;
      if (!in_grad_mat) continue;
199
      MatrixPtr src = in_grad_mat.subMatrix(begin, end - begin);
200 201
      MatrixPtr dst = const_cast<CpuMatrix&>(out_grad_mat)
                          .subMatrix(dst_begin, dst_end - dst_begin);
202 203 204 205 206 207
      src->addAtOffset(*dst, j * input_dim);
    }
  }
}

/**
X
xutianbing 已提交
208 209 210
 * Context Projection Backward Function.
 * Update the weight gradient and input layer gradient with backprop
 *
211 212 213 214
 * \param inputs[0]       input sequence.
 * \param inputs[1]       output layer grad.
 * \param outputs[0]      input layer grad.
 * \param outputs[1]      weight grad.
215 216 217 218 219 220 221 222 223
 */
template <DeviceType Device>
class ContextProjectionBackwardFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
    context_length_ = config.get<size_t>("context_length");
    context_start_ = config.get<int>("context_start");
    begin_pad_ = config.get<size_t>("begin_pad");
    is_padding_ = config.get<bool>("is_padding");
224
    total_pad_ = config.get<size_t>("total_pad");
225 226
  }

227
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
228 229
    CHECK_EQ((size_t)2, inputs.size());
    CHECK_EQ((size_t)2, outputs.size());
230

231 232
    CHECK(inputs[0].data() && inputs[1].data());
    CHECK_EQ(inputs[0].shape().ndims(), (size_t)1);
233
    CHECK_EQ(inputs[1].shape().ndims(), (size_t)2);
234 235
    CHECK_EQ(outputs[0].shape().ndims(), (size_t)2);
    CHECK_EQ(outputs[1].shape().ndims(), (size_t)2);
236

237 238 239 240 241 242
    /// dim of input grad == dim of weight
    CHECK_EQ(outputs[0].shape()[1], outputs[1].shape()[1]);
    /// input and output grad has the same batch_size
    CHECK_EQ(outputs[0].shape()[0], inputs[1].shape()[0]);
    /// dim of output val = dim of input grad * context_length
    CHECK_EQ(inputs[1].shape()[1], outputs[0].shape()[1] * context_length_);
243

244
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
245
    CHECK_EQ(outputs[1].getArgType(), ADD_TO);
246

247 248
    const auto seq_vec = inputs[0].vector<int, Device>();
    const auto out_grad_mat = inputs[1].matrix<Device>();
249
    auto in_grad_mat =
250 251 252 253
        !outputs[0].data()
            ? typename Tensor<real, Device>::Matrix(nullptr, 0, 0)
            : outputs[0].matrix<Device>();
    auto w_grad_mat = !outputs[1].data()
254
                          ? typename Tensor<real, Device>::Matrix(nullptr, 0, 0)
255
                          : outputs[1].matrix<Device>();
256 257 258
    ContextProjectionBackward<Device>(out_grad_mat,
                                      in_grad_mat,
                                      w_grad_mat,
259
                                      seq_vec,
260 261 262
                                      context_length_,
                                      context_start_,
                                      begin_pad_,
263 264
                                      is_padding_,
                                      total_pad_);
265 266 267 268 269 270 271
  }

private:
  size_t context_length_;
  int context_start_;
  size_t begin_pad_;
  bool is_padding_;
272
  size_t total_pad_;
273 274
};

275 276 277
REGISTER_TYPED_FUNC(ContextProjectionForward,
                    CPU,
                    ContextProjectionForwardFunc);
278 279 280
REGISTER_TYPED_FUNC(ContextProjectionBackward,
                    CPU,
                    ContextProjectionBackwardFunc);
281 282 283 284
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(ContextProjectionForward,
                    GPU,
                    ContextProjectionForwardFunc);
285 286 287
REGISTER_TYPED_FUNC(ContextProjectionBackward,
                    GPU,
                    ContextProjectionBackwardFunc);
288
#endif
289
}  // namespace paddle