“cfffb1a36251e7d06535dac6db220131e36fe9f8”上不存在“paddle/fluid/inference/lite/anakin_config.h”
elementwise_kernel.cc 16.4 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. */

#include "paddle/phi/kernels/sparse/elementwise_kernel.h"
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/core/tensor_meta.h"
19
#include "paddle/phi/core/tensor_utils.h"
20
#include "paddle/phi/core/visit_type.h"
Z
zhangkaihuo 已提交
21
#include "paddle/phi/kernels/elementwise_add_kernel.h"
22 23 24
#include "paddle/phi/kernels/elementwise_kernel.h"
#include "paddle/phi/kernels/funcs/elementwise_functor.h"
#include "paddle/phi/kernels/funcs/sparse/flatten_indices.h"
Z
zhangkaihuo 已提交
25
#include "paddle/phi/kernels/sparse/empty_kernel.h"
26 27 28 29 30 31 32 33 34
#include "paddle/phi/kernels/sparse/sparse_utils_kernel.h"

namespace phi {
namespace sparse {

template <typename T, typename Functor>
struct BinaryOPWithZeroCompareFunctor {
  explicit BinaryOPWithZeroCompareFunctor(Functor functor)
      : functor_(functor) {}
35
  inline HOSTDEVICE void operator()(const T* a,
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
                                    const T* b,
                                    T* result,
                                    const int64_t len) const {
    for (int64_t i = 0; i < len; ++i) {
      result[i] = functor_(a[i], b[i]);
    }
  }
  Functor functor_;
};

template <typename T, typename IntT, typename Functor>
void Merge(const IntT el_len,
           const IntT* a_index,
           const T* a_values,
           const IntT len_a,
           const IntT* b_index_org,
           const T* b_values_org,
           const IntT len_b,
           const IntT len_b_max,
           IntT* c_index,
           T* c_values,
57
           IntT* out_nnz,
58 59 60 61
           const Functor& functor_org,
           const bool is_divide) {
  IntT a = 0;
  IntT b = 0;
62
  IntT& nnz = (*out_nnz);
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  nnz = 0;
  const IntT* b_index = nullptr;
  std::vector<IntT> b_full_index;
  const std::vector<T> zero(el_len, 0);
  auto functor = BinaryOPWithZeroCompareFunctor<T, Functor>(functor_org);

  std::vector<const T*> b_values(len_b_max, zero.data());
  for (auto i = 0; i < len_b; ++i) {
    b_values[b_index_org[i]] = b_values_org + i * el_len;
  }
  //  if is divide expend b_index_org to b_full_index
  if (is_divide) {
    b_full_index = std::vector<IntT>(len_b_max);
    for (int64_t j = 0; j < static_cast<int64_t>(b_full_index.size()); ++j) {
      b_full_index[j] = j;
    }
    b_index = b_full_index.data();
  } else {
    b_index = b_index_org;
  }
  // merge
  while (a < len_a && b < (is_divide ? len_b_max : len_b)) {
    if (a_index[a] == b_index[b]) {
86 87 88 89 90 91
      functor(a_values + a * el_len,
              b_values[b_index[b]],
              c_values + nnz * el_len,
              el_len);
      c_index[nnz] = a_index[a];
      ++nnz;
92 93
      ++a;
      ++b;
94
    } else if (a_index[a] < b_index[b]) {  // coordinate x[a] < coordinate y[b]
95 96 97 98
      functor(
          a_values + a * el_len, zero.data(), c_values + nnz * el_len, el_len);
      c_index[nnz] = a_index[a];
      ++nnz;
99
      ++a;
100
    } else if (a_index[a] > b_index[b]) {  // coordinate x[a] > coordinate y[b]
101 102 103 104
      functor(
          zero.data(), b_values[b_index[b]], c_values + nnz * el_len, el_len);
      c_index[nnz] = b_index[b];
      ++nnz;
105 106 107 108 109
      ++b;
    }
  }
  // a tail
  while (a < len_a) {
110 111 112 113
    functor(
        a_values + a * el_len, zero.data(), c_values + nnz * el_len, el_len);
    c_index[nnz] = a_index[a];
    ++nnz;
114 115 116 117
    ++a;
  }
  //  b tail
  while (b < (is_divide ? len_b_max : len_b)) {
118 119 120
    functor(zero.data(), b_values[b_index[b]], c_values + nnz * el_len, el_len);
    c_index[nnz] = b_index[b];
    ++nnz;
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    ++b;
  }
}

// SparseCooTensor elementwise op, only support same shape tensor now
template <typename T, typename IntT, typename Context, typename Functor>
void ElementWiseCooKernelImpl(const Context& dev_ctx,
                              const SparseCooTensor& x,
                              const SparseCooTensor& y,
                              SparseCooTensor* out,
                              const Functor& functor) {
  PADDLE_ENFORCE_EQ(x.dims(),
                    y.dims(),
                    phi::errors::InvalidArgument(
                        "Currently only support same shape elementwise "
                        "compute. The input tensor X's shape "
                        "should be identical with Y's shape. But received X's "
                        "shape = [%s], Y's shape = [%s].",
                        x.dims(),
                        y.dims()));
Z
zhangkaihuo 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155

  // temporary policy: for broadcast add
  // TODO(zhangkaihuo): implement a correct function
  const bool is_add = std::is_same<Functor, funcs::AddFunctor<T>>::value;
  if (is_add && x.indices().numel() == y.indices().numel()) {
    int compare_indices = memcmp(x.indices().data<IntT>(),
                                 y.indices().data<IntT>(),
                                 sizeof(IntT) * x.indices().numel());
    if (compare_indices == 0) {
      EmptyLikeCooKernel<T, Context>(dev_ctx, x, out);
      phi::AddKernel<T, Context>(
          dev_ctx, x.values(), y.values(), out->mutable_values());
      return;
    }
  }
156
  int64_t element_size = 1;
157 158
  for (auto j = 1; j < x.values().dims().size(); ++j) {
    element_size *= x.values().dims()[j];
159 160
  }
  IntT nnz = 0;
161 162 163
  const auto x_values = x.values().data<T>();
  const auto y_values = y.values().data<T>();
  const auto sparse_dim = x.indices().dims()[0];
164 165 166 167 168 169 170 171 172 173 174 175 176
  const bool is_divide = std::is_same<Functor, funcs::DivideFunctor<T>>::value;

  int64_t max_len = 1;
  for (auto j = 0; j < sparse_dim; ++j) {
    max_len *= x.dims()[j];
  }

  std::vector<IntT> sparse_offsets(sparse_dim), x_indexs(x.nnz()),
      y_indexs(y.nnz());

  phi::funcs::sparse::CalcOffsetsPerDim<IntT>(
      x.dims(), sparse_dim, sparse_offsets.data());

177
  phi::funcs::sparse::FlattenIndices(x.indices().data<IntT>(),
178 179 180 181 182 183 184
                                     sparse_offsets.data(),
                                     x.nnz(),
                                     sparse_dim,
                                     0,
                                     1,
                                     x_indexs.data());

185
  phi::funcs::sparse::FlattenIndices(y.indices().data<IntT>(),
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
                                     sparse_offsets.data(),
                                     y.nnz(),
                                     sparse_dim,
                                     0,
                                     1,
                                     y_indexs.data());

  std::vector<IntT> out_indexs;
  std::vector<T> out_values_vec;
  if (is_divide) {
    out_indexs.reserve(max_len);
  } else {
    out_indexs.reserve(x.nnz() + y.nnz());
  }
  out_values_vec.reserve(max_len * element_size);

  //  merge x and y
  Merge<T, IntT, Functor>(element_size,
                          x_indexs.data(),
                          x_values,
                          x_indexs.size(),
                          y_indexs.data(),
                          y_values,
                          y_indexs.size(),
                          max_len,
                          out_indexs.data(),
                          out_values_vec.data(),
213
                          &nnz,
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
                          functor,
                          is_divide);

  std::vector<IntT> out_indices_vec;
  out_indices_vec.resize(nnz * sparse_dim);

  Dim<DDim::kMaxRank> const_dims;
  for (auto i = 0; i < x.dims().size(); i++) {
    const_dims[i] = x.dims()[i];
  }

  funcs::sparse::IndexToCoordinate<IntT>(out_indexs.data(),
                                         const_dims,
                                         nnz,
                                         sparse_dim,
                                         0,
                                         1,
                                         out_indices_vec.data());

  if (nnz == 0) {
234 235
    phi::DenseTensor out_indices = phi::EmptyLike<IntT>(dev_ctx, x.indices());
    phi::DenseTensor out_values = phi::EmptyLike<T>(dev_ctx, x.values());
236 237 238
    out->SetMember(out_indices, out_values, x.dims());
  } else {
    DenseTensorMeta indices_meta(
239
        phi::CppTypeToDataType<IntT>::Type(),
240 241 242
        phi::make_ddim(
            {static_cast<int64_t>(sparse_dim), static_cast<int64_t>(nnz)}),
        DataLayout::NCHW);
243 244
    auto indeces_dim =
        vectorize(slice_ddim(x.values().dims(), 1, x.values().dims().size()));
245 246
    indeces_dim.insert(indeces_dim.begin(), nnz);
    DenseTensorMeta values_meta(
Z
zhangkaihuo 已提交
247
        x.dtype(), phi::make_ddim(indeces_dim), DataLayout::NCHW);
248 249 250 251 252 253 254 255 256 257 258 259 260 261
    phi::DenseTensor out_indices = phi::Empty(dev_ctx, std::move(indices_meta));
    phi::DenseTensor out_values = phi::Empty(dev_ctx, std::move(values_meta));

    std::memcpy(out_indices.data<IntT>(),
                out_indices_vec.data(),
                sizeof(IntT) * sparse_dim * nnz);
    std::memcpy(out_values.data<T>(),
                out_values_vec.data(),
                sizeof(T) * nnz * element_size);

    out->SetMember(out_indices, out_values, x.dims());
  }
}

Z
zhangkaihuo 已提交
262 263 264 265 266 267 268 269 270 271
#define DEFINE_CSR_ELEMENTWISE_CPU_KERNEL(name)                               \
  template <typename T, typename IntT, typename Context>                      \
  void ElementWise##name##CsrCPUKernel(const Context& dev_ctx,                \
                                       const SparseCsrTensor& x,              \
                                       const SparseCsrTensor& y,              \
                                       SparseCsrTensor* out) {                \
    auto coo_x = CsrToCoo<T>(dev_ctx, x);                                     \
    auto coo_y = CsrToCoo<T>(dev_ctx, y);                                     \
    auto coo_out = ElementWise##name##Coo<T, Context>(dev_ctx, coo_x, coo_y); \
    CooToCsrKernel<T>(dev_ctx, coo_out, out);                                 \
272 273
  }

274 275 276 277 278 279 280 281 282 283
#define DEFINE_CSR_ELEMENTWISE_KERNEL(name)                               \
  template <typename T, typename Context>                                 \
  void ElementWise##name##CsrKernel(const Context& dev_ctx,               \
                                    const SparseCsrTensor& x,             \
                                    const SparseCsrTensor& y,             \
                                    SparseCsrTensor* out) {               \
    PD_VISIT_BASE_INTEGRAL_TYPES(                                         \
        x.crows().dtype(), "ElementWise##name##CsrCPUKernel", ([&] {      \
          ElementWise##name##CsrCPUKernel<T, data_t>(dev_ctx, x, y, out); \
        }));                                                              \
284 285 286 287 288 289 290 291 292 293 294 295 296
  }

