sgd_optimizer.cc 1.7 KB
Newer Older
1
#include "sgd_optimizer.h"
D
dzhwinter 已提交
2
#include "serialization.h"
3 4 5 6

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
7 8 9
void SGDOptimizer::Update(const Tensor *gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
10
  float velocity = 0.0;
D
dzhwinter 已提交
11
  Tensor &param = *parameter_;
12 13 14
  const Tensor &grad = *gradient;
  Tensor &m = *momentums_;
  for (size_t i = 0; i < param.size(); ++i) {
D
dzhwinter 已提交
15 16
    if (momentum_ == 0.0) {
      velocity = -learning_rate * grad[i] - learning_rate * decay_ * param[i];
17
    } else {
D
dzhwinter 已提交
18 19
      m[i] = momentum_ * m[i] - learning_rate * grad[i] -
             learning_rate * decay_ * param[i];
20
      velocity = m[i];
21
    }
D
dzhwinter 已提交
22 23
    if (nesterov_) {
      param[i] += momentum_ * velocity - learning_rate * grad[i];
24
    } else {
25
      param[i] += velocity;
26 27 28 29
    }
  }
}

D
dzhwinter 已提交
30
const char *SGDOptimizer::SerializeState(int *state_len) {
D
dzhwinter 已提交
31
  SGDOptimizerState state;
D
dzhwinter 已提交
32
  state.set_num_sample_passed(num_sample_passed_);
D
dongzhihong 已提交
33
  std::string lr_str = this->lr_policy_->SerializeState(state_len);
D
dongzhihong 已提交
34
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dongzhihong 已提交
35
  TensorToProto(*parameter_, state.mutable_parameter());
D
dzhwinter 已提交
36
  if (momentum_ != 0.0) TensorToProto(*momentums_, state.mutable_momentums());
D
dzhwinter 已提交
37
  auto str = state.SerializeAsString();
D
dongzhihong 已提交
38
  *state_len += str.size();
D
dzhwinter 已提交
39
  return str.c_str();
40 41
}

D
dzhwinter 已提交
42 43
void SGDOptimizer::DeserializeState(const std::string &str) {
  SGDOptimizerState state;
44
  state.ParseFromString(str);
D
dongzhihong 已提交
45 46
  auto lr_state = state.lr_state();
  this->lr_policy_->DeserializeState(lr_state.SerializeAsString());
D
dzhwinter 已提交
47 48
  num_sample_passed_ = state.num_sample_passed();
  ProtoToTensor(state.parameter(), parameter_);
D
dzhwinter 已提交
49
  if (momentum_ != 0.0) ProtoToTensor(state.parameter(), momentums_);
50 51
}

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