FirstOrderOptimizer.h 11.0 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 28 29 30 31 32

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 "ParameterOptimizer.h"
#include "Regularizer.h"

namespace paddle {

// Plain SGD optimization.
class SgdOptimizer : public ParameterOptimizer {
public:
  explicit SgdOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
33 34
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
35 36
                      size_t sparseId) const {
    (void)sparseId;
37 38 39
    real torch_learningRate = optConfig_.learning_method() == "torch_momentum"
                                  ? 1.0 - paraConfig.momentum()
                                  : 1.0;
Z
zhangjinchao01 已提交
40
    vecs[PARAMETER_VALUE]->sgdUpdate(
41 42
        *vecs[PARAMETER_GRADIENT],
        *vecs[PARAMETER_MOMENTUM],
Z
zhangjinchao01 已提交
43
        learningRate_ * paraConfig.learning_rate() *
44
            (firstTime_ ? 1.0 : torch_learningRate),
Z
zhangjinchao01 已提交
45 46 47
        paraConfig.momentum(),
        applyDecay_ ? paraConfig.decay_rate() : 0);
  }
48
  virtual void finishBatch() { firstTime_ = false; }
Z
zhangjinchao01 已提交
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
};

// SGD optimization with sparse support.
class SparseMomentumParameterOptimizer : public ParameterOptimizer {
  /* sparse momentum optimizer

    update scheme:

    \alpha_t = \alpha_{t-1} / k
    \beta_t = \beta_{t-1} / (1 + \lambda\gamma_t)
    u_t = u_{t-1} - \alpha_t \gamma_t g_t
    v_t = v_{t-1} + \tau_{t-1} \alpha_t \gamma_t g_t
    \tau_t = \tau_{t-1} + \beta_t / \alpha_t

    where:
    k: momentum
    lambda: decay rate
    \gamma_t: learning rate at the t'th step
  */

public:
  explicit SparseMomentumParameterOptimizer(
      const OptimizationConfig& optConfig);
  virtual void init(size_t numRows, const ParameterConfig* config);
  virtual void startBatch(int64_t numSamplesProcessed);
74 75
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
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
                      size_t sparseId) const;
  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const;
  virtual void finishBatch();

private:
  real alpha_;
  real beta_;
  real tau_;
  real gamma_;
  real threshold_;
  real momentum_;
  real decayRate_;

protected:
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
  bool isParameterSparse_;
};

/*
 * AdaGrad optimization.
 * http://www.magicbroom.info/Papers/DuchiHaSi10.pdf
 */
class AdagradParameterOptimizer : public ParameterOptimizer {
public:
  explicit AdagradParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_LEARNING_RATE);
    numUpdates_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    (void)numSamplesProcessed;
    ++numUpdates_;
  }
115 116
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      size_t sparseId) const;
  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const;

protected:
  int64_t numUpdates_;
  static const int64_t kMaxNumAccumulates = 16384;
};

/*
 * AdaDelta Optimization.
 * http://www.matthewzeiler.com/pubs/googleTR2012/googleTR2012.pdf
*/
class AdaDeltaParameterOptimizer : public ParameterOptimizer {
public:
  explicit AdaDeltaParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }

146 147
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      size_t sparseId) const;

protected:
  real rou_;
  real epsilon_;
};

// RMSProp Parameter Optimization.
class RMSPropParameterOptimizer : public ParameterOptimizer {
public:
  explicit RMSPropParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM1);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    t0Vec_.resize(numRows);
    t0Vec_.assign(t0Vec_.size(), 0);
    timer_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void finishBatch() { timer_++; }

179 180
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      size_t sparseId) const;

protected:
  real rou_;
  real epsilon_;

  /**
   *  counting batches, donot need catch up with
   *  t(timer_) is current time,
   *  t0(t0Vec_) are last occur time of i rows.
   *  if one block is update by multi threads,
   *  caller should hash sparse ids to avoid write conflict in t0Vec_.
   */
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
};

// Decayed AdaGrad Optimization.
class DecayedAdagradParameterOptimizer : public ParameterOptimizer {
public:
  explicit DecayedAdagradParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_GRADIENT_SQURESUM);
    addParameterType(PARAMETER_LEARNING_RATE);
    rou_ = optConfig.ada_rou();
    epsilon_ = optConfig.ada_epsilon();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    t0Vec_.resize(numRows);
    t0Vec_.assign(t0Vec_.size(), 0);
    timer_ = 0;
  }

  virtual void startBatch(int64_t numSamplesProcessed) {
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
  virtual void finishBatch() { timer_++; }

221 222
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      size_t sparseId) const;

