GatedRecurrentLayer.cpp 13.9 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

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 "GatedRecurrentLayer.h"
Y
Yu Yang 已提交
16
#include "Layer.h"
Z
zhangjinchao01 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(gated_recurrent, GatedRecurrentLayer);

bool GatedRecurrentLayer::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() * 3, parameters_[0]->getSize());
  CHECK_EQ(getSize() * 3, biasParameter_->getSize());
  weight_.reset(new Weight(getSize(), getSize() * 3, parameters_[0]));
  gateWeight_.reset(new Weight(getSize(), getSize() * 2, parameters_[0], 0));
32 33
  stateWeight_.reset(new Weight(
      getSize(), getSize(), parameters_[0], 2 * getSize() * getSize()));
Z
zhangjinchao01 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
  if (biasParameter_.get() != NULL) {
    bias_.reset(new Weight(1, getSize() * 3, biasParameter_));
  }

  reversed_ = config_.reversed();
  activationGate_.reset(ActivationFunction::create(config_.active_gate_type()));

  GruCompute::init(config_);
  useBatch_ = true;

  return true;
}

void GatedRecurrentLayer::resetState() {
  CHECK(!reversed_) << "state is not allowed for reversed gated "
                       "recurrent layer";
50 51
  Matrix::resizeOrCreate(
      prevOutput_, 1, getSize(), /* trans= */ false, useGpu_);
Z
zhangjinchao01 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
  prevOutput_->zeroMem();

  // TODO(hedaoyuan): support prev_batch_state
  CHECK(!FLAGS_prev_batch_state) << "Not supported";

  useBatch_ = false;
}

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

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

