momentum_op.h 16.1 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
S
sidgoyal78 已提交
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 <memory>
D
dzhwinter 已提交
17
#include <string>
Y
Yi Wang 已提交
18 19
#include "paddle/fluid/framework/eigen.h"
#include "paddle/fluid/framework/op_registry.h"
D
dzhwinter 已提交
20 21 22
#include "paddle/fluid/operators/math/algorithm.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/platform/for_range.h"
S
sidgoyal78 已提交
23 24 25 26

namespace paddle {
namespace operators {

D
dzhwinter 已提交
27 28 29 30 31
using framework::Tensor;
using framework::SelectedRows;
struct NoNesterov;
struct UseNesterov;

32 33 34 35 36 37
enum class RegularizationFlag {
  kNONE = 0,
  kL1DECAY = 1,  // do not need support right now
  kL2DECAY = 2,
};

38 39 40 41 42
class MomentumOpMaker : public framework::OpProtoAndCheckerMaker {
 public:
  void Make() override;
};

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
class MomentumOp : public framework::OperatorWithKernel {
 public:
  using framework::OperatorWithKernel::OperatorWithKernel;

 protected:
  void InferShape(framework::InferShapeContext* ctx) const override {
    PADDLE_ENFORCE(ctx->HasInput("Param"),
                   "Input(param) of Momentum should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Grad"),
                   "Input(grad) of Momentum should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("Velocity"),
                   "Input(velocity) of Momentum should not be null.");
    PADDLE_ENFORCE(ctx->HasInput("LearningRate"),
                   "Input(LearningRate) of Momentum should not be null.");
    PADDLE_ENFORCE(
        ctx->GetInputsVarType("Param").front() ==
            framework::proto::VarType::LOD_TENSOR,
        "The input var's type should be LoDTensor, but the received is %s",
        ctx->Inputs("Param").front(), ctx->GetInputsVarType("Param").front());

    PADDLE_ENFORCE(ctx->HasOutput("ParamOut"),
                   "Output(ParamOut) of Momentum should not be null.");
    PADDLE_ENFORCE(ctx->HasOutput("VelocityOut"),
                   "Output(VelocityOut) of Momentum should not be null.");

68 69 70 71 72 73 74 75 76
    auto lr_dims = ctx->GetInputDim("LearningRate");
    PADDLE_ENFORCE_NE(framework::product(lr_dims), 0,
                      "Maybe the Input variable LearningRate has not "
                      "been initialized. You may need to confirm "
                      "if you put exe.run(startup_program) "
                      "after optimizer.minimize function.");
    PADDLE_ENFORCE_EQ(framework::product(lr_dims), 1,
                      "Learning_rate should be a scalar");

77 78 79 80 81 82 83 84 85 86 87 88 89 90
    auto param_dim = ctx->GetInputDim("Param");
    if (ctx->GetInputsVarType("Grad")[0] ==
        framework::proto::VarType::LOD_TENSOR) {
      PADDLE_ENFORCE_EQ(
          param_dim, ctx->GetInputDim("Grad"),
          "Param and Grad input of MomentumOp should have the same dimension.");
      PADDLE_ENFORCE_EQ(
          param_dim, ctx->GetInputDim("Velocity"),
          "Param and Velocity of MomentumOp should have the same dimension.");
    }

    ctx->SetOutputDim("ParamOut", param_dim);
    ctx->SetOutputDim("VelocityOut", param_dim);
  }
S
sneaxiy 已提交
91

92 93
  framework::OpKernelType GetExpectedKernelType(
      const framework::ExecutionContext& ctx) const override {
94 95
    auto input_data_type =
        OperatorWithKernel::IndicateVarDataType(ctx, "Param");
96 97 98 99
    return framework::OpKernelType(input_data_type, ctx.GetPlace());
  }
};

D
dzhwinter 已提交
100 101 102 103 104 105 106 107 108
template <typename T>
class CPUDenseMomentumFunctor {
 private:
  const Tensor* param;
  const Tensor* grad;
  const Tensor* velocity;
  const Tensor* learning_rate;
  const T mu;
  const T use_nesterov;
109 110
  const RegularizationFlag regularization_flag;
  const T regularization_coeff;
D
dzhwinter 已提交
111 112 113 114 115 116 117
  Tensor* param_out;
  Tensor* velocity_out;

