elementwise_add_op_xpu.cc 6.9 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 26 27 28
/* 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"

namespace paddle {
namespace operators {

template <typename DeviceContext, typename T>
class ElementwiseAddXPUKernel : public framework::OpKernel<T> {
 public:
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  void Compute(const framework::ExecutionContext& ctx) const override {
    // XPUElementwise<T>(ctx, xpu::add<T>);
    // ToDo(QingshuChen): update this optimization to elementwise_xpu.h
    auto x_var = ctx.InputVar("X");
    PADDLE_ENFORCE_NE(x_var, nullptr, platform::errors::InvalidArgument(
                                          "Cannot get input Variable X"));
    PADDLE_ENFORCE_EQ(
        x_var->IsType<framework::LoDTensor>(), true,
        platform::errors::InvalidArgument(
            "XPU only support LoDTensor, Input(X) is not LoDTensor"));

    auto x = x_var->Get<framework::LoDTensor>();
    auto* y = ctx.Input<framework::LoDTensor>("Y");
    auto* z = ctx.Output<framework::LoDTensor>("Out");
    z->mutable_data<T>(ctx.GetPlace());
    auto x_dims = x.dims();
    auto y_dims = y->dims();
    int max_dim = std::max(x_dims.size(), y_dims.size());
    int axis = ctx.Attr<int>("axis");
    axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);

    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));
    std::vector<int> x_dims_vec(max_dim, 1);
    std::vector<int> y_dims_vec(max_dim, 1);
    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];
      }
    }
    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];
      }
    }
    const T* x_data = x.data<T>();
    const T* y_data = y->data<T>();
    T* z_data = z->data<T>();

    auto& dev_ctx =
        ctx.template device_context<paddle::platform::XPUDeviceContext>();
    int ret = xpu::SUCCESS;
    ret = xpu::broadcast_add<T>(dev_ctx.x_context(), x_data, y_data, z_data,
                                x_dims_vec, y_dims_vec);
    PADDLE_ENFORCE_EQ(
        ret, xpu::SUCCESS,
        platform::errors::External(
            "XPU kernel Elementwise occur error in XPUElementwise error code ",
            ret, XPUAPIErrorMsg[ret]));
94 95 96 97 98 99
  }
};

template <typename DeviceContext, typename T>
class ElementwiseAddGradXPUKernel : public ElemwiseGradKernel<T> {
 public:
100
  void Compute(const framework::ExecutionContext& ctx) const override {
101
    ElemwiseGradKernel<T>::Compute(ctx);
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
    // XPUElementwiseGrad<T>(ctx, xpu::add_grad<T>, false);
    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"));
    int axis = ctx.Attr<int>("axis");
    const framework::DDim& x_dims = x->dims();
    const framework::DDim& y_dims = y->dims();
    int max_dim = std::max(x_dims.size(), y_dims.size());
    axis = (axis == -1 ? std::abs(x_dims.size() - y_dims.size()) : axis);
    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));
    std::vector<int> x_dims_vec(max_dim, 1);
    std::vector<int> y_dims_vec(max_dim, 1);
125 126
    int x_len = 1;
    int y_len = 1;
127 128 129
    if (x_dims.size() == max_dim) {
      for (int i = 0; i < max_dim; i++) {
        x_dims_vec[i] = x_dims[i];
130
        x_len *= x_dims_vec[i];
131 132 133 134
      }
    } else {
      for (int i = 0; i < x_dims.size(); i++) {
        x_dims_vec[i + axis] = x_dims[i];
135
        x_len *= x_dims_vec[i];
136 137 138 139 140
      }
    }
    if (y_dims.size() == max_dim) {
      for (int i = 0; i < max_dim; i++) {
        y_dims_vec[i] = y_dims[i];
141
        y_len *= y_dims_vec[i];
142 143 144 145
      }
    } else {
      for (int i = 0; i < y_dims.size(); i++) {
        y_dims_vec[i + axis] = y_dims[i];
146
        y_len *= y_dims_vec[i];
147 148 149
      }
    }

150
    const T* dz_data = dz->data<T>();
151 152 153
    framework::Tensor dx_local_tensor;
    framework::Tensor dy_local_tensor;
    bool need_wait = false;
154 155 156 157
    T* dx_data = nullptr;
    T* dy_data = nullptr;
    if (dx) {
      dx_data = dx->mutable_data<T>(ctx.GetPlace());
158 159 160 161
    } else {
      dx_data =
          dx_local_tensor.mutable_data<T>(ctx.GetPlace(), x_len * sizeof(T));
      need_wait = true;
162 163 164
    }
    if (dy) {
      dy_data = dy->mutable_data<T>(ctx.GetPlace());
165 166 167 168
    } else {
      dy_data =
          dy_local_tensor.mutable_data<T>(ctx.GetPlace(), y_len * sizeof(T));
      need_wait = true;
169 170 171 172
    }

    auto& dev_ctx =
        ctx.template device_context<paddle::platform::XPUDeviceContext>();
173 174 175
    int ret = xpu::broadcast_add_grad<T>(dev_ctx.x_context(), dz_data, dz_data,
                                         dz_data, dz_data, dy_data, dx_data,
                                         x_dims_vec, y_dims_vec);
176 177 178 179 180
    PADDLE_ENFORCE_EQ(
        ret, xpu::SUCCESS,
        platform::errors::External(
            "XPU kernel Elementwise occur error in XPUElementwise error code ",
            ret, XPUAPIErrorMsg[ret]));
181 182 183
    if (need_wait && dev_ctx.x_context()->xpu_stream) {
      dev_ctx.Wait();
    }
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
  }
};

}  // namespace operators
}  // namespace paddle

namespace ops = paddle::operators;

REGISTER_OP_XPU_KERNEL(
    elementwise_add,
    ops::ElementwiseAddXPUKernel<paddle::platform::XPUDeviceContext, float>);
REGISTER_OP_XPU_KERNEL(elementwise_add_grad,
                       ops::ElementwiseAddGradXPUKernel<
                           paddle::platform::XPUDeviceContext, float>);
#endif