lr_policy.h 1.2 KB
Newer Older
D
dzhwinter 已提交
1
#pragma once
2

D
dzhwinter 已提交
3
#include <algorithm>
4
#include "OptimizerConfig.pb.h"
5 6 7 8

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
9
class LrPolicy {
10
public:
D
dzhwinter 已提交
11 12
  virtual ~LrPolicy() {}
  virtual double LearningRate(const uint64_t num_sample_passed) = 0;
D
dzhwinter 已提交
13 14
  virtual const char *SerializeState(int *state_len) = 0;
  virtual void DeserializeState(const std::string &state) = 0;
15 16 17
};

// constant learning rate policy
D
dzhwinter 已提交
18
class ConstLr final : public LrPolicy {
19
public:
D
dzhwinter 已提交
20 21
  ConstLr(double lr) : learning_rate(lr){};
  double LearningRate(const uint64_t num_sample_passed) {
22 23
    return learning_rate;
  }
D
dzhwinter 已提交
24 25
  const char *SerializeState(int *state_len);
  void DeserializeState(const std::string &state);
D
dzhwinter 已提交
26

27
private:
D
dzhwinter 已提交
28
  double learning_rate;
29 30
};

D
dzhwinter 已提交
31
class LinearLr final : public LrPolicy {
D
dzhwinter 已提交
32 33
public:
  LinearLr(double lr, double lr_decay_a, double lr_decay_b)
D
dzhwinter 已提交
34 35
      : learning_rate(lr), lr_decay_a(lr_decay_a), lr_decay_b(lr_decay_b) {}
  double LearningRate(const uint64_t num_sample_passed) {
D
dzhwinter 已提交
36 37
    return std::max(learning_rate - lr_decay_a * num_sample_passed, lr_decay_b);
  }
D
dzhwinter 已提交
38 39
  const char *SerializeState(int *state_len);
  void DeserializeState(const std::string &state);
D
dzhwinter 已提交
40 41

private:
D
dzhwinter 已提交
42
  double learning_rate;
D
dzhwinter 已提交
43 44 45 46
  double lr_decay_a;
  double lr_decay_b;
};

47 48
}  // namespace optimizer
}  // namespace paddle