ContextProjectionOp.cpp 16.5 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
#include "paddle/math/Matrix.h"
#include "paddle/math/Vector.h"

namespace paddle {
X
xutianbing 已提交
20 21 22 23
/**
 * Context Projection Forward with CPU Matrix Device.
 *
 */
24
template <>
25 26 27
void ContextProjectionForward<DEVICE_TYPE_CPU>(CpuMatrix& out_mat,
                                               const CpuMatrix& input_mat,
                                               const CpuMatrix& weight_mat,
28
                                               const CpuIVector& seq_vec,
29 30
                                               size_t context_length,
                                               int context_start,
31
                                               size_t begin_pad) {
32 33 34 35 36 37 38 39 40 41 42
  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]);
43 44 45 46 47
        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());
48 49 50 51 52 53 54
        }
        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]);
55 56 57 58 59 60 61
        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());
62 63 64 65 66
        }
        dst_end = starts[i + 1] - pad_size;
        end = starts[i + 1];
      }
      if (end <= begin) continue;
67 68 69 70
      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());
71 72 73 74 75
    }
  }
}

/**
X
xutianbing 已提交
76
 * Paddle Function for Context Projection Forward.
X
xutianbing 已提交
77
 * Calculate the output layer value sequence after context projection.
X
xutianbing 已提交
78
 *
X
xutianbing 已提交
79
 * What is Context Projection for a sequence?
X
xutianbing 已提交
80 81 82
 * 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:
83
 *
X
xutianbing 已提交
84 85 86 87 88 89 90 91 92 93 94
 * @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
 *
X
xutianbing 已提交
95 96 97 98 99
 * \param outputs[0].matrix   output layer value, n * (d * l)
 * \param outputs[0].vector   start position sequence, n * 1
 * \param inputs[0].matrix    input layer value, n * d
 * \param inputs[0].vector    start position sequence, n * 1
 * \param inputs[1].matrix    input layer weight, pad * d
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 {
111
    CHECK(1 == inputs.size() || 2 == inputs.size());
H
hedaoyuan 已提交
112
    CHECK_EQ((size_t)1, outputs.size());
X
xutianbing 已提交
113 114
    CHECK(inputs[0].isSequenceArg() && outputs[0].isSequenceArg())
        << "SequenceArg required here";
115
    const auto val_seqs = dynamic_cast<const SequenceArg&>(inputs[0]);
X
xutianbing 已提交
116
    auto out_seq = dynamic_cast<const SequenceArg&>(outputs[0]);
117

118
    CHECK(out_seq.data() && val_seqs.data() && val_seqs.getSequenceId().data());
X
xutianbing 已提交
119
    CHECK_EQ(out_seq.shape().ndims(), (size_t)2);
120
    CHECK_EQ(val_seqs.shape().ndims(), (size_t)2);
121
    CHECK_EQ(val_seqs.getSequenceId().shape().ndims(), (size_t)1);
X
xutianbing 已提交
122 123
    if (2 == inputs.size()) {
      CHECK_EQ(inputs[1].shape().ndims(), (size_t)2);
124
    }
125
    /// dim of output = dim of input * context_length
X
xutianbing 已提交
126
    CHECK_EQ(out_seq.shape()[1], val_seqs.shape()[1] * context_length_);
127
    /// input and output has the same batch_size
X
xutianbing 已提交
128
    CHECK_EQ(val_seqs.shape()[0], out_seq.shape()[0]);
129
    /// dim of input == dim of weight
X
xutianbing 已提交
130 131
    if (2 == inputs.size()) {
      CHECK_EQ(val_seqs.shape()[1], inputs[1].shape()[1]);
132
    }
133

X
xutianbing 已提交
134 135
    CHECK_EQ(out_seq.getArgType(), ADD_TO);
    auto out_mat = out_seq.matrix<Device>();
136
    const auto in_mat = val_seqs.matrix<Device>();
137
    const auto w_mat =
X
xutianbing 已提交
138 139 140
        (2 == inputs.size())
            ? inputs[1].matrix<Device>()
            : typename Tensor<real, Device>::Matrix(nullptr, 0, 0);
141
    const auto seq_vec = val_seqs.getSequenceId().vector<int, Device>();
142 143 144
    ContextProjectionForward<Device>(out_mat,
                                     in_mat,
                                     w_mat,
145
                                     seq_vec,
146 147
                                     context_length_,
                                     context_start_,
148
                                     begin_pad_);
149 150 151 152 153 154 155 156
  }

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

X
xutianbing 已提交
157 158 159 160
/**
 * Context Projection Backward with CPU Matrix Device.
 *
 */
