ParameterUpdater.h 7.5 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 21 22 23 24 25 26 27

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

#pragma once

#include "paddle/utils/Thread.h"
#include "paddle/utils/Util.h"

#include "paddle/parameter/AverageOptimizer.h"
#include "paddle/parameter/FirstOrderOptimizer.h"
#include "paddle/parameter/OptimizerFunctions.h"
#include "paddle/parameter/OptimizerWithRegularizer.h"
#include "paddle/parameter/Parameter.h"
#include "paddle/parameter/ParameterUpdaterBase.h"

#include "TrainerConfig.pb.h"
Y
Yu Yang 已提交
28
#include "paddle/gserver/layers/Layer.h"
Z
zhangjinchao01 已提交
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

#include <memory>
#include <vector>

namespace paddle {

/**
 * @brief Parameter Updater for SGD, and local(not cluster) run.
 */
class SgdLocalUpdater : public ParameterUpdater {
public:
  /**
   * @brief Ctor. Initialize optimizer locally by optConfig.
   * @param optConfig optimization config.
   * @param withAverager with average optimizer or not, default is true.
   */
  explicit SgdLocalUpdater(const OptimizationConfig& optConfig,
                           bool withAverager = true)
      : numSamplesProcessed_(0) {
    auto baseOptimizer = ParameterOptimizer::create(optConfig);
    optimizer_.reset(withAverager
                         ? AverageOptimizer::create(optConfig, baseOptimizer)
                         : baseOptimizer);
    CHECK(optimizer_) << "fail to create optimizer: "
                      << optConfig.learning_method();
    auto types = optimizer_->getParameterTypes();
    for (auto type : types) {
      addParameterType(type);
    }
  }

  /**
   * @brief Initialize parameters and optimizer_.
   *        For example,
   *           If optimizer need hassien vector, then parameter's hassien will
   *           be initialized.
   * @param parameters The parameter need to be initialized.
   */
  virtual void init(std::vector<ParameterPtr>& parameters) {
    ParameterUpdater::init(parameters);
    optimizer_->init(parameters_.size(), nullptr);
    // check no L1 decay in parameter configs
71 72
    CHECK(std::find_if(parameters.begin(),
                       parameters.end(),
Z
zhangjinchao01 已提交
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
                       [](const ParameterPtr& para) {
                         return para->getConfig().decay_rate_l1() > 0.0f;
                       }) == parameters.end())
        << "SgdLocalUpdater cannot support L1 decay in parameter";
  }

  /**
   * @brief Start a batch with current mini-batch size
   * @param current mini-batch size.
   * @return Always PASS_TRAIN.
   */
  virtual PassType startBatch(int64_t batchSize) {
    numSamplesProcessed_ += batchSize;
    optimizer_->startBatch(numSamplesProcessed_);
    return PASS_TRAIN;
  }

  /**
   * @brief finish a mini-batch.
   */
  virtual void finishBatch(real cost) { optimizer_->finishBatch(); }

  /**
   * @brief start a pass.
   */
  virtual void startPass() { optimizer_->startPass(); }

  /**
   * @brief finish a pass.
   * @param cost sum cost during one pass.
   * @return true if accept (used for owlqn).
   */
  virtual bool finishPass(real cost) {
    optimizer_->finishPass();
    return ParameterUpdater::finishPass(cost);
  }

  /**
   * @brief apply model average.
   */
  virtual void apply() {
    if (auto callback = optimizer_->apply()) {
      for (auto para : parameters_) {
        SetDevice device(para->getDeviceId());
        callback(para->getBufs(), para->getConfig(), -1UL);
      }
    }
  }

