adagrad_optimizer.cc 2.0 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 16
#include <cmath>

17 18 19 20 21
#include "adagrad_optimizer.h"

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
22 23 24
void AdagradOptimizer::Update(const Tensor* gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(num_sample_passed_);
25
  Tensor& param = *parameter_;
D
dzhwinter 已提交
26
  Tensor& accum_g = *accum_gradient_;
27 28 29
  const Tensor& grad = *gradient;
  for (size_t i = 0; i < param.size(); ++i) {
    accum_g[i] += grad[i] * grad[i];
D
dzhwinter 已提交
30 31
    param[i] += learning_rate * grad[i] / std::sqrt(accum_g[i] + epsilon_) +
                learning_rate * decay_ * param[i];
32 33
  }
}
34
std::string AdagradOptimizer::SerializeState() {
D
dzhwinter 已提交
35 36
  AdagradOptimizerState state;
  state.set_num_sample_passed(num_sample_passed_);
37
  std::string lr_str = this->lr_policy_->SerializeState();
D
dongzhihong 已提交
38
  state.mutable_lr_state()->ParseFromString(lr_str);
D
dzhwinter 已提交
39 40 41

  TensorToProto(*parameter_, state.mutable_parameter());
  TensorToProto(*accum_gradient_, state.mutable_accum_gradient());
42
  return state.SerializeAsString();
D
dzhwinter 已提交
43 44 45 46 47
}

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

D
dzhwinter 已提交
51 52 53 54
  num_sample_passed_ = state.num_sample_passed();
  ProtoToTensor(state.parameter(), parameter_);
  ProtoToTensor(state.accum_gradient(), accum_gradient_);
}
55 56

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