rmsprop_op.h 10.3 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15

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
S
sneaxiy 已提交
16
#include <math.h>
Y
Yi Wang 已提交
17 18
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
S
sneaxiy 已提交
19 20 21
#include "paddle/fluid/operators/math/algorithm.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/platform/for_range.h"
22 23 24 25

namespace paddle {
namespace operators {

S
sneaxiy 已提交
26 27 28 29 30 31 32 33 34 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
template <typename T>
struct DenseRmspropGradFunctor {
  inline explicit DenseRmspropGradFunctor(const T *grad) : grad_(grad) {}

  HOSTDEVICE inline T operator()(int64_t idx) const { return grad_[idx]; }

  const T *grad_;
};

template <typename T>
struct SparseRmspropGradFunctor {
  inline SparseRmspropGradFunctor(const T *grad, const int64_t *rows,
                                  int64_t row_numel, int64_t row_count)
      : grad_(grad),
        rows_(rows),
        row_numel_(row_numel),
        row_count_(row_count) {}

  HOSTDEVICE inline T operator()(int64_t idx) const {
    auto row_idx = math::BinarySearch(rows_, row_count_, idx / row_numel_);
    return row_idx >= 0 ? grad_[row_idx * row_numel_ + idx % row_numel_] : 0;
  }

  const T *grad_;
  const int64_t *rows_;
  int64_t row_numel_;
  int64_t row_count_;
};

template <typename T, typename GradFunctor>
struct UncenteredRmspropFunctor {
  UncenteredRmspropFunctor(T *param, T *ms, T *mom, const T *lr, T rho,
                           T epsilon, T momentum,
                           const GradFunctor &grad_functor)
      : param_(param),
        ms_(ms),
        mom_(mom),
        lr_(lr),
        rho_(rho),
        epsilon_(epsilon),
        momentum_(momentum),
        grad_functor_(grad_functor) {}

  HOSTDEVICE inline void operator()(int64_t idx) const {
    T g = grad_functor_(idx);
    T ms_out = rho_ * ms_[idx] + (1 - rho_) * g * g;
    T mom_out = momentum_ * mom_[idx] + lr_[0] * g / sqrt(ms_out + epsilon_);
    param_[idx] -= mom_out;
    ms_[idx] = ms_out;
    mom_[idx] = mom_out;
  }

  T *param_;
  T *ms_;
  T *mom_;
  const T *lr_;
  T rho_;
  T epsilon_;
  T momentum_;
  GradFunctor grad_functor_;
};

template <typename T, typename GradFunctor>
struct CenteredRmspropFunctor {
  CenteredRmspropFunctor(T *param, T *ms, T *mom, T *mean_grad, const T *lr,
                         T rho, T epsilon, T momentum,
                         const GradFunctor &grad_functor)
      : param_(param),
        ms_(ms),
        mom_(mom),
        mean_grad_(mean_grad),
        lr_(lr),
        rho_(rho),
        epsilon_(epsilon),
        momentum_(momentum),
        grad_functor_(grad_functor) {}

  HOSTDEVICE inline void operator()(int64_t idx) const {
    T g = grad_functor_(idx);
    T ms_out = rho_ * ms_[idx] + (1 - rho_) * g * g;
    T mg_out = rho_ * mean_grad_[idx] + (1 - rho_) * g;
    T mom_out = momentum_ * mom_[idx] +
                lr_[0] * g / sqrt(ms_out - mg_out * mg_out + epsilon_);
    param_[idx] -= mom_out;
    ms_[idx] = ms_out;
    mom_[idx] = mom_out;
    mean_grad_[idx] = mg_out;
  }

