elementwise_add_op_xpu.cc 5.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (c) 2020 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. */

#ifdef PADDLE_WITH_XPU
#include "paddle/fluid/operators/elementwise/elementwise_add_op.h"
#include <memory>
#include <string>
#include "paddle/fluid/operators/elementwise/elementwise_op.h"

#include "paddle/fluid/operators/elementwise/elementwise_xpu.h"
22
#include "paddle/fluid/platform/device/device_wrapper.h"
23 24 25 26

namespace paddle {
namespace operators {

27
template <typename T>
28
class ElementwiseAddXPUKernel : public framework::OpKernel<T> {
29 30
  using XPUType = typename XPUTypeTrait<T>::Type;

31
 public:
32
  void Compute(const framework::ExecutionContext& ctx) const override {
33 34 35
    XPUElementwise<T, XPUType>(ctx, xpu::broadcast_add<XPUType>);
  }
};
36

37 38 39 40 41 42
static std::vector<int> get_rdims(const std::vector<int>& xdims,
                                  const std::vector<int>& ydims) {
  std::vector<int> rdims;
  for (size_t i = 0; i < xdims.size(); i++) {
    if (xdims[i] != ydims[i]) {
      rdims.push_back(i);
43
    }
44
  }
45 46
  return rdims;
}
47

48
template <typename T>
49
class ElementwiseAddGradXPUKernel : public ElemwiseGradKernel<T> {
50 51
  using XPUType = typename XPUTypeTrait<T>::Type;

52
 public:
53
  void Compute(const framework::ExecutionContext& ctx) const override {
54
    ElemwiseGradKernel<T>::Compute(ctx);
55 56 57 58 59 60 61
    auto* x = ctx.Input<framework::Tensor>("X");
    auto* y = ctx.Input<framework::Tensor>("Y");
    auto* dz = 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"));
    const framework::DDim& x_dims = x->dims();
    const framework::DDim& y_dims = y->dims();
62 63
    const framework::DDim& dz_dims = dz->dims();
    int axis = ctx.Attr<int>("axis");
64
    axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
65
    int max_dim = std::max(x_dims.size(), y_dims.size());
66 67 68 69 70 71 72 73 74 75
    PADDLE_ENFORCE_GE(
        axis, 0,
        platform::errors::InvalidArgument(
            "Axis should be great than or equal to 0, but received axis is %d.",
            axis));
    PADDLE_ENFORCE_LT(
        axis, max_dim,
        platform::errors::InvalidArgument(
            "Axis should be less than %d, but received axis is %d.", max_dim,
            axis));
76

77 78
    std::vector<int> x_dims_vec(max_dim, 1);
    std::vector<int> y_dims_vec(max_dim, 1);
79
    std::vector<int> z_dims_vec(max_dim, 1);
80 81 82 83 84 85 86 87 88
    if (x_dims.size() == max_dim) {
      for (int i = 0; i < max_dim; i++) {
        x_dims_vec[i] = x_dims[i];
      }
    } else {
      for (int i = 0; i < x_dims.size(); i++) {
        x_dims_vec[i + axis] = x_dims[i];
      }
    }
89

90 91 92 93 94 95 96 97 98 99
    if (y_dims.size() == max_dim) {
      for (int i = 0; i < max_dim; i++) {
        y_dims_vec[i] = y_dims[i];
      }
    } else {
      for (int i = 0; i < y_dims.size(); i++) {
        y_dims_vec[i + axis] = y_dims[i];
      }
    }

100 101
    for (int i = 0; i < max_dim; i++) {
      z_dims_vec[i] = dz_dims[i];
102
    }
103 104 105 106 107
    std::vector<int> rdims_for_x;
    std::vector<int> rdims_for_y;
    rdims_for_x = get_rdims(x_dims_vec, z_dims_vec);
    rdims_for_y = get_rdims(y_dims_vec, z_dims_vec);
    const T* dz_data = dz->data<T>();
108 109
    auto& dev_ctx =
        ctx.template device_context<paddle::platform::XPUDeviceContext>();
110

111
    if (dx != nullptr) {
112
      T* dx_data = dx->mutable_data<T>(ctx.GetPlace());
113
      if (rdims_for_x.size() == 0) {
114 115 116 117 118
        if (dx_data != dz_data) {
          framework::TensorCopy(
              *dz, ctx.GetPlace(),
              ctx.template device_context<platform::DeviceContext>(), dx);
        }
119
      } else {
120 121 122 123 124 125 126
        // For inplace strategy, dx will be stored in addr of dz, which makes
        // the result of dy wrong.
        if (dx->IsSharedBufferWith(*dz)) {
          dx->clear();
          dx->mutable_data<T>(x->dims(), ctx.GetPlace());
        }

127 128 129
        int ret = xpu::reduce_sum<XPUType>(
            dev_ctx.x_context(), reinterpret_cast<const XPUType*>(dz_data),
            reinterpret_cast<XPUType*>(dx_data), z_dims_vec, rdims_for_x);
130
        PADDLE_ENFORCE_XDNN_SUCCESS(ret, "reduce_sum ");
131 132 133 134
      }
    }

    if (dy != nullptr) {
135
      T* dy_data = dy->mutable_data<T>(ctx.GetPlace());
136
      if (rdims_for_y.size() == 0) {
137 138 139 140 141
        if (dy_data != dz_data) {
          framework::TensorCopy(
              *dz, ctx.GetPlace(),
              ctx.template device_context<platform::DeviceContext>(), dy);
        }
142 143 144 145
      } else {
        int ret = xpu::reduce_sum<XPUType>(
            dev_ctx.x_context(), reinterpret_cast<const XPUType*>(dz_data),
            reinterpret_cast<XPUType*>(dy_data), z_dims_vec, rdims_for_y);
146
        PADDLE_ENFORCE_XDNN_SUCCESS(ret, "reduce_sum ");
147
      }
148
    }
149 150 151 152 153 154 155 156
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

157 158
REGISTER_OP_XPU_KERNEL(elementwise_add, ops::ElementwiseAddXPUKernel<float>,
                       ops::ElementwiseAddXPUKernel<paddle::platform::float16>);
159
REGISTER_OP_XPU_KERNEL(
160 161
    elementwise_add_grad, ops::ElementwiseAddGradXPUKernel<float>,
    ops::ElementwiseAddGradXPUKernel<paddle::platform::float16>);
162
#endif