test_CompareTwoNets.cpp 6.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
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. */

Y
Yu Yang 已提交
15
#include <gtest/gtest.h>
Z
zhangjinchao01 已提交
16 17
#include <paddle/utils/PythonUtil.h>
#include <algorithm>
Y
Yu Yang 已提交
18
#include <cstdlib>
Z
zhangjinchao01 已提交
19

X
Xin Pan 已提交
20
#include "paddle/legacy/trainer/Trainer.h"
Z
zhangjinchao01 已提交
21 22 23 24

using namespace paddle;  // NOLINT
using namespace std;     // NOLINT

25
DECLARE_int32(gpu_id);
Z
zhangjinchao01 已提交
26

27 28
DECLARE_bool(local);
DECLARE_bool(use_gpu);
Z
zhangjinchao01 已提交
29

30 31
DECLARE_string(config);
DECLARE_string(nics);
Z
zhangjinchao01 已提交
32

33 34 35 36
DEFINE_bool(need_high_accuracy,
            false,
            "whether need to run in double accuracy");
DEFINE_double(
37 38
    max_diff_ratio,
    0.0f,
Z
zhangjinchao01 已提交
39
    "max diff ratio allowed for outputs and parameters (value/gradient)");
40 41
DECLARE_bool(thread_local_rand_use_global_seed);
DECLARE_int32(seed);
Z
zhangjinchao01 已提交
42

X
Xin Pan 已提交
43 44
static const string& config_file_a =
    "legacy/gserver/tests/sequence_recurrent.py";
45
static const string& config_file_b =
X
Xin Pan 已提交
46
    "legacy/gserver/tests/sequence_recurrent_group.py";
47

Z
zhangjinchao01 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
struct ComData {
  vector<Argument> outArgs;
  vector<ParameterPtr> parameters;
};

void calcGradient(ComData& data, const string configFile) {
  FLAGS_config = configFile;

  FLAGS_local = true;
  FLAGS_use_gpu = false;

  FLAGS_nics = "";

  *ThreadLocalRand::getSeed() = FLAGS_seed;
  srand(FLAGS_seed);

  Trainer trainer;
  trainer.init(TrainerConfigHelper::createFromFlagConfig(), false);

  data.parameters = trainer.getGradientMachine()->getParameters();

  DataBatch dataBatch;
  int32_t batchSize = trainer.getConfig().opt_config().batch_size();

72
  trainer.getDataProvider()->reset();
Z
zhangjinchao01 已提交
73 74 75 76 77 78
  trainer.getDataProvider()->setSkipShuffle();
  trainer.getDataProvider()->getNextBatch(batchSize, &dataBatch);

  CHECK(dataBatch.getSize()) << "No data from data provider";
  vector<Argument>& inArgs = dataBatch.getStreams();

79
  trainer.getGradientMachine()->start();
80 81
  trainer.getGradientMachine()->forwardBackward(
      inArgs, &data.outArgs, PASS_TRAIN);
Z
zhangjinchao01 已提交
82 83 84 85

  trainer.getGradientMachine()->finish();
}

86 87 88 89 90 91
void checkBuffer(real* A,
                 const char* desA,
                 real* B,
                 const char* desB,
                 size_t len,
                 size_t width = 1) {
Z
zhangjinchao01 已提交
92 93 94 95 96 97 98 99 100 101 102
  int nNum = 0;
  real maxVal = 0;
  for (size_t i = 0; i < len; ++i) {
    maxVal = std::max(maxVal, std::max(A[i], B[i]));
  }
  real maxDiff = 0;
  for (size_t i = 0; i < len; ++i) {
    real diff = fabs(A[i] - B[i]);
    maxDiff = std::max(maxDiff, diff);
    if (diff > maxVal * FLAGS_max_diff_ratio) {
      nNum++;
103 104
      VLOG(1) << "Row: " << i / width << ", " << desA << " : " << A[i] << "    "
              << desB << " : " << B[i] << " diff=" << diff;
Z
zhangjinchao01 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    }
  }
  EXPECT_EQ(0, nNum);
  LOG(INFO) << "maxValue=" << maxVal << " maxDiff=" << maxDiff << "\n\n";
}

