elementwise_mlu.h 15.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
// Copyright (c) 2022 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.

#pragma once

#ifdef PADDLE_WITH_MLU
#include <vector>
19

20 21 22 23 24 25
#include "paddle/fluid/operators/elementwise/elementwise_op.h"
#include "paddle/fluid/operators/mlu/mlu_baseop.h"

namespace paddle {
namespace operators {

26 27
inline void GetReduceAxes(const int axis,
                          const framework::DDim& src_ddims,
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 57 58 59 60 61 62 63 64 65 66 67 68 69
                          const framework::DDim& target_ddims,
                          std::vector<int>* axes) {
  int64_t src_dim_size = src_ddims.size();
  int64_t target_dim_size = target_ddims.size();
  for (int64_t i = 0; i < src_dim_size; ++i) {
    if (i < axis || i >= target_dim_size + axis) {
      axes->push_back(i);
      continue;
    }
    if (src_ddims[i] > target_ddims[i - axis]) {
      axes->push_back(i);
    }
  }
}

inline void GetReduceAxesAndDstDims(const int axis,
                                    const framework::DDim& src_ddims,
                                    const framework::DDim& target_ddims,
                                    std::vector<int>* reduce_axes,
                                    std::vector<int>* dst_dims_vec) {
  int64_t src_dim_size = src_ddims.size();
  int64_t target_dim_size = target_ddims.size();

  int src_axis = (target_dim_size < src_dim_size ? axis : 0);
  for (int ax = 0; ax < src_dim_size; ++ax) {
    if ((ax < src_axis || ax >= src_axis + target_dim_size) ||
        (src_ddims[ax] > 1 && target_ddims[ax - src_axis] == 1)) {
      reduce_axes->push_back(ax);
    } else {
      dst_dims_vec->push_back(src_ddims[ax]);
    }
  }
  if (dst_dims_vec->size() == 0) {
    // target_var is scalar
    dst_dims_vec->push_back(1);
  }
}

template <typename T>
void MLUOpTensorKernel(const framework::ExecutionContext& ctx,
                       const cnnlOpTensorDesc_t op_tensor_op) {
  PADDLE_ENFORCE_EQ(
70 71
      platform::is_mlu_place(ctx.GetPlace()),
      true,
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
      platform::errors::Unavailable("This kernel only runs on MLU."));
  PADDLE_ENFORCE_EQ((op_tensor_op == CNNL_OP_TENSOR_ADD) ||
                        (op_tensor_op == CNNL_OP_TENSOR_SUB) ||
                        (op_tensor_op == CNNL_OP_TENSOR_MUL),
                    true,
                    platform::errors::Unavailable(
                        "This kernel of MLU only support ADD, SUB, MUL."));

  auto* x = ctx.Input<Tensor>("X");
  auto* y = ctx.Input<Tensor>("Y");
  auto* out = ctx.Output<Tensor>("Out");
  out->mutable_data<T>(ctx.GetPlace());

  int axis = ctx.Attr<int>("axis");
  const auto& x_dims = x->dims();
  const auto& y_dims = y->dims();
  axis =
      (axis < 0 ? (std::abs(x_dims.size() - y_dims.size()) + axis + 1) : axis);
  int max_dim = std::max(x_dims.size(), y_dims.size());
  std::vector<int> x_dims_array(max_dim);
  std::vector<int> y_dims_array(max_dim);
  std::vector<int> out_dims_array(max_dim);
94 95 96 97 98 99
  GetBroadcastDimsArrays(x_dims,
                         y_dims,
                         x_dims_array.data(),
                         y_dims_array.data(),
                         out_dims_array.data(),
                         max_dim,
100 101 102 103 104
                         axis);

  MLUCnnlTensorDesc x_desc(max_dim, x_dims_array.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(max_dim, y_dims_array.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*out);
105 106 107 108 109 110 111 112 113 114 115 116
  MLUCnnlOpTensorDesc op_tensor_desc(
      op_tensor_op, ToCnnlDataType<T>(), CNNL_NOT_PROPAGATE_NAN);

  MLUCnnl::OpTensor(ctx,
                    op_tensor_desc.get(),
                    x_desc.get(),
                    GetBasePtr(x),
                    y_desc.get(),
                    GetBasePtr(y),
                    out_desc.get(),
                    GetBasePtr(out),
                    ToCnnlDataType<T>());
117 118 119 120 121 122
}

// ------------------ BinaryOp -----------------
enum BINARY_FUNCTOR {
  DIV,
  DIVNONAN,
123
  MAXIMUM,
Q
qipengh 已提交
124
  MINIMUM,
Q
qipengh 已提交
125
  POW,
126 127 128 129 130
};

template <BINARY_FUNCTOR func>
void MLUBinary(const framework::ExecutionContext& ctx,
               cnnlComputationPreference_t prefer,
131 132 133 134 135 136
               const cnnlTensorDescriptor_t x_desc,
               const void* x,
               const cnnlTensorDescriptor_t y_desc,
               const void* y,
               const cnnlTensorDescriptor_t out_desc,
               void* out);
137 138 139 140

template <>
inline void MLUBinary<DIV>(const framework::ExecutionContext& ctx,
                           cnnlComputationPreference_t prefer,
141 142 143 144 145 146
                           const cnnlTensorDescriptor_t x_desc,
                           const void* x,
                           const cnnlTensorDescriptor_t y_desc,
                           const void* y,
                           const cnnlTensorDescriptor_t out_desc,
                           void* out) {
147 148 149
  MLUCnnl::Div(ctx, prefer, x_desc, x, y_desc, y, out_desc, out);
}

150 151 152 153
template <>
inline void MLUBinary<MAXIMUM>(
    const framework::ExecutionContext& ctx,
    cnnlComputationPreference_t prefer,  // useless, only for compatible
154 155 156 157 158 159
    const cnnlTensorDescriptor_t x_desc,
    const void* x,
    const cnnlTensorDescriptor_t y_desc,
    const void* y,
    const cnnlTensorDescriptor_t out_desc,
    void* out) {
160 161 162
  MLUCnnl::Maximum(ctx, x_desc, x, y_desc, y, out_desc, out);
}

Q
qipengh 已提交
163
template <>
164 165 166 167 168 169 170 171
inline void MLUBinary<MINIMUM>(const framework::ExecutionContext& ctx,
                               cnnlComputationPreference_t prefer,
                               const cnnlTensorDescriptor_t in1_desc,
                               const void* in1,
                               const cnnlTensorDescriptor_t in2_desc,
                               const void* in2,
                               const cnnlTensorDescriptor_t out_desc,
                               void* out) {
Q
qipengh 已提交
172 173 174
  MLUCnnl::Minimum(ctx, in1_desc, in1, in2_desc, in2, out_desc, out);
}

Q
qipengh 已提交
175 176 177 178 179 180 181 182 183 184 185 186
template <>
inline void MLUBinary<POW>(const framework::ExecutionContext& ctx,
                           cnnlComputationPreference_t prefer,
                           const cnnlTensorDescriptor_t x_desc,
                           const void* x,
                           const cnnlTensorDescriptor_t y_desc,
                           const void* y,
                           const cnnlTensorDescriptor_t out_desc,
                           void* out) {
  MLUCnnl::Pow(ctx, prefer, x_desc, x, y_desc, y, out_desc, out);
}

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
template <BINARY_FUNCTOR Functor, typename T>
void MLUBinaryOp(const framework::ExecutionContext& ctx) {
  auto* x = ctx.Input<Tensor>("X");
  auto* y = ctx.Input<Tensor>("Y");
  auto* out = ctx.Output<Tensor>("Out");
  out->mutable_data<T>(ctx.GetPlace());

  int axis = ctx.Attr<int>("axis");
  const auto& x_dims = x->dims();
  const auto& y_dims = y->dims();
  axis =
      (axis < 0 ? (std::abs(x_dims.size() - y_dims.size()) + axis + 1) : axis);
  int max_dim = std::max(x_dims.size(), y_dims.size());
  std::vector<int> x_dims_array(max_dim);
  std::vector<int> y_dims_array(max_dim);
  std::vector<int> out_dims_array(max_dim);
203 204 205 206 207 208
  GetBroadcastDimsArrays(x_dims,
                         y_dims,
                         x_dims_array.data(),
                         y_dims_array.data(),
                         out_dims_array.data(),
                         max_dim,
209 210 211 212 213 214 215
                         axis);

  MLUCnnlTensorDesc x_desc(max_dim, x_dims_array.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc y_desc(max_dim, y_dims_array.data(), ToCnnlDataType<T>());
  MLUCnnlTensorDesc out_desc(*out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<T>());

  cnnlComputationPreference_t prefer_type = CNNL_COMPUTATION_HIGH_PRECISION;
216 217 218 219 220 221 222
  MLUBinary<Functor>(ctx,
                     prefer_type,
                     x_desc.get(),
                     GetBasePtr(x),
                     y_desc.get(),
                     GetBasePtr(y),
                     out_desc.get(),
223 224 225 226 227 228 229 230 231 232 233 234
                     GetBasePtr(out));
}

// ------------------ UnaryOp -----------------
enum UNARY_FUNCTOR {
  NEG,
  RECIPROCAL,
};

template <UNARY_FUNCTOR func>
void MLUUnary(const framework::ExecutionContext& ctx,
              cnnlComputationPreference_t prefer,
235 236 237 238
              const cnnlTensorDescriptor_t input_desc,
              const void* input,
              const cnnlTensorDescriptor_t output_desc,
              void* output);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

template <>
inline void MLUUnary<NEG>(const framework::ExecutionContext& ctx,
                          cnnlComputationPreference_t prefer,
                          const cnnlTensorDescriptor_t input_desc,
                          const void* input,
                          const cnnlTensorDescriptor_t output_desc,
                          void* output) {
  MLUCnnl::Neg(ctx, input_desc, input, output_desc, output);
}

template <>
inline void MLUUnary<RECIPROCAL>(const framework::ExecutionContext& ctx,
                                 cnnlComputationPreference_t prefer,
                                 const cnnlTensorDescriptor_t input_desc,
                                 const void* input,
                                 const cnnlTensorDescriptor_t output_desc,
                                 void* output) {
  MLUCnnl::Reciprocal(ctx, input_desc, input, output_desc, output);
}

template <UNARY_FUNCTOR Functor, typename Tin, typename Tout = Tin>
void MLUUnaryOp(const framework::ExecutionContext& ctx) {
  auto* x = ctx.Input<Tensor>("X");
  auto* out = ctx.Output<Tensor>("Out");

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

  MLUCnnlTensorDesc x_desc(x, CNNL_LAYOUT_ARRAY, ToCnnlDataType<Tin>());
  MLUCnnlTensorDesc out_desc(*out, CNNL_LAYOUT_ARRAY, ToCnnlDataType<Tout>());

  cnnlComputationPreference_t prefer_type = CNNL_COMPUTATION_HIGH_PRECISION;
271 272 273 274 275 276
  MLUUnary<Functor>(ctx,
                    prefer_type,
                    x_desc.get(),
                    GetBasePtr(x),
                    out_desc.get(),
                    GetBasePtr(out));
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
// ------------------ MLUElementwiseGradOp -----------------
enum MINMAX_GRAD_FUNCTOR {
  MAXIMUM_GRAD,
  MINIMUM_GRAD,
};
template <MINMAX_GRAD_FUNCTOR Functor, typename Tin, typename Tout = Tin>
void MLUMinMaxGradHelper(const framework::ExecutionContext& ctx) {
  auto* x = ctx.Input<Tensor>("X");
  auto* y = ctx.Input<Tensor>("Y");
  auto* dout = ctx.Input<Tensor>(framework::GradVarName("Out"));
  auto* dx = ctx.Output<Tensor>(framework::GradVarName("X"));
  auto* dy = ctx.Output<Tensor>(framework::GradVarName("Y"));
  int axis = ctx.Attr<int>("axis");

  const auto& x_dims = x->dims();
  const auto& y_dims = y->dims();
  axis =
      (axis < 0 ? (std::abs(x_dims.size() - y_dims.size()) + axis + 1) : axis);
  int max_dim = std::max(x_dims.size(), y_dims.size());
  std::vector<int> x_dims_array(max_dim);
  std::vector<int> y_dims_array(max_dim);
  std::vector<int> out_dims_array(max_dim);
301 302 303 304 305 306
  GetBroadcastDimsArrays(x_dims,
                         y_dims,
                         x_dims_array.data(),
                         y_dims_array.data(),
                         out_dims_array.data(),
                         max_dim,
307 308 309 310 311 312 313 314 315 316 317 318 319
                         axis);

  // mask = Logic(x, y) only support min & max
  cnnlLogicOp_t logic =
      Functor == MAXIMUM_GRAD ? CNNL_LOGIC_OP_GE : CNNL_LOGIC_OP_LE;
  Tensor mask(x->dtype());
  mask.Resize(phi::make_ddim(out_dims_array));
  mask.mutable_data<Tin>(ctx.GetPlace());

  cnnlDataType_t data_type = ToCnnlDataType<Tin>();
  MLUCnnlTensorDesc x_desc(max_dim, x_dims_array.data(), data_type);
  MLUCnnlTensorDesc y_desc(max_dim, y_dims_array.data(), data_type);
  MLUCnnlTensorDesc mask_desc(max_dim, out_dims_array.data(), data_type);
320 321 322 323 324 325 326 327
  MLUCnnl::Logic(ctx,
                 logic,
                 x_desc.get(),
                 GetBasePtr(x),
                 y_desc.get(),
                 GetBasePtr(y),
                 mask_desc.get(),
                 GetBasePtr(&mask));
328 329 330 331 332 333

  // dx = Mul(dz, mask)
  Tensor dx_temp(x->dtype());
  dx_temp.Resize(dout->dims());
  dx_temp.mutable_data<Tout>(ctx.GetPlace());
  MLUCnnlTensorDesc dout_desc(*dout);
334 335 336 337 338 339 340 341 342 343 344
  MLUCnnlOpTensorDesc mul_op_desc(
      CNNL_OP_TENSOR_MUL, data_type, CNNL_NOT_PROPAGATE_NAN);
  MLUCnnl::OpTensor(ctx,
                    mul_op_desc.get(),
                    dout_desc.get(),
                    GetBasePtr(dout),
                    dout_desc.get(),
                    GetBasePtr(&mask),
                    dout_desc.get(),
                    GetBasePtr(&dx_temp),
                    data_type);
345 346 347 348 349

  // dy = Sub(dz, dx)
  Tensor dy_temp(y->dtype());
  dy_temp.Resize(dout->dims());
  dy_temp.mutable_data<Tout>(ctx.GetPlace());
350 351 352 353 354 355 356 357 358 359 360
  MLUCnnlOpTensorDesc sub_op_desc(
      CNNL_OP_TENSOR_SUB, data_type, CNNL_NOT_PROPAGATE_NAN);
  MLUCnnl::OpTensor(ctx,
                    sub_op_desc.get(),
                    dout_desc.get(),
                    GetBasePtr(dout),
                    dout_desc.get(),
                    GetBasePtr(&dx_temp),
                    dout_desc.get(),
                    GetBasePtr(&dy_temp),
                    data_type);
361 362 363 364 365 366

  if (dx) {
    if (dx->dims() != dout->dims()) {
      dx->mutable_data<Tout>(ctx.GetPlace());
      std::vector<int> reduce_axes;
      GetReduceAxes(axis, dx_temp.dims(), dx->dims(), &reduce_axes);
367 368 369 370 371 372
      MLUCnnlReduceDesc reduction_desc(reduce_axes,
                                       CNNL_REDUCE_ADD,
                                       data_type,
                                       CNNL_NOT_PROPAGATE_NAN,
                                       CNNL_REDUCE_NO_INDICES,
                                       CNNL_32BIT_INDICES);
373
      MLUCnnlTensorDesc dx_desc(*dx);
374 375 376 377 378 379 380 381 382 383 384
      MLUCnnl::Reduce(ctx,
                      true /*need_workspace*/,
                      reduction_desc.get(),
                      nullptr,
                      dout_desc.get(),
                      GetBasePtr(&dx_temp),
                      0,
                      nullptr,
                      nullptr,
                      dx_desc.get(),
                      GetBasePtr(dx));
385 386 387 388 389 390 391 392 393 394
    } else {
      dx->ShareDataWith(dx_temp);
    }
  }

  if (dy) {
    if (dy->dims() != dout->dims()) {
      dy->mutable_data<Tout>(ctx.GetPlace());
      std::vector<int> reduce_axes;
      GetReduceAxes(axis, dy_temp.dims(), dy->dims(), &reduce_axes);
395 396 397 398 399 400
      MLUCnnlReduceDesc reduction_desc(reduce_axes,
                                       CNNL_REDUCE_ADD,
                                       data_type,
                                       CNNL_NOT_PROPAGATE_NAN,
                                       CNNL_REDUCE_NO_INDICES,
                                       CNNL_32BIT_INDICES);
401
      MLUCnnlTensorDesc dy_desc(*dy);
402 403 404 405 406 407 408 409 410 411 412
      MLUCnnl::Reduce(ctx,
                      true /*need_workspace*/,
                      reduction_desc.get(),
                      nullptr,
                      dout_desc.get(),
                      GetBasePtr(&dy_temp),
                      0,
                      nullptr,
                      nullptr,
                      dy_desc.get(),
                      GetBasePtr(dy));
413 414 415 416 417 418
    } else {
      dy->ShareDataWith(dy_temp);
    }
  }
}

419 420 421
}  // namespace operators
}  // namespace paddle
#endif