elementwise_sub_op_npu.cc 6.0 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
/* 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>

#include "paddle/fluid/operators/elementwise/elementwise_sub_op.h"
#include "paddle/fluid/operators/npu_op_runner.h"

namespace paddle {
namespace operators {

using Tensor = framework::Tensor;

26
template <typename T>
27 28 29 30 31 32 33 34 35
class ElementwiseSubNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* x = ctx.Input<Tensor>("X");
    auto* y = ctx.Input<Tensor>("Y");
    auto* out = ctx.Output<Tensor>("Out");

    out->mutable_data<T>(ctx.GetPlace());

L
Leo Chen 已提交
36
    const auto& runner = NpuOpRunner("Sub", {*x, *y}, {*out}, {});
37 38 39 40 41 42 43 44

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

45
template <typename T>
46 47 48 49 50 51 52
class ElementwiseSubGradNPUKernel : public framework::OpKernel<T> {
 public:
  void Compute(const framework::ExecutionContext& ctx) const override {
    auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
    auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
    auto* dy = ctx.Output<Tensor>(framework::GradVarName("Y"));

53 54 55
    auto stream =
        ctx.template device_context<paddle::platform::NPUDeviceContext>()
            .stream();
56 57 58 59 60 61 62 63 64 65 66 67 68

    // NOTE(zhiqiu): It seems Ascend Sub follow the broadcast sematics with
    // default axis=-1?
    // So, the sub_grad should do reduce if needed.
    // For example, the shape of each variable in elementwise_sub:
    // x, dx: [2, 3, 5]
    // y, dy: [1, 5]
    // out, dout: [2, 3, 5]
    // Then, out = x - y  =>  dx = dout, dy = -dout
    // And, the shape of dy can be computed by two stages reduce,
    // 1. [2, 3, 5] => [3, 5], ReduceSumD on axis = 0, keep_dims = false.
    // 2. [3, 5] => [1, 5], ReduceSumD on axis = 0, keep_dims = true.

69 70 71 72 73 74 75
    if (dx) {
      dx->mutable_data<T>(ctx.GetPlace());
      // For dx
      // stage 1
      auto reduce_ndim = dout->dims().size() - dx->dims().size();
      std::vector<int> axes;
      for (auto i = 0; i < reduce_ndim; ++i) {
76 77
        axes.push_back(i);
      }
78 79 80 81 82 83 84 85 86
      Tensor* tmp_dout = const_cast<Tensor*>(dout);
      Tensor reduced_dout(dx->type());
      if (axes.size() != 0) {
        std::vector<int64_t> reduced_dout_dims;
        for (auto i = reduce_ndim; i < dout->dims().size(); ++i) {
          reduced_dout_dims.push_back(dout->dims()[i]);
        }
        reduced_dout.Resize(framework::make_ddim(reduced_dout_dims));
        reduced_dout.mutable_data<T>(ctx.GetPlace());
L
Leo Chen 已提交
87 88 89
        const auto& runner =
            NpuOpRunner("ReduceSumD", {*dout}, {reduced_dout},
                        {{"axes", axes}, {"keep_dims", false}});
90 91 92
        runner.Run(stream);
        tmp_dout = &reduced_dout;
      }
93

94 95 96 97 98 99 100 101
      // stage 2
      axes.clear();
      for (auto i = 0; i < dx->dims().size(); ++i) {
        if (dx->dims()[i] == 1) {
          axes.push_back(i);
        }
      }
      if (axes.size() != 0) {
L
Leo Chen 已提交
102 103
        const auto& runner = NpuOpRunner("ReduceSumD", {*tmp_dout}, {*dx},
                                         {{"axes", axes}, {"keep_dims", true}});
104 105
        runner.Run(stream);
      } else {
106 107 108
        framework::TensorCopy(
            *tmp_dout, ctx.GetPlace(),
            ctx.template device_context<platform::DeviceContext>(), dx);
109 110
      }
    }
111 112 113 114 115 116 117
    if (dy) {
      dy->mutable_data<T>(ctx.GetPlace());
      // For dy
      // stage 1
      auto reduce_ndim = dout->dims().size() - dy->dims().size();
      std::vector<int> axes;
      for (auto i = 0; i < reduce_ndim; ++i) {
118 119
        axes.push_back(i);
      }
120 121 122 123 124 125 126 127 128 129 130
      Tensor* tmp_dout = const_cast<Tensor*>(dout);
      Tensor reduced_dy(dy->type());
      Tensor reduced_dout(dy->type());

      if (axes.size() != 0) {
        std::vector<int64_t> reduced_dout_dims;
        for (auto i = reduce_ndim; i < dout->dims().size(); ++i) {
          reduced_dout_dims.push_back(dout->dims()[i]);
        }
        reduced_dout.Resize(framework::make_ddim(reduced_dout_dims));
        reduced_dout.mutable_data<T>(ctx.GetPlace());
L
Leo Chen 已提交
131 132 133
        const auto& runner =
            NpuOpRunner("ReduceSumD", {*dout}, {reduced_dout},
                        {{"axes", axes}, {"keep_dims", false}});
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        runner.Run(stream);
        tmp_dout = &reduced_dout;
      }

      // stage 2
      axes.clear();
      Tensor* tmp_dy = tmp_dout;
      for (auto i = 0; i < dy->dims().size(); ++i) {
        if (dy->dims()[i] == 1) {
          axes.push_back(i);
        }
      }
      if (axes.size() != 0) {
        reduced_dy.Resize(dy->dims());
        reduced_dy.mutable_data<T>(ctx.GetPlace());
L
Leo Chen 已提交
149 150 151
        const auto& runner =
            NpuOpRunner("ReduceSumD", {*tmp_dout}, {reduced_dy},
                        {{"axes", axes}, {"keep_dims", true}});
152 153 154 155 156
        runner.Run(stream);
        tmp_dy = &reduced_dy;
      }

      // stage 3, negative
L
Leo Chen 已提交
157
      const auto& runner = NpuOpRunner("Neg", {*tmp_dy}, {*dy}, {});
158 159 160 161 162 163 164 165 166
      runner.Run(stream);
    }
  }
};

}  // namespace operators
}  // namespace paddle

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

A
Aganlengzi 已提交
169 170
REGISTER_OP_NPU_KERNEL(elementwise_sub, ops::ElementwiseSubNPUKernel<int>,
                       ops::ElementwiseSubNPUKernel<float>,
171
                       ops::ElementwiseSubNPUKernel<plat::float16>);
172

173
REGISTER_OP_NPU_KERNEL(elementwise_sub_grad,
A
Aganlengzi 已提交
174
                       ops::ElementwiseSubGradNPUKernel<int>,
175 176
                       ops::ElementwiseSubGradNPUKernel<float>,
                       ops::ElementwiseSubGradNPUKernel<plat::float16>);