  /**
   * @brief restore parameter value before model average
   */
  virtual void restore() {
    if (auto callback = optimizer_->restore()) {
      for (auto para : parameters_) {
        SetDevice device(para->getDeviceId());
        callback(para->getBufs(), para->getConfig(), -1UL);
      }
    }
  }

protected:
  /**
   * @brief update method. Update value from gradient.
   * @param para parameter that will be updated.
   */
  virtual void updateImpl(Parameter* para) {
    optimizer_->update(para->getBufs(), para->getConfig());
    if (auto callback = optimizer_->needSpecialTraversal(para->getConfig())) {
      callback(para->getBufs(), para->getConfig(), -1UL);
    }

    para->setValueUpdated();
    para->getBuf(PARAMETER_GRADIENT)->zeroMem();
  }

  std::unique_ptr<ParameterOptimizer> optimizer_;

  /**
   * @brief total number of samples processed.
   */
  int64_t numSamplesProcessed_;
};

/**
 * @brief SgdCpuUpdater is used only in recursive neural network
 * @deprecated
 */
class SgdCpuUpdater : public SgdLocalUpdater, public Deprecated {
public:
  explicit SgdCpuUpdater(const OptimizationConfig& optConfig)
      : SgdLocalUpdater(optConfig),
165 166 167 168
        Deprecated(
            "SgdCpuUpdater is used only in recursive neural network, "
            "and recursive neural network is deprecated in paddle. "
            "Use it all by your own.") {}
Z
zhangjinchao01 已提交
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 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266

  /**
   * @brief update all parameter on finish batch.
   * @param cost
   */
  virtual void finishBatch(real cost) {
    for (auto para : parameters_) {
      SgdLocalUpdater::update(para.get());
    }
    optimizer_->finishBatch();
  }

protected:
  /**
   * @brief do nothing.
   * @param para
   */
  virtual void updateImpl(Parameter* para) {}
  virtual void update(Parameter* para) {}
};

/**
 * @brief Sgd Local Updater With average in cpu.
 *
 * It will do model average in cpu to reduce gpu memory comsuption.
 */
class SgdUpdaterWithCpuAverager : public SgdLocalUpdater {
public:
  /**
   * @brief Ctor.
   *
   * SgdUpdaterWithCpuAverager will do everything as a
   * SgdLocalUpdater, then copy parameter from GPU to CPU, and do model
   * average in cpu.
   */
  explicit SgdUpdaterWithCpuAverager(const OptimizationConfig& optConfig);
  ~SgdUpdaterWithCpuAverager();

  /**
   * @brief init. Initialize cpu parameters, model average optimizer.
   * @param parameters
   */
  virtual void init(std::vector<ParameterPtr>& parameters);

  virtual PassType startBatch(int64_t batchSize) {
    averager_->startBatch(-1UL);
    return SgdLocalUpdater::startBatch(batchSize);
  }
  virtual void finishBatch(real cost);

  virtual void startPass() {
    averager_->startPass();
    SgdLocalUpdater::startPass();
  }
  virtual bool finishPass(real cost) {
    averager_->finishPass();
    return SgdLocalUpdater::finishPass(cost);
  }

  /// apply the averaged parameter to PARAMETER_VALUE
  /// use PARAETER_GRADIENT for backing up PARAMETER_VALUE
  virtual void apply();

  /**
   * @brief Restore parameter before apply().
   */
  virtual void restore();

protected:
  virtual void updateImpl(Parameter* para);

  void updateFunc(Parameter* para);

protected:
  std::unique_ptr<ParameterOptimizer> averager_;

  /**
   * @brief The thread worker which do model average.
   *
   * For each parameter, GPU->CPU parameter is async, and do model average in
   * another thread. Because the training process don't need model average while
   * training, and model average only used in evaluation stage and saving stage.
   * So the model average is totally async.
   */
  ThreadWorker updateWorker_;

  /**
   * @brief The parameter mirror in cpu.
   */
  std::vector<ParameterPtr> cpuParameters_;

  /**
   * @brief GPU -> CPU copy event. Model average will wait after copy done.
   */
  std::vector<hl_event_t> copyEvents_;
};

}  // namespace paddle