test_RecurrentLayer.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 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 <gtest/gtest.h>
#include <paddle/utils/Version.h>
Y
Yu Yang 已提交
17 18
#include <vector>
#include "ModelConfig.pb.h"
Z
zhangjinchao01 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
#include "paddle/gserver/layers/DataLayer.h"
#include "paddle/gserver/layers/Layer.h"

#include "TestUtil.h"

using namespace paddle;  // NOLINT
using namespace std;     // NOLINT
P_DECLARE_bool(use_gpu);
P_DECLARE_bool(rnn_use_batch);
P_DECLARE_int32(fixed_seq_length);

void checkError(const Matrix& matrix1, const Matrix& matrix2) {
  CHECK(matrix1.getHeight() == matrix2.getHeight());
  CHECK(matrix1.getWidth() == matrix2.getWidth());
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif

  int height = matrix1.getHeight();
  int width = matrix1.getWidth();
  const real* data1 = matrix1.getData();
  const real* data2 = matrix2.getData();
  int count = 0;
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      if (fabs(data1[i * width + j] - data2[i * width + j]) > err) {
        count++;
      }
    }
  }
  EXPECT_EQ(count, 0) << "There are " << count << " different element.";
}

void checkError(const CpuVector& vector1, const CpuVector& vector2) {
  CHECK(vector1.getSize() == vector2.getSize());
#ifndef PADDLE_TYPE_DOUBLE
  real err = 1e-3;
#else
  real err = 1e-10;
#endif

  int size = vector1.getSize();
  const real* data1 = vector1.getData();
  const real* data2 = vector2.getData();
  int count = 0;
  for (int i = 0; i < size; i++) {
    if (fabs(data1[i] - data2[i]) > err) {
      count++;
    }
  }
  EXPECT_EQ(count, 0) << "There are " << count << " different element.";
}

74 75 76
LayerPtr creatDataLayer(string name,
                        size_t batchSize,
                        int layerSize,
Z
zhangjinchao01 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
                        bool useGpu) {
  LayerConfig dataConfig;
  dataConfig.set_name(name);
  dataConfig.set_type("data");
  dataConfig.set_size(layerSize);
  LayerPtr layer = LayerPtr(new DataLayer(dataConfig));

  Argument data;
  data.value = Matrix::create(batchSize, layer->getSize(), false, useGpu);
  data.grad = Matrix::create(batchSize, layer->getSize(), false, useGpu);
  data.value->randomizeUniform();
  data.value->add(-0.5);
  data.value->sigmoid(*data.value);
  data.grad->zeroMem();

  generateSequenceStartPositions(batchSize, data.sequenceStartPositions);

  DataLayerPtr dataLayer = std::dynamic_pointer_cast<DataLayer>(layer);
  dataLayer->setData(data);
  dataLayer->forward(PASS_GC);

  return layer;
}

101 102 103
ParameterPtr creatParameter(string name,
                            int pid,
                            size_t paraSize,
Z
zhangjinchao01 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
                            bool useGpu) {
  ParameterConfig paraConfig;
  paraConfig.set_name(name);
  paraConfig.set_size(paraSize);

  ParameterPtr parameter =
      std::make_shared<Parameter>(paraConfig, useGpu, /*initialize */ false);
  parameter->enableType(PARAMETER_VALUE);
  parameter->enableType(PARAMETER_GRADIENT);
  parameter->randomize();
  parameter->setID(pid);

  return parameter;
}

119 120 121
ParameterPtr creatParameterBias(string name,
                                int pid,
                                size_t paraSize,
Z
zhangjinchao01 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135
                                bool useGpu) {
  ParameterConfig paraConfig;
  paraConfig.set_name(name);
  paraConfig.set_size(paraSize);
  paraConfig.set_initial_std(1);

  ParameterPtr parameter =
      std::make_shared<Parameter>(paraConfig, useGpu, /*initialize */ true);
  parameter->randomize();
  parameter->setID(pid);

  return parameter;
}

