LstmLayer.cpp 28.5 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 15 16

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

#include "LstmLayer.h"
#include "paddle/math/BaseMatrix.h"
Y
Yu Yang 已提交
17
#include "paddle/math/Matrix.h"
Z
zhangjinchao01 已提交
18 19
#include "paddle/utils/Stat.h"

20
DECLARE_bool(prev_batch_state);
Z
zhangjinchao01 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36

namespace paddle {

REGISTER_LAYER(lstmemory, LstmLayer);

bool LstmLayer::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() * 4, parameters_[0]->getSize());
  CHECK_EQ(getSize() * 7, biasParameter_->getSize());
  weight_.reset(new Weight(getSize(), getSize() * 4, parameters_[0]));
  if (biasParameter_.get() != NULL) {
    bias_.reset(new Weight(1, getSize() * 7, biasParameter_));
    if (bias_->getW()) {
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
      localBias_ = Matrix::create(nullptr,
                                  /* height= */ 1,
                                  getSize() * 4,
                                  /* trans= */ false,
                                  useGpu_);
      checkIg_ = Matrix::create(nullptr,
                                /* height= */ 1,
                                getSize(),
                                /* trans= */ false,
                                useGpu_);
      checkFg_ = Matrix::create(nullptr,
                                /* height= */ 1,
                                getSize(),
                                /* trans= */ false,
                                useGpu_);
      checkOg_ = Matrix::create(nullptr,
                                /* height= */ 1,
                                getSize(),
                                /* trans= */ false,
                                useGpu_);
Z
zhangjinchao01 已提交
57 58 59 60 61 62 63 64

      localBias_->setData(bias_->getW()->getData());
      checkIg_->setData(bias_->getW()->getData() + getSize() * 4);
      checkFg_->setData(bias_->getW()->getData() + getSize() * 5);
      checkOg_->setData(bias_->getW()->getData() + getSize() * 6);
    }

    if (bias_->getWGrad()) {
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
      localBiasGrad_ = Matrix::create(nullptr,
                                      /* height= */ 1,
                                      getSize() * 4,
                                      /* trans= */ false,
                                      useGpu_);
      checkIgGrad_ = Matrix::create(nullptr,
                                    /* height= */ 1,
                                    getSize(),
                                    /* trans= */ false,
                                    useGpu_);
      checkFgGrad_ = Matrix::create(nullptr,
                                    /* height= */ 1,
                                    getSize(),
                                    /* trans= */ false,
                                    useGpu_);
      checkOgGrad_ = Matrix::create(nullptr,
                                    /* height= */ 1,
                                    getSize(),
                                    /* trans= */ false,
                                    useGpu_);
Z
zhangjinchao01 已提交
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
      localBiasGrad_->setData(bias_->getWGrad()->getData());
      checkIgGrad_->setData(bias_->getWGrad()->getData() + getSize() * 4);
      checkFgGrad_->setData(bias_->getWGrad()->getData() + getSize() * 5);
      checkOgGrad_->setData(bias_->getWGrad()->getData() + getSize() * 6);
    }
  } else {
    LOG(FATAL) << "Bias should be here.";
  }
  reversed_ = config_.reversed();

  // create IdentityActivation for using drop_rate
  activation_.reset(ActivationFunction::create(""));

  LstmCompute::init(config_);
  useBatch_ = true;
  useSeqParallel_ = false;
  if (useGpu_ && (getSize() == 32 || getSize() == 64)) {
    useSeqParallel_ = true;
  }

  return true;
}

