p_norm_op_npu.cc 7.1 KB
Newer Older
R
ronnywang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/* Copyright (c) 2021 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. */

15
#include "paddle/fluid/framework/op_registry.h"
16
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
R
ronnywang 已提交
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 55 56

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class PnormNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* in_x = ctx.Input<framework::Tensor>("X");
    auto* out_norm = ctx.Output<framework::Tensor>("Out");
    out_norm->mutable_data<T>(ctx.GetPlace());

    float porder = ctx.Attr<float>("porder");
    int axis = ctx.Attr<int>("axis");
    bool keepdim = ctx.Attr<bool>("keepdim");

    auto xdim = in_x->dims();
    if (axis < 0) axis = xdim.size() + axis;

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

    int p = 0;
    bool combine_op =
        !(porder == 0 || porder == INFINITY || porder == -INFINITY);
    if (porder == INFINITY) {
      p = INT_MAX;
    } else if (porder == -INFINITY) {
      p = INT_MIN;
    } else {
      p = static_cast<int>(porder);
      float t = 0;
      float diff = abs(std::modf(porder, &t));
      if (diff < 1e-5) {
        combine_op = false;
      }
    }

    if (!combine_op) {
57 58 59
      const auto& runner = NpuOpRunner("LpNorm",
                                       {*in_x},
                                       {*out_norm},
R
ronnywang 已提交
60 61 62 63 64 65 66 67 68
                                       {{"p", p},
                                        {"axes", std::vector<int32_t>({axis})},
                                        {"keep_dims", keepdim}});
      runner.Run(stream);
    } else {
      Tensor tmp_x;
      tmp_x.mutable_data<T>(xdim, ctx.GetPlace());

      const auto& power_runner1 =
69 70 71
          NpuOpRunner("Power",
                      {*in_x},
                      {tmp_x},
R
ronnywang 已提交
72 73 74 75
                      {{"power", porder}, {"scale", 1.0f}, {"shift", 0.0f}});
      power_runner1.Run(stream);

      const auto& reduce_runner = NpuOpRunner(
76 77 78
          "ReduceSumD",
          {tmp_x},
          {*out_norm},
R
ronnywang 已提交
79 80 81 82
          {{"axes", std::vector<int32_t>({axis})}, {"keep_dims", keepdim}});
      reduce_runner.Run(stream);

      const auto& power_runner2 = NpuOpRunner(
83 84 85
          "Power",
          {*out_norm},
          {*out_norm},
R
ronnywang 已提交
86 87 88 89 90 91
          {{"power", 1 / porder}, {"scale", 1.0f}, {"shift", 0.0f}});
      power_runner2.Run(stream);
    }
  }
};

