Tester.cpp 12.8 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 17 18 19 20

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 "Tester.h"

#include <fenv.h>
#include <stdio.h>

#include <iomanip>
Y
Yu Yang 已提交
21
#include <iostream>
Z
zhangjinchao01 已提交
22
#include <limits>
Y
Yu Yang 已提交
23
#include <sstream>
Z
zhangjinchao01 已提交
24 25 26

#include <google/protobuf/text_format.h>

Y
Yu Yang 已提交
27
#include "paddle/utils/GlobalConstants.h"
Z
zhangjinchao01 已提交
28 29 30 31
#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/Util.h"

Y
Yu Yang 已提交
32
#include "TesterConfig.h"
X
Xin Pan 已提交
33 34 35
#include "paddle/legacy/gserver/gradientmachines/GradientMachineMode.h"
#include "paddle/legacy/gserver/gradientmachines/NeuralNetwork.h"
#include "paddle/legacy/gserver/layers/ValidationLayer.h"
Z
zhangjinchao01 已提交
36 37 38

namespace paddle {

39 40 41 42 43 44 45 46 47 48
Tester::Tester(const std::shared_ptr<TrainerConfigHelper>& config,
               std::unique_ptr<TesterConfig>&& intconfig,
               const GradientMachinePtr& gradientMachine,
               const std::shared_ptr<ParameterUpdater>& parameterUpdater,
               std::shared_ptr<DataProvider> testDataProvider)
    : config_(config),
      intconfig_(std::move(intconfig)),
      gradientMachine_(gradientMachine),
      parameterUpdater_(parameterUpdater),
      testDataProvider_(testDataProvider) {
49 50
  if (config_->getOptConfig().use_sparse_remote_updater()) {
    LOG(FATAL) << "It's prohibited to set sparse_remote_update "
W
wangyanfei01 已提交
51 52 53
               << "when doing train and test jobs in the same "
               << "process. You could run paddle --job=test in "
               << "a separate process.";
54
  }
55
  testEvaluator_.reset(gradientMachine_->makeEvaluator());
Z
zhangjinchao01 已提交
56 57 58 59 60
  if (intconfig_->distributeTest) {
    testParameterClient_.reset(new ParameterClient2(true));
  }

  if (testParameterClient_) {
61
    testParameterClient_->init(gradientMachine_->getParameters());
Z
zhangjinchao01 已提交
62 63 64
  }

  std::unique_ptr<ParameterUtilConfig> paramConfig(
65 66 67 68
      new ParameterUtilConfig(intconfig_->saveOnlyOne,
                              intconfig_->savingPeriod,
                              intconfig_->loadsaveParametersInPserver,
                              intconfig_->config));
Z
zhangjinchao01 已提交
69 70

  paramUtil_.reset(new ParameterUtil(
71
      config_, std::move(paramConfig), gradientMachine_, parameterUpdater_));
Z
zhangjinchao01 已提交
72 73
}

E
emailweixu 已提交
74
void Tester::startTestPeriod() {
75 76 77
  if (testDataProvider_) {
    testDataProvider_->reset();
  }
E
emailweixu 已提交
78 79 80 81 82 83 84 85 86 87 88
  testEvaluator_->start();
  testContext_.cost = 0;
  testContext_.numSamples = 0;

  parameterUpdater_->apply();
  if (intconfig_->prevBatchState) {
    gradientMachine_->getState(*intconfig_->trainState);
    gradientMachine_->setState(*intconfig_->testState);
  }
}

89 90 91 92
void Tester::testOneDataBatch(const DataBatch& dataBatch,
                              std::vector<Argument>* outArgs) {
  testContext_.cost +=
      forwardOneBatch(dataBatch, testEvaluator_.get(), outArgs);
E
emailweixu 已提交
93 94 95
  testContext_.numSamples += dataBatch.getSize();
}

W
wangyanfei01 已提交
96
void Tester::testOnePeriod() {
Z
zhangjinchao01 已提交
97 98
  DataBatch dataBatch;
  int64_t batchSize = config_->getOptConfig().batch_size();
E
emailweixu 已提交
99 100
  std::vector<Argument> outArgs;
  startTestPeriod();
Y
Yu Yang 已提交
101
  while (testDataProvider_->getNextBatch(batchSize, &dataBatch) != 0) {
E
emailweixu 已提交
102
    testOneDataBatch(dataBatch, &outArgs);
Z
zhangjinchao01 已提交
103
  }
Y
Yu Yang 已提交
104
  finishTestPeriod();
E
emailweixu 已提交
105 106 107
}

void Tester::finishTestPeriod() {
Y
Yu Yang 已提交
108 109 110
  if (intconfig_->prevBatchState) {
    gradientMachine_->resetState();
  }
Z
zhangjinchao01 已提交
111
  testEvaluator_->finish();
E
emailweixu 已提交
112 113 114 115 116
  CHECK_GT(testContext_.numSamples, 0)
      << "There is no samples in your test batch. Possibly "
         "wrong implementation of DataProvidor.reset()";
  LOG(INFO) << " Test samples=" << testContext_.numSamples
            << " cost=" << testContext_.cost / testContext_.numSamples
Z
zhangjinchao01 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
            << " Eval: " << *testEvaluator_;
  parameterUpdater_->restore();
  if (intconfig_->prevBatchState) {
    gradientMachine_->getState(*intconfig_->testState);
    gradientMachine_->setState(*intconfig_->trainState);
  }
}

int64_t Tester::testOneBatchById(int64_t batchId) {
  DataBatch dataBatch;
  int32_t batchSize = config_->getOptConfig().batch_size();

  testDataProvider_->getNextBatch(batchSize, &dataBatch);

  int64_t actualBatchSize = dataBatch.getSize();
  if (actualBatchSize == 0) {
    return 0;
  }

E
emailweixu 已提交
136 137
  std::vector<Argument> outArgs;

Z
zhangjinchao01 已提交
138 139
  stats_ += std::pair<int64_t, real>{
      actualBatchSize,
E
emailweixu 已提交
140
      forwardOneBatch(dataBatch, testEvaluator_.get(), &outArgs)};
Z
zhangjinchao01 已提交
141 142 143 144 145 146 147 148

  if (((batchId + 1) % intconfig_->logPeriod) == 0) {
    LOG(INFO) << " Batch=" << batchId + 1 << " " << stats_.getStats(false);
  }

  return actualBatchSize;
}

149 150
real Tester::forwardOneBatch(const DataBatch& dataBatch,
                             Evaluator* evaluator,
E
emailweixu 已提交
151 152
                             std::vector<Argument>* pOutArgs) {
  auto& outArgs = *pOutArgs;
Z
zhangjinchao01 已提交
153 154 155 156 157 158 159 160 161 162 163 164
  const std::vector<Argument>& inArgs = dataBatch.getStreams();
  if (intconfig_->loadsaveParametersInPserver) {
    REGISTER_TIMER("prefetch");
    gradientMachine_->prefetch(inArgs);
    parameterUpdater_->getParametersRemote(false /*full parameter*/,
                                           true /*after apply*/);
  }

  gradientMachine_->forward(inArgs, &outArgs, PASS_TEST);

  // write features if set this flag and outArgs is not empty
  std::string featFile = intconfig_->featFile;
E
emailweixu 已提交
165
  if (!featFile.empty() && outArgs.empty()) {
Z
zhangjinchao01 已提交
166 167 168 169 170
    size_t numOutputs = outArgs.size();
    std::vector<MatrixPtr> featMatrices;
    featMatrices.resize(numOutputs);
    for (size_t i = 0; i < numOutputs; ++i) {
      featMatrices[i] = Matrix::create(outArgs[i].value->getHeight(),
171 172
                                       outArgs[i].value->getWidth(),
                                       false,
Z
zhangjinchao01 已提交
173 174 175 176 177
                                       false);  // CPU data buffer
      featMatrices[i]->copyFrom(*(outArgs[i].value), HPPL_STREAM_DEFAULT);
    }
    hl_stream_synchronize(HPPL_STREAM_DEFAULT);
    FILE* fp = fopen(featFile.c_str(), "ab+");
Y
Yu Yang 已提交
178
    CHECK(!ferror(fp)) << "Fail to open " << featFile;
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

    size_t sampleNum = featMatrices[0]->getHeight();
    for (size_t i = 0; i < sampleNum; ++i) {
      for (size_t j = 0; j < numOutputs; ++j) {
        size_t dim = featMatrices[j]->getWidth();
        fwrite(featMatrices[j]->getData() + i * dim, sizeof(real), dim, fp);
      }
    }
    fclose(fp);
  }
  if (evaluator) {
    gradientMachine_->eval(evaluator);
  }

  // Save the output layers if predict_output_dir is not empty
  std::string predictOutputDir = intconfig_->predictOutputDir;
  if (!predictOutputDir.empty() && !outArgs.empty()) {
    CHECK(intconfig_->testing) << "Only valid in test mode";
    if (!os_.is_open()) {
      // TODO(yuyang18): Refactor these lines.
      constexpr int kBufLen = 100;
      char buf[kBufLen];
      snprintf(buf, kBufLen, "rank-%05d", intconfig_->trainerId);
      mkDir(predictOutputDir.c_str());
      std::string filename = path::join(predictOutputDir, buf);
      os_.open(filename, std::ofstream::trunc);
      CHECK(os_.is_open()) << "Failed to open file " << filename;
    }
    printOutput(outArgs, os_);
    return 0.0;  // In this case, there is no meaning to calculate cost
  }

211
  return Argument::sum(outArgs);
Z
zhangjinchao01 已提交
212 213 214 215 216 217
}

void Tester::testOnePassBatch(int passId) {
  stats_.reset();
  const std::vector<Argument> inArgs;
  gradientMachine_->forward(inArgs, nullptr, PASS_TEST);
218 219
  int64_t num;
  real cost;
Z
zhangjinchao01 已提交
220
  gradientMachine_->getStats(cost, num);
221
  stats_ += std::pair<int64_t, real>{num, cost};
Z
zhangjinchao01 已提交
222 223 224 225 226 227 228 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
  gradientMachine_->onPassEnd();

  LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false);
}