136 137 138 139
LayerPtr initRecurrentLayer(LayerConfig layerConfig,
                            size_t batchSize,
                            int layerSize,
                            bool useGpu) {
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 212 213 214 215 216 217 218 219 220 221 222 223
  FLAGS_use_gpu = useGpu;
  LayerMap layerMap;
  ParameterMap parameterMap;
  LayerPtr dataLayer = creatDataLayer("layer_0", batchSize, layerSize, useGpu);
  layerMap[dataLayer->getName()] = dataLayer;

  ParameterPtr para =
      creatParameter("para_0", 0, layerSize * layerSize, useGpu);
  parameterMap[para->getName()] = para;

  layerConfig.add_inputs();
  LayerInputConfig& input = *(layerConfig.mutable_inputs(0));
  input.set_input_layer_name("layer_0");
  input.set_input_parameter_name("para_0");
  LayerPtr testLayer = Layer::create(layerConfig);
  layerMap[testLayer->getName()] = testLayer;

  testLayer->init(layerMap, parameterMap);
  testLayer->setNeedGradient(true);

  return testLayer;
}

void checkRecurrentLayer(LayerPtr testLayer) {
  const VectorPtr& weightGrad =
      (testLayer->getParameters()[0])->getBuf(PARAMETER_GRADIENT);
  const MatrixPtr& inputGrad = testLayer->getPrev(0)->getOutputGrad();
  CpuVector seqPara(weightGrad->getSize());
  CpuVector batPara(weightGrad->getSize());
  CpuMatrix seqInputGrad(inputGrad->getHeight(), inputGrad->getWidth());
  CpuMatrix batInputGrad(inputGrad->getHeight(), inputGrad->getWidth());

  CpuMatrix outputGrad(inputGrad->getHeight(), inputGrad->getWidth());
  outputGrad.randomizeUniform();

  /* use sequence calculate */
  FLAGS_rnn_use_batch = false;
  weightGrad->zero();
  inputGrad->zero();
  testLayer->forward(PASS_GC);
  testLayer->getOutputGrad()->copyFrom(outputGrad);
  testLayer->backward();
  seqPara.copyFrom(*weightGrad);
  seqInputGrad.copyFrom(*inputGrad);

  /* use batch calculate */
  FLAGS_rnn_use_batch = true;
  weightGrad->zero();
  inputGrad->zero();
  testLayer->forward(PASS_GC);
  testLayer->getOutputGrad()->copyFrom(outputGrad);
  testLayer->backward();
  batPara.copyFrom(*weightGrad);
  batInputGrad.copyFrom(*inputGrad);

  /* check */
  checkError(seqInputGrad, batInputGrad);
  checkError(seqPara, batPara);
}

TEST(Layer, RecurrentLayer) {
  LayerConfig layerConfig;
  layerConfig.set_name("rnn");
  layerConfig.set_type("recurrent");
  layerConfig.set_active_type("tanh");
  for (auto layerSize : {1, 10, 64, 128, 256, 512}) {
    for (auto batchSize : {1, 5, 20, 100, 128}) {
      for (auto useGpu : {false, true}) {
        for (auto reversed : {false, true}) {
          LOG(INFO) << " layerSize=" << layerSize << " batchSize=" << batchSize
                    << " useGpu=" << useGpu << " reversed=" << reversed;
          layerConfig.set_size(layerSize);
          layerConfig.set_reversed(reversed);
          LayerPtr testLayer =
              initRecurrentLayer(layerConfig, batchSize, layerSize, useGpu);
          checkRecurrentLayer(testLayer);
        }
      }
    }
  }
}