161
template <>
162
void ContextProjectionBackward<DEVICE_TYPE_CPU>(const CpuMatrix& out_grad_mat,
163 164
                                                CpuMatrix& in_grad_mat,
                                                CpuMatrix& w_grad_mat,
165
                                                const CpuIVector& seq_vec,
166 167 168
                                                size_t context_length,
                                                int context_start,
                                                size_t begin_pad,
169 170
                                                bool is_padding,
                                                size_t total_pad) {
171 172
  size_t input_dim = in_grad_mat ? in_grad_mat.getWidth()
                                 : w_grad_mat ? w_grad_mat.getWidth() : 0;
173 174 175 176 177 178 179 180 181 182 183 184
  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) {
185 186
          MatrixPtr mat = const_cast<CpuMatrix&>(out_grad_mat)
                              .subMatrix(starts[i], pad_size);
187
          MatrixPtr sub = w_grad_mat.subMatrix(j, pad_size);
188 189 190 191 192 193 194 195 196
          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) {
197 198
          MatrixPtr mat = const_cast<CpuMatrix&>(out_grad_mat)
                              .subMatrix(starts[i + 1] - pad_size, pad_size);
199
          MatrixPtr sub = w_grad_mat.subMatrix(
200 201 202 203 204 205 206 207
              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;
208
      MatrixPtr src = in_grad_mat.subMatrix(begin, end - begin);
209 210
      MatrixPtr dst = const_cast<CpuMatrix&>(out_grad_mat)
                          .subMatrix(dst_begin, dst_end - dst_begin);
211 212 213 214 215 216
      src->addAtOffset(*dst, j * input_dim);
    }
  }
}

/**
X
xutianbing 已提交
217 218 219
 * Context Projection Backward Function.
 * Update the weight gradient and input layer gradient with backprop
 *
X
xutianbing 已提交
220 221 222 223 224
 * \param inputs[0].matrix          output layer grad, n * (d * l)
 * \param inputs[0].vector          start position sequence, n * 1
 * \param outputs[0].matrix         input layer grad, n * d
 * \param outputs[0].vector         start position sequence, n * 1
 * \param outputs[1]                weight grad, pad * d
225 226 227 228 229 230 231 232 233
 */
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");
234
    total_pad_ = config.get<size_t>("total_pad");
235 236
  }

237
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
X
xutianbing 已提交
238
    CHECK_EQ((size_t)1, inputs.size());
239
    CHECK_EQ((size_t)2, outputs.size());
X
xutianbing 已提交
240 241 242 243
    CHECK(inputs[0].isSequenceArg() && outputs[0].isSequenceArg())
        << "SequenceArg required here";
    const auto in_seq = dynamic_cast<const SequenceArg&>(inputs[0]);
    auto out_seq = dynamic_cast<const SequenceArg&>(outputs[0]);
244
    CHECK(in_seq.data() && in_seq.getSequenceId().data());
X
xutianbing 已提交
245
    CHECK_EQ(in_seq.shape().ndims(), (size_t)2);
246
    CHECK_EQ(in_seq.getSequenceId().shape().ndims(), (size_t)1);
X
xutianbing 已提交
247
    CHECK_EQ(out_seq.shape().ndims(), (size_t)2);
248
    CHECK_EQ(out_seq.getSequenceId().shape().ndims(), (size_t)1);