void Tester::testOnePass(int passId) {
  stats_.reset();
  int64_t batchId = 0;
  int num = 0;
  if (intconfig_->prevBatchState) {
    gradientMachine_->resetState();
  }

  testEvaluator_->start();

  do {
    num = testOneBatchById(batchId);
    ++batchId;
  } while (num > 0);

  gradientMachine_->onPassEnd();
  testEvaluator_->finish();

  LOG(INFO) << " Pass=" << passId << " " << stats_.getStats(false)
            << " Eval: " << *testEvaluator_;

  if (intconfig_->distributeTest) {
    testEvaluator_->distributeEval(testParameterClient_.get());
    if (0 == intconfig_->trainerId) {
      LOG(INFO) << "distribute eval: " << *testEvaluator_;
    }
  }
}

void Tester::test() {
  CHECK(testDataProvider_) << "TestData is not specified";
  testDataProvider_->setSkipShuffle();
  testDataProvider_->reset();
260
  gradientMachine_->start();
Z
zhangjinchao01 已提交
261 262 263 264 265 266 267 268 269 270

  // For evaluation
  std::vector<std::string> modelList;
  std::string modelListFromConfig = intconfig_->modelList;
  std::string initModelPath = intconfig_->initModelPath;
  if (!modelListFromConfig.empty()) {
    loadFileList(modelListFromConfig, modelList);
    intconfig_->testPass = 0;
    intconfig_->numPasses = modelList.size();
    intconfig_->savingPeriod = 1;
271
    CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
Z
zhangjinchao01 已提交
272 273 274 275 276
  } else if (!initModelPath.empty()) {
    modelList.push_back(initModelPath);
    intconfig_->testPass = 0;
    intconfig_->numPasses = 1;
    intconfig_->savingPeriod = 1;
277
    CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
Z
zhangjinchao01 已提交
278 279 280 281 282 283
  }

  for (int i = intconfig_->testPass; i < intconfig_->numPasses; ++i) {
    int passId = i;
    if (passId % intconfig_->savingPeriod == 0) {
      if (intconfig_->testWait) {
284 285
        while (paramUtil_->loadParameters(
                   passId, true /*local*/, true /*remote*/) == false) {
Z
zhangjinchao01 已提交
286 287 288 289 290
          LOG(INFO) << "Waiting for parameters of pass " << passId;
          sleep(60);  // sleep 60s
        }
      } else {
        if (modelList.size() == 0) {
291 292 293
          CHECK_EQ(paramUtil_->loadParameters(
                       passId, true /*local*/, true /*remote*/),
                   true);
Z
zhangjinchao01 已提交
294
        } else {
295 296
          paramUtil_->loadParametersWithPath(
              modelList[i], true /*local*/, true /*remote*/);
Z
zhangjinchao01 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
        }
      }
      if (IGradientMachineMode::trainWholeDataInOneBatch(intconfig_->mode)) {
        testOnePassBatch(passId);
      } else {
        testOnePass(passId);
      }
      if (passId + intconfig_->savingPeriod < intconfig_->numPasses) {
        // if there is at least 1 more pass to test, then call reset,
        // otherwise not.
        testDataProvider_->reset();
      }
    }
  }

  gradientMachine_->finish();
}