void GatedRecurrentLayer::forward(PassType passType) {
  REGISTER_TIMER_INFO("GruFwTimer", 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() * 3, input.value->getWidth());
  const int* starts = input.sequenceStartPositions->getData(false);
  // batchSize = length of total frames in a batch (NOT size of mini-batch)
  CHECK_EQ(starts[numSequences], batchSize);

87 88 89 90 91 92 93 94 95 96
  Matrix::resizeOrCreate(gate_.value,
                         /* height= */ batchSize,
                         getSize() * 3,
                         /* trans= */ false,
                         useGpu_);
  Matrix::resizeOrCreate(resetOutput_.value,
                         /* height= */ batchSize,
                         getSize(),
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112

  if (useBatch_) {
    forwardBatch(batchSize, numSequences, starts, input.value);
  } else {
    forwardSequence(batchSize, numSequences, starts, input.value);
  }
}

void GatedRecurrentLayer::backward(const UpdateCallback& callback) {
  REGISTER_TIMER_INFO("GruBwTimer", 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();

113 114 115 116 117 118 119 120 121 122
  Matrix::resizeOrCreate(gate_.grad,
                         /* height= */ batchSize,
                         getSize() * 3,
                         /* trans= */ false,
                         useGpu_);
  Matrix::resizeOrCreate(resetOutput_.grad,
                         /* height= */ batchSize,
                         getSize(),
                         /* trans= */ false,
                         useGpu_);
Z
zhangjinchao01 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138

  if (useBatch_) {
    backwardBatch(batchSize, input.grad);
  } else {
    backwardSequence(batchSize, numSequences, starts, input.grad);
  }

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

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

void GatedRecurrentLayer::forwardSequence(int batchSize,
                                          size_t numSequences,
139
                                          const int* starts,
Z
zhangjinchao01 已提交
140 141 142 143 144 145 146 147 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 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
                                          MatrixPtr inputValue) {
  REGISTER_TIMER_INFO("GruFwSequenceTime", getName().c_str());
  gate_.value->assign(*inputValue);
  if (bias_) {
    gate_.value->addBias(*(bias_->getW()), 1);
  }

  hl_gru_value gruValue;
  gruValue.gateWeight = (gateWeight_->getW())->getData();
  gruValue.stateWeight = (stateWeight_->getW())->getData();
  gruValue.gateValue = gate_.value->getData();
  gruValue.resetOutputValue = resetOutput_.value->getData();
  gruValue.outputValue = output_.value->getData();
  gruValue.prevOutValue = nullptr;

  if (reversed_) {
    gruValue.gateValue += (batchSize - 1) * getSize() * 3;
    gruValue.resetOutputValue += (batchSize - 1) * getSize();
    gruValue.outputValue += (batchSize - 1) * getSize();
  }

  auto nextFrame = [&gruValue](bool reversed, int frameSize) {
    gruValue.prevOutValue = gruValue.outputValue;
    if (!reversed) {
      gruValue.gateValue += frameSize * 3;
      gruValue.resetOutputValue += frameSize;
      gruValue.outputValue += frameSize;
    } else {
      gruValue.gateValue -= frameSize * 3;
      gruValue.resetOutputValue -= frameSize;
      gruValue.outputValue -= frameSize;
    }
  };

  if (!reversed_) {
    if (prevOutput_) {
      gruValue.prevOutValue = prevOutput_->getData();
    }
  }
  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_) {
        GruCompute::forward<1>(gruValue, getSize());
      } else {
        GruCompute::forward<0>(gruValue, getSize());
      }

      nextFrame(reversed_, getSize());
    }
    if (!reversed_) {
      if (!prevOutput_) gruValue.prevOutValue = nullptr;
    } else {
      gruValue.prevOutValue = nullptr;
    }
  }

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

void GatedRecurrentLayer::backwardSequence(int batchSize,
                                           size_t numSequences,
212
                                           const int* starts,
Z
zhangjinchao01 已提交
213 214 215 216 217 218 219 220 221 222 223 224
                                           MatrixPtr inputGrad) {
  REGISTER_TIMER_INFO("GruBwSequenceTime", getName().c_str());

  hl_gru_value gruValue;
  gruValue.gateWeight = (gateWeight_->getW())->getData();
  gruValue.stateWeight = (stateWeight_->getW())->getData();
  gruValue.gateValue = gate_.value->getData();
  gruValue.resetOutputValue = resetOutput_.value->getData();
  gruValue.outputValue = output_.value->getData();

  hl_gru_grad gruGrad;
  gruGrad.gateWeightGrad =
225
      (gateWeight_->getWGrad() ? gateWeight_->getWGrad()->getData() : nullptr);
Z
zhangjinchao01 已提交
226
  gruGrad.stateWeightGrad =
227 228
      (stateWeight_->getWGrad() ? stateWeight_->getWGrad()->getData()
                                : nullptr);
Z
zhangjinchao01 已提交
229 230 231 232 233 234 235 236 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 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 302 303 304 305 306 307 308 309 310 311 312
  gruGrad.gateGrad = gate_.grad->getData();
  gruGrad.resetOutputGrad = resetOutput_.grad->getData();
  gruGrad.outputGrad = output_.grad->getData();

  if (!reversed_) {
    gruValue.gateValue += (batchSize - 1) * getSize() * 3;
    gruValue.resetOutputValue += (batchSize - 1) * getSize();
    gruValue.outputValue += (batchSize - 1) * getSize();
    gruGrad.gateGrad += (batchSize - 1) * getSize() * 3;
    gruGrad.resetOutputGrad += (batchSize - 1) * getSize();
    gruGrad.outputGrad += (batchSize - 1) * getSize();
    gruValue.prevOutValue = gruValue.outputValue - getSize();
    gruGrad.prevOutGrad = gruGrad.outputGrad - getSize();
  } else {
    gruValue.prevOutValue = gruValue.outputValue + getSize();
    gruGrad.prevOutGrad = gruGrad.outputGrad + getSize();
  }

  auto nextFrame = [&gruValue, &gruGrad](bool reversed, int frameSize) {
    if (reversed) {
      gruValue.gateValue += frameSize * 3;
      gruValue.resetOutputValue += frameSize;
      gruValue.outputValue += frameSize;
      gruGrad.gateGrad += frameSize * 3;
      gruGrad.resetOutputGrad += frameSize;
      gruGrad.outputGrad += frameSize;
      gruValue.prevOutValue = gruValue.outputValue + frameSize;
      gruGrad.prevOutGrad = gruGrad.outputGrad + frameSize;
    } else {
      gruValue.gateValue -= frameSize * 3;
      gruValue.resetOutputValue -= frameSize;
      gruValue.outputValue -= frameSize;
      gruGrad.gateGrad -= frameSize * 3;
      gruGrad.resetOutputGrad -= frameSize;
      gruGrad.outputGrad -= frameSize;
      gruValue.prevOutValue = gruValue.outputValue - frameSize;
      gruGrad.prevOutGrad = gruGrad.outputGrad - frameSize;
    }
  };

  {
    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 (l == length - 1) {
          gruValue.prevOutValue = nullptr;
          gruGrad.prevOutGrad = nullptr;
        }
        if (useGpu_) {
          GruCompute::backward<1>(gruValue, gruGrad, getSize());
        } else {
          GruCompute::backward<0>(gruValue, gruGrad, getSize());
        }
        nextFrame(reversed_, getSize());
      }
    }
  }

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

