sgd_optmizer.cc 1.1 KB
Newer Older
1 2 3 4 5
#include "sgd_optimizer.h"

namespace paddle {
namespace optimizer {

D
dzhwinter 已提交
6
void SGDOptimizer::set_weight(Tensor *p) {
7
  //  ParameterOptimizer::set_weight(p);
8
  size_t size = p->size();
9 10
  // TODO: fix it with align aware allocator bind to Tensor
  if (momentum != 0.0) {
D
dzhwinter 已提交
11 12
    real *ptr = new real[size];
    momentums_ = new Tensor(ptr, size);
13 14 15
  }
}

D
dzhwinter 已提交
16
void SGDOptimizer::update(const Tensor &gradient) {
17 18 19
  num_sample_passed += 1;
  double learning_rate = lr_policy->get_learning_rate(num_sample_passed);
  double velocity = 0.0;
D
dzhwinter 已提交
20
  for (size_t i = 0; i < parameter_->size(); ++i) {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
    if (momentum == 0.0) {
      velocity =
          -learning_rate * gradient[i] - learning_rate * decay * parameter_[i];
    } else {
      momentums_[i] = momentum * momentums_[i] - learning_rate * gradient[i] -
                      learning_rate * decay * parameter_[i];
      velocity = momentums_[i];
    }
    if (nesterov) {
      parameter_[i] += momentum * velocity - learning_rate * gradient[i];
    } else {
      parameter_[i] += velocity;
    }
  }
}

}  // namespace optimizer
}  // namespace paddle