|
| 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 | + |
| 15 | +#include <memory> |
| 16 | +#include <string> |
| 17 | + |
| 18 | +#include "paddle/fluid/operators/npu_op_runner.h" |
| 19 | +#include "paddle/fluid/operators/scale_op.h" |
| 20 | + |
| 21 | +namespace paddle { |
| 22 | +namespace operators { |
| 23 | + |
| 24 | +template <typename DeviceContext, typename T> |
| 25 | +class ScaleNPUKernel : public framework::OpKernel<T> { |
| 26 | + public: |
| 27 | + void Compute(const framework::ExecutionContext& ctx) const override { |
| 28 | + auto* x = ctx.Input<framework::Tensor>("X"); |
| 29 | + auto* out = ctx.Output<framework::Tensor>("Out"); |
| 30 | + auto scale = static_cast<float>(ctx.Attr<float>("scale")); |
| 31 | + auto bias = static_cast<float>(ctx.Attr<float>("bias")); |
| 32 | + auto bias_after_scale = ctx.Attr<bool>("bias_after_scale"); |
| 33 | + auto stream = |
| 34 | + ctx.template device_context<paddle::platform::NPUDeviceContext>() |
| 35 | + .stream(); |
| 36 | + float _power = 1.0; |
| 37 | + if (bias_after_scale) { |
| 38 | + out->mutable_data<T>(ctx.GetPlace()); |
| 39 | + auto runner = |
| 40 | + NpuOpRunner("Power", {*x}, {*out}, |
| 41 | + {{"power", _power}, {"scale", scale}, {"shift", bias}}); |
| 42 | + |
| 43 | + runner.Run(stream); |
| 44 | + } else { |
| 45 | + Tensor tmp_x(x->type()); |
| 46 | + tmp_x.Resize(x->dims()); |
| 47 | + tmp_x.mutable_data<T>(ctx.GetPlace()); |
| 48 | + auto runner_tmp = NpuOpRunner("Adds", {*x}, {tmp_x}, {{"value", bias}}); |
| 49 | + runner_tmp.Run(stream); |
| 50 | + |
| 51 | + out->mutable_data<T>(ctx.GetPlace()); |
| 52 | + float _bias = 0.0; |
| 53 | + auto runner = |
| 54 | + NpuOpRunner("Power", {tmp_x}, {*out}, |
| 55 | + {{"power", _power}, {"scale", scale}, {"shift", _bias}}); |
| 56 | + runner.Run(stream); |
| 57 | + } |
| 58 | + } |
| 59 | +}; |
| 60 | + |
| 61 | +} // namespace operators |
| 62 | +} // namespace paddle |
| 63 | + |
| 64 | +namespace ops = paddle::operators; |
| 65 | + |
| 66 | +REGISTER_OP_NPU_KERNEL( |
| 67 | + scale, ops::ScaleNPUKernel<paddle::platform::NPUDeviceContext, float>, |
| 68 | + ops::ScaleNPUKernel<paddle::platform::NPUDeviceContext, |
| 69 | + paddle::platform::float16>); |
0 commit comments