adagrad_optimizer.cc 1.5 KB
Newer Older
1 2
#include <cmath>

3 4 5 6 7
#include "adagrad_optimizer.h"

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
8 9 10
void AdagradOptimizer::Update(const Tensor* gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
11
  Tensor& param = *parameter_;
D
dzhwinter 已提交
12
  Tensor& accum_g = *accum_gradient_;
13 14 15
  const Tensor& grad = *gradient;
  for (size_t i = 0; i < param.size(); ++i) {
    accum_g[i] += grad[i] * grad[i];
D
dzhwinter 已提交
16 17
    param[i] += learning_rate * grad[i] / std::sqrt(accum_g[i] + epsilon_) +
                learning_rate * decay_ * param[i];
18 19
  }
}
D
dzhwinter 已提交
20 21 22
const char* AdagradOptimizer::SerializeState(int* state_len) {
  AdagradOptimizerState state;
  state.set_num_sample_passed(num_sample_passed_);
D
dongzhihong 已提交
23 24
  std::string lr_str = this->lr_policy_->SerializeState(state_len);
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dzhwinter 已提交
25 26 27

  TensorToProto(*parameter_, state.mutable_parameter());
  TensorToProto(*accum_gradient_, state.mutable_accum_gradient());
D
dzhwinter 已提交
28
  auto str = state.SerializeAsString();
D
dongzhihong 已提交
29
  *state_len += str.size();
D
dzhwinter 已提交
30
  return str.c_str();
D
dzhwinter 已提交
31 32 33 34 35
}

void AdagradOptimizer::DeserializeState(const std::string& str) {
  AdagradOptimizerState state;
  state.ParseFromString(str);
D
dongzhihong 已提交
36 37 38
  auto lr_state = state.lr_state();
  this->lr_policy_->DeserializeState(lr_state.SerializeAsString());

D
dzhwinter 已提交
39 40 41 42
  num_sample_passed_ = state.num_sample_passed();
  ProtoToTensor(state.parameter(), parameter_);
  ProtoToTensor(state.accum_gradient(), accum_gradient_);
}
43 44

}  // namespace optimizer
D
dzhwinter 已提交
45
}  // namespace paddle