elementwise_add_op_npu.cc 5.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* 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. */

#include <memory>
#include <string>

18
#include "paddle/fluid/framework/tensor_util.h"
19
#include "paddle/fluid/operators/elementwise/elementwise_npu.h"
20
#include "paddle/fluid/platform/device/npu/npu_op_runner.h"
21 22 23

namespace paddle {
namespace operators {
24
using Tensor = framework::Tensor;
25

26
template <typename T>
27 28 29
class ElementwiseAddNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
30 31
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
32 33 34 35 36
    auto* x = ctx.Input<framework::LoDTensor>("X");
    auto* y = ctx.Input<framework::LoDTensor>("Y");
    auto* out = ctx.Output<framework::LoDTensor>("Out");
    out->mutable_data<T>(ctx.GetPlace());

37 38 39 40 41 42 43
    int axis = ctx.Attr<int>("axis");

    bool direct_compute = false;
    auto x_dims = x->dims();
    auto y_dims = y->dims();
    axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
    if (x_dims.size() >= y_dims.size()) {
44
      direct_compute = x_dims.size() == (y_dims.size() + axis);
45
    } else {
46
      direct_compute = y_dims.size() == (x_dims.size() + axis);
47 48 49
    }

    if (direct_compute) {
50 51
      const auto& runner = NpuOpRunner("Add", {*x, *y}, {*out}, {});
      runner.Run(dev_ctx.stream());
52
    } else {
53
      Tensor transformed_x, transformed_y;
54 55
      NpuElementWiseOpBroadcast<T>(dev_ctx, x, y, axis, &transformed_x,
                                   &transformed_y);
56 57 58
      const auto& runner =
          NpuOpRunner("Add", {transformed_x, transformed_y}, {*out}, {});
      runner.Run(dev_ctx.stream());
59
    }
60 61 62
  }
};

63 64 65 66
template <typename T>
class ElementwiseAddGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
67 68 69 70 71 72 73 74 75 76 77
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::NPUDeviceContext>();
    auto* x = ctx.Input<framework::Tensor>("X");
    auto* y = ctx.Input<framework::Tensor>("Y");
    auto* dout = ctx.Input<framework::Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<framework::Tensor>(framework::GradVarName("X"));
    auto* dy = ctx.Output<framework::Tensor>(framework::GradVarName("Y"));
    int axis = ctx.Attr<int>("axis");

    axis = (axis == -1 ? std::abs(x->dims().size() - y->dims().size()) : axis);
    auto stream = dev_ctx.stream();
78 79
    if (dx) {
      dx->mutable_data<T>(ctx.GetPlace());
80 81 82 83 84 85 86 87 88 89 90 91 92 93
      if (dx->dims() != dout->dims()) {
        std::vector<int> dst_dims_vec;
        std::vector<int> reduce_axes;
        auto src_dims = dx->dims();
        auto dout_dims = dout->dims();

        int src_axis = (src_dims.size() < dout_dims.size() ? axis : 0);
        for (int ax = 0; ax < dout_dims.size(); ++ax) {
          if ((ax < src_axis || ax >= src_axis + src_dims.size()) ||
              (dout_dims[ax] > 1 && src_dims[ax - src_axis] == 1)) {
            reduce_axes.push_back(ax);
          } else {
            dst_dims_vec.push_back(dout_dims[ax]);
          }
94
        }
95 96 97
        if (!reduce_axes.empty()) {
          Tensor tmp;
          tmp.ShareDataWith(*dx);
98
          tmp.Resize(phi::make_ddim(dst_dims_vec));
99 100 101 102
          const auto& runner =
              NpuOpRunner("ReduceSumD", {*dout}, {tmp},
                          {{"axes", reduce_axes}, {"keep_dims", false}});
          runner.Run(stream);
103 104
        }
      } else {
105
        framework::TensorCopy(*dout, ctx.GetPlace(), dev_ctx, dx);
106 107 108
      }
    }
    if (dy) {
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
      dy->mutable_data<T>(ctx.GetPlace());
      if (dy->dims() != dout->dims()) {
        std::vector<int> dst_dims_vec;
        std::vector<int> reduce_axes;
        auto src_dims = dy->dims();
        auto dout_dims = dout->dims();

        int src_axis = (src_dims.size() < dout_dims.size() ? axis : 0);
        for (int ax = 0; ax < dout_dims.size(); ++ax) {
          if ((ax < src_axis || ax >= src_axis + src_dims.size()) ||
              (dout_dims[ax] > 1 && src_dims[ax - src_axis] == 1)) {
            reduce_axes.push_back(ax);
          } else {
            dst_dims_vec.push_back(dout_dims[ax]);
          }
124
        }
125 126 127
        if (!reduce_axes.empty()) {
          Tensor tmp;
          tmp.ShareDataWith(*dy);
128
          tmp.Resize(phi::make_ddim(dst_dims_vec));
129 130 131 132
          const auto& runner =
              NpuOpRunner("ReduceSumD", {*dout}, {tmp},
                          {{"axes", reduce_axes}, {"keep_dims", false}});
          runner.Run(stream);
133 134
        }
      } else {
135
        framework::TensorCopy(*dout, ctx.GetPlace(), dev_ctx, dy);
136 137 138 139 140
      }
    }
  }
};

141 142 143 144
}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;
145 146 147
namespace plat = paddle::platform;

REGISTER_OP_NPU_KERNEL(elementwise_add, ops::ElementwiseAddNPUKernel<float>,
148 149 150
#ifdef PADDLE_WITH_ASCEND_INT64
                       ops::ElementwiseAddNPUKernel<int64_t>,
#endif
151
                       ops::ElementwiseAddNPUKernel<plat::float16>);
152

153 154 155
REGISTER_OP_NPU_KERNEL(elementwise_add_grad,
                       ops::ElementwiseAddGradNPUKernel<float>,
                       ops::ElementwiseAddGradNPUKernel<plat::float16>);