#define protected public
#include "paddle/gserver/layers/GatedRecurrentLayer.h"
Y
Yu Yang 已提交
224
#include "paddle/gserver/layers/LstmLayer.h"
225
template <class T>
Z
zhangjinchao01 已提交
226 227 228 229 230 231 232 233 234 235 236 237
class TestRecurrentLayer {
public:
  LayerConfig config_;
  bool useGpu_;
  bool useBatch_;
  LayerPtr testLayer_;
  LayerPtr dataLayer_;
  ParameterPtr para_;
  ParameterPtr bias_;
  LayerMap layerMap_;
  ParameterMap parameterMap_;
  TestRecurrentLayer(const LayerConfig& config,
238 239 240
                     bool useGpu,
                     bool useBatch = false)
      : config_(config), useGpu_(useGpu), useBatch_(useBatch) {}
Z
zhangjinchao01 已提交
241 242 243 244 245
  void init(size_t batchSize) {
    FLAGS_use_gpu = useGpu_;
    testLayer_ = Layer::create(config_);
    if (typeid(T) == typeid(GatedRecurrentLayer)) {
      dataLayer_ = creatDataLayer(config_.mutable_inputs(0)->input_layer_name(),
246 247 248
                                  batchSize,
                                  config_.size() * 3,
                                  useGpu_);
Z
zhangjinchao01 已提交
249
      para_ = creatParameter(config_.mutable_inputs(0)->input_parameter_name(),
250 251 252 253 254
                             0,
                             config_.size() * config_.size() * 3,
                             useGpu_);
      bias_ = creatParameterBias(
          config_.bias_parameter_name(), 1, config_.size() * 3, useGpu_);
Z
zhangjinchao01 已提交
255 256
    } else if (typeid(T) == typeid(LstmLayer)) {
      dataLayer_ = creatDataLayer(config_.mutable_inputs(0)->input_layer_name(),
257 258 259
                                  batchSize,
                                  config_.size() * 4,
                                  useGpu_);
Z
zhangjinchao01 已提交
260
      para_ = creatParameter(config_.mutable_inputs(0)->input_parameter_name(),
261 262 263 264 265
                             0,
                             config_.size() * config_.size() * 4,
                             useGpu_);
      bias_ = creatParameterBias(
          config_.bias_parameter_name(), 1, config_.size() * 7, useGpu_);
Z
zhangjinchao01 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    }
    layerMap_[dataLayer_->getName()] = dataLayer_;
    parameterMap_[para_->getName()] = para_;
    parameterMap_[bias_->getName()] = bias_;

    layerMap_[testLayer_->getName()] = testLayer_;
    testLayer_->init(layerMap_, parameterMap_);
    testLayer_->setNeedGradient(true);
    (dynamic_cast<T*>(testLayer_.get()))->useBatch_ = useBatch_;
  }
  void forward() {
    FLAGS_use_gpu = useGpu_;
    testLayer_->forward(PASS_GC);
  }
  void backward() {
    FLAGS_use_gpu = useGpu_;
    testLayer_->backward(nullptr);
  }
};

286 287 288 289 290
template <class T>
void checkRecurrentLayer(LayerConfig layerConfig,
                         size_t batchSize,
                         bool cpuBatch,
                         bool gpuBatch) {
Z
zhangjinchao01 已提交
291 292 293 294
  TestRecurrentLayer<T> testCpu(layerConfig, false, cpuBatch);
  TestRecurrentLayer<T> testGpu(layerConfig, true, gpuBatch);
  testCpu.init(batchSize);
  testGpu.init(batchSize);
295 296
  auto checkError = [](
      MatrixPtr cpu, MatrixPtr gpu, int numSequences, const char* str) {
Z
zhangjinchao01 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
    CpuMatrix check(gpu->getHeight(), gpu->getWidth());
    check.copyFrom(*gpu);
    int height = cpu->getHeight();
    int width = cpu->getWidth();
    const real* data1 = cpu->getData();
    const real* data2 = check.getData();
    int count = 0;
    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        if (fabs(data1[i * width + j] - data2[i * width + j]) / numSequences >
            1e-4) {
          count++;
        }
      }
    }
312 313
    EXPECT_EQ(count, 0) << "[" << str << "]"
                        << "There are " << count << " different element.";
Z
zhangjinchao01 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  };
  T* cpuLayer = dynamic_cast<T*>(testCpu.testLayer_.get());
  T* gpuLayer = dynamic_cast<T*>(testGpu.testLayer_.get());

  Argument& cpuInput = testCpu.dataLayer_->getOutput();
  Argument& gpuInput = testGpu.dataLayer_->getOutput();
  gpuInput.resizeAndCopyFrom(cpuInput, true);

  const VectorPtr& cpuVec = testCpu.para_->getBuf(PARAMETER_VALUE);
  const VectorPtr& gpuVec = testGpu.para_->getBuf(PARAMETER_VALUE);
  gpuVec->copyFrom(*cpuVec);

  const VectorPtr& cpuBiasVec = testCpu.bias_->getBuf(PARAMETER_VALUE);
  const VectorPtr& gpuBiasVec = testGpu.bias_->getBuf(PARAMETER_VALUE);
  gpuBiasVec->copyFrom(*cpuBiasVec);

  /* check forward */
  testCpu.forward();
  testGpu.forward();