  T *param_;
  T *ms_;
  T *mom_;
  T *mean_grad_;
  const T *lr_;
  T rho_;
  T epsilon_;
  T momentum_;
  GradFunctor grad_functor_;
};

Q
QI JUN 已提交
126
template <typename DeviceContext, typename T>
127 128
class RmspropOpKernel : public framework::OpKernel<T> {
 public:
S
sneaxiy 已提交
129
  void Compute(const framework::ExecutionContext &ctx) const override {
S
sneaxiy 已提交
130
    using LoDTensor = framework::LoDTensor;
S
sneaxiy 已提交
131
    auto *grad_var = ctx.InputVar("Grad");
S
sneaxiy 已提交
132 133 134
    auto *param_out = ctx.Output<LoDTensor>("ParamOut");
    auto *moment_out = ctx.Output<LoDTensor>("MomentOut");
    auto *mean_square_out = ctx.Output<LoDTensor>("MeanSquareOut");
135

S
sneaxiy 已提交
136 137 138 139
    auto epsilon = static_cast<T>(ctx.Attr<float>("epsilon"));
    auto rho = static_cast<T>(ctx.Attr<float>("decay"));
    auto momentum = static_cast<T>(ctx.Attr<float>("momentum"));
    bool centered = ctx.Attr<bool>("centered");
140

S
sneaxiy 已提交
141 142 143 144
    auto &p_tensor = *ctx.Input<LoDTensor>("Param");
    auto &ms_tensor = *ctx.Input<LoDTensor>("MeanSquare");
    auto &lr_tensor = *ctx.Input<LoDTensor>("LearningRate");
    auto &mom_tensor = *ctx.Input<LoDTensor>("Moment");
145

146
    PADDLE_ENFORCE_EQ(p_tensor.IsSharedBufferWith(*param_out), true,
C
Chengmo 已提交
147 148
                      platform::errors::InvalidArgument(
                          "Param and ParamOut must be the same Tensor"));
149
    PADDLE_ENFORCE_EQ(mom_tensor.IsSharedBufferWith(*moment_out), true,
C
Chengmo 已提交
150 151 152
                      platform::errors::InvalidArgument(
                          "Moment and MomentOut must be the same Tensor"));
    PADDLE_ENFORCE_EQ(
153
        ms_tensor.IsSharedBufferWith(*mean_square_out), true,
C
Chengmo 已提交
154 155
        platform::errors::InvalidArgument(
            "MeanSquare and MeanSquareOut must be the same Tensor"));
S
sneaxiy 已提交
156 157 158 159

    auto &dev_ctx = ctx.template device_context<DeviceContext>();
    size_t limit = static_cast<size_t>(ms_tensor.numel());

S
sneaxiy 已提交
160 161
    if (grad_var->IsType<LoDTensor>()) {
      auto &grad_tensor = grad_var->Get<LoDTensor>();
S
sneaxiy 已提交
162 163 164 165 166 167

      if (std::is_same<DeviceContext, platform::CPUDeviceContext>::value) {
        auto &place =
            *ctx.template device_context<DeviceContext>().eigen_device();
        auto lr_value = lr_tensor.data<T>()[0];

168 169 170 171
        auto p = framework::EigenVector<T>::Flatten(p_tensor);
        auto ms = framework::EigenVector<T>::Flatten(ms_tensor);
        auto g = framework::EigenVector<T>::Flatten(grad_tensor);
        auto mom = framework::EigenVector<T>::Flatten(mom_tensor);
S
sneaxiy 已提交
172

173 174 175
        auto p_out = framework::EigenVector<T>::Flatten(*param_out);
        auto mom_out = framework::EigenVector<T>::Flatten(*moment_out);
        auto ms_out = framework::EigenVector<T>::Flatten(*mean_square_out);
S
sneaxiy 已提交
176 177 178

        ms_out.device(place) = rho * ms + (1 - rho) * g * g;
        if (centered) {
S
sneaxiy 已提交
179
          auto &mg_tensor = *ctx.Input<LoDTensor>("MeanGrad");
180
          auto mg = framework::EigenVector<T>::Flatten(mg_tensor);
S
sneaxiy 已提交
181
          auto *mean_grad_out = ctx.Output<LoDTensor>("MeanGradOut");
C
Chengmo 已提交
182 183 184 185
          PADDLE_ENFORCE_EQ(
              &mg_tensor, mean_grad_out,
              platform::errors::InvalidArgument(
                  "MeanGrad and MeanGradOut must be the same Tensor"));
186
          auto mg_out = framework::EigenVector<T>::Flatten(*mean_grad_out);
S
sneaxiy 已提交
187 188 189 190 191 192 193 194 195 196 197 198 199 200

          mg_out.device(place) = rho * mg + (1 - rho) * g;
          mom_out.device(place) =
              momentum * mom +
              lr_value * g / (ms_out - mg_out.square() + epsilon).sqrt();
        } else {
          mom_out.device(place) =
              momentum * mom + lr_value * g / (ms_out + epsilon).sqrt();
        }
        p_out.device(place) = p - mom_out;
      } else {
        DenseRmspropGradFunctor<T> grad_func(grad_tensor.data<T>());
        platform::ForRange<DeviceContext> for_range(dev_ctx, limit);
        if (centered) {
S
sneaxiy 已提交
201 202
          auto &mg_tensor = *ctx.Input<LoDTensor>("MeanGrad");
          auto *mean_grad_out = ctx.Output<LoDTensor>("MeanGradOut");
C
Chengmo 已提交
203 204 205 206
          PADDLE_ENFORCE_EQ(
              &mg_tensor, mean_grad_out,
              platform::errors::InvalidArgument(
                  "MeanGrad and MeanGradOut must be the same Tensor"));
S
sneaxiy 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220
          for_range(CenteredRmspropFunctor<T, DenseRmspropGradFunctor<T>>(
              param_out->mutable_data<T>(ctx.GetPlace()),
              mean_square_out->mutable_data<T>(ctx.GetPlace()),
              moment_out->mutable_data<T>(ctx.GetPlace()),
              mean_grad_out->mutable_data<T>(ctx.GetPlace()),
              lr_tensor.data<T>(), rho, epsilon, momentum, grad_func));
        } else {
          for_range(UncenteredRmspropFunctor<T, DenseRmspropGradFunctor<T>>(
              param_out->mutable_data<T>(ctx.GetPlace()),
              mean_square_out->mutable_data<T>(ctx.GetPlace()),
              moment_out->mutable_data<T>(ctx.GetPlace()), lr_tensor.data<T>(),
              rho, epsilon, momentum, grad_func));
        }
      }
221 222 223 224
    } else if (grad_var->IsType<pten::SelectedRows>()) {
      auto &grad = grad_var->Get<pten::SelectedRows>();
      pten::SelectedRows tmp_merged_grad;
      pten::SelectedRows *merged_grad = &tmp_merged_grad;
S
sneaxiy 已提交
225 226 227 228
      math::scatter::MergeAdd<DeviceContext, T> merge_func;
      merge_func(dev_ctx, grad, merged_grad);

      platform::ForRange<DeviceContext> for_range(dev_ctx, limit);
S
sneaxiy 已提交
229 230
      const int64_t *rows = merged_grad->rows().Data(ctx.GetPlace());

S
sneaxiy 已提交
231 232 233 234 235
      auto &merged_tensor = merged_grad->value();
      int64_t row_count = merged_grad->rows().size();
      int64_t row_numel = merged_tensor.numel() / row_count;
      SparseRmspropGradFunctor<T> grad_func(merged_tensor.data<T>(), rows,
                                            row_numel, row_count);
236

S
sneaxiy 已提交
237
      if (centered) {
S
sneaxiy 已提交
238 239
        auto &mg_tensor = *ctx.Input<LoDTensor>("MeanGrad");
        auto *mean_grad_out = ctx.Output<LoDTensor>("MeanGradOut");
C
Chengmo 已提交
240 241 242 243
        PADDLE_ENFORCE_EQ(
            &mg_tensor, mean_grad_out,
            platform::errors::InvalidArgument(
                "MeanGrad and MeanGradOut must be the same Tensor"));
S
sneaxiy 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256
        for_range(CenteredRmspropFunctor<T, SparseRmspropGradFunctor<T>>(
            param_out->mutable_data<T>(ctx.GetPlace()),
            mean_square_out->mutable_data<T>(ctx.GetPlace()),
            moment_out->mutable_data<T>(ctx.GetPlace()),
            mean_grad_out->mutable_data<T>(ctx.GetPlace()), lr_tensor.data<T>(),
            rho, epsilon, momentum, grad_func));
      } else {
        for_range(UncenteredRmspropFunctor<T, SparseRmspropGradFunctor<T>>(
            param_out->mutable_data<T>(ctx.GetPlace()),
            mean_square_out->mutable_data<T>(ctx.GetPlace()),
            moment_out->mutable_data<T>(ctx.GetPlace()), lr_tensor.data<T>(),
            rho, epsilon, momentum, grad_func));
      }
257
    } else {
C
Chengmo 已提交
258 259 260 261 262 263
      PADDLE_ENFORCE_EQ(false, true,
                        platform::errors::PermissionDenied(
                            "Unsupported Variable Type of Grad "
                            "in RmspropOp. Excepted LodTensor "
                            "or SelectedRows, But received [%s]",
                            paddle::framework::ToTypeName(grad_var->Type())));
264
    }
265 266 267 268 269
  }
};

}  // namespace operators
}  // namespace paddle