adam_optimizer.cc 1.8 KB
Newer Older
1
#include "adam_optimizer.h"
2
#include <cmath>
3 4 5 6

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
7 8 9 10 11
void AdamOptimizer::Update(const Tensor *gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
  double coef1 = 1.0 - std::pow(beta_1_, num_sample_passed_);
  double coef2 = 1.0 - std::pow(beta_2_, num_sample_passed_);
12
  learning_rate *= std::sqrt(coef2) / coef1;
13 14 15 16 17
  Tensor &param = *parameter_;
  const Tensor &grad = *gradient;
  Tensor &m = *momentums_;
  Tensor &v = *velocitys_;
  for (size_t i = 0; i < param.size(); ++i) {
D
dzhwinter 已提交
18 19
    m[i] = beta_1_ * m[i] + (1.0 - beta_1_) * grad[i];
    v[i] = beta_2_ * v[i] + (1.0 - beta_2_) * grad[i] * grad[i];
20
    param[i] -=
D
dzhwinter 已提交
21
        learning_rate * (m[i] / std::sqrt(v[i] + epsilon_) + decay_ * param[i]);
22 23
  }
}
D
dzhwinter 已提交
24

D
dzhwinter 已提交
25 26
const char *AdamOptimizer::SerializeState(int *state_len) {
  AdamOptimizerState state;
D
dongzhihong 已提交
27 28
  std::string lr_str = this->lr_policy_->SerializeState(state_len);
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dzhwinter 已提交
29
  state.set_num_sample_passed(num_sample_passed_);
D
dongzhihong 已提交
30

D
dzhwinter 已提交
31
  TensorToProto(*parameter_, state.mutable_parameter());
D
dzhwinter 已提交
32 33
  TensorToProto(*momentums_, state.mutable_momentums());
  TensorToProto(*velocitys_, state.mutable_velocitys());
D
dzhwinter 已提交
34
  auto str = state.SerializeAsString();
D
dongzhihong 已提交
35
  *state_len += str.size();
D
dzhwinter 已提交
36
  return str.c_str();
D
dzhwinter 已提交
37 38
}

D
dzhwinter 已提交
39 40
void AdamOptimizer::DeserializeState(const std::string &str) {
  AdamOptimizerState state;
D
dzhwinter 已提交
41
  state.ParseFromString(str);
D
dongzhihong 已提交
42 43
  auto lr_state = state.lr_state();
  this->lr_policy_->DeserializeState(lr_state.SerializeAsString());
D
dzhwinter 已提交
44 45 46
  num_sample_passed_ = state.num_sample_passed();

  ProtoToTensor(state.parameter(), parameter_);
D
dzhwinter 已提交
47
  ProtoToTensor(state.momentums(), momentums_);
D
dzhwinter 已提交
48
  ProtoToTensor(state.velocitys(), velocitys_);
D
dzhwinter 已提交
49
}
50 51
}  // namespace optimizer
}  // namespace paddle