#define DEFINE_COO_ELEMENTWISE_CPU_KERNEL(name)                          \
  template <typename T, typename IntT, typename Context>                 \
  void ElementWise##name##CooCPUKernel(const Context& dev_ctx,           \
                                       const SparseCooTensor& x,         \
                                       const SparseCooTensor& y,         \
                                       SparseCooTensor* out) {           \
    funcs::name##Functor<T> functor;                                     \
    ElementWiseCooKernelImpl<T, IntT, Context, funcs::name##Functor<T>>( \
        dev_ctx, x, y, out, functor);                                    \
  }

297 298 299 300 301 302 303 304 305 306
#define DEFINE_COO_ELEMENTWISE_KERNEL(name)                               \
  template <typename T, typename Context>                                 \
  void ElementWise##name##CooKernel(const Context& dev_ctx,               \
                                    const SparseCooTensor& x,             \
                                    const SparseCooTensor& y,             \
                                    SparseCooTensor* out) {               \
    PD_VISIT_BASE_INTEGRAL_TYPES(                                         \
        x.indices().dtype(), "ElementWise##name##CooCPUKernel", ([&] {    \
          ElementWise##name##CooCPUKernel<T, data_t>(dev_ctx, x, y, out); \
        }));                                                              \
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  }

DEFINE_CSR_ELEMENTWISE_CPU_KERNEL(Add)
DEFINE_CSR_ELEMENTWISE_CPU_KERNEL(Subtract)
DEFINE_CSR_ELEMENTWISE_CPU_KERNEL(Multiply)
DEFINE_CSR_ELEMENTWISE_CPU_KERNEL(Divide)

