matmul_kernel_impl.h 18.3 KB
Newer Older
Z
zyfncg 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/* 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. */

#pragma once

17
#include "paddle/phi/core/dense_tensor.h"
18 19
#include "paddle/phi/kernels/funcs/blas/blas.h"
#include "paddle/phi/kernels/funcs/complex_functors.h"
Z
zyfncg 已提交
20

21
namespace phi {
Z
zyfncg 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39

static void GetBroadcastFromDims(const int x_ndim,
                                 const std::int64_t* x_dims,
                                 const int y_ndim,
                                 const std::int64_t* y_dims,
                                 std::int64_t* x_bd_dims,
                                 std::int64_t* y_bd_dims,
                                 std::int64_t* out_bd_dims) {
  const int ndim = (std::max)(x_ndim, y_ndim);
  std::fill(x_bd_dims, x_bd_dims + ndim - x_ndim, 1);
  std::fill(y_bd_dims, y_bd_dims + ndim - y_ndim, 1);
  std::copy(x_dims, x_dims + x_ndim, x_bd_dims + ndim - x_ndim);
  std::copy(y_dims, y_dims + y_ndim, y_bd_dims + ndim - y_ndim);

  for (int i = 0; i < ndim; ++i) {
    PADDLE_ENFORCE_EQ(
        x_bd_dims[i] == y_bd_dims[i] || x_bd_dims[i] <= 1 || y_bd_dims[i] <= 1,
        true,
40
        phi::errors::InvalidArgument(
Z
zyfncg 已提交
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
            "Input(X) and Input(Y) has error dim."
            "X_broadcast's shape[%s] must be equal to Y_broadcast's shape[%s],"
            "or X_broadcast's shape[%s] <= 1, or Y_broadcast's shape[%s] <= 1,"
            "But received X_broadcast's shape[%s] = [%s]"
            "received Y_broadcast's shape[%s] = [%s]",
            i,
            i,
            i,
            i,
            i,
            x_bd_dims[i],
            i,
            y_bd_dims[i]));
    if (x_bd_dims[i] == 0 || y_bd_dims[i] == 0) {
      out_bd_dims[i] = 0;
    } else {
      out_bd_dims[i] = (std::max)(x_bd_dims[i], y_bd_dims[i]);
    }
  }
}

static int64_t GetIndexMessage(const int n,
                               const int64_t* dims,
                               const int64_t* index) {
  int64_t sum = 0;
  for (int i = 0; i < n; ++i) {
    if (dims[i] > 1) {
      sum = sum * dims[i] + index[i];
    }
  }
  return sum;
}

static void IndexIncreaseFromDims(const int ndim,
                                  const int64_t* dims,
                                  int64_t* index) {
  for (int i = ndim - 1; i >= 0; --i) {
    ++index[i];
    if (index[i] >= dims[i]) {
      index[i] -= dims[i];
    } else {
      break;
    }
  }
}

87
template <typename Context, typename T>
88
void MatMulFunction(const Context& dev_ctx,
Z
zyfncg 已提交
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
                    const DenseTensor& X,
                    const DenseTensor& Y,
                    const std::vector<std::int64_t>& x_dims,
                    const std::vector<std::int64_t>& y_dims,
                    DenseTensor* Out,
                    bool trans_x,
                    bool trans_y,
                    bool flag = false) {
  const int x_ndim = x_dims.size();
  const int y_ndim = y_dims.size();

  // Get data ptr
  const T* x_data = X.data<T>();
  const T* y_data = Y.data<T>();

104
  auto blas = phi::funcs::GetBlas<Context, T>(dev_ctx);
L
Linjie Chen 已提交
105

Z
zyfncg 已提交
106
  if (x_ndim == 1 && y_ndim == 1) {
L
Linjie Chen 已提交
107 108
    const int M = X.numel();
    const int N = Y.numel();
Z
zyfncg 已提交
109
    PADDLE_ENFORCE_EQ(
L
Linjie Chen 已提交
110 111
        M,
        N,
112
        phi::errors::InvalidArgument(
Z
zyfncg 已提交
113 114 115
            "X's numbers must be equal to Y's numbers,"
            "when X/Y's dims =1. But received X has [%d] elements,"
            "received Y has [%d] elements",
L
Linjie Chen 已提交
116 117
            M,
            N));
Z
zyfncg 已提交
118
    VLOG(3) << "MatMul's case 1";
119
    Out->Resize({1});
120
    dev_ctx.template Alloc<T>(Out);
L
Linjie Chen 已提交
121 122 123 124 125 126 127 128 129
    blas.GEMM(CblasNoTrans,
              CblasTrans,
              1,
              1,
              M,
              static_cast<T>(1),
              y_data,
              x_data,
              static_cast<T>(flag),
130
              dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
131 132 133 134 135 136
    return;
  }

  if (x_ndim == 1) {
    const int N = X.numel();
    if (trans_y) {
137 138 139 140 141 142 143 144 145 146
      PADDLE_ENFORCE_EQ(
          y_dims[y_ndim - 1],
          N,
          phi::errors::InvalidArgument("Input(Y) has error dim."
                                       "Y'dims[%d] must be equal to %d"
                                       "But received Y'dims[%d] is %d",
                                       y_ndim - 1,
                                       N,
                                       y_ndim - 1,
                                       y_dims[y_ndim - 1]));
Z
zyfncg 已提交
147
    } else {
148 149 150 151 152 153 154 155 156 157
      PADDLE_ENFORCE_EQ(
          y_dims[y_ndim - 2],
          N,
          phi::errors::InvalidArgument("Input(Y) has error dim."
                                       "Y'dims[%d] must be equal to %d"
                                       "But received Y'dims[%d] is %d",
                                       y_ndim - 2,
                                       N,
                                       y_ndim - 2,
                                       y_dims[y_ndim - 2]));
Z
zyfncg 已提交
158 159 160 161 162 163 164 165
    }
    std::vector<std::int64_t> out_dims(y_ndim - 1);
    if (trans_y) {
      std::copy_n(y_dims.cbegin(), y_ndim - 1, out_dims.begin());
    } else {
      std::copy_n(y_dims.cbegin(), y_ndim - 2, out_dims.begin());
      out_dims.back() = y_dims.back();
    }
166
    Out->ResizeAndAllocate(phi::make_ddim(out_dims));
167
    dev_ctx.template Alloc<T>(Out);
Z
zyfncg 已提交
168 169 170 171 172 173 174 175 176 177
    if (trans_y) {
      const int M = Y.numel() / N;
      VLOG(3) << "MatMul's case 2";
      blas.GEMV(false,
                M,
                N,
                static_cast<T>(1),
                y_data,
                x_data,
                static_cast<T>(flag),
178
                dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
179 180 181 182 183 184 185 186 187 188 189 190
    } else {
      const int M = y_dims[y_ndim - 1];
      const int batch_size = Y.numel() / (M * N);
      if (batch_size == 1) {
        VLOG(3) << "MatMul's case 3";
        blas.GEMV(true,
                  N,
                  M,
                  static_cast<T>(1),
                  y_data,
                  x_data,
                  static_cast<T>(flag),
191
                  dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
192 193 194 195 196 197 198 199 200 201 202
      } else {
        VLOG(3) << "MatMul's case 4";
        blas.BatchedGEMM(CblasTrans,
                         CblasNoTrans,
                         M,
                         1,
                         N,
                         static_cast<T>(1),
                         y_data,
                         x_data,
                         static_cast<T>(flag),
203
                         dev_ctx.template Alloc<T>(Out),
Z
zyfncg 已提交
204 205 206 207 208 209 210 211 212 213 214
                         batch_size,
                         M * N,
                         0);
      }
    }
    return;
  }

  if (y_ndim == 1) {
    const int N = Y.numel();
    if (trans_x) {
215 216 217 218 219 220 221 222 223 224
      PADDLE_ENFORCE_EQ(
          x_dims[x_ndim - 2],
          N,
          phi::errors::InvalidArgument("Input(X) has error dim."
                                       "X'dims[%d] must be equal to %d"
                                       "But received X'dims[%d] is %d",
                                       x_ndim - 2,
                                       N,
                                       x_ndim - 2,
                                       x_dims[x_ndim - 2]));
Z
zyfncg 已提交
225
    } else {
226 227 228 229 230 231 232 233 234 235
      PADDLE_ENFORCE_EQ(
          x_dims[x_ndim - 1],
          N,
          phi::errors::InvalidArgument("Input(X) has error dim."
                                       "X'dims[%d] must be equal to %d"
                                       "But received X'dims[%d] is %d",
                                       x_ndim - 1,
                                       N,
                                       x_ndim - 1,
                                       x_dims[x_ndim - 1]));
Z
zyfncg 已提交
236 237 238 239 240 241 242 243
    }
    std::vector<std::int64_t> out_dims(x_ndim - 1);
    if (trans_x) {
      std::copy_n(x_dims.cbegin(), x_ndim - 2, out_dims.begin());
      out_dims.back() = x_dims.back();
    } else {
      std::copy_n(x_dims.cbegin(), x_ndim - 1, out_dims.begin());
    }
244
    Out->ResizeAndAllocate(phi::make_ddim(out_dims));
245
    dev_ctx.template Alloc<T>(Out);
Z
zyfncg 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258

    if (trans_x) {
      const int M = x_dims[x_ndim - 1];
      const int batch_size = X.numel() / (M * N);
      if (batch_size == 1) {
        VLOG(3) << "MatMul's case 5";
        blas.GEMV(true,
                  N,
                  M,
                  static_cast<T>(1),
                  x_data,
                  y_data,
                  static_cast<T>(flag),
259
                  dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
260 261 262 263 264 265 266 267 268 269 270
      } else {
        VLOG(3) << "MatMul's case 6";
        blas.BatchedGEMM(CblasTrans,
                         CblasNoTrans,
                         M,
                         1,
                         N,
                         static_cast<T>(1),
                         x_data,
                         y_data,
                         static_cast<T>(flag),
271
                         dev_ctx.template Alloc<T>(Out),
Z
zyfncg 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285
                         batch_size,
                         M * N,
                         0);
      }
    } else {
      const int M = X.numel() / N;
      VLOG(3) << "MatMul's case 7";
      blas.GEMV(false,
                M,
                N,
                static_cast<T>(1),
                x_data,
                y_data,
                static_cast<T>(flag),
286
                dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
287 288 289 290 291 292 293
    }
    return;
  }

  const int M = trans_x ? x_dims[x_ndim - 1] : x_dims[x_ndim - 2];
  const int K = trans_x ? x_dims[x_ndim - 2] : x_dims[x_ndim - 1];
  if (trans_y) {
294 295 296 297 298 299 300 301 302 303
    PADDLE_ENFORCE_EQ(
        y_dims[y_ndim - 1],
        K,
        phi::errors::InvalidArgument("Input(Y) has error dim."
                                     "Y'dims[%d] must be equal to %d"
                                     "But received Y'dims[%d] is %d",
                                     y_ndim - 1,
                                     K,
                                     y_ndim - 1,
                                     y_dims[y_ndim - 1]));
Z
zyfncg 已提交
304
  } else {
305 306 307 308 309 310 311 312 313 314
    PADDLE_ENFORCE_EQ(
        y_dims[y_ndim - 2],
        K,
        phi::errors::InvalidArgument("Input(Y) has error dim."
                                     "Y'dims[%d] must be equal to %d"
                                     "But received Y'dims[%d] is %d",
                                     y_ndim - 2,
                                     K,
                                     y_ndim - 2,
                                     y_dims[y_ndim - 2]));
Z
zyfncg 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  }
  const int N = trans_y ? y_dims[y_ndim - 2] : y_dims[y_ndim - 1];
  const int ndim = (std::max)(x_ndim, y_ndim);
  std::vector<std::int64_t> x_broadcast_dims(ndim);
  std::vector<std::int64_t> y_broadcast_dims(ndim);
  std::vector<std::int64_t> out_broadcast_dims(ndim);

  GetBroadcastFromDims(x_ndim - 2,
                       x_dims.data(),
                       y_ndim - 2,
                       y_dims.data(),
                       x_broadcast_dims.data(),
                       y_broadcast_dims.data(),
                       out_broadcast_dims.data());
  out_broadcast_dims[ndim - 2] = M;
  out_broadcast_dims[ndim - 1] = N;

332
  Out->ResizeAndAllocate(phi::make_ddim(out_broadcast_dims));
333
  dev_ctx.template Alloc<T>(Out);
Z
zyfncg 已提交
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

  const int batch_dim = ndim - 2;
  // broadcast message
  const bool is_broadcast_dims =
      !std::equal(x_broadcast_dims.cbegin(),
                  x_broadcast_dims.cbegin() + batch_dim,
                  y_broadcast_dims.cbegin());

  const std::int64_t x_batch_size =
      std::accumulate(x_broadcast_dims.cbegin(),
                      x_broadcast_dims.cbegin() + batch_dim,
                      1LL,
                      std::multiplies<std::int64_t>());
  const std::int64_t y_batch_size =
      std::accumulate(y_broadcast_dims.cbegin(),
                      y_broadcast_dims.cbegin() + batch_dim,
                      1LL,
                      std::multiplies<std::int64_t>());
  const std::int64_t out_batch_size =
      std::accumulate(out_broadcast_dims.cbegin(),
                      out_broadcast_dims.cbegin() + batch_dim,
                      1LL,
                      std::multiplies<std::int64_t>());
  if (out_batch_size == 0) return;
  if (x_batch_size == 1 && y_batch_size == 1) {
    VLOG(3) << "MatMul's case 8";
    blas.GEMM(trans_x ? CblasTrans : CblasNoTrans,
              trans_y ? CblasTrans : CblasNoTrans,
              M,
              N,
              K,
              static_cast<T>(1),
              x_data,
              y_data,
              static_cast<T>(flag),
369
              dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
370 371 372 373 374 375 376 377 378 379
  } else if (x_batch_size == 1) {
    if (M == 1 && trans_y) {
      VLOG(3) << "MatMul's case 9";
      blas.GEMV(false,
                y_batch_size * N,
                K,
                static_cast<T>(1),
                y_data,
                x_data,
                static_cast<T>(flag),
380
                dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
381 382 383 384 385 386 387 388 389 390 391
    } else {
      VLOG(3) << "MatMul's case 10";
      blas.BatchedGEMM(trans_x ? CblasTrans : CblasNoTrans,
                       trans_y ? CblasTrans : CblasNoTrans,
                       M,
                       N,
                       K,
                       static_cast<T>(1),
                       x_data,
                       y_data,
                       static_cast<T>(flag),
392
                       dev_ctx.template Alloc<T>(Out),
Z
zyfncg 已提交
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408
                       out_batch_size,
                       0,
                       K * N);
    }
  } else if (y_batch_size == 1) {
    if (!trans_x) {
      VLOG(3) << "MatMul's case 11";
      blas.GEMM(CblasNoTrans,
                trans_y ? CblasTrans : CblasNoTrans,
                x_batch_size * M,
                N,
                K,
                static_cast<T>(1),
                x_data,
                y_data,
                static_cast<T>(flag),
409
                dev_ctx.template Alloc<T>(Out));
Z
zyfncg 已提交
410 411 412 413 414 415 416 417 418 419 420
    } else {
      VLOG(3) << "MatMul's case 12";
      blas.BatchedGEMM(CblasTrans,
                       trans_y ? CblasTrans : CblasNoTrans,
                       M,
                       N,
                       K,
                       static_cast<T>(1),
                       x_data,
                       y_data,
                       static_cast<T>(flag),
421
                       dev_ctx.template Alloc<T>(Out),
Z
zyfncg 已提交
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
                       out_batch_size,
                       M * K,
                       0);
    }
  } else if (!is_broadcast_dims) {
    VLOG(3) << "MatMul's case 13";
    blas.BatchedGEMM(trans_x ? CblasTrans : CblasNoTrans,
                     trans_y ? CblasTrans : CblasNoTrans,
                     M,
                     N,
                     K,
                     static_cast<T>(1),
                     x_data,
                     y_data,
                     static_cast<T>(flag),
437
                     dev_ctx.template Alloc<T>(Out),
Z
zyfncg 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
                     out_batch_size,
                     M * K,
                     K * N);
  } else {
    // in the case, can't use stridedgemm
    std::vector<const T*> x_ptr(out_batch_size);
    std::vector<const T*> y_ptr(out_batch_size);
    std::vector<T*> out_ptr(out_batch_size);
    std::vector<std::int64_t> index(batch_dim, 0);
    for (std::int64_t i = 0; i < out_batch_size; ++i) {
      // using the index to get offset
      const std::int64_t x_index =
          GetIndexMessage(batch_dim, x_broadcast_dims.data(), index.data());
      const std::int64_t y_index =
          GetIndexMessage(batch_dim, y_broadcast_dims.data(), index.data());

      x_ptr[i] = x_data + x_index * M * K;
      y_ptr[i] = y_data + y_index * K * N;
456
      out_ptr[i] = dev_ctx.template Alloc<T>(Out) + i * M * N;
Z
zyfncg 已提交
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
      IndexIncreaseFromDims(batch_dim, out_broadcast_dims.data(), index.data());
    }
    VLOG(3) << "MatMul's case 14";
    blas.BatchedGEMM(trans_x ? CblasTrans : CblasNoTrans,
                     trans_y ? CblasTrans : CblasNoTrans,
                     M,
                     N,
                     K,
                     static_cast<T>(1),
                     x_ptr.data(),
                     y_ptr.data(),
                     static_cast<T>(flag),
                     out_ptr.data(),
                     out_batch_size);
  }
}

474
template <typename Context, typename T>
475
void MatMulFunction(const Context& dev_ctx,
Z
zyfncg 已提交
476 477 478 479 480 481 482 483
                    const DenseTensor& X,
                    const DenseTensor& Y,
                    DenseTensor* Out,
                    bool trans_x,
                    bool trans_y,
                    bool flag = false) {
  const std::vector<std::int64_t> x_dims = vectorize(X.dims());
  const std::vector<std::int64_t> y_dims = vectorize(Y.dims());
484
  MatMulFunction<Context, T>(
485
      dev_ctx, X, Y, x_dims, y_dims, Out, trans_x, trans_y, flag);
486 487 488
}

template <typename T, typename Context>
489
void MatmulKernel(const Context& dev_ctx,
490 491 492 493 494
                  const DenseTensor& x,
                  const DenseTensor& y,
                  bool transpose_x,
                  bool transpose_y,
                  DenseTensor* out) {
495 496 497 498 499 500 501 502 503 504
  PADDLE_ENFORCE_NE(
      phi::product(x.dims()),
      0,
      phi::errors::InvalidArgument("The Input(X) dims size must not be equal 0,"
                                   " but reviced dims size is 0. "));
  PADDLE_ENFORCE_NE(
      phi::product(y.dims()),
      0,
      phi::errors::InvalidArgument("The Input(Y) dims size must not be equal 0,"
                                   " but reviced dims size is 0. "));
505
  MatMulFunction<Context, T>(dev_ctx, x, y, out, transpose_x, transpose_y);
Z
zyfncg 已提交
506 507
}

508 509 510 511 512 513 514 515
template <typename T, typename Context>
void MatmulWithFlattenKernel(const Context& dev_ctx,
                             const DenseTensor& x,
                             const DenseTensor& y,
                             int x_num_col_dims,
                             int y_num_col_dims,
                             DenseTensor* out) {
  const DenseTensor x_matrix =
516
      x.dims().size() > 2 ? phi::ReshapeToMatrix(x, x_num_col_dims) : x;
517
  const DenseTensor y_matrix =
518
      y.dims().size() > 2 ? phi::ReshapeToMatrix(y, y_num_col_dims) : y;
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533

  dev_ctx.template Alloc<T>(out);
  auto z_dim = out->dims();
  if (z_dim.size() != 2) {
    out->Resize({x_matrix.dims()[0], y_matrix.dims()[1]});
  }

  auto blas = phi::funcs::GetBlas<Context, T>(dev_ctx);

  blas.MatMul(x_matrix, y_matrix, out);
  if (z_dim.size() != 2) {
    out->Resize(z_dim);
  }
}

534
}  // namespace phi