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
  }
}

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

}  // namespace optimizer
}  // namespace paddle