protected:
  real rou_;
  real epsilon_;

  /**
   *  counting batches, donot need catch up with
   *  t(timer_) is current time,
   *  t0(t0Vec_) are last occur time of i rows.
   *  if one block is update by multi threads,
   *  caller should hash sparse ids to avoid write conflict in t0Vec_.
   */
  int64_t timer_;
  mutable std::vector<int64_t> t0Vec_;
};

/**
 * Adam Optimizer.
 * Reference Paper: http://arxiv.org/abs/1412.6980 Algorithm 1
 */
class AdamParameterOptimizer : public ParameterOptimizer {
public:
  explicit AdamParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig),
        beta1_(optConfig.adam_beta1()),
        beta2_(optConfig.adam_beta2()),
        epsilon_(optConfig.adam_epsilon()),
        step_(1),
        learningRate_(optConfig.learning_rate()) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_SECOND_MOMENTUM);
  }

  virtual void finishBatch() { ++step_; }

259 260
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
                      size_t sparseId) const;

protected:
  real beta1_;
  real beta2_;
  real epsilon_;
  int64_t step_;
  real learningRate_;
};

/**
 * AdaMax Optimizer.
 * Reference Paper: http://arxiv.org/abs/1412.6980 Algorithm 2
 */
class AdamaxParameterOptimizer : public ParameterOptimizer {
public:
  explicit AdamaxParameterOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig),
        beta1_(optConfig.adam_beta1()),
        beta2_(optConfig.adam_beta2()),
        step_(1),
        learningRate_(optConfig.learning_rate()) {
    addParameterType(PARAMETER_MOMENTUM);
    addParameterType(PARAMETER_WEIGHTED_INFINITY_NORM);
  }

  virtual void finishBatch() { ++step_; }

289 290
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                      size_t sparseId) const;

protected:
  real beta1_;
  real beta2_;
  int64_t step_;
  real learningRate_;
};

// Used in pserver,
// when PARAMETER_DELTA stores in PARAMETER_GRADIENT.
class AddOptimizer : public ParameterOptimizer {
public:
  explicit AddOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {}

  virtual void startBatch(int64_t numSamplesProcessed) {
    // learningRate required by regularizer
    learningRate_ = calcLearningRate(numSamplesProcessed, pass_);
  }
311 312
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
313 314 315 316 317 318 319 320 321 322 323 324
                      size_t sparseId) const {
    vecs[PARAMETER_VALUE]->add(*vecs[PARAMETER_GRADIENT],
                               optConfig_.delta_add_rate());
  }
};

// A optimizer which does nothing.
class DummyOptimizer : public ParameterOptimizer {
public:
  explicit DummyOptimizer(const OptimizationConfig& optConfig)
      : ParameterOptimizer(optConfig) {}

325 326
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
                      size_t sparseId) const {}
};

// Do gradient clipping before sgd update
class OptimizerWithGradientClipping : public ParameterOptimizer {
public:
  OptimizerWithGradientClipping(const OptimizationConfig& optConfig,
                                ParameterOptimizer* optimizer)
      : ParameterOptimizer(optConfig), optimizer_(optimizer) {
    parameterTypes_ = optimizer_->getParameterTypes();
  }

  virtual void init(size_t numRows, const ParameterConfig* config) {
    optimizer_->init(numRows, config);
  }

  virtual void startPass() { optimizer_->startPass(); }
  virtual void finishPass() { optimizer_->finishPass(); }

  virtual void startBatch(int64_t numSamplesProcessed) {
    optimizer_->startBatch(numSamplesProcessed);
    learningRate_ = optimizer_->getLearningRate();
  }
  virtual void finishBatch() { optimizer_->finishBatch(); }

  virtual TraverseCallback needSpecialTraversal(
      const ParameterConfig& config) const {
    return optimizer_->needSpecialTraversal(config);
  }
356 357
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
358 359 360 361 362 363 364 365 366
                      size_t sparseId) const;

  virtual void setNoDecay() { optimizer_->setNoDecay(); }

protected:
  std::unique_ptr<ParameterOptimizer> optimizer_;
};

}  // namespace paddle