Tester.cpp 12.9 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
/* 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. */

#include "Tester.h"

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

#include <iostream>
#include <iomanip>
#include <sstream>
#include <limits>

#include <google/protobuf/text_format.h>

#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/Util.h"
#include "paddle/utils/GlobalConstants.h"

#include "paddle/gserver/gradientmachines/NeuralNetwork.h"
#include "paddle/gserver/layers/ValidationLayer.h"
#include "paddle/gserver/gradientmachines/GradientMachineMode.h"
#include "TesterConfig.h"

namespace paddle {

39 40 41 42 43 44 45 46 47 48 49
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) {
  testEvaluator_.reset(gradientMachine_->makeEvaluator());
Z
zhangjinchao01 已提交
50 51 52 53 54
  if (intconfig_->distributeTest) {
    testParameterClient_.reset(new ParameterClient2(true));
  }

  if (testParameterClient_) {
55
    testParameterClient_->init(gradientMachine_->getParameters());
Z
zhangjinchao01 已提交
56 57 58
  }

  std::unique_ptr<ParameterUtilConfig> paramConfig(
59 60 61 62
      new ParameterUtilConfig(intconfig_->saveOnlyOne,
                              intconfig_->savingPeriod,
                              intconfig_->loadsaveParametersInPserver,
                              intconfig_->config));
Z
zhangjinchao01 已提交
63 64

  paramUtil_.reset(new ParameterUtil(
65
      config_, std::move(paramConfig), gradientMachine_, parameterUpdater_));
Z
zhangjinchao01 已提交
66 67
}

E
emailweixu 已提交
68 69 70 71 72 73 74 75 76 77 78 79
void Tester::startTestPeriod() {
  testEvaluator_->start();
  testContext_.cost = 0;
  testContext_.numSamples = 0;

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

80 81 82 83
void Tester::testOneDataBatch(const DataBatch& dataBatch,
                              std::vector<Argument>* outArgs) {
  testContext_.cost +=
      forwardOneBatch(dataBatch, testEvaluator_.get(), outArgs);
E
emailweixu 已提交
84 85 86
  testContext_.numSamples += dataBatch.getSize();
}

Z
zhangjinchao01 已提交
87 88 89 90 91 92 93 94
void Tester::testOnePeriod() {
  DataBatch dataBatch;
  int64_t batchSize = config_->getOptConfig().batch_size();
  bool testAllData =
      intconfig_->testPeriod == 0 || intconfig_->testAllDataInOnePeriod;
  int batches =
      testAllData ? std::numeric_limits<int>::max() : intconfig_->testPeriod;

E
emailweixu 已提交
95
  std::vector<Argument> outArgs;
Z
zhangjinchao01 已提交
96

E
emailweixu 已提交
97
  startTestPeriod();
Z
zhangjinchao01 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110
  for (int i = 0; i < batches; ++i) {
    int num = testDataProvider_->getNextBatch(batchSize, &dataBatch);
    if (num == 0) {
      testDataProvider_->reset();
      if (intconfig_->prevBatchState) {
        gradientMachine_->resetState();
      }
      if (testAllData) {
        break;
      } else {
        num = testDataProvider_->getNextBatch(batchSize, &dataBatch);
      }
    }
E
emailweixu 已提交
111
    testOneDataBatch(dataBatch, &outArgs);
Z
zhangjinchao01 已提交
112
  }
Y
Yu Yang 已提交
113
  finishTestPeriod();
E
emailweixu 已提交
114 115 116
}

void Tester::finishTestPeriod() {
Z
zhangjinchao01 已提交
117
  testEvaluator_->finish();
E
emailweixu 已提交
118 119 120 121 122
  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 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
            << " 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 已提交
142 143
  std::vector<Argument> outArgs;

Z
zhangjinchao01 已提交
144 145
  stats_ += std::pair<int64_t, real>{
      actualBatchSize,
E
emailweixu 已提交
146
      forwardOneBatch(dataBatch, testEvaluator_.get(), &outArgs)};
Z
zhangjinchao01 已提交
147 148 149 150 151 152 153 154

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

  return actualBatchSize;
}

155 156
real Tester::forwardOneBatch(const DataBatch& dataBatch,
                             Evaluator* evaluator,
E
emailweixu 已提交
157 158
                             std::vector<Argument>* pOutArgs) {
  auto& outArgs = *pOutArgs;
Z
zhangjinchao01 已提交
159 160 161 162 163 164 165 166 167 168 169 170
  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 已提交
171
  if (!featFile.empty() && outArgs.empty()) {
Z
zhangjinchao01 已提交
172 173 174 175 176
    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(),
177 178
                                       outArgs[i].value->getWidth(),
                                       false,
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 211 212 213 214 215 216 217 218 219 220 221 222 223
                                       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+");
    PCHECK(!ferror(fp)) << "Fail to open " << featFile;

    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
  }

  return Argument::sumCosts(outArgs);
}

void Tester::testOnePassBatch(int passId) {
  stats_.reset();
  const std::vector<Argument> inArgs;
  gradientMachine_->forward(inArgs, nullptr, PASS_TEST);
224 225
  int64_t num;
  real cost;
Z
zhangjinchao01 已提交
226
  gradientMachine_->getStats(cost, num);
227
  stats_ += std::pair<int64_t, real>{num, cost};
Z
zhangjinchao01 已提交
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 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
  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();
  gradientMachine_->start(*config_, testDataProvider_);

  // 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;
277
    CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
Z
zhangjinchao01 已提交
278 279 280 281 282
  } else if (!initModelPath.empty()) {
    modelList.push_back(initModelPath);
    intconfig_->testPass = 0;
    intconfig_->numPasses = 1;
    intconfig_->savingPeriod = 1;
283
    CHECK_EQ(intconfig_->testWait, 0) << "--test_wait must be 0 for evaluation";
Z
zhangjinchao01 已提交
284 285 286 287 288 289
  }

  for (int i = intconfig_->testPass; i < intconfig_->numPasses; ++i) {
    int passId = i;
    if (passId % intconfig_->savingPeriod == 0) {
      if (intconfig_->testWait) {
290 291
        while (paramUtil_->loadParameters(
                   passId, true /*local*/, true /*remote*/) == false) {
Z
zhangjinchao01 已提交
292 293 294 295 296
          LOG(INFO) << "Waiting for parameters of pass " << passId;
          sleep(60);  // sleep 60s
        }
      } else {
        if (modelList.size() == 0) {
297 298 299
          CHECK_EQ(paramUtil_->loadParameters(
                       passId, true /*local*/, true /*remote*/),
                   true);
Z
zhangjinchao01 已提交
300
        } else {
301 302
          paramUtil_->loadParametersWithPath(
              modelList[i], true /*local*/, true /*remote*/);
Z
zhangjinchao01 已提交
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        }
      }
      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,
322
                         std::ostream& os) {
Z
zhangjinchao01 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  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());
340 341 342 343 344 345 346
          cpuMat_[i] = Matrix::createSparseMatrix(sparseMat->getHeight(),
                                                  sparseMat->getWidth(),
                                                  sparseMat->getElementCnt(),
                                                  sparseMat->getValueType(),
                                                  sparseMat->format_,
                                                  false,  /* trans */
                                                  false); /* useGpu */
Z
zhangjinchao01 已提交
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 381 382 383 384 385 386
          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