TrainerInternal.cpp 10.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 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 "TrainerInternal.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 28 29
#include "paddle/gserver/gradientmachines/NeuralNetwork.h"
#include "paddle/gserver/layers/ValidationLayer.h"
#include "paddle/utils/GlobalConstants.h"
Z
zhangjinchao01 已提交
30 31 32 33 34
#include "paddle/utils/PythonUtil.h"
#include "paddle/utils/Stat.h"
#include "paddle/utils/Util.h"

#include "RemoteParameterUpdater.h"
Y
Yu Yang 已提交
35
#include "ThreadParameterUpdater.h"
Z
zhangjinchao01 已提交
36 37 38

namespace paddle {

39 40 41 42
void TrainerInternal::init(const std::shared_ptr<TrainerConfigHelper>& config,
                           const GradientMachinePtr& gradientMachine,
                           std::unique_ptr<TrainerInternalConfig>&& intconfig,
                           const std::shared_ptr<TrainerStats>& stats,
Z
zhangjinchao01 已提交
43
                           bool testing) {
44 45 46
  config_ = config;
  intconfig_ = std::move(intconfig);
  stats_ = stats;
Z
zhangjinchao01 已提交
47

48 49 50
  //! in training will use parameter updater definitly.
  //! But only use parameter in testing mode when some parameter in pserver.
  if (!testing || (config_->getOptConfig().use_sparse_remote_updater() &&
Z
zhangjinchao01 已提交
51
                   intconfig_->loadsave_parameters_in_pserver)) {
52 53
    createParameterUpdater(testing);
  }
Z
zhangjinchao01 已提交
54

55 56 57 58 59 60 61 62 63
  gradientMachine_ = gradientMachine;
  if (!gradientMachine) {
    CHECK(config_->getConfig().has_model_config())
        << "Missing model_config in trainer_config";
    gradientMachine_.reset(
        GradientMachine::create(config_->getConfig().model_config(),
                                intconfig_->mode,
                                parameterUpdater_->getParameterTypes()));
  }
Z
zhangjinchao01 已提交
64 65 66
}

void TrainerInternal::trainOneBatch(int64_t batchId,
E
emailweixu 已提交
67 68
                                    const DataBatch& dataBatch,
                                    std::vector<Argument>* outArgs) {
Z
zhangjinchao01 已提交
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
  // true means updating parameter whenever gradient is ready during backward()
  bool doPipelineUpdate =
      (intconfig_->mode != GradientMachine::kSgdSparseCpuTraining) &&
      (intconfig_->local || intconfig_->use_gpu ||
       intconfig_->trainer_count <= 1);

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

  bool showStats = intconfig_->show_param_stats_period > 0 &&
                   (batchId + 1) % intconfig_->show_param_stats_period == 0 &&
                   intconfig_->trainer_id == 0;

  std::vector<ParaStat> paraStats;
  if (showStats) {
    paraStats.resize(gradientMachine_->getParameters().size());
  }

  const std::vector<Argument>& inArgs = dataBatch.getStreams();

  PassType passType = parameterUpdater_->startBatch(actualBatchSize);

  if (config_->getOptConfig().use_sparse_remote_updater()) {
    REGISTER_TIMER("prefetch");
    gradientMachine_->prefetch(inArgs);
    parameterUpdater_->getParametersRemote();
  }

99 100
  UpdateCallback updateCallback = [this, showStats, &paraStats](
      Parameter* para) {
Z
zhangjinchao01 已提交
101 102 103 104 105
    if (showStats) {
      //! @TODO(yuyang18) Show stats is actually a ParameterHook, refactor
      // it
      //! to ParameterHook.
      auto& grad = para->getBuf(PARAMETER_GRADIENT);
106
      SetDevice device(para->getDeviceId());
Z
zhangjinchao01 已提交
107 108 109 110 111 112 113 114 115 116 117 118
      paraStats[para->getID()].avgAbsGrad = grad->getAbsSum() / para->getSize();
      paraStats[para->getID()].maxAbsGrad = grad->getAbsMax();
    }
    parameterUpdater_->update(para);
  };

  {
#ifndef PADDLE_DISABLE_TIMER
    Timer timer;
    timer.start();
#endif
    REGISTER_TIMER("forwardBackward");
119 120
    forwardBackwardBatch(
        inArgs, *outArgs, passType, updateCallback, doPipelineUpdate);
Z
zhangjinchao01 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
#ifndef PADDLE_DISABLE_TIMER
    timer.stop();
    parameterUpdater_->setForwardbackwardTime(timer.get());
#endif
  }

  if (!doPipelineUpdate) {
    auto& parameters = gradientMachine_->getNonStaticParameters();
    for (auto& para : parameters) {
      updateCallback(para.get());
    }
  }

  real cost = 0;
  {
    REGISTER_TIMER("sumCost");
137
    cost = Argument::sum(*outArgs);
Z
zhangjinchao01 已提交
138 139 140 141 142 143 144 145 146 147 148 149
  }

  if (batchId % intconfig_->log_period == 0) {
    currentEvaluator_->start();
    stats_->resetCurrentStat();
  }
  {
    REGISTER_TIMER("eval");
    gradientMachine_->eval(currentEvaluator_);
    gradientMachine_->eval(evaluator_);
  }

150
  *stats_ += {actualBatchSize, cost};
Z
zhangjinchao01 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163 164
  {
    REGISTER_TIMER("finishBatch");
    parameterUpdater_->finishBatch(cost);
  }

  if (showStats) {
    showParameterStats(paraStats);
  }
  if ((batchId + 1) % intconfig_->log_period == 0) {
    currentEvaluator_->finish();

    if (intconfig_->dot_period > 0) {
      std::cerr << std::endl;
    }
165
    LOG(INFO) << " Batch=" << batchId + 1 << " " << *stats_
Z
zhangjinchao01 已提交
166 167 168
              << " Eval: " << *evaluator_
              << " CurrentEval: " << *currentEvaluator_;
  } else if (intconfig_->dot_period > 0 &&
169
             (batchId + 1) % intconfig_->dot_period == 0) {
Z
zhangjinchao01 已提交
170 171 172 173 174 175 176 177 178 179 180
    std::cerr << ".";
  }
}

/**
 * finish train pass
 */
void TrainerInternal::finishTrainPass(int passId, int batchId) {
  gradientMachine_->onPassEnd();
  parameterUpdater_->finishPass();
  evaluator_->finish();
181 182
  LOG(INFO) << " Pass=" << passId << " Batch=" << batchId << " "
            << stats_->getStats(false /*without current cost*/)
Z
zhangjinchao01 已提交
183 184 185
            << " Eval: " << *evaluator_;
}

186 187
void TrainerInternal::showParameterStats(
    const std::vector<ParaStat>& paraStats) {
Z
zhangjinchao01 已提交
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
  std::vector<ParameterPtr>& parameters = gradientMachine_->getParameters();
  for (auto& parameter : parameters) {
    SetDevice device(parameter->getDeviceId());
    real sum = parameter->getBuf(PARAMETER_VALUE)->getAbsSum();
    const auto& lr = parameter->getBuf(PARAMETER_LEARNING_RATE);
    std::ostringstream osLrHistogram;
    if (lr) {
      if (VLOG_IS_ON(2)) {
        osLrHistogram << " lr_histogram: ";
        lr->histogram(osLrHistogram);
      } else {
        osLrHistogram << " max_lr=" << std::setw(11) << lr->getMax()
                      << " min_lr=" << std::setw(11) << lr->getMin()
                      << " avg_lr=" << std::setw(11)
                      << lr->getSum() / parameter->getSize();
      }
    }
    int pid = parameter->getID();
    LOG(INFO) << std::setiosflags(std::ios::left) << std::setfill(' ')
              << std::setw(20) << parameter->getName()
              << " avg_abs_val=" << std::setw(11) << sum / parameter->getSize()
              << " max_val=" << std::setw(11)
              << parameter->getBuf(PARAMETER_VALUE)->getAbsMax()
              << " avg_abs_grad=" << std::setw(11) << paraStats[pid].avgAbsGrad
              << " max_grad=" << std::setw(11) << paraStats[pid].maxAbsGrad
              << osLrHistogram.str();
  }
}

void TrainerInternal::createParameterUpdater(bool testing) {
  const std::string& alg = config_->getOptConfig().algorithm();
  parameterUpdater_.reset(ParameterUpdaterCreators::tryCreateUpdater(
220 221 222 223
      alg, config_->getOptConfig(), intconfig_->local, intconfig_->num_passes));
  if (parameterUpdater_) {
    return;
  }
Z
zhangjinchao01 已提交
224 225 226 227 228 229

  if (!intconfig_->local) {
    if (testing && config_->getOptConfig().use_sparse_remote_updater()) {
      std::unique_ptr<ParameterUpdater> localUpdater;
      localUpdater.reset(
          new SgdLocalUpdater(config_->getOptConfig()));  // do nothing
230 231 232 233 234
      parameterUpdater_.reset(
          new SparseRemoteParameterUpdaterComposite(config_->getOptConfig(),
                                                    intconfig_->num_passes,
                                                    testing,
                                                    std::move(localUpdater)));
Z
zhangjinchao01 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    } else {
      if (GradientMachine::kSgdSparseCpuTraining == intconfig_->mode &&
          !intconfig_->use_old_updater) {
        intconfig_->use_old_updater = true;
        LOG(INFO) << "Sgd sparse training can not work with"
                  << " ConcurrentRemoteParameterUpdater,"
                  << " automatically reset --use_old_updater=true";
      }

      std::unique_ptr<ParameterUpdater> localUpdater;
      if (config_->getOptConfig().num_batches_per_send_parameter() > 1) {
        CHECK(alg == TrainAlgorithm::SGD || alg == TrainAlgorithm::AsyncSGD)
            << "Unsupported algorithm in remote-local mode: " << alg;
        if (GradientMachine::kSgdSparseCpuTraining == intconfig_->mode) {
          localUpdater.reset(new SgdThreadUpdater(*config_));
        } else {
          localUpdater.reset(new SgdLocalUpdater(*config_));
        }
      }

      localUpdater.reset(
256
          intconfig_->use_old_updater
Z
zhangjinchao01 已提交
257
              ? new RemoteParameterUpdater(
258
                    *config_, intconfig_->num_passes, std::move(localUpdater))
Z
zhangjinchao01 已提交
259
              : new ConcurrentRemoteParameterUpdater(
260
                    *config_, intconfig_->num_passes, std::move(localUpdater)));
Z
zhangjinchao01 已提交
261 262

      if (config_->getOptConfig().use_sparse_remote_updater()) {
263 264 265 266 267
        localUpdater.reset(
            new SparseRemoteParameterUpdaterComposite(*config_,
                                                      intconfig_->num_passes,
                                                      testing,
                                                      std::move(localUpdater)));
Z
zhangjinchao01 已提交
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
      }

      this->parameterUpdater_ = std::move(localUpdater);
    }
  } else {
    CHECK_EQ(config_->getOptConfig().num_batches_per_send_parameter(), 1)
        << "num_batches_per_send_parameter should be one in local mode!";

    if (GradientMachine::kSgdSparseCpuTraining == intconfig_->mode) {
      parameterUpdater_.reset(new SgdThreadUpdater(*config_));
    } else if (alg == TrainAlgorithm::SGD || alg == TrainAlgorithm::AsyncSGD) {
      if (config_->getModelConfig().type() == "recursive_nn") {
        parameterUpdater_.reset(new SgdCpuUpdater(*config_));
      } else if (intconfig_->use_gpu &&
                 config_->getOptConfig().do_average_in_cpu() &&
                 config_->getOptConfig().average_window() > 0) {
284
        parameterUpdater_.reset(new SgdUpdaterWithCpuAverager(*config_));
Z
zhangjinchao01 已提交
285 286 287 288 289 290 291 292 293 294
      } else {
        parameterUpdater_.reset(new SgdLocalUpdater(*config_));
      }
    } else {
      LOG(FATAL) << "Unsupported algorithm in local mode: " << alg;
    }
  }
}

void TrainerInternal::forwardBackwardBatch(const std::vector<Argument>& inArgs,
295 296 297 298
                                           std::vector<Argument>& outArgs,
                                           PassType& passType,
                                           UpdateCallback updateCallback,
                                           bool doPipelineUpdate) {
Z
zhangjinchao01 已提交
299 300 301 302 303
  gradientMachine_->forwardBackward(
      inArgs, &outArgs, passType, doPipelineUpdate ? updateCallback : nullptr);
}

}  // namespace paddle