void compareGradient(ComData& comDataA, ComData& comDataB) {
  vector<Argument> outArgsA = comDataA.outArgs;
  vector<Argument> outArgsB = comDataB.outArgs;

  for (size_t i = 0; i < outArgsA.size(); ++i) {
    CpuMatrix matA(outArgsA[i].value->getHeight(),
                   outArgsA[i].value->getWidth());
    CpuMatrix matB(outArgsB[i].value->getHeight(),
                   outArgsB[i].value->getWidth());

    matA.copyFrom(*outArgsA[i].value);
    matB.copyFrom(*outArgsB[i].value);

    LOG(INFO) << "\n--------------------------------"
              << " Check Network Output_" << i << ":"
              << " -------------------------------------\n";
127 128 129 130 131 132
    checkBuffer(matA.getData(),
                "network A output",
                matB.getData(),
                "network B output",
                matA.getElementCnt(),
                matA.getWidth());
Z
zhangjinchao01 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  }

  vector<ParameterPtr>& parametersA = comDataA.parameters;
  vector<ParameterPtr>& parametersB = comDataB.parameters;

  LOG(INFO) << "\n\n--------------------------------"
            << " Check Gradient Machine Parameters:"
            << " -------------------------------------\n";
  for (size_t i = 0; i < parametersA.size(); ++i) {
    ParameterPtr parameterA, parameterB;
    parameterA = parametersA[i];
    parameterB = parametersB[i];

    CpuVector paraA(parameterA->getSize());
    CpuVector paraB(parameterB->getSize());
    paraA.copyFrom(*parameterA->getBuf(PARAMETER_VALUE));
    paraB.copyFrom(*parameterB->getBuf(PARAMETER_VALUE));

    LOG(INFO) << "\n\n----------- PARAMETER_VALUE:  " << parameterA->getName()
              << " ; size : " << paraA.getSize() << " ------------";
153 154 155 156
    checkBuffer(paraA.getData(),
                "Network A",
                paraB.getData(),
                "Network B",
Z
zhangjinchao01 已提交
157 158 159 160 161 162 163
                paraA.getSize());

    CpuVector gradA(*parameterA->getBuf(PARAMETER_GRADIENT));
    CpuVector gradB(*parameterB->getBuf(PARAMETER_GRADIENT));

    LOG(INFO) << "\n\n----------- PARAMETER_GRADIENT: " << parameterA->getName()
              << " ; size : " << gradA.getSize() << " -----------";
164 165 166 167
    checkBuffer(gradA.getData(),
                "Network A",
                gradB.getData(),
                "Network B",
Z
zhangjinchao01 已提交
168 169 170 171 172 173
                gradA.getSize());
  }
}

TEST(Trainer, create) {
  ComData dataA;
174
  calcGradient(dataA, config_file_a);
Z
zhangjinchao01 已提交
175 176 177
  LOG(INFO) << "\n\nforwardBackward of Network A is finished\n\n";

  ComData dataB;
178
  calcGradient(dataB, config_file_b);
Z
zhangjinchao01 已提交
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
  LOG(INFO) << "\n\nforwardBackward of the Network B is finished\n\n";

  compareGradient(dataA, dataB);
}

int main(int argc, char** argv) {
  FLAGS_thread_local_rand_use_global_seed = true;
  paddle::initMain(argc, argv);
  testing::InitGoogleTest(&argc, argv);
  initPython(argc, argv);

#ifndef PADDLE_TYPE_DOUBLE
  if (FLAGS_need_high_accuracy) {
    LOG(INFO) << "skip test due to it's need high accuracy";
    return 0;
  }
  if (FLAGS_max_diff_ratio == 0.0f) {
    FLAGS_max_diff_ratio = 1e-5;
    LOG(INFO) << "auto set max_diff_ratio " << FLAGS_max_diff_ratio
              << " in low accuracy mode";
  }
#else
  if (FLAGS_max_diff_ratio == 0.0f) {
    FLAGS_max_diff_ratio = 1e-10;
    LOG(INFO) << "auto set max_diff_ratio " << FLAGS_max_diff_ratio
              << " in high accuracy mode";
  }
#endif

  int ret = RUN_ALL_TESTS();
  return ret;
}