lr_policy.h 1.8 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;
13
  virtual std::string SerializeState() = 0;
D
dzhwinter 已提交
14
  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
dongzhihong 已提交
20
  ConstLr(double lr) : learning_rate_(lr){};
D
dzhwinter 已提交
21
  double LearningRate(const uint64_t num_sample_passed) {
D
dongzhihong 已提交
22 23
    return learning_rate_;
  }
24
  std::string SerializeState() {
D
dongzhihong 已提交
25 26
    LrPolicyState state;
    state.set_learning_rate(learning_rate_);
27
    return state.SerializeAsString();
D
dongzhihong 已提交
28
  }
D
dongzhihong 已提交
29
  void DeserializeState(const std::string &str) {
D
dongzhihong 已提交
30 31 32
    LrPolicyState state;
    state.ParseFromString(str);
    learning_rate_ = state.learning_rate();
33
  }
D
dzhwinter 已提交
34

35
private:
D
dongzhihong 已提交
36
  double learning_rate_;
37 38
};

D
dzhwinter 已提交
39
class LinearLr final : public LrPolicy {
D
dzhwinter 已提交
40 41
public:
  LinearLr(double lr, double lr_decay_a, double lr_decay_b)
D
dongzhihong 已提交
42
      : learning_rate_(lr), lr_decay_a_(lr_decay_a), lr_decay_b_(lr_decay_b) {}
D
dzhwinter 已提交
43
  double LearningRate(const uint64_t num_sample_passed) {
D
dongzhihong 已提交
44 45
    return std::max(learning_rate_ - lr_decay_a_ * num_sample_passed,
                    lr_decay_b_);
D
dzhwinter 已提交
46
  }
47
  std::string SerializeState() {
D
dongzhihong 已提交
48 49 50 51
    LrPolicyState state;
    state.set_learning_rate(learning_rate_);
    state.set_lr_decay_a(lr_decay_a_);
    state.set_lr_decay_b(lr_decay_b_);
52
    return state.SerializeAsString();
D
dzhwinter 已提交
53
  }
D
dongzhihong 已提交
54 55 56 57 58 59
  void DeserializeState(const std::string &str) {
    LrPolicyState state;
    state.ParseFromString(str);
    learning_rate_ = state.learning_rate();
    lr_decay_a_ = state.lr_decay_a();
    lr_decay_b_ = state.lr_decay_b();
D
dzhwinter 已提交
60
  }
D
dzhwinter 已提交
61 62

private:
D
dongzhihong 已提交
63 64 65
  double learning_rate_;
  double lr_decay_a_;
  double lr_decay_b_;
D
dzhwinter 已提交
66 67
};

68 69
}  // namespace optimizer
}  // namespace paddle