test_NetworkCompare.cpp 8.2 KB
Newer Older
Z
zhangjinchao01 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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 74 75 76 77 78 79 80 81 82 83 84 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 110 111 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 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
/* Copyright (c) 2016 Baidu, Inc. All Rights Reserve.

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

#undef PADDLE_DISABLE_TIMER
#include <paddle/utils/PythonUtil.h>
#include <cstdlib>
#include <algorithm>
#include <gtest/gtest.h>

#include "paddle/trainer/Trainer.h"
#include "paddle/utils/Stat.h"
#include "TestUtil.h"

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

P_DECLARE_int32(gpu_id);
P_DECLARE_double(checkgrad_eps);
P_DEFINE_bool(use_label, true, "input label or sequence label");
P_DEFINE_bool(static_para, false, "static parameter");

struct DataIn {
  std::vector<Argument> inArgs;
  std::vector<MatrixPtr> outGrads;
  std::vector<VectorPtr> paraValues;
};

struct DataOut {
  std::vector<MatrixPtr> outValues;
  std::vector<VectorPtr> paraGrads;
};

void initArgument(DataIn& data, const std::string& configPath,
                  bool useGpu = FLAGS_use_gpu) {
  TrainerConfigHelper config(configPath);
  size_t batchSize = config.getOptConfig().batch_size();

  for (const auto& layer_name : config.getModelConfig().input_layer_names()) {
    auto layer_config = std::find_if(config.getModelConfig().layers().begin(),
                                     config.getModelConfig().layers().end(),
                                     [=](const LayerConfig& layer_config) {
                                       return layer_config.name() == layer_name;
                                     });
    CHECK(layer_config != config.getModelConfig().layers().end());

    size_t layerSize = layer_config->size();
    Argument arg;
    arg.value = Matrix::create(batchSize, layerSize, false, useGpu);
    arg.grad = Matrix::create(batchSize, layerSize, false, useGpu);
    arg.value->randomizeUniform();
    arg.value->add(-0.5);
    arg.value->sigmoid(*arg.value);
    arg.grad->zeroMem();
    if (FLAGS_use_label) {
      arg.ids = VectorT<int>::create(batchSize, useGpu);
      arg.ids->rand(layerSize);
    }
    generateSequenceStartPositions(batchSize, arg.sequenceStartPositions);
    data.inArgs.push_back(arg);
  }

  for (const auto& layer_name : config.getModelConfig().output_layer_names()) {
    auto layer_config = std::find_if(config.getModelConfig().layers().begin(),
                                     config.getModelConfig().layers().end(),
                                     [=](const LayerConfig& layer_config) {
                                       return layer_config.name() == layer_name;
                                     });
    CHECK(layer_config != config.getModelConfig().layers().end());

    size_t layerSize = layer_config->size();
    MatrixPtr grad = Matrix::create(batchSize, layerSize, false, useGpu);
    grad->randomizeUniform();
    data.outGrads.push_back(grad);
  }

  for (const auto& para_config : config.getModelConfig().parameters()) {
    VectorPtr value = Vector::create(para_config.size(), useGpu);
    value->randnorm(0, 2);
    data.paraValues.push_back(value);
  }
}

void calcGradient(DataIn& in, DataOut& out, const std::string& configPath) {
  *ThreadLocalRand::getSeed() = 0;
  srand(0);

  Trainer trainer;
  auto config = std::make_shared<TrainerConfigHelper>(configPath);
  trainer.init(config, false);

  std::vector<ParameterPtr> parameters;
  vector<Argument> outArgs;

  auto gradientMachine = trainer.getGradientMachine();
  parameters = gradientMachine->getParameters();
  if (FLAGS_static_para) {
    for (size_t i = 0; i < parameters.size(); i++) {
      parameters[i]->getBuf(PARAMETER_VALUE)->one();
    }
  } else {
    for (size_t i = 0; i < in.paraValues.size(); i++) {
      parameters[i]->getBuf(PARAMETER_VALUE)->copyFrom(*in.paraValues[i]);
    }
  }
  gradientMachine->start(trainer.getConfig(), nullptr);
  gradientMachine->forward(in.inArgs, &outArgs, PASS_TRAIN);
  for (size_t i = 0; i < in.outGrads.size(); i++) {
    outArgs[i].grad->copyFrom(*in.outGrads[i]);
  }
  gradientMachine->backward();
  for (size_t i = 0; i < in.outGrads.size(); i++) {
    MatrixPtr value =
        Matrix::create(outArgs[i].value->getHeight(),
                       outArgs[i].value->getWidth(), false, false);
    value->copyFrom(*outArgs[i].value);
    out.outValues.push_back(value);
  }
  for (size_t i = 0; i < in.paraValues.size(); i++) {
    VectorPtr grad = Vector::create(
        parameters[i]->getBuf(PARAMETER_GRADIENT)->getSize(), false);
    grad->copyFrom(*parameters[i]->getBuf(PARAMETER_GRADIENT));
    out.paraGrads.push_back(grad);
  }

  for (int i = 0; i < 20; i++) {
    REGISTER_TIMER("forward");
    gradientMachine->forward(in.inArgs, &outArgs, PASS_TRAIN);
  }
  for (int i = 0; i < 20; i++) {
    REGISTER_TIMER("backward");
    gradientMachine->backward();
  }

  gradientMachine->finish();
}

void checkBuffer(real* A, const char* desA, real* B, const char* desB,
                 size_t len, size_t width = 1) {
  int nNum = 0;
  for (size_t i = 0; i < len; ++i) {
    real diff = fabs(A[i] - B[i]);
    if (diff > 0.0f &&
        diff / std::max(fabs(A[i]), fabs(B[i])) > FLAGS_checkgrad_eps) {
      nNum++;
      LOG(INFO) << "Row: " << i / width << ", " << desA << " : " << A[i]
                << "    " << desB << " : " << B[i];
    }
  }
  EXPECT_EQ(0, nNum);
}

void compareGradient(DataOut& outA, DataOut& outB) {
  LOG(INFO) << "------------------------------"
            << " Check Network Output "
            << "------------------------------";
  for (size_t i = 0; i < outA.outValues.size(); ++i) {
    LOG(INFO) << "OUTPUT VALUE: " << i;
    checkBuffer(outA.outValues[i]->getData(), "network A output",
                outB.outValues[i]->getData(), "network B output",
                outA.outValues[i]->getElementCnt(),
                outA.outValues[i]->getWidth());
  }

  if (!FLAGS_static_para) {
    LOG(INFO) << "------------------------------"
              << " Check Parameters "
              << "------------------------------";
    for (size_t i = 0; i < outA.paraGrads.size(); ++i) {
      LOG(INFO) << "PARAMETER GRADIENT: " << i;
      checkBuffer(outA.paraGrads[i]->getData(), "Network A",
                  outB.paraGrads[i]->getData(), "Network B",
                  outA.paraGrads[i]->getSize());
    }
  }
}

void compareNetwork(const std::string& config_file_a,
                    const std::string& config_file_b) {
  DataIn in;
  initArgument(in, config_file_a);

  DataOut dataA;
  calcGradient(in, dataA, config_file_a);
  LOG(INFO) << "forwardBackward of Network A is finished";
  globalStat.printSegTimerStatus();
  globalStat.reset();
  LOG(INFO) << "\n\n";

  DataOut dataB;
  calcGradient(in, dataB, config_file_b);
  LOG(INFO) << "forwardBackward of the Network B is finished";
  globalStat.printSegTimerStatus();
  globalStat.reset();
  LOG(INFO) << "\n\n";

  compareGradient(dataA, dataB);
}

TEST(Compare, concat_dotmul) {
  std::string config_file_a = "./gserver/tests/concat_dotmul_a.conf";
  std::string config_file_b = "./gserver/tests/concat_dotmul_b.conf";
  compareNetwork(config_file_a, config_file_b);
}

TEST(Compare, concat_fullmatrix) {
  std::string config_file_a = "./gserver/tests/concat_fullmatrix_a.conf";
  std::string config_file_b = "./gserver/tests/concat_fullmatrix_b.conf";
  compareNetwork(config_file_a, config_file_b);
}

TEST(Compare, concat_table) {
  std::string config_file_a = "./gserver/tests/concat_table_a.conf";
  std::string config_file_b = "./gserver/tests/concat_table_b.conf";
  compareNetwork(config_file_a, config_file_b);
}

P_DEFINE_string(config_file_a, "", "config of one network to compare");
P_DEFINE_string(config_file_b, "", "config of another network to compare");
TEST(Compare, network) {
  if (FLAGS_config_file_a != "" && FLAGS_config_file_b != "") {
    compareNetwork(FLAGS_config_file_a, FLAGS_config_file_b);
  }
}

int main(int argc, char** argv) {
  testing::InitGoogleTest(&argc, argv);
  paddle::initMain(argc, argv);
  initPython(argc, argv);
  int ret = RUN_ALL_TESTS();
  return ret;
}