 public:
  CPUDenseMomentumFunctor(const Tensor* param, const Tensor* grad,
                          const Tensor* velocity, const Tensor* learning_rate,
                          const T mu, const bool use_nesterov,
118 119 120
                          const RegularizationFlag regularization_flag,
                          const T regularization_coeff, Tensor* param_out,
                          Tensor* velocity_out)
D
dzhwinter 已提交
121 122 123 124 125 126
      : param(param),
        grad(grad),
        velocity(velocity),
        learning_rate(learning_rate),
        mu(mu),
        use_nesterov(use_nesterov),
127 128
        regularization_flag(regularization_flag),
        regularization_coeff(regularization_coeff),
D
dzhwinter 已提交
129 130 131 132 133 134 135 136 137 138 139 140
        param_out(param_out),
        velocity_out(velocity_out) {}

  inline void operator()() {
    auto p_out = framework::EigenVector<T>::Flatten(*param_out);
    auto v_out = framework::EigenVector<T>::Flatten(*velocity_out);

    auto p = framework::EigenVector<T>::Flatten(*param);
    auto v = framework::EigenVector<T>::Flatten(*velocity);
    auto g = framework::EigenVector<T>::Flatten(*grad);
    auto* lr = learning_rate->data<T>();

141 142 143 144 145 146 147
    if (regularization_flag == RegularizationFlag::kL2DECAY) {
      v_out = v * mu + p * regularization_coeff + g;
      if (use_nesterov) {
        p_out = p - (p * regularization_coeff + g + v_out * mu) * lr[0];
      } else {
        p_out = p - lr[0] * v_out;
      }
D
dzhwinter 已提交
148
    } else {
149 150 151 152 153 154
      v_out = v * mu + g;
      if (use_nesterov) {
        p_out = p - (g + v_out * mu) * lr[0];
      } else {
        p_out = p - lr[0] * v_out;
      }
D
dzhwinter 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
    }
  }
};

template <typename T, typename UpdateMethod>
class DenseMomentumFunctor;

// NOTE(dzh) for performance.
// avoid if/else in inside kernel, implement GPU UseNesterov/NoNesterov as two
// functor.
template <typename T>
class DenseMomentumFunctor<T, UseNesterov> {
 private:
  const T* p_;
  const T* g_;
  const T* v_;
  const T* lr_;
  const T mu_;
  const int64_t num_;
  T* p_out_;
  T* v_out_;
176 177
  const RegularizationFlag regularization_flag;
  const T regularization_coeff;
D
dzhwinter 已提交
178 179 180 181

 public:
  DenseMomentumFunctor(const T* p, const T* g, const T* v,
                       const T* learning_rate, const T mu, const int64_t num,
182 183
                       const RegularizationFlag regularization_flag,
                       const T regularization_coeff, T* p_out, T* v_out)
D
dzhwinter 已提交
184 185 186 187 188 189 190
      : p_(p),
        g_(g),
        v_(v),
        lr_(learning_rate),
        mu_(mu),
        num_(num),
        p_out_(p_out),
191 192 193
        v_out_(v_out),
        regularization_flag(regularization_flag),
        regularization_coeff(regularization_coeff) {}
D
dzhwinter 已提交
194 195 196
  inline HOSTDEVICE void operator()(size_t i) const {
    // put memory access in register
    const T p = p_[i];
197
    T g = g_[i];
D
dzhwinter 已提交
198 199
    const T lr = lr_[0];
    const T v = v_[i];
200 201 202 203 204

    g = regularization_flag == RegularizationFlag::kL2DECAY
            ? g + regularization_coeff * p
            : g;

D
dzhwinter 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    T v_out = v * mu_ + g;
    T p_out = p - (g + v_out * mu_) * lr;
    // write reigster to memory
    v_out_[i] = v_out;
    p_out_[i] = p_out;
  }
};

template <typename T>
class DenseMomentumFunctor<T, NoNesterov> {
 private:
  const T* p_;
  const T* g_;
  const T* v_;
  const T* lr_;
  const T mu_;
  const int64_t num_;
  T* p_out_;
  T* v_out_;
224 225
  const RegularizationFlag regularization_flag;
  const T regularization_coeff;
D
dzhwinter 已提交
226 227 228 229

