lr_policy.h 1.4 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) { return nullptr; }
  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 40 41 42 43 44
  const char *SerializeState(int *state_len) {
    // TODO(zhihong) : add lr_policy serialization
    return nullptr;
  }
  void DeserializeState(const std::string &state) {
    // TODO(zhihong) : add lr_policy serialization
  }
D
dzhwinter 已提交
45 46

private:
D
dzhwinter 已提交
47
  double learning_rate;
D
dzhwinter 已提交
48 49 50 51
  double lr_decay_a;
  double lr_decay_b;
};

52 53
}  // namespace optimizer
}  // namespace paddle