|
| 1 | +/* Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved. |
| 2 | +
|
| 3 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +you may not use this file except in compliance with the License. |
| 5 | +You may obtain a copy of the License at |
| 6 | +
|
| 7 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +
|
| 9 | +Unless required by applicable law or agreed to in writing, software |
| 10 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +See the License for the specific language governing permissions and |
| 13 | +limitations under the License. */ |
| 14 | +#include <string> |
| 15 | +#include "paddle/fluid/operators/npu_op_runner.h" |
| 16 | +#include "paddle/fluid/operators/optimizers/sgd_op.h" |
| 17 | + |
| 18 | +namespace paddle { |
| 19 | +namespace operators { |
| 20 | + |
| 21 | +template <typename T> |
| 22 | +class NPUMomentumOpKernel : public framework::OpKernel<T> { |
| 23 | + public: |
| 24 | + void Compute(const framework::ExecutionContext& ctx) const override { |
| 25 | + auto& dev_ctx = ctx.template device_context<platform::NPUDeviceContext>(); |
| 26 | + |
| 27 | + auto param = ctx.Input<framework::Tensor>("Param"); |
| 28 | + auto velocity = ctx.Input<framework::Tensor>("Velocity"); |
| 29 | + auto learning_rate = ctx.Input<framework::Tensor>("LearningRate"); |
| 30 | + auto grad = ctx.Input<framework::Tensor>("Grad"); |
| 31 | + auto param_out = ctx.Output<framework::Tensor>("ParamOut"); |
| 32 | + auto velocity_out = ctx.Output<framework::Tensor>("VelocityOut"); |
| 33 | + param_out->mutable_data<T>(ctx.GetPlace()); |
| 34 | + velocity_out->mutable_data<T>(ctx.GetPlace()); |
| 35 | + |
| 36 | + T mu = static_cast<T>(ctx.Attr<float>("mu")); |
| 37 | + bool use_nesterov = ctx.Attr<bool>("use_nesterov"); |
| 38 | + |
| 39 | + Tensor mu_tensor; |
| 40 | + mu_tensor.mutable_data<T>(framework::make_ddim({1}), ctx.GetPlace()); |
| 41 | + FillNpuTensorWithConstant<T>(&mu_tensor, mu); |
| 42 | + framework::TensorCopy(*param, ctx.GetPlace(), dev_ctx, param_out); |
| 43 | + framework::TensorCopy(*velocity, ctx.GetPlace(), dev_ctx, velocity_out); |
| 44 | + const auto& runner = NpuOpRunner( |
| 45 | + "ApplyMomentum", |
| 46 | + {*param_out, *velocity_out, *learning_rate, *grad, mu_tensor}, |
| 47 | + {*param_out}, {{"use_nesterov", use_nesterov}}); |
| 48 | + auto stream = dev_ctx.stream(); |
| 49 | + runner.Run(stream); |
| 50 | + } |
| 51 | +}; |
| 52 | +} // namespace operators |
| 53 | +} // namespace paddle |
| 54 | + |
| 55 | +namespace ops = paddle::operators; |
| 56 | +REGISTER_OP_NPU_KERNEL(momentum, ops::NPUMomentumOpKernel<float>); |
0 commit comments