void LstmLayer::resetState() {
  CHECK(!reversed_) << "state is not allowed for reversed lstmemory layer";
110 111
  Matrix::resizeOrCreate(
      prevOutput_, 1, getSize(), /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
  Matrix::resizeOrCreate(prevState_, 1, getSize(), /* trans= */ false, useGpu_);
  prevOutput_->resize(0, getSize());
  prevState_->resize(0, getSize());
  if (FLAGS_prev_batch_state) {
    useBatch_ = true;
  } else {
    useBatch_ = false;
  }
}

void LstmLayer::setState(LayerStatePtr state) {
  CHECK(state->value.size() == 2) << "two matrices are expected for LSTM state";
  prevOutput_->resize(state->value[0]->getHeight(),
                      state->value[0]->getWidth());
  prevState_->resize(state->value[1]->getHeight(), state->value[1]->getWidth());
  prevOutput_->copyFrom(*(state->value[0]));
  prevState_->copyFrom(*(state->value[1]));
}

LayerStatePtr LstmLayer::getState() {
  LayerStatePtr res = std::make_shared<LayerState>();
  if (prevOutput_->getHeight() && prevOutput_->getWidth()) {
    res->value.push_back(prevOutput_->clone(0, 0, useGpu_));
    res->value[0]->copyFrom(*prevOutput_);
    res->value.push_back(prevState_->clone(0, 0, useGpu_));
    res->value[1]->copyFrom(*prevState_);
  } else {
    MatrixPtr output =
        Matrix::create(1, getSize(), /* trans= */ false, useGpu_);
    MatrixPtr state = Matrix::create(1, getSize(), /* trans= */ false, useGpu_);
    output->resize(0, getSize());
    state->resize(0, getSize());
    res->value.push_back(output);
    res->value.push_back(state);
  }
  return res;
}

void LstmLayer::forward(PassType passType) {
  REGISTER_TIMER_INFO("LstmFwTimer", getName().c_str());
  Layer::forward(passType);

  const Argument &input = getInput(0);
  CHECK(input.sequenceStartPositions);
  int batchSize = input.getBatchSize();
  resetOutput(batchSize, getSize());
  CHECK_EQ(getSize() * 4, input.value->getWidth());
  size_t numSequences = input.getNumSequences();
  const int *starts = input.sequenceStartPositions->getData(false);
  CHECK_EQ(starts[numSequences], batchSize);

  Matrix::resizeOrCreate(gate_.value,
164 165 166 167
                         /* height= */ batchSize,
                         getSize() * 4,
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
168 169 170 171 172 173 174 175 176 177 178
  if (prevOutput_) {
    size_t prevNumSeq = useBatch_ ? numSequences : 1;
    if (prevOutput_->getHeight() == 0) {
      prevOutput_->resize(prevNumSeq, getSize());
      prevState_->resize(prevNumSeq, getSize());
      prevOutput_->zeroMem();
      prevState_->zeroMem();
    } else {
      CHECK_EQ(prevOutput_->getHeight(), prevNumSeq)
          << "the number of sequences must be the same";
    }
179 180 181 182 183 184 185 186 187 188
    Matrix::resizeOrCreate(totalState_,
                           prevState_->getHeight() + batchSize,
                           getSize(),
                           /*trans*/ false,
                           useGpu_);
    state_.value = Matrix::create(nullptr,
                                  /* height= */ batchSize,
                                  getSize(),
                                  /* trans= */ false,
                                  useGpu_);
Z
zhangjinchao01 已提交
189 190 191
    state_.value->setData(totalState_->getData() +
                          prevState_->getHeight() * getSize());
  } else {
192 193 194 195 196
    Matrix::resizeOrCreate(state_.value,
                           /* height= */ batchSize,
                           getSize(),
                           /* trans= */ false,
                           useGpu_);
Z
zhangjinchao01 已提交
197 198
  }
  Matrix::resizeOrCreate(preOutput_.value,
199 200 201
                         /* height= */ batchSize,
                         getSize(),
                         /* trans= */ false,
Z
zhangjinchao01 已提交
202 203 204 205 206 207 208 209
                         useGpu_);

  if (!useBatch_) {
    forwardSequence(batchSize, numSequences, starts, input.value);
  } else {
    if (!useSeqParallel_) {
      forwardBatch(batchSize, numSequences, starts, input.value);
    } else {
210
      const int *starts = input.sequenceStartPositions->getData(useGpu_);
Z
zhangjinchao01 已提交
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      forwardSeqParallel(batchSize, numSequences, starts, input.value);
    }
  }
  /*  activation */ { forwardActivation(); }
}

void LstmLayer::backward(const UpdateCallback &callback) {
  REGISTER_TIMER_INFO("LstmBwTimer", getName().c_str());
  /*  Do derivation */ { backwardActivation(); }

  const Argument &input = getInput(0);
  CHECK(input.sequenceStartPositions);
  int batchSize = input.getBatchSize();
  size_t numSequences = input.getNumSequences();

  Matrix::resizeOrCreate(gate_.grad,
227 228 229 230
                         /* height= */ batchSize,
                         getSize() * 4,
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
231
  Matrix::resizeOrCreate(state_.grad,
232 233 234
                         /* height= */ batchSize,
                         getSize(),
                         /* trans= */ false,
Z
zhangjinchao01 已提交
235 236
                         useGpu_);
  Matrix::resizeOrCreate(preOutput_.grad,
237 238 239
                         /* height= */ batchSize,
                         getSize(),
                         /* trans= */ false,
Z
zhangjinchao01 已提交
240 241 242 243 244 245 246 247 248 249
                         useGpu_);
  state_.grad->zero();

  const int *starts = input.sequenceStartPositions->getData(false);
  if (!useBatch_) {
    backwardSequence(batchSize, numSequences, starts, input.grad);
  } else {
    if (!useSeqParallel_) {
      backwardBatch(batchSize, numSequences, starts, input.grad);
    } else {
250
      const int *starts = input.sequenceStartPositions->getData(useGpu_);
Z
zhangjinchao01 已提交
251 252 253 254 255 256 257 258 259 260
      backwardSeqParallel(batchSize, numSequences, starts, input.grad);
    }
  }

  if (bias_) {
    bias_->getParameterPtr()->incUpdate(callback);
  }
  weight_->getParameterPtr()->incUpdate(callback);
}

261 262 263 264
void LstmLayer::forwardSequence(int batchSize,
                                size_t numSequences,
                                const int *starts,
                                MatrixPtr inputValue) {
Z
zhangjinchao01 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
  REGISTER_TIMER_INFO("LstmFwSequenceTime", getName().c_str());
  gate_.value->assign(*inputValue);
  if (bias_) {
    gate_.value->addBias(*localBias_, 1);
  }

  hl_lstm_value lstmValue;
  lstmValue.checkIg = checkIg_->getData();
  lstmValue.checkFg = checkFg_->getData();
  lstmValue.checkOg = checkOg_->getData();
  lstmValue.gateValue = gate_.value->getData();
  lstmValue.stateValue = state_.value->getData();
  lstmValue.stateActiveValue = preOutput_.value->getData();
  lstmValue.outputValue = output_.value->getData();
  lstmValue.prevStateValue = nullptr;
  if (reversed_) {
    lstmValue.gateValue += (batchSize - 1) * getSize() * 4;
    lstmValue.stateValue += (batchSize - 1) * getSize();
    lstmValue.stateActiveValue += (batchSize - 1) * getSize();
    lstmValue.outputValue += (batchSize - 1) * getSize();
  }

  auto nextFrame = [&lstmValue](bool reversed, int frameSize) {
    lstmValue.prevStateValue = lstmValue.stateValue;
    if (!reversed) {
      lstmValue.gateValue += frameSize * 4;
      lstmValue.stateValue += frameSize;
      lstmValue.stateActiveValue += frameSize;
      lstmValue.outputValue += frameSize;
    } else {
      lstmValue.gateValue -= frameSize * 4;
      lstmValue.stateValue -= frameSize;
      lstmValue.stateActiveValue -= frameSize;
      lstmValue.outputValue -= frameSize;
    }
  };

302 303 304 305 306 307 308 309 310 311
  MatrixPtr frameGate = Matrix::create(nullptr,
                                       /* height= */ 1,
                                       getSize() * 4,
                                       /* trans= */ false,
                                       useGpu_);
  MatrixPtr frameOutput = Matrix::create(nullptr,
                                         /* height= */ 1,
                                         getSize(),
                                         /* trans= */ false,
                                         useGpu_);
Z
zhangjinchao01 已提交
312 313 314 315 316 317 318

  if (!reversed_) {
    if (prevState_) {
      lstmValue.prevStateValue = prevState_->getData();
    }
    if (prevOutput_) {
      frameGate->setData(lstmValue.gateValue);
319
      frameGate->mul(*prevOutput_, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
    }
  }
  AsyncGpuBlock asyncGpuBlock;
  for (size_t n = 0; n < numSequences; ++n) {
    int length;
    if (!reversed_) {
      length = starts[n + 1] - starts[n];
    } else {
      length = starts[numSequences - n] - starts[numSequences - n - 1];
    }
    for (int l = 0; l < length; ++l) {
      if (useGpu_) {
        LstmCompute::forwardOneSequence<1>(lstmValue, getSize());
      } else {
        LstmCompute::forwardOneSequence<0>(lstmValue, getSize());
      }

      if (l != length - 1) {
        frameOutput->setData(lstmValue.outputValue);
        nextFrame(reversed_, getSize());
        frameGate->setData(lstmValue.gateValue);
341
        frameGate->mul(*frameOutput, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
342 343 344 345 346 347 348 349 350
      }
    }
    if (n != numSequences - 1) {
      frameOutput->setData(lstmValue.outputValue);
      nextFrame(reversed_, getSize());
      frameGate->setData(lstmValue.gateValue);
      if (!reversed_) {
        if (!prevState_) lstmValue.prevStateValue = nullptr;
        if (prevOutput_) {
351
          frameGate->mul(*frameOutput, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
        }
      } else {
        lstmValue.prevStateValue = nullptr;
      }
    }
  }

  if (!reversed_) {
    if (prevState_) {
      prevState_->assign(*state_.value->subMatrix(batchSize - 1, 1));
    }
    if (prevOutput_) {
      prevOutput_->assign(*output_.value->subMatrix(batchSize - 1, 1));
    }
  }
}

369 370 371 372
void LstmLayer::backwardSequence(int batchSize,
                                 size_t numSequences,
                                 const int *starts,
                                 MatrixPtr inputGrad) {
Z
zhangjinchao01 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
  REGISTER_TIMER_INFO("LstmBwSequenceTime", getName().c_str());
  MatrixPtr weightT = weight_->getW()->getTranspose();

  hl_lstm_value lstmValue;
  hl_lstm_grad lstmGrad;
  lstmValue.checkIg = checkIg_->getData();
  lstmValue.checkFg = checkFg_->getData();
  lstmValue.checkOg = checkOg_->getData();
  lstmValue.gateValue = gate_.value->getData();
  lstmValue.stateValue = state_.value->getData();
  lstmValue.stateActiveValue = preOutput_.value->getData();
  lstmValue.outputValue = nullptr;

  if (bias_->getWGrad()) {
    lstmGrad.checkIgGrad = checkIgGrad_->getData();
    lstmGrad.checkFgGrad = checkFgGrad_->getData();
    lstmGrad.checkOgGrad = checkOgGrad_->getData();
  } else {
    lstmGrad.checkIgGrad = nullptr;
    lstmGrad.checkFgGrad = nullptr;
    lstmGrad.checkOgGrad = nullptr;
  }
  lstmGrad.gateGrad = gate_.grad->getData();
  lstmGrad.stateGrad = state_.grad->getData();
  lstmGrad.stateActiveGrad = nullptr;
  lstmGrad.outputGrad = output_.grad->getData();

  if (!reversed_) {
    lstmValue.gateValue += (batchSize - 1) * getSize() * 4;
    lstmGrad.gateGrad += (batchSize - 1) * getSize() * 4;
    lstmValue.stateValue += (batchSize - 1) * getSize();
    lstmGrad.stateGrad += (batchSize - 1) * getSize();
    lstmValue.stateActiveValue += (batchSize - 1) * getSize();
    lstmGrad.outputGrad += (batchSize - 1) * getSize();
    lstmValue.prevStateValue = lstmValue.stateValue - getSize();
    lstmGrad.prevStateGrad = lstmGrad.stateGrad - getSize();
  } else {
    lstmValue.prevStateValue = lstmValue.stateValue + getSize();
    lstmGrad.prevStateGrad = lstmGrad.stateGrad + getSize();
  }

  auto nextFrame = [&lstmValue, &lstmGrad](bool reversed, int frameSize) {
    if (reversed) {
      lstmValue.gateValue += frameSize * 4;
      lstmGrad.gateGrad += frameSize * 4;
      lstmValue.stateValue += frameSize;
      lstmGrad.stateGrad += frameSize;
      lstmValue.stateActiveValue += frameSize;
      lstmGrad.outputGrad += frameSize;
      lstmValue.prevStateValue = lstmValue.stateValue + frameSize;
      lstmGrad.prevStateGrad = lstmGrad.stateGrad + frameSize;
    } else {
      lstmValue.gateValue -= frameSize * 4;
      lstmGrad.gateGrad -= frameSize * 4;
      lstmValue.stateValue -= frameSize;
      lstmGrad.stateGrad -= frameSize;
      lstmValue.stateActiveValue -= frameSize;
      lstmGrad.outputGrad -= frameSize;
      lstmValue.prevStateValue = lstmValue.stateValue - frameSize;
      lstmGrad.prevStateGrad = lstmGrad.stateGrad - frameSize;
    }
  };

436 437 438 439 440 441 442 443 444 445
  MatrixPtr frameGate = Matrix::create(nullptr,
                                       /* height= */ 1,
                                       getSize() * 4,
                                       /* trans= */ false,
                                       useGpu_);
  MatrixPtr frameOutput = Matrix::create(nullptr,
                                         /* height= */ 1,
                                         getSize(),
                                         /* trans= */ false,
                                         useGpu_);
Z
zhangjinchao01 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472

  {
    AsyncGpuBlock asyncGpuBlock;
    for (size_t n = 0; n < numSequences; ++n) {
      int length;
      int start;
      if (reversed_) {
        length = starts[n + 1] - starts[n];
        start = starts[n];
      } else {
        length = starts[numSequences - n] - starts[numSequences - n - 1];
        start = starts[numSequences - n - 1];
      }
      for (int l = 0; l < length; ++l) {
        if (l == length - 1) {
          lstmValue.prevStateValue = nullptr;
          lstmGrad.prevStateGrad = nullptr;
        }
        if (useGpu_) {
          LstmCompute::backwardOneSequence<1>(lstmValue, lstmGrad, getSize());
        } else {
          LstmCompute::backwardOneSequence<0>(lstmValue, lstmGrad, getSize());
        }
        if (l != length - 1) {
          frameGate->setData(lstmGrad.gateGrad);
          nextFrame(reversed_, getSize());
          frameOutput->setData(lstmGrad.outputGrad);
473
          frameOutput->mul(*frameGate, *weightT, 1, 1);
Z
zhangjinchao01 已提交
474 475 476 477 478 479 480 481
        } else {
          nextFrame(reversed_, getSize());
        }
      }

      if (weight_->getWGrad()) {
        if (!reversed_) {
          weight_->getWGrad()->mul(
482 483
              *output_.value->subMatrix(start, length - 1)->getTranspose(),
              *gate_.grad->subMatrix(start + 1, length - 1),
484 485
              1,
              1);
Z
zhangjinchao01 已提交
486 487
        } else {
          weight_->getWGrad()->mul(
488 489
              *output_.value->subMatrix(start + 1, length - 1)->getTranspose(),
              *gate_.grad->subMatrix(start, length - 1),
490 491
              1,
              1);
Z
zhangjinchao01 已提交
492 493 494 495 496 497 498 499 500 501 502 503 504
        }
      }
    }
  }

  if (inputGrad) {
    inputGrad->add(*gate_.grad);
  }
  if (bias_ && bias_->getWGrad()) {
    localBiasGrad_->collectBias(*gate_.grad, 1);
  }
}

505 506 507 508
void LstmLayer::forwardBatch(int batchSize,
                             size_t numSequences,
                             const int *starts,
                             MatrixPtr inputValue) {
Z
zhangjinchao01 已提交
509 510 511 512 513 514 515 516 517 518
  REGISTER_TIMER_INFO("LstmFwBatchTime", getName().c_str());

  hl_lstm_value lstmValue;
  lstmValue.checkIg = checkIg_->getData();
  lstmValue.checkFg = checkFg_->getData();
  lstmValue.checkOg = checkOg_->getData();

  if (!batchValue_) {
    batchValue_.reset(new SequenceToBatch(useGpu_));
  }
519 520
  batchValue_->resizeOrCreateBatch(
      batchSize, numSequences, starts, reversed_, prevOutput_ ? true : false);
Z
zhangjinchao01 已提交
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543

  batchValue_->resizeOrCreate(*output_.value);
  batchValue_->copy(*inputValue, *gate_.value, /* seq2batch */ true);
  if (bias_) {
    gate_.value->addBias(*localBias_, 1);
  }

  {
    int numBatch = batchValue_->getNumBatch();
    int batchSize = 0;
    AsyncGpuBlock asyncGpuBlock;
    if (prevState_) {
      lstmValue.prevStateValue = totalState_->getData();
    } else {
      lstmValue.prevStateValue = nullptr;
    }
    for (int n = 0; n < numBatch; n++) {
      MatrixPtr outputValue = batchValue_->getBatchValue(n);
      MatrixPtr gateValue = batchValue_->getBatchValue(*gate_.value, n);
      batchSize = outputValue->getHeight();

      if (n != 0) {
        MatrixPtr batch1 = batchValue_->getBatchValue(n - 1, batchSize);
544
        gateValue->mul(*batch1, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
545
      } else if (prevOutput_) {
546 547 548 549 550
        Matrix::resizeOrCreate(prevBatchOutput2_,
                               gateValue->getHeight(),
                               getSize(),
                               false,
                               useGpu_);
Z
zhangjinchao01 已提交
551
        batchValue_->prevOutput2Batch(*prevOutput_, *prevBatchOutput2_);
552
        gateValue->mul(*prevBatchOutput2_, *weight_->getW(), 1, 1);
Z
zhangjinchao01 已提交
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594

        batchValue_->prevOutput2Batch(*prevState_,
                                      *totalState_->subMatrix(0, numSequences));
      }

      lstmValue.gateValue = gateValue->getData();
      lstmValue.outputValue = outputValue->getData();
      lstmValue.stateValue =
          batchValue_->getBatchValue(*state_.value, n)->getData();
      lstmValue.stateActiveValue =
          batchValue_->getBatchValue(*preOutput_.value, n)->getData();
      {
        if (useGpu_) {
          LstmCompute::forwardBatch<1>(lstmValue, getSize(), batchSize);
        } else {
          LstmCompute::forwardBatch<0>(lstmValue, getSize(), batchSize);
        }
      }
      lstmValue.prevStateValue = lstmValue.stateValue;
    }
  }
  {
    REGISTER_TIMER_INFO("batchToSeq", getName().c_str());
    batchValue_->copyBackSeq(*output_.value);
  }
  if (prevOutput_) {
    getPrevBatchOutput(numSequences);
    getPrevBatchState(numSequences);
  }
}

void LstmLayer::getPrevBatchOutput(size_t numSequences) {
  prevOutput_->resize(numSequences, getSize());
  batchValue_->getSeqOutputFromBatch(*prevOutput_,
                                     *batchValue_->getBatchValue());
}

void LstmLayer::getPrevBatchState(size_t numSequences) {
  prevState_->resize(numSequences, getSize());
  batchValue_->getSeqOutputFromBatch(*prevState_, *state_.value);
}

595 596 597 598
void LstmLayer::backwardBatch(int batchSize,
                              size_t numSequences,
                              const int *starts,
                              MatrixPtr inputGrad) {
Z
zhangjinchao01 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  REGISTER_TIMER_INFO("LstmBwBatchTime", getName().c_str());

  hl_lstm_value lstmValue;
  lstmValue.checkIg = checkIg_->getData();
  lstmValue.checkFg = checkFg_->getData();
  lstmValue.checkOg = checkOg_->getData();

  hl_lstm_grad lstmGrad;
  lstmGrad.stateActiveGrad = preOutput_.grad->getData();

  if (bias_->getWGrad()) {
    lstmGrad.checkIgGrad = checkIgGrad_->getData();
    lstmGrad.checkFgGrad = checkFgGrad_->getData();
    lstmGrad.checkOgGrad = checkOgGrad_->getData();
  } else {
    lstmGrad.checkIgGrad = nullptr;
    lstmGrad.checkFgGrad = nullptr;
    lstmGrad.checkOgGrad = nullptr;
  }

  if (!batchGrad_) {
    batchGrad_.reset(new SequenceToBatch(useGpu_));
  }
  batchGrad_->shareIndexWith(*batchValue_);

  {
    REGISTER_TIMER_INFO("seqToBatch", getName().c_str());
    batchGrad_->copyFromSeq(*output_.grad);
  }

  {
    MatrixPtr weightT = weight_->getW()->getTranspose();
    int numBatch = batchGrad_->getNumBatch();
    int batchSize = 0;
    AsyncGpuBlock asyncGpuBlock;
    for (int n = (int)numBatch - 1; n >= 0; n--) {
      MatrixPtr outputGrad = batchGrad_->getBatchValue(n);
      MatrixPtr gateGrad = batchGrad_->getBatchValue(*gate_.grad, n);

      lstmValue.gateValue =
          batchGrad_->getBatchValue(*gate_.value, n)->getData();
      lstmValue.stateValue =
          batchGrad_->getBatchValue(*state_.value, n)->getData();
      lstmValue.stateActiveValue =
          batchGrad_->getBatchValue(*preOutput_.value, n)->getData();
      lstmGrad.stateGrad =
          batchGrad_->getBatchValue(*state_.grad, n)->getData();
      lstmGrad.gateGrad = gateGrad->getData();
      lstmGrad.outputGrad = outputGrad->getData();
      {
        batchSize = outputGrad->getHeight();
        if (n != 0) {
          lstmValue.prevStateValue =
              batchGrad_->getBatchValue(*state_.value, n - 1)->getData();
          lstmGrad.prevStateGrad =
              batchGrad_->getBatchValue(*state_.grad, n - 1)->getData();
        } else {
          if (prevState_) {
            lstmValue.prevStateValue = totalState_->getData();
            lstmGrad.prevStateGrad = nullptr;
          } else {
            lstmValue.prevStateValue = nullptr;
            lstmGrad.prevStateGrad = nullptr;
          }
        }
        if (useGpu_) {
665 666
          LstmCompute::backwardBatch<1>(
              lstmValue, lstmGrad, getSize(), batchSize);
Z
zhangjinchao01 已提交
667
        } else {
668 669
          LstmCompute::backwardBatch<0>(
              lstmValue, lstmGrad, getSize(), batchSize);
Z
zhangjinchao01 已提交
670 671 672 673 674
        }
      }

      if (n != 0) {
        MatrixPtr tmp = batchGrad_->getBatchValue(n - 1, batchSize);
675
        tmp->mul(*gateGrad, *weightT, 1, 1);
Z
zhangjinchao01 已提交
676 677 678 679 680
      }

      if (n != 0 && weight_->getWGrad()) {
        /* backward weight */
        MatrixPtr outputValue = batchValue_->getBatchValue(n - 1, batchSize);
681
        weight_->getWGrad()->mul(*outputValue->getTranspose(), *gateGrad, 1, 1);
Z
zhangjinchao01 已提交
682
      } else if (prevOutput_ && weight_->getWGrad()) {
683
        weight_->getWGrad()->mul(
684
            *prevBatchOutput2_->getTranspose(), *gateGrad, 1, 1);
Z
zhangjinchao01 已提交
685 686 687 688 689 690 691 692 693 694 695 696
      }
    }
  }

  if (inputGrad) {
    batchGrad_->add(*inputGrad, *gate_.grad, /* seq2batch */ false);
  }
  if (bias_ && bias_->getWGrad()) {
    localBiasGrad_->collectBias(*gate_.grad, /* scale */ 1);
  }
}

697 698 699 700
void LstmLayer::forwardSeqParallel(int batchSize,
                                   size_t numSequences,
                                   const int *starts,
                                   MatrixPtr inputValue) {
Z
zhangjinchao01 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714
  REGISTER_TIMER_INFO("LstmFwSeqParallelTime", getName().c_str());
  gate_.value->assign(*inputValue);
  if (bias_) {
    gate_.value->addBias(*localBias_, /* scale */ 1);
  }

  real *gateValue = gate_.value->getData();
  real *stateValue = state_.value->getData();
  real *outputValue = output_.value->getData();
  real *preOutputValue = preOutput_.value->getData();
  real *checkIg = checkIg_->getData();
  real *checkFg = checkFg_->getData();
  real *checkOg = checkOg_->getData();
  real *weight = weight_->getW()->getData();
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
  hl_lstm_parallel_forward(gateValue,
                           stateValue,
                           preOutputValue,
                           outputValue,
                           checkIg,
                           checkFg,
                           checkOg,
                           weight,
                           starts,
                           getSize(),
                           numSequences,
                           reversed_,
                           activeNode_,
                           activeGate_,
                           activeState_);
Z
zhangjinchao01 已提交
730 731
}

732 733 734 735
void LstmLayer::backwardSeqParallel(int batchSize,
                                    size_t numSequences,
                                    const int *starts,
                                    MatrixPtr inputGrad) {
Z
zhangjinchao01 已提交
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
  REGISTER_TIMER_INFO("LstmBwSeqParallelTime", getName().c_str());
  real *gateValue = gate_.value->getData();
  real *gateGrad = gate_.grad->getData();
  real *stateValue = state_.value->getData();
  real *stateGrad = state_.grad->getData();
  real *preOutputValue = preOutput_.value->getData();
  real *preOutputGrad = preOutput_.grad->getData();
  real *checkIg = checkIg_->getData();
  real *checkFg = checkFg_->getData();
  real *checkOg = checkOg_->getData();
  real *outputGrad = output_.grad->getData();
  real *weight = weight_->getW()->getData();

  real *checkIgGrad;
  real *checkFgGrad;
  real *checkOgGrad;
  if (bias_->getWGrad()) {
    checkIgGrad = checkIgGrad_->getData();
    checkFgGrad = checkFgGrad_->getData();
    checkOgGrad = checkOgGrad_->getData();
  } else {
    checkIgGrad = nullptr;
    checkFgGrad = nullptr;
    checkOgGrad = nullptr;
  }

762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
  hl_lstm_parallel_backward_data(gateValue,
                                 gateGrad,
                                 stateValue,
                                 stateGrad,
                                 preOutputValue,
                                 preOutputGrad,
                                 outputGrad,
                                 checkIg,
                                 checkIgGrad,
                                 checkFg,
                                 checkFgGrad,
                                 checkOg,
                                 checkOgGrad,
                                 weight,
                                 starts,
                                 getSize(),
                                 numSequences,
                                 reversed_,
                                 activeNode_,
                                 activeGate_,
                                 activeState_);
Z
zhangjinchao01 已提交
783 784 785 786 787 788 789 790 791 792 793

  if (inputGrad) {
    inputGrad->add(*gate_.grad);
  }
  if (bias_ && bias_->getWGrad()) {
    localBiasGrad_->collectBias(*gate_.grad, 1);
  }

  real *outputValue = output_.value->getData();
  if (weight_->getWGrad()) {
    real *weightGrad = weight_->getWGrad()->getData();
794 795 796 797 798 799 800 801
    hl_lstm_parallel_backward_weight(weightGrad,
                                     outputValue,
                                     gateGrad,
                                     starts,
                                     getSize(),
                                     batchSize,
                                     numSequences,
                                     reversed_);
Z
zhangjinchao01 已提交
802 803 804 805
  }
}

}  // namespace paddle