RecurrentLayer.cpp 13.8 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
Z
zhangjinchao01 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14

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

L
liaogang 已提交
15
#include <gflags/gflags.h>
Z
zhangjinchao01 已提交
16 17
#include "Layer.h"
#include "SequenceToBatch.h"
Y
Yu Yang 已提交
18
#include "paddle/utils/Stat.h"
Z
zhangjinchao01 已提交
19

20
DEFINE_bool(rnn_use_batch, false, "Using the batch method for calculation.");
Z
zhangjinchao01 已提交
21 22 23

namespace paddle {

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
/**
 * @brief RecurrentLayer takes 1 input layer. The output size is the same with
 * input layer.
 * For each sequence [start, end] it performs the following computation:
 * \f[
 *    out_{i} = act(in_{i})     \      \      \text{for} \ i = start \\
 *    out_{i} = act(in_{i} + out_{i-1} * W) \ \ \text{for} \ start < i <= end
 *
 * \f]
 * If reversed is true, the order is reversed:
 * \f[
 *   out_{i} = act(in_{i})           \    \   \text{for} \ i = end  \\
 *   out_{i} = act(in_{i} + out_{i+1} * W) \ \ \text{for} \ start <= i < end
 * \f]
 * There are two methods to calculate rnn. One way is to compute rnn one
 * sequence by one sequence. The other way is to reorganize the input
 * into batches, then compute rnn one batch by one batch. Users can select
 * them by rnn_use_batch flag.
 */

Z
zhangjinchao01 已提交
44 45 46 47
class RecurrentLayer : public Layer {
public:
  explicit RecurrentLayer(const LayerConfig& config) : Layer(config) {}

Y
Yu Yang 已提交
48 49
  bool init(const LayerMap& layerMap,
            const ParameterMap& parameterMap) override;
Z
zhangjinchao01 已提交
50

Y
Yu Yang 已提交
51
  void forward(PassType passType) override;
Z
zhangjinchao01 已提交
52

Y
Yu Yang 已提交
53
  void backward(const UpdateCallback& callback) override;
Z
zhangjinchao01 已提交
54

Y
Yu Yang 已提交
55
  void resetState() override;
Z
zhangjinchao01 已提交
56

Y
Yu Yang 已提交
57
  void setState(LayerStatePtr state) override;
Z
zhangjinchao01 已提交
58

Y
Yu Yang 已提交
59
  LayerStatePtr getState() override;
Z
zhangjinchao01 已提交
60 61

protected:
62 63 64 65 66 67 68
  /**
   * @brief If user do not set --rnn_use_batch=true, it will
   * compute rnn forward one sequence by one sequence in default.
   * @param batchSize Total words number of all samples in this batch.
   * @param numSequences The sample number.
   * @param starts Each start position of each samples.
   */
Z
zhangjinchao01 已提交
69
  void forwardSequence(int batchSize, size_t numSequences, const int* starts);
70 71 72 73 74 75
  /**
   * @brief Compute rnn forward by one sequence.
   * @param start The start position of this sequence (or sample).
   * @param length The length of this sequence (or sample), namely the words
   * number of this sequence.
   */
Z
zhangjinchao01 已提交
76
  void forwardOneSequence(int start, int length);
77 78 79 80 81 82
  /**
   * @brief Compute rnn backward one sequence by onesequence.
   * @param batchSize Total words number of all samples in this batch.
   * @param numSequences The sample number.
   * @param starts Each start position of each samples.
   */
Z
zhangjinchao01 已提交
83
  void backwardSequence(int batchSize, size_t numSequences, const int* starts);
84 85 86 87 88 89
  /**
   * @brief Compute rnn backward by one sequence.
   * @param start The start position of this sequence (or sample).
   * @param length The length of this sequence (or sample), namely the words
   * number of this sequence.
   */
Z
zhangjinchao01 已提交
90 91
  void backwardOneSequence(int start, int length);

92 93 94 95 96 97 98 99
  /**
   * @brief Reorganize input into batches and compute rnn forward batch
   * by batch. It will convert batch shape to sequence after finishing forward.
   * The batch info can refer to SequenceToBatch class.
   * @param batchSize Total words number of all samples in this batch.
   * @param numSequences The sample number.
   * @param starts Each start position of each samples.
   */
Z
zhangjinchao01 已提交
100
  void forwardBatch(int batchSize, size_t numSequences, const int* starts);
101 102 103 104 105 106 107 108

