adam_optimizer.cc 2.3 KB
Newer Older
D
dzhwinter 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License. */

15
#include "adam_optimizer.h"
16
#include <cmath>
17 18 19 20

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
21 22 23 24 25
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_);
26
  learning_rate *= std::sqrt(coef2) / coef1;
27 28 29 30 31
  Tensor &param = *parameter_;
  const Tensor &grad = *gradient;
  Tensor &m = *momentums_;
  Tensor &v = *velocitys_;
  for (size_t i = 0; i < param.size(); ++i) {
D
dzhwinter 已提交
32 33
    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];
34
    param[i] -=
D
dzhwinter 已提交
35
        learning_rate * (m[i] / std::sqrt(v[i] + epsilon_) + decay_ * param[i]);
36 37
  }
}
D
dzhwinter 已提交
38

39
std::string AdamOptimizer::SerializeState() {
D
dzhwinter 已提交
40
  AdamOptimizerState state;
41
  std::string lr_str = this->lr_policy_->SerializeState();
D
dongzhihong 已提交
42
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dzhwinter 已提交
43
  state.set_num_sample_passed(num_sample_passed_);
D
dongzhihong 已提交
44

D
dzhwinter 已提交
45
  TensorToProto(*parameter_, state.mutable_parameter());
D
dzhwinter 已提交
46 47
  TensorToProto(*momentums_, state.mutable_momentums());
  TensorToProto(*velocitys_, state.mutable_velocitys());
48
  return state.SerializeAsString();
D
dzhwinter 已提交
49 50
}

D
dzhwinter 已提交
51 52
void AdamOptimizer::DeserializeState(const std::string &str) {
  AdamOptimizerState state;
D
dzhwinter 已提交
53
  state.ParseFromString(str);
D
dongzhihong 已提交
54 55
  auto lr_state = state.lr_state();
  this->lr_policy_->DeserializeState(lr_state.SerializeAsString());
D
dzhwinter 已提交
56 57 58
  num_sample_passed_ = state.num_sample_passed();

  ProtoToTensor(state.parameter(), parameter_);
D
dzhwinter 已提交
59
  ProtoToTensor(state.momentums(), momentums_);
D
dzhwinter 已提交
60
  ProtoToTensor(state.velocitys(), velocitys_);
D
dzhwinter 已提交
61
}
62 63
}  // namespace optimizer
}  // namespace paddle