test_RecurrentGradientMachine.cpp 4.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 <gtest/gtest.h>
16
#include <paddle/gserver/gradientmachines/GradientMachine.h>
Y
Yu Yang 已提交
17
#include <paddle/parameter/ParameterUpdateFunctions.h>
Z
zhangjinchao01 已提交
18 19
#include <paddle/trainer/Trainer.h>
#include <paddle/trainer/TrainerInternal.h>
20 21 22
#include <paddle/utils/PythonUtil.h>
#include <paddle/utils/Util.h>
#include <paddle/utils/Version.h>
Z
zhangjinchao01 已提交
23

24
DECLARE_int32(seed);
25

Z
zhangjinchao01 已提交
26
using namespace paddle;  // NOLINT
27
using namespace std;     // NOLINT
Z
zhangjinchao01 已提交
28 29 30 31
class TrainerForTest : public paddle::Trainer {
public:
  void startTrain() {
    GradientMachine& gm = *this->trainerInternal_.getGradientMachine();
32
    gm.start();
Z
zhangjinchao01 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
  }

  void finishTrain() {
    GradientMachine& gm = *this->trainerInternal_.getGradientMachine();
    gm.finish();
  }

  /**
   * Get total dimension of all parameters.
   *
   * @return the total dimension of all parameters
   */
  size_t getTotalParameterSize() const {
    auto p = const_cast<TrainerForTest*>(this);
47 48
    auto& params = p->getGradientMachine()->getParameters();
    return std::accumulate(
49 50 51
        params.begin(), params.end(), 0UL, [](size_t a, const ParameterPtr& p) {
          return a + p->getSize();
        });
Z
zhangjinchao01 已提交
52 53 54
  }
};

55 56 57
void CalCost(const string& conf,
             const string& dir,
             real* cost,
Z
zhangjinchao01 已提交
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
             int num_passes) {
  auto config = std::make_shared<TrainerConfigHelper>(conf);
  TrainerForTest trainer;
  trainer.init(config);
  mkDir(dir.c_str());
  config->setSaveDir(dir);
  auto dataProvider = trainer.getDataProvider();
  int32_t batchSize = config->getOptConfig().batch_size();
  real learningRate = config->getOptConfig().learning_rate();
  real momentum = 0;
  real decayRate = 0;
  int64_t dim = trainer.getTotalParameterSize();
  CpuVector vecW(dim);
  CpuVector vecGradient(dim);
  CpuVector vecMomentum(dim);

  // vecW needs to be assigned, otherwise the variable is an uncertain value.
75 76 77

  *ThreadLocalRand::getSeed() = FLAGS_seed;
  vecW.randnorm(0, 0.1);
78
  vecMomentum.randnorm(0, 0.1);
Z
zhangjinchao01 已提交
79 80 81 82 83 84 85 86 87 88

  trainer.startTrain();
  for (int i = 0; i < num_passes; ++i) {
    real totalCost = 0;
    dataProvider->reset();
    while (true) {
      DataBatch dataBatch;
      int num = dataProvider->getNextBatch(batchSize, &dataBatch);
      if (num == 0) break;
      totalCost += trainer.calcGradient(dataBatch, vecW, vecGradient);
89 90
      sgdUpdate(
          learningRate, momentum, decayRate, &vecW, &vecGradient, &vecMomentum);
Z
zhangjinchao01 已提交
91 92 93 94 95 96 97
    }
    cost[i] = totalCost;
  }
  trainer.finishTrain();
  rmDir(dir.c_str());
}

98 99 100 101 102
void test(const string& conf1, const string& conf2, double eps, bool useGpu) {
  if (!paddle::version::isWithGpu() && useGpu) {
    return;
  }
  FLAGS_use_gpu = useGpu;
Z
zhangjinchao01 已提交
103 104 105 106 107 108 109 110 111 112 113
  int num_passes = 5;
  real* cost1 = new real[num_passes];
  const string dir1 = "gserver/tests/t1";
  CalCost(conf1, dir1, cost1, num_passes);

  real* cost2 = new real[num_passes];
  const string dir2 = "gserver/tests/t2";
  CalCost(conf2, dir2, cost2, num_passes);

  for (int i = 0; i < num_passes; i++) {
    LOG(INFO) << "num_passes: " << i << ", cost1=" << cost1[i]
114 115 116
              << ", cost2=" << cost2[i]
              << ", diff=" << std::abs(cost1[i] - cost2[i]);
    ASSERT_NEAR(cost1[i], cost2[i], eps);
Z
zhangjinchao01 已提交
117 118 119 120 121
  }
  delete[] cost1;
  delete[] cost2;
}

122
TEST(RecurrentGradientMachine, HasSubSequence) {
123 124 125
  for (bool useGpu : {false, true}) {
    test("gserver/tests/sequence_layer_group.conf",
         "gserver/tests/sequence_nest_layer_group.conf",
126 127
         1e-5,
         useGpu);
128
  }
129 130
}

Y
Yu Yang 已提交
131
TEST(RecurrentGradientMachine, rnn) {
132 133 134
  for (bool useGpu : {false, true}) {
    test("gserver/tests/sequence_rnn.conf",
         "gserver/tests/sequence_nest_rnn.conf",
135 136
         1e-6,
         useGpu);
137
  }
138 139
}

Y
Yu Yang 已提交
140
TEST(RecurrentGradientMachine, rnn_multi_input) {
141 142 143
  for (bool useGpu : {false, true}) {
    test("gserver/tests/sequence_rnn_multi_input.conf",
         "gserver/tests/sequence_nest_rnn_multi_input.conf",
144 145
         1e-6,
         useGpu);
146 147
  }
}
148

Y
Yu Yang 已提交
149
TEST(RecurrentGradientMachine, rnn_multi_unequalength_input) {
150
  for (bool useGpu : {false, true}) {
151 152
    test("gserver/tests/sequence_rnn_multi_unequalength_inputs.py",
         "gserver/tests/sequence_nest_rnn_multi_unequalength_inputs.py",
153 154 155
         1e-6,
         useGpu);
  }
156 157
}

Z
zhangjinchao01 已提交
158
int main(int argc, char** argv) {
Y
Yu Yang 已提交
159 160
  testing::InitGoogleTest(&argc, argv);

Z
zhangjinchao01 已提交
161 162 163 164 165 166 167 168 169 170 171
  if (paddle::version::isWithPyDataProvider()) {
    if (!paddle::version::isWithGpu()) {
      FLAGS_use_gpu = false;
    }
    initMain(argc, argv);
    initPython(argc, argv);
    return RUN_ALL_TESTS();
  } else {
    return 0;
  }
}