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

namespace paddle {
namespace optimizer {

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

D
dzhwinter 已提交
16 17 18
void SGDOptimizer::Update(const Tensor *gradient) {
  num_sample_passed_ += 1;
  double learning_rate = lr_policy_->LearningRate(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) {
D
dzhwinter 已提交
24 25
    if (momentum_ == 0.0) {
      velocity = -learning_rate * grad[i] - learning_rate * decay_ * param[i];
26
    } else {
D
dzhwinter 已提交
27 28
      m[i] = momentum_ * m[i] - learning_rate * grad[i] -
             learning_rate * decay_ * param[i];
29
      velocity = m[i];
30
    }
D
dzhwinter 已提交
31 32
    if (nesterov_) {
      param[i] += momentum_ * velocity - learning_rate * grad[i];
33
    } else {
34
      param[i] += velocity;
35 36 37 38
    }
  }
}

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
const char *SGDOptimizer::SerializeState() {
  OptimizerState state;
  // version is a global const value
  state.set_version(kOptimizerVersion);
  TensorToProto(*parameter_, state.add_data());
  TensorToProto(*momentums_, state.add_data());
  state.add_hyperparam(momentum_);
  return state.SerializeAsString().c_str();
}

void SGDOptimizer::DeSerializeState(const std::string &str) {
  OptimizerState state;
  state.ParseFromString(str);
  CHECK(state.version() == kOptimizerVersion)
      << "error version of state"
      << "expected : " << kOptimizerVersion << "get : " << state.version();

  ProtoToTensor(state.data(0), parameter_);
  if (state.data_size() == 2) {
    ProtoToTensor(state.data(1), momentums_);
    momentum_ = state.hyperparam(0);
  }
}

63 64
}  // namespace optimizer
}  // namespace paddle