 public:
  DenseMomentumFunctor(const T* p, const T* g, const T* v,
                       const T* learning_rate, const T mu, const int64_t num,
230 231
                       const RegularizationFlag regularization_flag,
                       const T regularization_coeff, T* p_out, T* v_out)
D
dzhwinter 已提交
232 233 234 235 236 237 238
      : p_(p),
        g_(g),
        v_(v),
        lr_(learning_rate),
        mu_(mu),
        num_(num),
        p_out_(p_out),
239 240 241
        v_out_(v_out),
        regularization_flag(regularization_flag),
        regularization_coeff(regularization_coeff) {}
D
dzhwinter 已提交
242 243 244
  inline HOSTDEVICE void operator()(size_t i) const {
    // put memory access in register
    const T p = p_[i];
245
    T g = g_[i];
D
dzhwinter 已提交
246 247
    const T lr = lr_[0];
    const T v = v_[i];
248 249 250 251 252

    g = regularization_flag == RegularizationFlag::kL2DECAY
            ? g + regularization_coeff * p
            : g;

D
dzhwinter 已提交
253 254 255 256 257 258 259 260 261 262 263
    T v_out = v * mu_ + g;
    T p_out = p - lr * v_out;
    // write reigster to memory
    v_out_[i] = v_out;
    p_out_[i] = p_out;
  }
};

template <typename T, typename UpdateMethod>
class SparseMomentumFunctor;

264
template <typename T>
D
dzhwinter 已提交
265 266 267 268 269 270 271 272 273 274 275 276
class SparseMomentumFunctor<T, UseNesterov> {
 private:
  const T* p_;
  const T* g_;
  const T* v_;
  const T* lr_;
  const T mu_;
  const int64_t* rows_;
  const int64_t row_numel_;
  const int64_t row_height_;
  T* p_out_;
  T* v_out_;
277 278
  const RegularizationFlag regularization_flag;
  const T regularization_coeff;
D
dzhwinter 已提交
279 280 281 282

 public:
  SparseMomentumFunctor(const T* p, const T* g, const T* v, const T* lr,
                        const T mu, const int64_t* rows, int64_t row_numel,
283 284 285
                        int64_t row_height,
                        const RegularizationFlag regularization_flag,
                        const T regularization_coeff, T* p_out, T* v_out)
D
dzhwinter 已提交
286 287 288 289 290 291 292 293 294
      : p_(p),
        g_(g),
        v_(v),
        lr_(lr),
        mu_(mu),
        rows_(rows),
        row_numel_(row_numel),
        row_height_(row_height),
        p_out_(p_out),
295 296 297
        v_out_(v_out),
        regularization_flag(regularization_flag),
        regularization_coeff(regularization_coeff) {}
D
dzhwinter 已提交
298 299 300 301

  inline HOSTDEVICE void operator()(size_t i) {
    auto row_idx =
        math::BinarySearch<int64_t>(rows_, row_height_, i / row_numel_);
302 303
    T g = row_idx >= 0 ? g_[row_idx * row_numel_ + i % row_numel_]
                       : static_cast<T>(0);
D
dzhwinter 已提交
304 305 306 307
    // put memory access in register
    const T p = p_[i];
    const T lr = lr_[0];
    const T v = v_[i];
308 309 310 311 312

    g = regularization_flag == RegularizationFlag::kL2DECAY
            ? g + regularization_coeff * p
            : g;

D
dzhwinter 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
    T v_out = v * mu_ + g;
    T p_out = p - (g + v_out * mu_) * lr;
    // write reigster to memory
    v_out_[i] = v_out;
    p_out_[i] = p_out;
  }
};

template <typename T>
class SparseMomentumFunctor<T, NoNesterov> {
 private:
  const T* p_;
  const T* g_;
  const T* v_;
  const T* lr_;
  const T mu_;
  const int64_t* rows_;
  const int64_t row_numel_;
  const int64_t row_height_;
  T* p_out_;
  T* v_out_;
334 335
  const RegularizationFlag regularization_flag;
  const T regularization_coeff;
D
dzhwinter 已提交
336 337 338 339