249
    CHECK_EQ(outputs[1].shape().ndims(), (size_t)2);
250

251
    /// dim of input grad == dim of weight
X
xutianbing 已提交
252
    CHECK_EQ(out_seq.shape()[1], outputs[1].shape()[1]);
253
    /// input and output grad has the same batch_size
X
xutianbing 已提交
254 255 256 257
    CHECK_EQ(out_seq.shape()[0], in_seq.shape()[0]);
    /// dim of output grad = dim of input grad * context_length
    CHECK_EQ(in_seq.shape()[1], out_seq.shape()[1] * context_length_);
    CHECK_EQ(out_seq.getArgType(), ADD_TO);
258
    CHECK_EQ(outputs[1].getArgType(), ADD_TO);
259

260
    const auto seq_vec = in_seq.getSequenceId().vector<int, Device>();
X
xutianbing 已提交
261
    const auto out_grad_mat = in_seq.matrix<Device>();
262
    auto in_grad_mat =
X
xutianbing 已提交
263 264
        !out_seq.data() ? typename Tensor<real, Device>::Matrix(nullptr, 0, 0)
                        : out_seq.matrix<Device>();
265
    auto w_grad_mat = !outputs[1].data()
266
                          ? typename Tensor<real, Device>::Matrix(nullptr, 0, 0)
267
                          : outputs[1].matrix<Device>();
268 269 270
    ContextProjectionBackward<Device>(out_grad_mat,
                                      in_grad_mat,
                                      w_grad_mat,
271
                                      seq_vec,
272 273 274
                                      context_length_,
                                      context_start_,
                                      begin_pad_,
275 276
                                      is_padding_,
                                      total_pad_);
277 278 279 280 281 282 283
  }

private:
  size_t context_length_;
  int context_start_;
  size_t begin_pad_;
  bool is_padding_;
284
  size_t total_pad_;
285 286 287
};

/**
X
xutianbing 已提交
288 289 290 291 292 293 294 295 296
 * Context Projection Backward Data Function
 * Update input layer grad
 * input:  sequence of output layer grad
 * output: sequence of input layer grad
 *
 * \param outputs[0].matrix              input layer grad, n * d
 * \param outputs[0].vector              start position sequence, n * 1
 * \param inputs[0].matrix               output layer grad, n * (d * l)
 * \param inputs[0].vector               start positon sequence, n * 1
297 298 299 300 301 302 303 304 305
 */
template <DeviceType Device>
class ContextProjectionBackwardDataFunc : public FunctionBase {
public:
  void init(const FuncConfig& config) override {
    context_length_ = config.get<size_t>("context_length");
    context_start_ = config.get<int>("context_start");
  }

306 307
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(1, static_cast<int>(inputs.size()));
L
liaogang 已提交
308
    CHECK_EQ(1, static_cast<int>(outputs.size()));
X
xutianbing 已提交
309 310 311 312 313
    CHECK(inputs[0].isSequenceArg() && outputs[0].isSequenceArg())
        << "SequenceArg required here";
    const auto in_seq = dynamic_cast<const SequenceArg&>(inputs[0]);
    const auto out_seq = dynamic_cast<const SequenceArg&>(outputs[0]);

314
    CHECK(in_seq.data() && out_seq.data() && in_seq.getSequenceId().data());
X
xutianbing 已提交
315 316
    CHECK_EQ(static_cast<int>(out_seq.shape().ndims()), 2);
    CHECK_EQ(static_cast<int>(in_seq.shape().ndims()), 2);
317
    CHECK_EQ(static_cast<int>(in_seq.getSequenceId().shape().ndims()), 1);
X
xutianbing 已提交
318 319
    /// output layer grad dim == input layer grad dim * context_length_
    CHECK_EQ(in_seq.shape().ndims(), out_seq.shape().ndims() * context_length_);
320
    /// input and output has the same batch_size
X
xutianbing 已提交
321 322
    CHECK_EQ(in_seq.shape()[0], out_seq.shape()[0]);
    CHECK_EQ(outputs[0].getArgType(), ASSIGN_TO);
323

X
xutianbing 已提交
324
    const auto out_grad_mat = in_seq.matrix<Device>();
325
    const auto seq_vec = in_seq.getSequenceId().vector<int, Device>();
X
xutianbing 已提交
326
    auto in_grad_mat = out_seq.matrix<Device>();
327

328 329
    ContextProjectionBackwardData<Device>(
        out_grad_mat, in_grad_mat, seq_vec, context_length_, context_start_);
330 331 332 333 334 335 336 337
  }