DEFINE_CSR_ELEMENTWISE_KERNEL(Add)
DEFINE_CSR_ELEMENTWISE_KERNEL(Subtract)
DEFINE_CSR_ELEMENTWISE_KERNEL(Multiply)
DEFINE_CSR_ELEMENTWISE_KERNEL(Divide)

DEFINE_COO_ELEMENTWISE_CPU_KERNEL(Add)
DEFINE_COO_ELEMENTWISE_CPU_KERNEL(Subtract)
DEFINE_COO_ELEMENTWISE_CPU_KERNEL(Multiply)
DEFINE_COO_ELEMENTWISE_CPU_KERNEL(Divide)

DEFINE_COO_ELEMENTWISE_KERNEL(Add)
DEFINE_COO_ELEMENTWISE_KERNEL(Subtract)
DEFINE_COO_ELEMENTWISE_KERNEL(Multiply)
DEFINE_COO_ELEMENTWISE_KERNEL(Divide)

}  // namespace sparse
}  // namespace phi

PD_REGISTER_KERNEL(add_csr_csr,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseAddCsrKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_CSR);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_CSR);
}

PD_REGISTER_KERNEL(add_coo_coo,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseAddCooKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_COO);
}

PD_REGISTER_KERNEL(subtract_csr_csr,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseSubtractCsrKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_CSR);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_CSR);
}

PD_REGISTER_KERNEL(subtract_coo_coo,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseSubtractCooKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_COO);
}

PD_REGISTER_KERNEL(multiply_csr_csr,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseMultiplyCsrKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_CSR);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_CSR);
}

PD_REGISTER_KERNEL(multiply_coo_coo,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseMultiplyCooKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_COO);
}

PD_REGISTER_KERNEL(divide_csr_csr,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseDivideCsrKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_CSR);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_CSR);
}

PD_REGISTER_KERNEL(divide_coo_coo,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseDivideCooKernel,
                   float,
                   double,
                   int16_t,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
  kernel->InputAt(1).SetDataLayout(phi::DataLayout::SPARSE_COO);
}
Z
zhangkaihuo 已提交
435 436 437 438 439 440 441 442 443 444 445

PD_REGISTER_KERNEL(add_coo_dense,
                   CPU,
                   ALL_LAYOUT,
                   phi::sparse::ElementWiseAddDenseKernel,
                   float,
                   double,
                   int,
                   int64_t) {
  kernel->InputAt(0).SetDataLayout(phi::DataLayout::SPARSE_COO);
}