adam_op.h 7.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/* 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. */

#pragma once
Y
Yang Yu 已提交
16
#include <math.h>  // for sqrt in CPU and CUDA
17
#include "paddle/framework/op_registry.h"
Y
Yang Yu 已提交
18
#include "paddle/operators/detail/safe_ref.h"
Y
Yang Yu 已提交
19
#include "paddle/platform/for_range.h"
20 21 22 23

namespace paddle {
namespace operators {

Y
Yang Yu 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
template <typename T>
struct AdamFunctor {
  T beta1_;
  T beta2_;
  T epsilon_;

  const T* beta1_pow_;
  const T* beta2_pow_;
  const T* moment1_;
  T* moment1_out_;
  const T* moment2_;
  T* moment2_out_;
  const T* lr_;
  const T* grad_;
  const T* param_;
Y
Yang Yu 已提交
39
  T* param_out_;
Y
Yang Yu 已提交
40 41 42

  AdamFunctor(T beta1, T beta2, T epsilon, const T* beta1_pow,
              const T* beta2_pow, const T* mom1, T* mom1_out, const T* mom2,
Y
Yang Yu 已提交
43 44
              T* mom2_out, const T* lr, const T* grad, const T* param,
              T* param_out)
Y
Yang Yu 已提交
45 46 47 48 49 50 51 52 53 54 55
      : beta1_(beta1),
        beta2_(beta2),
        epsilon_(epsilon),
        beta1_pow_(beta1_pow),
        beta2_pow_(beta2_pow),
        moment1_(mom1),
        moment1_out_(mom1_out),
        moment2_(mom2),
        moment2_out_(mom2_out),
        lr_(lr),
        grad_(grad),
Y
Yang Yu 已提交
56 57
        param_(param),
        param_out_(param_out) {}
Y
Yang Yu 已提交
58

Y
Yang Yu 已提交
59
  inline HOSTDEVICE void operator()(size_t i) const {
Y
Yang Yu 已提交
60 61 62 63 64 65 66
    // Merge all memory access together.
    T g = grad_[i];
    T mom1 = moment1_[i];
    T mom2 = moment2_[i];
    T lr = *lr_;
    T beta1_pow = *beta1_pow_;
    T beta2_pow = *beta2_pow_;
Y
Yang Yu 已提交
67
    T p = param_[i];
Y
Yang Yu 已提交
68 69

    // Calculation
Y
Yang Yu 已提交
70
    lr *= sqrt(1 - beta2_pow) / (1 - beta1_pow);
Y
Yang Yu 已提交
71 72
    mom1 = beta1_ * mom1 + (1 - beta1_) * g;
    mom2 = beta2_ * mom2 + (1 - beta2_) * g * g;
Y
Yang Yu 已提交
73
    p -= lr * (mom1 / (sqrt(mom2) + epsilon_));
Y
Yang Yu 已提交
74 75 76 77

    // Write back to global memory
    moment1_out_[i] = mom1;
    moment2_out_[i] = mom2;
Y
Yang Yu 已提交
78
    param_out_[i] = p;
Y
Yang Yu 已提交
79 80 81
  }
};

T
wip  
typhoonzero 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
template <typename T>
struct SparseAdamFunctor {
  T beta1_;
  T beta2_;
  T epsilon_;

  const T* beta1_pow_;
  const T* beta2_pow_;
  const T* moment1_;
  T* moment1_out_;
  const T* moment2_;
  T* moment2_out_;
  const T* lr_;
  const T* grad_;
  const T* param_;
  T* param_out_;

  const int64_t* rows_;
  int64_t row_numel_;

  SparseAdamFunctor(T beta1, T beta2, T epsilon, const T* beta1_pow,
                    const T* beta2_pow, const T* mom1, T* mom1_out,
                    const T* mom2, T* mom2_out, const T* lr, const T* grad,
                    const T* param, T* param_out, const int64_t* rows,
T
typhoonzero 已提交
106
                    int64_t row_numel)
T
wip  
typhoonzero 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120
      : beta1_(beta1),
        beta2_(beta2),
        epsilon_(epsilon),
        beta1_pow_(beta1_pow),
        beta2_pow_(beta2_pow),
        moment1_(mom1),
        moment1_out_(mom1_out),
        moment2_(mom2),
        moment2_out_(mom2_out),
        lr_(lr),
        grad_(grad),
        param_(param),
        param_out_(param_out),
        rows_(rows),
T
typhoonzero 已提交
121
        row_numel_(row_numel) {}
T
wip  
typhoonzero 已提交
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136