  /**
   * @brief Reorganize input into batches and compute rnn forward batch
   * by batch.
   * @param batchSize Total words number of all samples in this batch.
   * @param numSequences The sample number.
   * @param starts Each start position of each samples.
   */
Z
zhangjinchao01 已提交
109 110 111 112 113 114
  void backwardBatch(int batchSize, size_t numSequences, const int* starts);

protected:
  std::unique_ptr<Weight> weight_;
  std::unique_ptr<Weight> bias_;

115
  /// frameOutput_[i] is used to hold the i-th sample of output_
Z
zhangjinchao01 已提交
116 117
  std::vector<Argument> frameOutput_;
  MatrixPtr prevOutput_;
118
  /// Whether compute rnn by reverse.
Z
zhangjinchao01 已提交
119
  bool reversed_;
120 121
  /// If compute batch by batch, batchValue_ will be used to save the
  /// reorganized input value.
Z
zhangjinchao01 已提交
122
  std::unique_ptr<SequenceToBatch> batchValue_;
123 124
  /// If compute batch by batch, batchGrad_ will be used to save the
  /// gradient with respect to reorganized input value.
Z
zhangjinchao01 已提交
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  std::unique_ptr<SequenceToBatch> batchGrad_;
};

REGISTER_LAYER(recurrent, RecurrentLayer);

bool RecurrentLayer::init(const LayerMap& layerMap,
                          const ParameterMap& parameterMap) {
  if (!Layer::init(layerMap, parameterMap)) return false;
  CHECK_EQ(1U, inputLayers_.size());
  CHECK_EQ(1U, parameters_.size());
  CHECK_EQ(getSize() * getSize(), parameters_[0]->getSize());
  weight_.reset(new Weight(getSize(), getSize(), parameters_[0]));
  if (biasParameter_.get() != NULL) {
    bias_.reset(new Weight(1, getSize(), biasParameter_));
  }
  reversed_ = config_.reversed();
  return true;
}

void RecurrentLayer::resetState() {
  CHECK(!reversed_) << "state is not allowed for reversed recurrent layer";
146 147
  Matrix::resizeOrCreate(
      prevOutput_, 1, getSize(), /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
  prevOutput_->zeroMem();
}

void RecurrentLayer::setState(LayerStatePtr state) {
  CHECK(state->value.size() == 1) << "one matrix is expected for RNN state";
  prevOutput_->copyFrom(*(state->value[0]));
}

LayerStatePtr RecurrentLayer::getState() {
  LayerStatePtr res = std::make_shared<LayerState>();
  res->value.push_back(prevOutput_->clone(0, 0, useGpu_));
  res->value[0]->copyFrom(*prevOutput_);
  return res;
}

void RecurrentLayer::forward(PassType passType) {
  REGISTER_TIMER_INFO("RecurrentFwTimer", getName().c_str());
  Layer::forward(passType);
  const Argument& input = getInput(0);
  CHECK(input.sequenceStartPositions);
  int batchSize = input.getBatchSize();
  size_t numSequences = input.getNumSequences();
  resetOutput(batchSize, getSize());
  CHECK_EQ(getSize(), input.value->getWidth());
  const int* starts = input.sequenceStartPositions->getData(false);
  CHECK_EQ(starts[numSequences], batchSize);

  output_.value->assign(*input.value);
  if (bias_) {
    output_.value->addBias(*bias_->getW(), 1);
  }
  if (!FLAGS_rnn_use_batch) {
    forwardSequence(batchSize, numSequences, starts);
  } else {
    forwardBatch(batchSize, numSequences, starts);
  }
}

186 187
void RecurrentLayer::forwardSequence(int batchSize,
                                     size_t numSequences,
Z
zhangjinchao01 已提交
188 189 190 191 192
                                     const int* starts) {
  REGISTER_TIMER_INFO("RecurrentFwSequence", getName().c_str());
  frameOutput_.reserve(batchSize);
  for (int i = frameOutput_.size(); i < batchSize; ++i) {
    Argument arg;
193 194 195 196 197 198 199 200 201 202
    arg.value = Matrix::create(nullptr,
                               /* height= */ 1,
                               getSize(),
                               /* trans= */ false,
                               useGpu_);
    arg.grad = Matrix::create(nullptr,
                              /* height= */ 1,
                              getSize(),
                              /* trans= */ false,
                              useGpu_);
Z
zhangjinchao01 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
    frameOutput_.push_back(arg);
  }

  for (int i = 0; i < batchSize; ++i) {
    frameOutput_[i].value->setData(output_.value->getData() + i * getSize());
  }

  AsyncGpuBlock asyncGpuBlock;
  for (size_t i = 0; i < numSequences; ++i) {
    forwardOneSequence(starts[i], starts[i + 1] - starts[i]);
  }
}

void RecurrentLayer::forwardOneSequence(int start, int length) {
  if (!reversed_) {
    if (prevOutput_) {
219
      frameOutput_[start].value->mul(*prevOutput_, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
220
    }
221 222
    activation_->forward(frameOutput_[start]).check();

Z
zhangjinchao01 已提交
223
    for (int i = 1; i < length; ++i) {
224
      frameOutput_[start + i].value->mul(
225
          *frameOutput_[start + i - 1].value, *weight_->getW(), 1, 1);
226
      activation_->forward(frameOutput_[start + i]).check();
Z
zhangjinchao01 已提交
227 228 229 230 231
    }
    if (prevOutput_) {
      prevOutput_->assign(*frameOutput_[start + length - 1].value);
    }
  } else {
232
    activation_->forward(frameOutput_[start + length - 1]).check();
Z
zhangjinchao01 已提交
233
    for (int i = length - 2; i >= 0; --i) {
234
      frameOutput_[start + i].value->mul(
235
          *frameOutput_[start + i + 1].value, *weight_->getW(), 1, 1);
236
      activation_->forward(frameOutput_[start + i]).check();
Z
zhangjinchao01 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
    }
  }
}

void RecurrentLayer::backward(const UpdateCallback& callback) {
  REGISTER_TIMER_INFO("RecurrentBwTimer", getName().c_str());
  const Argument& input = getInput(0);
  CHECK(input.sequenceStartPositions);
  int batchSize = input.getBatchSize();
  const int* starts = input.sequenceStartPositions->getData(false);
  size_t numSequences = input.getNumSequences();

  if (!FLAGS_rnn_use_batch) {
    backwardSequence(batchSize, numSequences, starts);
  } else {
    backwardBatch(batchSize, numSequences, starts);
  }

  if (input.grad) {
    input.grad->add(*output_.grad);
  }

  if (bias_ && bias_->getWGrad()) {
    bias_->getWGrad()->collectBias(*output_.grad, 1);
    bias_->getParameterPtr()->incUpdate(callback);
  }

  weight_->getParameterPtr()->incUpdate(callback);
}

267 268
void RecurrentLayer::backwardSequence(int batchSize,
                                      size_t numSequences,
Z
zhangjinchao01 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
                                      const int* starts) {
  REGISTER_TIMER_INFO("RecurrentBwSequence", getName().c_str());
  for (int i = 0; i < batchSize; ++i) {
    frameOutput_[i].grad->setData(output_.grad->getData() + i * getSize());
  }

  AsyncGpuBlock asyncGpuBlock;
  for (size_t i = 0; i < numSequences; ++i) {
    backwardOneSequence(starts[i], starts[i + 1] - starts[i]);
  }
}

void RecurrentLayer::backwardOneSequence(int start, int length) {
  MatrixPtr weightT = weight_->getW()->getTranspose();
  if (!reversed_) {
    for (int i = length - 1; i > 0; --i) {
285
      activation_->backward(frameOutput_[start + i]).check();
286
      frameOutput_[start + i - 1].grad->mul(
287
          *frameOutput_[start + i].grad, *weightT, 1, 1);
Z
zhangjinchao01 已提交
288
    }
289
    activation_->backward(frameOutput_[start]).check();
Z
zhangjinchao01 已提交
290 291
    if (weight_->getWGrad()) {
      weight_->getWGrad()->mul(
292 293
          *output_.value->subMatrix(start, length - 1)->getTranspose(),
          *output_.grad->subMatrix(start + 1, length - 1),
294 295
          1,
          1);
Z
zhangjinchao01 已提交
296 297 298
    }
  } else {
    for (int i = 0; i < length - 1; ++i) {
299
      activation_->backward(frameOutput_[start + i]).check();
300
      frameOutput_[start + i + 1].grad->mul(
301
          *frameOutput_[start + i].grad, *weightT, 1, 1);
Z
zhangjinchao01 已提交
302
    }
303
    activation_->backward(frameOutput_[start + length - 1]).check();
Z
zhangjinchao01 已提交
304 305
    if (weight_->getWGrad()) {
      weight_->getWGrad()->mul(
306 307
          *output_.value->subMatrix(start + 1, length - 1)->getTranspose(),
          *output_.grad->subMatrix(start, length - 1),
308 309
          1,
          1);
Z
zhangjinchao01 已提交
310 311 312 313
    }
  }
}

314 315
void RecurrentLayer::forwardBatch(int batchSize,
                                  size_t numSequences,
Z
zhangjinchao01 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
                                  const int* starts) {
  if (!batchValue_) {
    batchValue_.reset(new SequenceToBatch(useGpu_));
  }

  batchValue_->resizeOrCreateBatch(batchSize, numSequences, starts, reversed_);

  batchValue_->copyFromSeq(*output_.value);
  {
    REGISTER_TIMER_INFO("RecurrentFwBatch", getName().c_str());
    AsyncGpuBlock asyncGpuBlock;
    /* forward one batch */
    for (size_t n = 0; n < batchValue_->getNumBatch(); n++) {
      MatrixPtr batch2 = batchValue_->getBatchValue(n);

      if (n != 0) {
        MatrixPtr batch1 =
            batchValue_->getBatchValue(n - 1, batch2->getHeight());
334
        batch2->mul(*batch1, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
335 336 337
      }
      Argument arg;
      arg.value = batch2;
338
      activation_->forward(arg).check();
Z
zhangjinchao01 已提交
339 340 341 342 343
    }
  }
  batchValue_->copyBackSeq(*output_.value);
}

344 345
void RecurrentLayer::backwardBatch(int batchSize,
                                   size_t numSequences,
Z
zhangjinchao01 已提交
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
                                   const int* starts) {
  if (!batchGrad_) {
    batchGrad_.reset(new SequenceToBatch(useGpu_));
  }
  batchGrad_->shareIndexWith(*batchValue_);

  size_t numBatch = batchGrad_->getNumBatch();
  bool backwardByBatch = numBatch < numSequences;

  batchGrad_->copyFromSeq(*output_.grad);
  {
    REGISTER_TIMER_INFO("RecurrentBwData", getName().c_str());
    MatrixPtr weightT = weight_->getW()->getTranspose();
    AsyncGpuBlock asyncGpuBlock;
    /* backward one batch */
    for (int n = (int)numBatch - 1; n >= 0; n--) {
      MatrixPtr batch2 = batchGrad_->getBatchValue(n);
      MatrixPtr batch1 = batchValue_->getBatchValue(n, batch2->getHeight());

      Argument arg;
      arg.value = batch1;
      arg.grad = batch2;
368
      activation_->backward(arg).check();
Z
zhangjinchao01 已提交
369 370 371

      if (n != 0) {
        batch1 = batchGrad_->getBatchValue(n - 1, batch2->getHeight());
372
        batch1->mul(*batch2, *weightT, 1, 1);
Z
zhangjinchao01 已提交
373 374 375 376 377 378
      }

      if (backwardByBatch && weight_->getWGrad()) {
        if (n != 0) {
          /* backward weight */
          batch1 = batchValue_->getBatchValue(n - 1, batch2->getHeight());
379
          weight_->getWGrad()->mul(*batch1->getTranspose(), *batch2, 1, 1);
Z
zhangjinchao01 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393
        }
      }
    }
  }

  batchGrad_->copyBackSeq(*output_.grad);

  if (!backwardByBatch && weight_->getWGrad()) {
    REGISTER_TIMER_INFO("RecurrentBwWeight", getName().c_str());
    AsyncGpuBlock asyncGpuBlock;
    for (size_t seq = 0; seq < numSequences; ++seq) {
      int len = starts[seq + 1] - starts[seq];
      if (!reversed_) {
        weight_->getWGrad()->mul(
394 395
            *output_.value->subMatrix(starts[seq], len - 1)->getTranspose(),
            *output_.grad->subMatrix(starts[seq] + 1, len - 1),
396 397
            1,
            1);
Z
zhangjinchao01 已提交
398 399
      } else {
        weight_->getWGrad()->mul(
400 401
            *output_.value->subMatrix(starts[seq] + 1, len - 1)->getTranspose(),
            *output_.grad->subMatrix(starts[seq], len - 1),
402 403
            1,
            1);
Z
zhangjinchao01 已提交
404 405 406 407 408 409
      }
    }
  }
}

}  // namespace paddle