void Tester::printOutput(const std::vector<Argument>& outArgs,
316
                         std::ostream& os) {
Z
zhangjinchao01 已提交
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  size_t numOutputs = outArgs.size();
  size_t numIns = outArgs[0].getBatchSize();
  if (cpuMat_.size() != numOutputs || cpuVec_.size() != numOutputs) {
    cpuMat_.resize(numOutputs, nullptr);
    cpuVec_.resize(numOutputs, nullptr);
  }

  for (size_t i = 0; i < numOutputs; ++i) {
    if (outArgs[i].value != nullptr) {
      if (outArgs[i].value->useGpu()) {
        if (dynamic_cast<GpuMatrix*>(outArgs[i].value.get())) {
          size_t dim = outArgs[i].value->getWidth();
          Matrix::resizeOrCreate(cpuMat_[i], numIns, dim, false, false);
          cpuMat_[i]->copyFrom(*outArgs[i].value);
        } else if (dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get())) {
          auto sparseMat =
              dynamic_cast<GpuSparseMatrix*>(outArgs[i].value.get());
334 335 336 337 338 339 340
          cpuMat_[i] = Matrix::createSparseMatrix(sparseMat->getHeight(),
                                                  sparseMat->getWidth(),
                                                  sparseMat->getElementCnt(),
                                                  sparseMat->getValueType(),
                                                  sparseMat->format_,
                                                  false,  /* trans */
                                                  false); /* useGpu */
Z
zhangjinchao01 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
          hl_stream_t stream = HPPL_STREAM_DEFAULT;
          cpuMat_[i]->copyFrom(*sparseMat, stream);
        } else {
          LOG(WARNING) << "Not supported gpu matrix type";
        }
      }
    } else if (outArgs[i].ids != nullptr) {
      if (outArgs[i].ids->useGpu()) {
        IVector::resizeOrCreate(cpuVec_[i], outArgs[i].ids->getSize(), false);
        cpuVec_[i]->copyFrom(*outArgs[i].ids);
      }
    } else if (outArgs[i].strs != nullptr) {
      continue;
    } else {
      LOG(WARNING) << "outArgs[" << i << "] has no data to print";
    }
  }

  for (size_t i = 0; i < numIns; ++i) {
    for (size_t j = 0; j < numOutputs; ++j) {
      if (outArgs[j].value != nullptr) {
        if (outArgs[j].value->useGpu()) {
          cpuMat_[j]->printOneRow(os, i);
        } else {
          outArgs[j].value->printOneRow(os, i);
        }
      } else if (outArgs[j].ids != nullptr) {
        if (outArgs[j].ids->useGpu()) {
          cpuVec_[j]->printOneElement(os, i);
        } else {
          outArgs[j].ids->printOneElement(os, i);
        }
      } else if (outArgs[j].strs != nullptr) {
        os << (*outArgs[j].strs)[i] << ";";
      }
    }
    os << std::endl;
  }
}
}  // namespace paddle