Z
zhulei 已提交
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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
template <typename DeviceContext, typename T>
class PnormGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    using Tensor = framework::Tensor;
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Input<Tensor>("Out");
    auto* dy = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));

    auto place = ctx.GetPlace();
    dx->mutable_data<T>(place);

    auto xdim = x->dims();
    float porder = ctx.Attr<float>("porder");
    bool keepdim = ctx.Attr<bool>("keepdim");

    int axis = ctx.Attr<int>("axis");
    axis = axis < 0 ? xdim.size() + axis : axis;

    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();

    Tensor y_share(y->type());
    Tensor dy_share(dy->type());
    y_share.ShareDataWith(*y);
    dy_share.ShareDataWith(*dy);
    auto ydim = xdim;
    if (!keepdim) {
      ydim[axis] = 1;
    } else {
      ydim = y->dims();
    }
    y_share.Resize(ydim);
    dy_share.Resize(ydim);

    if (porder == 0) {
      FillNpuTensorWithConstant(dx, static_cast<T>(0));
      dx->Resize(xdim);
    } else if (porder == INFINITY || porder == -INFINITY) {
      Tensor x_abs;
      x_abs.mutable_data<T>(xdim, place);
      const auto& r_abs = NpuOpRunner("Abs", {*x}, {x_abs}, {});
      r_abs.Run(stream);

      Tensor t_cond;
      t_cond.mutable_data<bool>(xdim, place);
      const auto& r_equal =
          NpuOpRunner("Equal", {x_abs, y_share}, {t_cond}, {});
      r_equal.Run(stream);

      Tensor t_zero;
      t_zero.mutable_data<T>({1}, place);
      FillNpuTensorWithConstant(&t_zero, static_cast<T>(0));

      Tensor x_sign;
      x_sign.mutable_data<T>(xdim, place);
      const auto& r_sign = NpuOpRunner("Sign", {*x}, {x_sign}, {});
      r_sign.Run(stream);

      const auto& r_mul = NpuOpRunner("Mul", {x_sign, dy_share}, {*dx}, {});
      r_mul.Run(stream);

      const auto& r_sel =
          NpuOpRunner("SelectV2", {t_cond, *dx, t_zero}, {*dx}, {});
      r_sel.Run(stream);
    } else {
      Tensor x_abs;
      x_abs.mutable_data<T>(xdim, place);
      const auto& r_abs = NpuOpRunner("Abs", {*x}, {x_abs}, {});
      r_abs.Run(stream);

      Tensor x_sign;
      x_sign.mutable_data<T>(xdim, place);
      const auto& r_sign = NpuOpRunner("Sign", {*x}, {x_sign}, {});
      r_sign.Run(stream);

      Tensor y_pow;
      y_pow.mutable_data<T>(ydim, place);
      if (porder >= 1) {
        const auto& r_pow1 = NpuOpRunner(
174 175 176
            "Power",
            {x_abs},
            {x_abs},
Z
zhulei 已提交
177 178 179 180
            {{"power", (porder - 1)}, {"scale", 1.0f}, {"shift", 0.0f}});
        r_pow1.Run(stream);

        const auto& r_pow2 = NpuOpRunner(
181 182 183
            "Power",
            {y_share},
            {y_pow},
Z
zhulei 已提交
184 185 186 187 188 189 190
            {{"power", (porder - 1)}, {"scale", 1.0f}, {"shift", 0.0f}});
        r_pow2.Run(stream);

        const auto& r_div = NpuOpRunner("DivNoNan", {x_abs, y_pow}, {*dx}, {});
        r_div.Run(stream);
      } else {
        const auto& r_pow1 = NpuOpRunner(
191 192 193
            "Power",
            {x_abs},
            {x_abs},
Z
zhulei 已提交
194 195 196 197
            {{"power", (1 - porder)}, {"scale", 1.0f}, {"shift", 0.0f}});
        r_pow1.Run(stream);

        const auto& r_pow2 = NpuOpRunner(
198 199 200
            "Power",
            {y_share},
            {y_pow},
Z
zhulei 已提交
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            {{"power", (1 - porder)}, {"scale", 1.0f}, {"shift", 0.0f}});
        r_pow2.Run(stream);

        const auto& r_div = NpuOpRunner("DivNoNan", {y_pow, x_abs}, {*dx}, {});
        r_div.Run(stream);
      }

      const auto& r_mul1 = NpuOpRunner("Mul", {*dx, x_sign}, {*dx}, {});
      r_mul1.Run(stream);

      const auto& r_mul2 = NpuOpRunner("Mul", {*dx, dy_share}, {*dx}, {});
      r_mul2.Run(stream);
    }
  }
};
R
ronnywang 已提交
216 217 218 219 220 221 222
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
namespace plat = paddle::platform;

REGISTER_OP_NPU_KERNEL(
223 224
    p_norm,
    ops::PnormNPUKernel<plat::NPUDeviceContext, float>,
R
ronnywang 已提交
225
    ops::PnormNPUKernel<plat::NPUDeviceContext, plat::float16>);
Z
zhulei 已提交
226 227

REGISTER_OP_NPU_KERNEL(
228 229
    p_norm_grad,
    ops::PnormGradNPUKernel<plat::NPUDeviceContext, float>,
Z
zhulei 已提交
230
    ops::PnormGradNPUKernel<plat::NPUDeviceContext, plat::float16>);