 public:
  SparseMomentumFunctor(const T* p, const T* g, const T* v, const T* lr,
                        const T mu, const int64_t* rows, int64_t row_numel,
340 341 342
                        int64_t row_height,
                        const RegularizationFlag regularization_flag,
                        const T regularization_coeff, T* p_out, T* v_out)
D
dzhwinter 已提交
343 344 345 346 347 348 349 350 351
      : p_(p),
        g_(g),
        v_(v),
        lr_(lr),
        mu_(mu),
        rows_(rows),
        row_numel_(row_numel),
        row_height_(row_height),
        p_out_(p_out),
352 353 354
        v_out_(v_out),
        regularization_flag(regularization_flag),
        regularization_coeff(regularization_coeff) {}
D
dzhwinter 已提交
355 356 357 358

  inline HOSTDEVICE void operator()(size_t i) {
    auto row_idx =
        math::BinarySearch<int64_t>(rows_, row_height_, i / row_numel_);
359 360
    T g = row_idx >= 0 ? g_[row_idx * row_numel_ + i % row_numel_]
                       : static_cast<T>(0);
D
dzhwinter 已提交
361 362 363 364
    // put memory access in register
    const T p = p_[i];
    const T lr = lr_[0];
    const T v = v_[i];
365 366 367 368 369

    g = regularization_flag == RegularizationFlag::kL2DECAY
            ? g + regularization_coeff * p
            : g;

D
dzhwinter 已提交
370 371 372 373 374 375 376 377 378
    T v_out = v * mu_ + g;
    T p_out = p - v_out * lr;
    // write reigster to memory
    v_out_[i] = v_out;
    p_out_[i] = p_out;
  }
};

template <typename DeviceContext, typename T>
S
sidgoyal78 已提交
379 380 381
class MomentumOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
382 383 384 385 386 387 388 389 390 391
    std::string regularization_method =
        ctx.Attr<std::string>("regularization_method");
    T regularization_coeff =
        static_cast<T>(ctx.Attr<float>("regularization_coeff"));
    RegularizationFlag regularization_flag{
        RegularizationFlag::kNONE};  // disable regularization
    if (regularization_method == "l2_decay") {
      regularization_flag = RegularizationFlag::kL2DECAY;
    }

392
    T mu = static_cast<T>(ctx.Attr<float>("mu"));
393
    bool use_nesterov = ctx.Attr<bool>("use_nesterov");
S
sidgoyal78 已提交
394

395 396 397
    auto learning_rate = ctx.Input<framework::Tensor>("LearningRate");
    auto param = ctx.Input<framework::Tensor>("Param");
    auto param_out = ctx.Output<framework::Tensor>("ParamOut");
D
dzhwinter 已提交
398 399
    auto* velocity = ctx.Input<framework::Tensor>("Velocity");
    auto velocity_out = ctx.Output<framework::Tensor>("VelocityOut");
400

D
dzhwinter 已提交
401 402 403
    param_out->mutable_data<T>(ctx.GetPlace());
    velocity_out->mutable_data<T>(ctx.GetPlace());

404 405 406
    auto* grad_var = ctx.InputVar("Grad");
    if (grad_var->IsType<framework::LoDTensor>()) {
      auto grad = ctx.Input<framework::Tensor>("Grad");
D
dzhwinter 已提交
407
      if (platform::is_cpu_place(ctx.GetPlace())) {
408 409 410
        CPUDenseMomentumFunctor<T> functor(
            param, grad, velocity, learning_rate, mu, use_nesterov,
            regularization_flag, regularization_coeff, param_out, velocity_out);
D
dzhwinter 已提交
411 412 413 414 415 416 417 418
        functor();
      } else if (platform::is_gpu_place(ctx.GetPlace())) {
        platform::ForRange<DeviceContext> for_range(
            static_cast<const DeviceContext&>(ctx.device_context()),
            param->numel());
        if (use_nesterov) {
          DenseMomentumFunctor<T, UseNesterov> functor(
              param->data<T>(), grad->data<T>(), velocity->data<T>(),
419 420
              learning_rate->data<T>(), mu, param->numel(), regularization_flag,
              regularization_coeff, param_out->mutable_data<T>(ctx.GetPlace()),
D
dzhwinter 已提交
421 422 423 424 425 426
              velocity_out->mutable_data<T>(ctx.GetPlace()));
          for_range(functor);

        } else {
          DenseMomentumFunctor<T, NoNesterov> functor(
              param->data<T>(), grad->data<T>(), velocity->data<T>(),
427 428
              learning_rate->data<T>(), mu, param->numel(), regularization_flag,
              regularization_coeff, param_out->mutable_data<T>(ctx.GetPlace()),
D
dzhwinter 已提交
429 430 431
              velocity_out->mutable_data<T>(ctx.GetPlace()));
          for_range(functor);
        }
432
      }
D
dzhwinter 已提交
433

434 435 436
    } else if (grad_var->IsType<framework::SelectedRows>()) {
      // sparse update embedding with selectedrows
      auto grad = ctx.Input<framework::SelectedRows>("Grad");
S
sidgoyal78 已提交
437

438 439
      // sparse update maybe empty.
      if (grad->rows().size() == 0) {
M
minqiyang 已提交
440
        VLOG(3) << "Grad SelectedRows contains no data!";
441 442
        return;
      }
S
sneaxiy 已提交
443 444 445

      framework::SelectedRows tmp_merged_grad;
      framework::SelectedRows* merged_grad = &tmp_merged_grad;
D
dzhwinter 已提交
446 447 448 449
      math::scatter::MergeAdd<DeviceContext, T> merge_func;
      merge_func(ctx.template device_context<DeviceContext>(), *grad,
                 merged_grad);

S
sneaxiy 已提交
450
      const int64_t* rows = merged_grad->rows().Data(ctx.GetPlace());
D
dzhwinter 已提交
451 452 453 454 455
      int64_t row_numel =
          merged_grad->value().numel() / merged_grad->rows().size();
      platform::ForRange<DeviceContext> for_range(
          static_cast<const DeviceContext&>(ctx.device_context()),
          param->numel());
D
dzhwinter 已提交
456 457 458
      if (use_nesterov) {
        SparseMomentumFunctor<T, UseNesterov> functor(
            param->data<T>(), merged_grad->value().data<T>(),
D
dzhwinter 已提交
459
            velocity->data<T>(), learning_rate->data<T>(), mu, rows, row_numel,
D
dzhwinter 已提交
460
            static_cast<int64_t>(merged_grad->rows().size()),
461
            regularization_flag, regularization_coeff,
D
dzhwinter 已提交
462 463 464 465 466 467 468
            param_out->mutable_data<T>(ctx.GetPlace()),
            velocity_out->mutable_data<T>(ctx.GetPlace()));
        for_range(functor);

      } else {
        SparseMomentumFunctor<T, NoNesterov> functor(
            param->data<T>(), merged_grad->value().data<T>(),
D
dzhwinter 已提交
469
            velocity->data<T>(), learning_rate->data<T>(), mu, rows, row_numel,
D
dzhwinter 已提交
470
            static_cast<int64_t>(merged_grad->rows().size()),
471
            regularization_flag, regularization_coeff,
D
dzhwinter 已提交
472 473 474
            param_out->mutable_data<T>(ctx.GetPlace()),
            velocity_out->mutable_data<T>(ctx.GetPlace()));
        for_range(functor);
475
      }
K
kavyasrinet 已提交
476
    } else {
D
dzhwinter 已提交
477 478 479
      PADDLE_THROW(
          string::Sprintf("MomentumOp only supports LoDTensor or SelectedRows "
                          "gradient, but the received Variable Type is %s",
S
sneaxiy 已提交
480
                          framework::ToTypeName(grad_var->Type())));
K
kavyasrinet 已提交
481
    }
S
sidgoyal78 已提交
482 483 484 485 486
  }
};

}  // namespace operators
}  // namespace paddle