adamw_op.h 6.5 KB
Newer Older
Z
zhaoyingli 已提交
1
/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
R
Roc 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

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
#include <paddle/fluid/operators/optimizers/adam_op.h>

namespace paddle {
namespace operators {

class AdamWOp : public AdamOp {
  using AdamOp::AdamOp;
};

Z
zhaoyingli 已提交
25
struct GPUAdamW;
R
Roc 已提交
26 27 28 29 30 31 32 33
struct CPUAdamW;

template <typename T, typename Flavour>
class AdamWFunctor;

template <typename T>
class AdamWFunctor<T, CPUAdamW> {
 private:
34
  const T coeff_;
35
  const T lr_ratio_;
36
  const T* lr_;
R
Roc 已提交
37 38 39
  T* param_;

 public:
40 41
  AdamWFunctor(const T coeff, const T lr_ratio, const T* lr, T* param)
      : coeff_(coeff), lr_ratio_(lr_ratio), lr_(lr), param_(param) {}
R
Roc 已提交
42 43 44 45

  inline HOSTDEVICE void operator()(size_t numel) const {
    Eigen::Map<Eigen::Array<T, 1, Eigen::Dynamic>> param{
        param_, static_cast<Eigen::Index>(numel)};
46 47 48

    T lr = *lr_;

R
Roc 已提交
49
    // Calculation
50
    param -= lr * lr_ratio_ * coeff_ * param;
R
Roc 已提交
51 52 53
  }
};

Z
zhaoyingli 已提交
54 55 56 57 58 59 60 61 62 63
template <typename T, typename Flavour, typename MT = T>
class SparseAdamWFunctor;

template <typename T, typename MT>
class SparseAdamWFunctor<T, GPUAdamW, MT> {
 private:
  MT beta1_;
  MT beta2_;
  MT epsilon_;
  MT coeff_;
64
  MT lr_ratio_;
Z
zhaoyingli 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

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

  const int64_t* rows_;
  int64_t row_numel_;
  int64_t row_count_;
  bool lazy_mode_;

 public:
85
  SparseAdamWFunctor(MT beta1, MT beta2, MT epsilon, MT coeff, MT lr_ratio,
Z
zhaoyingli 已提交
86 87 88 89 90 91 92 93 94 95
                     const MT* beta1_pow, const MT* beta2_pow, const MT* mom1,
                     MT* mom1_out, const MT* mom2, MT* mom2_out, const MT* lr,
                     const T* grad, const T* param, T* param_out,
                     const MT* master_param, MT* master_param_out,
                     const int64_t* rows, int64_t row_numel, int64_t row_count,
                     bool lazy_mode)
      : beta1_(beta1),
        beta2_(beta2),
        epsilon_(epsilon),
        coeff_(coeff),
96
        lr_ratio_(lr_ratio),
Z
zhaoyingli 已提交
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
        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),
        master_param_(master_param),
        master_param_out_(master_param_out),
        rows_(rows),
        row_numel_(row_numel),
        row_count_(row_count),
        lazy_mode_(lazy_mode) {}

  inline HOSTDEVICE void adamw_update(size_t i, MT g) const {
    // The following code is the same as dense
    MT mom1 = moment1_[i];
    MT mom2 = moment2_[i];
118 119
    MT lr = *lr_ * lr_ratio_;
    MT lr_orig = lr;
Z
zhaoyingli 已提交
120 121 122 123 124 125 126 127 128 129
    MT beta1_pow = *beta1_pow_;
    MT beta2_pow = *beta2_pow_;
    MT p = master_param_ ? master_param_[i] : static_cast<MT>(param_[i]);

    // Calculation
    lr *= sqrt(static_cast<MT>(1.0) - beta2_pow) /
          (static_cast<MT>(1.0) - beta1_pow);

    mom1 = beta1_ * mom1 + (static_cast<MT>(1.0) - beta1_) * g;
    mom2 = beta2_ * mom2 + (static_cast<MT>(1.0) - beta2_) * g * g;
130 131 132
    p -= lr_orig * coeff_ * p;
    p -= lr * (mom1 / (sqrt(mom2) +
                       epsilon_ * sqrt(static_cast<MT>(1.0) - beta2_pow)));
Z
zhaoyingli 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

    // Write back to global memory
    moment1_out_[i] = mom1;
    moment2_out_[i] = mom2;
    param_out_[i] = static_cast<T>(p);
    if (master_param_out_) {
      master_param_out_[i] = p;
    }
  }

  inline HOSTDEVICE void operator()(size_t i) const {
    auto row_idx =
        math::BinarySearch<int64_t>(rows_, row_count_, i / row_numel_);
    if (lazy_mode_ && row_idx < 0) {
      return;
    } else {
      MT g = row_idx >= 0
                 ? static_cast<MT>(grad_[row_idx * row_numel_ + i % row_numel_])
                 : static_cast<MT>(0);
      adamw_update(i, g);
    }
  }
};

R
Roc 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
template <typename DeviceContext, typename T>
class AdamWOpKernel : public AdamOpKernel<DeviceContext, T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    const auto* param_var = ctx.InputVar("Param");
    PADDLE_ENFORCE_EQ(param_var->IsType<framework::LoDTensor>(), true,
                      platform::errors::InvalidArgument(
                          "The Var(%s)'s type should be LoDTensor, "
                          "but the received is %s",
                          ctx.InputNames("Param").front(),
                          framework::ToTypeName(param_var->Type())));

    using paddle::framework::LoDTensor;
    bool skip_update = false;
    // TODO(liupeng):
    if (ctx.HasInput("SkipUpdate")) {
      VLOG(3) << "Has SkipUpdate";
      auto* skip_update_tensor = ctx.Input<framework::Tensor>("SkipUpdate");
      PADDLE_ENFORCE_EQ(skip_update_tensor->numel(), 1,
                        platform::errors::InvalidArgument(
                            "Input(SkipUpdate) size must be 1, but get %d",
                            skip_update_tensor->numel()));
      std::vector<bool> skip_update_vec;
      TensorToVector(*skip_update_tensor, ctx.device_context(),
                     &skip_update_vec);
      skip_update = skip_update_vec[0];
    }
    VLOG(3) << "Skip update" << skip_update;
    bool with_decay = ctx.Attr<bool>("with_decay");

    if (skip_update || !with_decay) {
      AdamOpKernel<DeviceContext, T>::Compute(ctx);
      return;
    }

192
    T coeff = static_cast<T>(ctx.Attr<float>("coeff"));
193
    T lr_ratio = static_cast<T>(ctx.Attr<float>("lr_ratio"));
R
Roc 已提交
194 195 196 197 198 199 200 201 202 203 204
    auto* lr = ctx.Input<LoDTensor>("LearningRate");

    LoDTensor* param;

    if (ctx.HasInput("MasterParam")) {
      // TODO(liupeng): master
      param = const_cast<LoDTensor*>(ctx.Input<LoDTensor>("MasterParam"));
    } else {
      param = const_cast<LoDTensor*>(ctx.Input<LoDTensor>("Param"));
    }

205 206
    AdamWFunctor<T, CPUAdamW> functor(coeff, lr_ratio, lr->data<T>(),
                                      param->data<T>());
R
Roc 已提交
207 208 209 210 211 212 213
    functor(param->numel());

    AdamOpKernel<DeviceContext, T>::Compute(ctx);
  }
};
}  // namespace operators
}  // namespace paddle