  inline HOSTDEVICE void operator()(size_t i) const {
    for (int64_t j = 0; j < row_numel_; ++j) {
      T g = grad_[i * row_numel_ + j];
      T mom1 = moment1_[rows_[i] * row_numel_ + j];
      T mom2 = moment2_[rows_[i] * row_numel_ + j];
      T lr = *lr_;
      T beta1_pow = *beta1_pow_;
      T beta2_pow = *beta2_pow_;
      T p = param_[rows_[i] * row_numel_ + j];

      lr *= sqrt(1 - beta2_pow) / (1 - beta1_pow);
      mom1 = beta1_ * mom1 + (1 - beta1_) * g;
      mom2 = beta2_ * mom2 + (1 - beta2_) * g * g;
      p -= lr * (mom1 / (sqrt(mom2) + epsilon_));
T
typhoonzero 已提交
137
      // IMPORTANT:
T
wip  
typhoonzero 已提交
138 139 140 141 142 143 144 145
      // FIXME(typhoonzero): row id may be duplicate
      moment1_out_[rows_[i] * row_numel_ + j] = mom1;
      moment2_out_[rows_[i] * row_numel_ + j] = mom2;
      param_out_[rows_[i] * row_numel_ + j] = p;
    }  // for col id
  }
};

Q
QI JUN 已提交
146
template <typename DeviceContext, typename T>
147 148 149
class AdamOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
Y
Yang Yu 已提交
150 151
    using paddle::framework::LoDTensor;
    using paddle::operators::detail::Ref;
152

153 154 155
    T beta1 = static_cast<T>(ctx.Attr<float>("beta1"));
    T beta2 = static_cast<T>(ctx.Attr<float>("beta2"));
    T epsilon = static_cast<T>(ctx.Attr<float>("epsilon"));
Y
Yang Yu 已提交
156
    auto& param = Ref(ctx.Input<LoDTensor>("Param"), "Must set Param");
T
wip  
typhoonzero 已提交
157 158
    // auto& grad = Ref(ctx.Input<LoDTensor>("Grad"), "Must set Grad");
    auto* grad_var = ctx.InputVar("Grad");
Y
Yang Yu 已提交
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    auto& mom1 = Ref(ctx.Input<LoDTensor>("Moment1"), "Must set Moment1");
    auto& mom2 = Ref(ctx.Input<LoDTensor>("Moment2"), "Must set Moment2");
    auto& lr =
        Ref(ctx.Input<LoDTensor>("LearningRate"), "Must set LearningRate");

    auto& beta1_pow =
        Ref(ctx.Input<LoDTensor>("Beta1Pow"), "Must set Beta1Pow");
    auto& beta2_pow =
        Ref(ctx.Input<LoDTensor>("Beta2Pow"), "Must set Beta2Pow");

    auto& param_out =
        Ref(ctx.Output<LoDTensor>("ParamOut"), "Must set ParamOut");
    auto& mom1_out =
        Ref(ctx.Output<LoDTensor>("Moment1Out"), "Must set Moment1Out");
    auto& mom2_out =
        Ref(ctx.Output<LoDTensor>("Moment2Out"), "Must set Moment1Out");

T
wip  
typhoonzero 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
    if (grad_var->IsType<framework::LoDTensor>()) {
      auto& grad = Ref(ctx.Input<LoDTensor>("Grad"), "Must set Grad");
      AdamFunctor<T> functor(
          beta1, beta2, epsilon, beta1_pow.template data<T>(),
          beta2_pow.template data<T>(), mom1.template data<T>(),
          mom1_out.template mutable_data<T>(ctx.GetPlace()),
          mom2.template data<T>(),
          mom2_out.template mutable_data<T>(ctx.GetPlace()),
          lr.template data<T>(), grad.template data<T>(),
          param.template data<T>(),
          param_out.template mutable_data<T>(ctx.GetPlace()));
      platform::ForRange<DeviceContext> for_range(
          static_cast<const DeviceContext&>(ctx.device_context()),
          param.numel());
      for_range(functor);
    } else if (grad_var->IsType<framework::SelectedRows>()) {
      auto& grad =
          Ref(ctx.Input<framework::SelectedRows>("Grad"), "Must set Grad");
      auto& grad_tensor = grad.value();
      const T* grad_data = grad_tensor.template data<T>();
      auto* rows = grad.rows().data();
T
typhoonzero 已提交
197
      auto row_numel = grad_tensor.numel() / grad.rows().size();
T
wip  
typhoonzero 已提交
198 199 200 201 202 203 204 205

      SparseAdamFunctor<T> functor(
          beta1, beta2, epsilon, beta1_pow.template data<T>(),
          beta2_pow.template data<T>(), mom1.template data<T>(),
          mom1_out.template mutable_data<T>(ctx.GetPlace()),
          mom2.template data<T>(),
          mom2_out.template mutable_data<T>(ctx.GetPlace()),
          lr.template data<T>(), grad_data, param.template data<T>(),
T
typhoonzero 已提交
206
          param_out.template mutable_data<T>(ctx.GetPlace()), rows, row_numel);
T
wip  
typhoonzero 已提交
207 208 209 210 211 212 213
      platform::ForRange<DeviceContext> for_range(
          static_cast<const DeviceContext&>(ctx.device_context()),
          grad.rows().size());
      for_range(functor);
    } else {
      PADDLE_THROW("Variable type not supported by adam_op");
    }
214 215 216 217 218
  }
};

}  // namespace operators
}  // namespace paddle