void GatedRecurrentLayer::forwardBatch(int batchSize,
                                       size_t numSequences,
                                       const int* starts,
                                       MatrixPtr inputValue) {
  REGISTER_TIMER_INFO("GruFwBatchTime", getName().c_str());
  hl_gru_value gruValue;
  gruValue.gateWeight = (gateWeight_->getW())->getData();
  gruValue.stateWeight = (stateWeight_->getW())->getData();

  if (!batchValue_) {
    batchValue_.reset(new SequenceToBatch(useGpu_));
  }
313
  batchValue_->resizeOrCreateBatch(batchSize, numSequences, starts, reversed_);
Z
zhangjinchao01 已提交
314 315

  batchValue_->resizeOrCreate(*output_.value);
316
  batchValue_->copy(*inputValue, *gate_.value, /* seq2batch */ true);
Z
zhangjinchao01 已提交
317 318 319 320 321 322 323 324 325 326 327 328
  if (bias_ && bias_->getWGrad()) {
    gate_.value->addBias(*(bias_->getW()), 1);
  }

  {
    int numBatch = batchValue_->getNumBatch();
    int batchSize = 0;
    AsyncGpuBlock asyncGpuBlock;
    for (int n = 0; n < numBatch; n++) {
      MatrixPtr outputValueTmp = batchValue_->getBatchValue(n);
      gruValue.outputValue = outputValueTmp->getData();
      gruValue.gateValue =
329
          (batchValue_->getBatchValue(*gate_.value, n))->getData();
Z
zhangjinchao01 已提交
330
      gruValue.resetOutputValue =
331
          (batchValue_->getBatchValue(*resetOutput_.value, n))->getData();
Z
zhangjinchao01 已提交
332 333 334

      batchSize = outputValueTmp->getHeight();
      gruValue.prevOutValue =
335 336
          (n == 0 ? nullptr
                  : (batchValue_->getBatchValue(n - 1, batchSize))->getData());
Z
zhangjinchao01 已提交
337 338 339 340 341 342 343 344 345 346

      {
        if (useGpu_) {
          GruCompute::forward<1>(gruValue, getSize(), batchSize);
        } else {
          GruCompute::forward<0>(gruValue, getSize(), batchSize);
        }
      }
    }
  }
347
  { batchValue_->copyBackSeq(*output_.value); }
Z
zhangjinchao01 已提交
348 349
}

350
void GatedRecurrentLayer::backwardBatch(int batchSize, MatrixPtr inputGrad) {
Z
zhangjinchao01 已提交
351 352 353 354 355 356 357
  REGISTER_TIMER_INFO("GruBwBatchTime", getName().c_str());
  hl_gru_value gruValue;
  gruValue.gateWeight = (gateWeight_->getW())->getData();
  gruValue.stateWeight = (stateWeight_->getW())->getData();

  hl_gru_grad gruGrad;
  gruGrad.gateWeightGrad =
358
      (gateWeight_->getWGrad() ? gateWeight_->getWGrad()->getData() : nullptr);
Z
zhangjinchao01 已提交
359
  gruGrad.stateWeightGrad =
360 361
      (stateWeight_->getWGrad() ? stateWeight_->getWGrad()->getData()
                                : nullptr);
Z
zhangjinchao01 已提交
362 363 364 365 366 367

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

368
  { batchGrad_->copyFromSeq(*output_.grad); }
Z
zhangjinchao01 已提交
369 370 371 372 373 374 375

  {
    int numBatch = batchGrad_->getNumBatch();
    int batchSize = 0;
    AsyncGpuBlock asyncGpuBlock;
    for (int n = (int)numBatch - 1; n >= 0; n--) {
      gruValue.gateValue =
376
          (batchGrad_->getBatchValue(*gate_.value, n))->getData();
Z
zhangjinchao01 已提交
377
      gruValue.resetOutputValue =
378
          (batchGrad_->getBatchValue(*resetOutput_.value, n))->getData();
Z
zhangjinchao01 已提交
379

380
      MatrixPtr outputGradTmp = batchGrad_->getBatchValue(n);
Z
zhangjinchao01 已提交
381
      gruGrad.outputGrad = outputGradTmp->getData();
382
      gruGrad.gateGrad = (batchGrad_->getBatchValue(*gate_.grad, n))->getData();
Z
zhangjinchao01 已提交
383
      gruGrad.resetOutputGrad =
384
          (batchGrad_->getBatchValue(*resetOutput_.grad, n))->getData();
Z
zhangjinchao01 已提交
385 386 387 388

      {
        batchSize = outputGradTmp->getHeight();
        gruValue.prevOutValue =
Y
Yu Yang 已提交
389 390 391
            (n == 0
                 ? nullptr
                 : (batchValue_->getBatchValue(n - 1, batchSize))->getData());
Z
zhangjinchao01 已提交
392
        gruGrad.prevOutGrad =
393 394
            (n == 0 ? nullptr
                    : (batchGrad_->getBatchValue(n - 1, batchSize))->getData());
Z
zhangjinchao01 已提交
395 396

        if (useGpu_) {
397
          GruCompute::backward<1>(gruValue, gruGrad, getSize(), batchSize);
Z
zhangjinchao01 已提交
398
        } else {
399
          GruCompute::backward<0>(gruValue, gruGrad, getSize(), batchSize);
Z
zhangjinchao01 已提交
400 401 402 403 404 405
        }
      }
    }
  }

  if (inputGrad) {
406
    batchGrad_->add(*inputGrad, *gate_.grad, /* seq2batch */ false);
Z
zhangjinchao01 已提交
407 408 409 410 411 412 413
  }
  if (bias_ && bias_->getWGrad()) {
    bias_->getWGrad()->collectBias(*gate_.grad, /* scale */ 1);
  }
}

}  // namespace paddle