private:
  size_t context_length_;
  int context_start_;
};

/**
X
xutianbing 已提交
338 339 340 341 342 343 344 345
 * Context Projection Backward Weight Function
 * Update weight grad by backprop
 * input:  sequence of output layer grad
 * output: weight grad
 *
 * \param outputs[0]                   weight grad, pad * d
 * \param inputs[0].matrix             output layer grad, n * (d * l)
 * \param inputs[0].vecotr             start positon sequence, n * 1
346 347 348 349 350 351 352 353 354 355 356
 */
template <DeviceType Device>
class ContextProjectionBackwardWeightFunc : 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");
    total_pad_ = config.get<size_t>("total_pad");
  }

357 358
  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(1, static_cast<int>(inputs.size()));
L
liaogang 已提交
359
    CHECK_EQ(1, static_cast<int>(outputs.size()));
X
xutianbing 已提交
360 361
    CHECK(inputs[0].isSequenceArg()) << "SequenceArg required here";
    const auto in_seq = dynamic_cast<const SequenceArg&>(inputs[0]);
362
    CHECK(in_seq.data() && in_seq.getSequenceId().data() && outputs[0].data());
363
    CHECK_EQ(static_cast<int>(outputs[0].shape().ndims()), 2);
X
xutianbing 已提交
364
    CHECK_EQ(static_cast<int>(in_seq.shape().ndims()), 2);
365
    CHECK_EQ(static_cast<int>(in_seq.getSequenceId().shape().ndims()), 1);
X
xutianbing 已提交
366 367 368 369
    CHECK_EQ(in_seq.shape()[0], outputs[0].shape()[0]);
    /// output layer grad dim == weight dim * context_length_
    CHECK_EQ(in_seq.shape()[1], outputs[0].shape()[1] * context_length_);
    CHECK_EQ(outputs[0].getArgType(), ADD_TO);
370

371
    const auto seq_vec = in_seq.getSequenceId().vector<int, Device>();
X
xutianbing 已提交
372 373
    const auto out_grad_mat = in_seq.matrix<Device>();
    auto w_grad_mat = outputs[0].matrix<Device>();
374 375
    ContextProjectionBackwardWeight<Device>(out_grad_mat,
                                            w_grad_mat,
376
                                            seq_vec,
377 378 379 380 381 382 383 384 385 386 387 388 389
                                            context_length_,
                                            context_start_,
                                            total_pad_,
                                            begin_pad_);
  }

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

390 391 392
REGISTER_TYPED_FUNC(ContextProjectionForward,
                    CPU,
                    ContextProjectionForwardFunc);
393 394 395
REGISTER_TYPED_FUNC(ContextProjectionBackward,
                    CPU,
                    ContextProjectionBackwardFunc);
396 397 398 399
#ifndef PADDLE_ONLY_CPU
REGISTER_TYPED_FUNC(ContextProjectionForward,
                    GPU,
                    ContextProjectionForwardFunc);
400 401 402
REGISTER_TYPED_FUNC(ContextProjectionBackward,
                    GPU,
                    ContextProjectionBackwardFunc);
403 404 405 406 407 408
REGISTER_TYPED_FUNC(ContextProjectionBackwardData,
                    GPU,
                    ContextProjectionBackwardDataFunc);
REGISTER_TYPED_FUNC(ContextProjectionBackwardWeight,
                    GPU,
                    ContextProjectionBackwardWeightFunc);
409 410
#endif
}  // namespace paddle