momentum_op_mlu.cc 4.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 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
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.

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. */

#include "paddle/fluid/operators/optimizers/momentum_op.h"
#include "paddle/fluid/operators/mlu/mlu_baseop.h"

namespace paddle {
namespace operators {

template <typename T>
class MLUMomentumOpKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto& dev_ctx = ctx.template device_context<platform::MLUDeviceContext>();

    std::string regularization_method =
        ctx.Attr<std::string>("regularization_method");
    auto regularization_coeff = ctx.Attr<float>("regularization_coeff");
    RegularizationType regularization_flag{
        RegularizationType::kNONE};  // disable regularization
    if (regularization_method == "l2_decay") {
      regularization_flag = RegularizationType::kL2DECAY;
    }

    T mu = static_cast<T>(ctx.Attr<float>("mu"));
    bool use_nesterov = ctx.Attr<bool>("use_nesterov");

    auto learning_rate = ctx.Input<framework::Tensor>("LearningRate");
    auto param = ctx.Input<framework::Tensor>("Param");
    auto velocity = ctx.Input<framework::Tensor>("Velocity");

    auto param_out = ctx.Output<framework::Tensor>("ParamOut");
    auto velocity_out = ctx.Output<framework::Tensor>("VelocityOut");

    param_out->mutable_data<T>(ctx.GetPlace());
    velocity_out->mutable_data<T>(ctx.GetPlace());

    auto* grad_var = ctx.InputVar("Grad");
    if (grad_var->IsType<framework::LoDTensor>()) {
      auto grad = ctx.Input<framework::Tensor>("Grad");
      Tensor mu_tensor =
          ctx.AllocateTmpTensor<T, MLUDeviceContext>({1}, dev_ctx);
      MLUCnnlTensorDesc mu_tensor_desc(mu_tensor);
55 56
      MLUCnnl::Fill(ctx, CNNL_POINTER_MODE_HOST, &mu, mu_tensor_desc.get(),
                    GetBasePtr(&mu_tensor));
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77

      Tensor regularized_grad;
      MLUCnnlTensorDesc param_desc(*param);
      if (regularization_flag == RegularizationType::kL2DECAY) {
        regularized_grad =
            ctx.AllocateTmpTensor<T, MLUDeviceContext>(param->dims(), dev_ctx);
        MLUCnnlOpTensorDesc op_tensor_desc(
            CNNL_OP_TENSOR_ADD, ToCnnlDataType<T>(), CNNL_NOT_PROPAGATE_NAN);
        MLUCnnl::OpTensor(ctx, op_tensor_desc.get(), param_desc.get(),
                          GetBasePtr(param), param_desc.get(), GetBasePtr(grad),
                          param_desc.get(), GetBasePtr(&regularized_grad),
                          ToCnnlDataType<T>(), regularization_coeff);
      } else {
        regularized_grad = *grad;
      }
      framework::TensorCopy(*param, ctx.GetPlace(), dev_ctx, param_out);
      framework::TensorCopy(*velocity, ctx.GetPlace(), dev_ctx, velocity_out);
      MLUCnnl::ApplyMomentum(ctx, param_desc.get(),
                             GetBasePtr(&regularized_grad), use_nesterov,
                             GetBasePtr(learning_rate), GetBasePtr(&mu_tensor),
                             GetBasePtr(param_out), GetBasePtr(velocity_out));
78
    } else if (grad_var->IsType<phi::SelectedRows>()) {
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
      PADDLE_ENFORCE_EQ(false, true, platform::errors::PermissionDenied(
                                         "Unsupport SparseMomentum"));
    } else {
      PADDLE_ENFORCE_EQ(false, true,
                        platform::errors::PermissionDenied(
                            "Unsupported Variable Type of Grad "
                            "in MomentumOp. Excepted LodTensor "
                            "or SelectedRows, But received [%s]",
                            paddle::framework::ToTypeName(grad_var->Type())));
    }
  }
};
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;
REGISTER_OP_MLU_KERNEL(momentum, ops::MLUMomentumOpKernel<float>,
                       ops::MLUMomentumOpKernel<plat::float16>);