FirstOrderOptimizer.h 11.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

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"
T
tensor-tang 已提交
18
#include "ParameterUpdateFunctions.h"
Z
zhangjinchao01 已提交
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#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_);
  }
34 35
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
36 37
                      size_t sparseId) const {
    (void)sparseId;
38 39 40
    real torch_learningRate = optConfig_.learning_method() == "torch_momentum"
                                  ? 1.0 - paraConfig.momentum()
                                  : 1.0;
T
tensor-tang 已提交
41
#ifdef PADDLE_USE_MKLDNN
T
tensor-tang 已提交
42 43 44 45 46 47 48
    sgdUpdate(learningRate_ * paraConfig.learning_rate() *
                  (firstTime_ ? 1.0 : torch_learningRate),
              paraConfig.momentum(),
              applyDecay_ ? paraConfig.decay_rate() : 0,
              vecs[PARAMETER_VALUE].get(),
              vecs[PARAMETER_GRADIENT].get(),
              vecs[PARAMETER_MOMENTUM].get());
T
tensor-tang 已提交
49
#else
Z
zhangjinchao01 已提交
50
    vecs[PARAMETER_VALUE]->sgdUpdate(
51 52
        *vecs[PARAMETER_GRADIENT],
        *vecs[PARAMETER_MOMENTUM],
Z
zhangjinchao01 已提交
53
        learningRate_ * paraConfig.learning_rate() *
54
            (firstTime_ ? 1.0 : torch_learningRate),
Z
zhangjinchao01 已提交
55 56
        paraConfig.momentum(),
        applyDecay_ ? paraConfig.decay_rate() : 0);
T
tensor-tang 已提交
57
#endif
Z
zhangjinchao01 已提交
58
  }
59
  virtual void finishBatch() { firstTime_ = false; }
Z
zhangjinchao01 已提交
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
};

// 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);
85 86
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
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
                      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_;
  }
126 127
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
128 129 130 131 132 133 134 135 136 137 138 139
                      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
L
liaogang 已提交
140
 */
Z
zhangjinchao01 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
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_);
  }

157 158
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
                      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_++; }

190 191
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      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_++; }

232 233
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
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
                      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_; }

270 271
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
                      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_; }

300 301
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
                      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_);
  }
322 323
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
324 325 326 327 328 329 330 331 332 333 334 335
                      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) {}

336 337
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& paraConfig,
Z
zhangjinchao01 已提交
338 339 340 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
                      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);
  }
367 368
  virtual void update(const VectorPtr vecs[],
                      const ParameterConfig& config,
Z
zhangjinchao01 已提交
369 370 371 372 373 374 375 376 377
                      size_t sparseId) const;

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

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

}  // namespace paddle