334 335
  checkError(
      cpuLayer->getOutputValue(), gpuLayer->getOutputValue(), 1, "outputValue");
Z
zhangjinchao01 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348

  /* check backward */
  cpuLayer->getOutputGrad()->randomizeUniform();
  gpuLayer->getOutputGrad()->copyFrom(*cpuLayer->getOutputGrad());
  hl_stream_synchronize(HPPL_STREAM_DEFAULT);

  testCpu.backward();
  testGpu.backward();

  // check input grad
  checkError(cpuInput.grad, gpuInput.grad, 1, "inputGrad");
  // check weight grad
  int numSequences = cpuInput.getNumSequences();
349 350 351 352
  checkError(cpuLayer->weight_->getWGrad(),
             gpuLayer->weight_->getWGrad(),
             numSequences,
             "weightGrad");
Z
zhangjinchao01 已提交
353
  // check bias grad
354 355 356 357
  checkError(cpuLayer->bias_->getWGrad(),
             gpuLayer->bias_->getWGrad(),
             numSequences,
             "biasGrad");
Z
zhangjinchao01 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
}

TEST(Layer, GatedRecurrentLayer) {
  LayerConfig layerConfig;
  layerConfig.set_type("gated_recurrent");
  layerConfig.set_active_type("sigmoid");
  layerConfig.set_active_gate_type("sigmoid");

  layerConfig.add_inputs();
  LayerInputConfig& input = *(layerConfig.mutable_inputs(0));
  input.set_input_layer_name("layer_0");
  input.set_input_parameter_name("para_0");
  layerConfig.set_bias_parameter_name("bias");

  for (auto frameSize : {32, 64, 128, 256, 512}) {
    for (auto batchSize : {1, 5, 100, 500}) {
      for (auto reversed : {false, true}) {
        for (auto cpuBatch : {false, true}) {
          for (auto gpuBatch : {false, true}) {
            LOG(INFO) << " batchSize=" << batchSize
                      << " frameSize=" << frameSize << " reversed=" << reversed
                      << " cpuBatch=" << cpuBatch << " gpuBatch=" << gpuBatch;
            layerConfig.set_size(frameSize);
            layerConfig.set_reversed(reversed);
            checkRecurrentLayer<GatedRecurrentLayer>(
383
                layerConfig, batchSize, cpuBatch, gpuBatch);
Z
zhangjinchao01 已提交
384 385 386 387 388 389 390 391 392 393 394
          }
        }
      }
    }
  }
}

TEST(Layer, LstmLayer) {
  LayerConfig layerConfig;
  layerConfig.set_type("lstmemory");
  layerConfig.set_active_type("relu");
395
  layerConfig.set_active_state_type("tanh");
Z
zhangjinchao01 已提交
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
  layerConfig.set_active_gate_type("sigmoid");

  layerConfig.add_inputs();
  LayerInputConfig& input = *(layerConfig.mutable_inputs(0));
  input.set_input_layer_name("layer_0");
  input.set_input_parameter_name("para_0");
  layerConfig.set_bias_parameter_name("bias");

  for (auto frameSize : {32, 64, 128, 256, 512}) {
    for (auto batchSize : {1, 5, 100, 500}) {
      for (auto reversed : {false, true}) {
        for (auto cpuBatch : {false, true}) {
          for (auto gpuBatch : {false, true}) {
            LOG(INFO) << " batchSize=" << batchSize
                      << " frameSize=" << frameSize << " reversed=" << reversed
                      << " cpuBatch=" << cpuBatch << " gpuBatch=" << gpuBatch;
            layerConfig.set_size(frameSize);
            layerConfig.set_reversed(reversed);
414 415
            checkRecurrentLayer<LstmLayer>(
                layerConfig, batchSize, cpuBatch, gpuBatch);
Z
zhangjinchao01 已提交
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
          }
        }
      }
    }
  }
}

int main(int argc, char** argv) {
  if (version::isWithGpu()) {
    testing::InitGoogleTest(&argc, argv);
    initMain(argc, argv);
    return RUN_ALL_TESTS();
  } else {
    return 0;
  }
}