fused_gemm_epilogue.h 37.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
Copyright (c) 2022 NVIDIA 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

18 19 20 21
#include <algorithm>
#include <mutex>
#include <unordered_map>

22 23
#ifdef PADDLE_WITH_CUDA

24 25
#include <cuda_runtime_api.h>  // NOLINT
#include "cuda.h"              // NOLINT
26 27

#if CUDA_VERSION >= 11060
28

29
#include "gflags/gflags.h"
30
#include "glog/logging.h"
31
#include "paddle/phi/backends/all_context.h"
32
#include "paddle/phi/backends/dynload/cublasLt.h"
33 34
#include "paddle/phi/backends/gpu/cuda/cuda_helper.h"
#include "paddle/phi/common/amp_type_traits.h"
35 36
#include "paddle/phi/common/float16.h"
#include "paddle/phi/common/memory_utils.h"
37
#include "paddle/phi/core/dense_tensor.h"
38 39
#include "paddle/phi/core/enforce.h"
#include "paddle/phi/core/scope_guard.h"
40
#include "paddle/utils/optional.h"
41 42 43

DECLARE_int64(cublaslt_exhaustive_search_times);

44 45
namespace phi {
namespace funcs {
46 47 48

class GemmEpilogueAlgoCache {
 public:
49
  static GemmEpilogueAlgoCache& Instance() {
50 51 52 53 54
    static GemmEpilogueAlgoCache instance(
        FLAGS_cublaslt_exhaustive_search_times);
    return instance;
  }

55 56
  GemmEpilogueAlgoCache(GemmEpilogueAlgoCache const&) = delete;
  void operator=(GemmEpilogueAlgoCache const&) = delete;
57

58
  cublasLtMatmulAlgo_t* GetGemmAlgo(cublasLtHandle_t lt_handle,
59 60 61 62
                                    cublasLtMatmulDesc_t op_desc,
                                    cublasLtMatrixLayout_t a_desc,
                                    cublasLtMatrixLayout_t b_desc,
                                    cublasLtMatrixLayout_t c_desc,
63 64 65 66 67
                                    const void* alpha,
                                    const void* beta,
                                    const void* a,
                                    const void* b,
                                    void* c,
68
                                    cudaStream_t stream,
69
                                    void* workspace,
70
                                    size_t workspace_size) {
71 72
    if (search_times_ <= 0) return nullptr;

73 74 75 76 77 78 79 80 81 82 83
    int64_t seed = 0;
    std::hash<int64_t> hash_fn;

    HashMatmulDesc_(op_desc, &seed, hash_fn);
    HashMatrixLayoutDesc_(a_desc, &seed, hash_fn);
    HashMatrixLayoutDesc_(b_desc, &seed, hash_fn);
    HashMatrixLayoutDesc_(c_desc, &seed, hash_fn);

    cublasLtMatmulAlgo_t ret;
    {
      std::lock_guard<std::mutex> lock(cache_mutex_);
84
      auto it = map_.find(seed);
85
      if (it != map_.end()) {
86
        return &(it->second);
87 88 89
      }
    }

90 91
    cublasLtMatmulPreference_t preference;
    PADDLE_ENFORCE_GPU_SUCCESS(
92
        phi::dynload::cublasLtMatmulPreferenceCreate(&preference));
93
    PADDLE_ENFORCE_GPU_SUCCESS(
94
        phi::dynload::cublasLtMatmulPreferenceSetAttribute(
95 96 97 98
            preference,
            CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES,
            &workspace_size,
            sizeof(workspace_size)));
99 100 101 102 103

    int returned_results = 0;
    std::vector<cublasLtMatmulHeuristicResult_t> heuristic_results(
        requested_algo_count_);
    PADDLE_ENFORCE_GPU_SUCCESS(
104 105 106 107 108 109 110 111 112 113
        phi::dynload::cublasLtMatmulAlgoGetHeuristic(lt_handle,
                                                     op_desc,
                                                     a_desc,
                                                     b_desc,
                                                     c_desc,
                                                     c_desc,
                                                     preference,
                                                     requested_algo_count_,
                                                     heuristic_results.data(),
                                                     &returned_results));
114 115

    PADDLE_ENFORCE_GT(
116 117
        returned_results,
        0,
118
        phi::errors::Unavailable("No GEMM epilogue algorithm support!"));
119 120

    PADDLE_ENFORCE_GPU_SUCCESS(
121
        phi::dynload::cublasLtMatmulPreferenceDestroy(preference));
122 123 124 125 126 127 128

    int best_algo_idx = -1;
    float best_algo_time = 0;

    // Run 100 times for warmup
    int warmup_algo_idx = 0;
    for (int t = 0; t < 100; t++) {
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
      cublasStatus_t status =
          phi::dynload::cublasLtMatmul(lt_handle,
                                       op_desc,
                                       alpha,
                                       a,
                                       a_desc,
                                       b,
                                       b_desc,
                                       beta,
                                       c,
                                       c_desc,
                                       c,
                                       c_desc,
                                       &heuristic_results[warmup_algo_idx].algo,
                                       workspace,
                                       workspace_size,
                                       stream);
146 147 148 149
      if (status != CUBLAS_STATUS_SUCCESS) {
        t = -1;
        warmup_algo_idx += 1;
        if (warmup_algo_idx == requested_algo_count_) {
150 151
          PADDLE_THROW(
              phi::errors::Unavailable("No GEMM epilogue algorithm support!"));
152
        }
153 154
      }
    }
155

156 157 158 159 160 161 162 163 164 165
    cudaEvent_t start_event, stop_event;
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventCreate(&start_event));
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventCreate(&stop_event));

    for (int algo_idx = 0; algo_idx < returned_results; ++algo_idx) {
      float curr_time = 0;
      for (int check_idx = 0; check_idx < search_times_; check_idx++) {
        float time = 0;
        PADDLE_ENFORCE_GPU_SUCCESS(cudaEventRecord(start_event, stream));

166
        cublasStatus_t status =
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            phi::dynload::cublasLtMatmul(lt_handle,
                                         op_desc,
                                         alpha,
                                         a,
                                         a_desc,
                                         b,
                                         b_desc,
                                         beta,
                                         c,
                                         c_desc,
                                         c,
                                         c_desc,
                                         &heuristic_results[algo_idx].algo,
                                         workspace,
                                         workspace_size,
                                         stream);
183 184 185 186 187 188 189 190 191

        PADDLE_ENFORCE_GPU_SUCCESS(cudaEventRecord(stop_event, stream));
        PADDLE_ENFORCE_GPU_SUCCESS(cudaEventSynchronize(stop_event));
        PADDLE_ENFORCE_GPU_SUCCESS(
            cudaEventElapsedTime(&time, start_event, stop_event));
        curr_time += time;
        if (status != CUBLAS_STATUS_SUCCESS) {
          curr_time = 3.40282e+038;  // Max Value of float
          break;
192 193 194
        }
      }

195 196 197 198 199
      curr_time = curr_time / search_times_;
      if (curr_time < best_algo_time || algo_idx == 0) {
        best_algo_idx = algo_idx;
        best_algo_time = curr_time;
      }
200 201
    }

202 203 204 205 206
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventDestroy(start_event));
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventDestroy(stop_event));

    if (best_algo_idx == -1) {
      PADDLE_THROW(
207
          phi::errors::Unavailable("No GEMM epilogue algorithm support!"));
208 209 210 211 212 213
    }

    ret = heuristic_results[best_algo_idx].algo;

    VLOG(4) << "Search time:" << search_times_ << ", hash-key (" << seed
            << ") not found in GemmEpilogueAlgoCache";
214

215
    std::lock_guard<std::mutex> lock(cache_mutex_);
216
    auto& algo_in_map = map_[seed];
217 218
    algo_in_map = ret;
    return &algo_in_map;
219 220 221 222 223 224 225 226 227 228 229 230
  }

 private:
  explicit GemmEpilogueAlgoCache(int search_times)
      : search_times_(search_times) {
    map_.clear();
  }
  std::unordered_map<int64_t, cublasLtMatmulAlgo_t> map_;
  int search_times_;
  const int requested_algo_count_ = 10;
  std::mutex cache_mutex_;

231
  void HashMatmulDesc_(cublasLtMatmulDesc_t desc,
232 233
                       int64_t* seed,
                       const std::hash<int64_t>& hash_fn) {
234 235 236 237
    size_t size_to_write;
    int trans_a, trans_b;
    uint32_t epilogue;

238 239 240 241 242 243
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescGetAttribute(
        desc,
        CUBLASLT_MATMUL_DESC_TRANSA,
        &trans_a,
        sizeof(trans_a),
        &size_to_write));
244 245
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_a));

246 247 248 249 250 251
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescGetAttribute(
        desc,
        CUBLASLT_MATMUL_DESC_TRANSB,
        &trans_b,
        sizeof(trans_b),
        &size_to_write));
252 253
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_b));

254 255 256 257 258 259
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescGetAttribute(
        desc,
        CUBLASLT_MATMUL_DESC_EPILOGUE,
        &epilogue,
        sizeof(epilogue),
        &size_to_write));
260 261 262
    HashValue_(seed, hash_fn, static_cast<int64_t>(epilogue));
  }

263
  void HashMatrixLayoutDesc_(cublasLtMatrixLayout_t desc,
264 265
                             int64_t* seed,
                             const std::hash<int64_t>& hash_fn) {
266 267 268 269 270 271
    size_t size_to_write;
    uint32_t dtype;
    int32_t batch;
    uint64_t row, col;
    int64_t ld, batch_offset;

272 273 274 275 276 277
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc,
        CUBLASLT_MATRIX_LAYOUT_TYPE,
        &dtype,
        sizeof(dtype),
        &size_to_write));
278 279
    HashValue_(seed, hash_fn, static_cast<int64_t>(dtype));

280 281 282 283 284 285
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc,
        CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT,
        &batch,
        sizeof(batch),
        &size_to_write));
286 287
    HashValue_(seed, hash_fn, static_cast<int64_t>(batch));

288 289
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc, CUBLASLT_MATRIX_LAYOUT_ROWS, &row, sizeof(row), &size_to_write));
290 291
    HashValue_(seed, hash_fn, static_cast<int64_t>(row));

292 293
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc, CUBLASLT_MATRIX_LAYOUT_COLS, &col, sizeof(col), &size_to_write));
294 295
    HashValue_(seed, hash_fn, static_cast<int64_t>(col));

296 297
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc, CUBLASLT_MATRIX_LAYOUT_LD, &ld, sizeof(ld), &size_to_write));
298 299
    HashValue_(seed, hash_fn, static_cast<int64_t>(ld));

300 301 302 303 304 305
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutGetAttribute(
        desc,
        CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET,
        &batch_offset,
        sizeof(batch_offset),
        &size_to_write));
306 307 308
    HashValue_(seed, hash_fn, static_cast<int64_t>(batch_offset));
  }

309 310
  void HashValue_(int64_t* seed,
                  const std::hash<int64_t>& hash_fn,
311 312 313 314 315
                  int64_t value) {
    *seed ^= hash_fn(value) + 0x9e3779b9 + (*seed << 6) + (*seed >> 2);
  }
};

316 317 318 319 320 321 322 323 324 325 326
static cublasLtEpilogue_t GetEpilogueType(const std::string& activation,
                                          bool enable_auxiliary) {
  if (activation == "relu") {
    return enable_auxiliary ? CUBLASLT_EPILOGUE_RELU_AUX_BIAS
                            : CUBLASLT_EPILOGUE_RELU_BIAS;
  } else if (activation == "gelu") {
    return enable_auxiliary ? CUBLASLT_EPILOGUE_GELU_AUX_BIAS
                            : CUBLASLT_EPILOGUE_GELU_BIAS;
  } else if (activation == "none") {
    return CUBLASLT_EPILOGUE_BIAS;
  } else {
327
    PADDLE_THROW(phi::errors::InvalidArgument(
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
        "The activation attribute of fused_gemm_epilogue op should be"
        " one of {\"none\", \"relu\", \"gelu\"}. But received %s."
        "But received activation=%s.",
        activation));
  }
}

template <typename T>
void ComputeFusedGemmEpilogueForward(const phi::GPUContext& dev_ctx,
                                     const phi::DenseTensor* x,
                                     const phi::DenseTensor* y,
                                     const phi::DenseTensor* bias,
                                     int64_t M,
                                     int64_t N,
                                     int64_t K,
                                     bool trans_x,
                                     bool trans_y,
                                     const std::string& activation,
                                     phi::DenseTensor* out,
                                     phi::DenseTensor* reserve_space) {
  using MT = typename phi::dtype::MPTypeTrait<T>::Type;

  VLOG(6) << "x.shape={" << x->dims() << "}, y.shape={" << y->dims()
          << "}, out.shape={" << out->dims() << "}, M=" << M << ", N=" << N
          << ", K=" << K << ", trans_x=" << trans_x << ", trans_y=" << trans_y
          << ", activation=" << activation
          << ", reserve_space=" << reserve_space;

  bool enable_auxiliary = reserve_space == nullptr ? false : true;
  auto* out_data = out->data<T>();

  cudaDataType_t mat_type = phi::backends::gpu::ToCudaDataType<T>();
  cudaDataType_t scale_type = phi::backends::gpu::ToCudaDataType<MT>();
  cublasComputeType_t compute_type = CUBLAS_COMPUTE_32F;
  if (std::is_same<T, double>::value) {
    compute_type = CUBLAS_COMPUTE_64F;
  }

  cublasLtMatmulDesc_t operation_desc = NULL;
367
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescCreate(
368 369 370
      &operation_desc, compute_type, scale_type));
  cublasOperation_t transx = trans_x ? CUBLAS_OP_T : CUBLAS_OP_N;
  cublasOperation_t transy = trans_y ? CUBLAS_OP_T : CUBLAS_OP_N;
371
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
372
      operation_desc, CUBLASLT_MATMUL_DESC_TRANSB, &transx, sizeof(transx)));
373
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
374 375 376 377
      operation_desc, CUBLASLT_MATMUL_DESC_TRANSA, &transy, sizeof(transy)));

  cublasLtEpilogue_t epiloque_func =
      GetEpilogueType(activation, enable_auxiliary);
378
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
379 380 381 382 383
      operation_desc,
      CUBLASLT_MATMUL_DESC_EPILOGUE,
      &epiloque_func,
      sizeof(epiloque_func)));
  const T* bias_data = bias->data<T>();
384
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
      operation_desc,
      CUBLASLT_MATMUL_DESC_BIAS_POINTER,
      &bias_data,
      sizeof(bias_data)));

  if (enable_auxiliary && activation != "none") {
    // Note (Ming Huang): The initialization of ReseveSpace is happened in the
    // dev_ctx.Alloc. Therefore, we set real date type up here.
    if (activation == "relu") {
      phi::DataType rs_type = phi::DataType::BOOL;
      size_t reserve_space_size =
          phi::product(reserve_space->dims()) * SizeOf(rs_type);
      dev_ctx.Alloc(reserve_space, rs_type, reserve_space_size);
    } else {
      size_t reserve_space_size =
          phi::product(reserve_space->dims()) * sizeof(T);
      dev_ctx.Alloc<T>(reserve_space, reserve_space_size);
    }

    void* aux_data = reserve_space->data();

406 407 408 409 410
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        operation_desc,
        CUBLASLT_MATMUL_DESC_EPILOGUE_AUX_POINTER,
        &aux_data,
        sizeof(aux_data)));
411
    int64_t aux_ld = N;
412 413 414 415 416
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        operation_desc,
        CUBLASLT_MATMUL_DESC_EPILOGUE_AUX_LD,
        &aux_ld,
        sizeof(aux_ld)));
417 418 419 420
  }

  cublasLtMatrixLayout_t x_desc = NULL, y_desc = NULL, out_desc = NULL;
  if (trans_x) {
421 422
    PADDLE_ENFORCE_GPU_SUCCESS(
        phi::dynload::cublasLtMatrixLayoutCreate(&x_desc, mat_type, M, K, M));
423
  } else {
424 425
    PADDLE_ENFORCE_GPU_SUCCESS(
        phi::dynload::cublasLtMatrixLayoutCreate(&x_desc, mat_type, K, M, K));
426 427
  }
  if (trans_y) {
428 429
    PADDLE_ENFORCE_GPU_SUCCESS(
        phi::dynload::cublasLtMatrixLayoutCreate(&y_desc, mat_type, K, N, K));
430
  } else {
431 432
    PADDLE_ENFORCE_GPU_SUCCESS(
        phi::dynload::cublasLtMatrixLayoutCreate(&y_desc, mat_type, N, K, N));
433
  }
434 435
  PADDLE_ENFORCE_GPU_SUCCESS(
      phi::dynload::cublasLtMatrixLayoutCreate(&out_desc, mat_type, N, M, N));
436 437 438 439 440 441

  cublasLtHandle_t lt_handle = dev_ctx.cublaslt_handle();
  // NOTE(zengjinle): I do not know whether the 4MB workspace size is
  // "enough". I just followed the settings from the NVIDIA MLPerf BERT code.
  size_t workspace_size = static_cast<size_t>(4) * 1024 * 1024;
  cudaStream_t stream = dev_ctx.stream();
442
  auto workspace = memory_utils::Alloc(
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
      dev_ctx.GetPlace(),
      workspace_size,
      phi::Stream(reinterpret_cast<phi::StreamId>(dev_ctx.stream())));

  MT alpha = static_cast<MT>(1);
  MT beta = static_cast<MT>(0);

  const auto* y_data = y->data<T>();
  const auto* x_data = x->data<T>();

  auto algo = GemmEpilogueAlgoCache::Instance().GetGemmAlgo(lt_handle,
                                                            operation_desc,
                                                            y_desc,
                                                            x_desc,
                                                            out_desc,
                                                            &alpha,
                                                            &beta,
                                                            y_data,
                                                            x_data,
                                                            out_data,
                                                            stream,
                                                            workspace->ptr(),
                                                            workspace_size);
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmul(lt_handle,
                                                          operation_desc,
                                                          &alpha,
                                                          y_data,
                                                          y_desc,
                                                          x_data,
                                                          x_desc,
                                                          &beta,
                                                          out_data,
                                                          out_desc,
                                                          out_data,
                                                          out_desc,
                                                          algo,
                                                          workspace->ptr(),
                                                          workspace_size,
                                                          stream));
482 483

  PADDLE_ENFORCE_GPU_SUCCESS(
484 485 486
      phi::dynload::cublasLtMatmulDescDestroy(operation_desc));
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutDestroy(y_desc));
  PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutDestroy(x_desc));
487
  PADDLE_ENFORCE_GPU_SUCCESS(
488
      phi::dynload::cublasLtMatrixLayoutDestroy(out_desc));
489 490
}

491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
enum FusedGEMMGradInType { kDX = 0, kDY = 1, kDZ = 2 };

template <bool TransX, bool TransY>
struct FusedGEMMGradTrait;

template <>
struct FusedGEMMGradTrait<false, false> {
  static constexpr auto kXGradA = FusedGEMMGradInType::kDZ;
  static constexpr auto kXGradB = FusedGEMMGradInType::kDY;
  static constexpr auto kXGradATrans = false;
  static constexpr auto kXGradBTrans = true;

  static constexpr auto kYGradA = FusedGEMMGradInType::kDX;
  static constexpr auto kYGradB = FusedGEMMGradInType::kDZ;
  static constexpr auto kYGradATrans = true;
  static constexpr auto kYGradBTrans = false;
};

template <>
struct FusedGEMMGradTrait<true, false> {
  static constexpr auto kXGradA = FusedGEMMGradInType::kDY;
  static constexpr auto kXGradB = FusedGEMMGradInType::kDZ;
  static constexpr auto kXGradATrans = false;
  static constexpr auto kXGradBTrans = true;

  static constexpr auto kYGradA = FusedGEMMGradInType::kDX;
  static constexpr auto kYGradB = FusedGEMMGradInType::kDZ;
  static constexpr auto kYGradATrans = false;
  static constexpr auto kYGradBTrans = false;
};

template <>
struct FusedGEMMGradTrait<false, true> {
  static constexpr auto kXGradA = FusedGEMMGradInType::kDZ;
  static constexpr auto kXGradB = FusedGEMMGradInType::kDY;
  static constexpr auto kXGradATrans = false;
  static constexpr auto kXGradBTrans = false;

  static constexpr auto kYGradA = FusedGEMMGradInType::kDZ;
  static constexpr auto kYGradB = FusedGEMMGradInType::kDX;
  static constexpr auto kYGradATrans = true;
  static constexpr auto kYGradBTrans = false;
};

template <>
struct FusedGEMMGradTrait<true, true> {
  static constexpr auto kXGradA = FusedGEMMGradInType::kDY;
  static constexpr auto kXGradB = FusedGEMMGradInType::kDZ;
  static constexpr auto kXGradATrans = true;
  static constexpr auto kXGradBTrans = true;

  static constexpr auto kYGradA = FusedGEMMGradInType::kDZ;
  static constexpr auto kYGradB = FusedGEMMGradInType::kDX;
  static constexpr auto kYGradATrans = true;
  static constexpr auto kYGradBTrans = true;
};

static constexpr auto BoolToCuBlasEnum(bool transpose) {
  return transpose ? CUBLAS_OP_T : CUBLAS_OP_N;
}

static cublasLtEpilogue_t GetEpilogueGradType(
    const std::string& activation_grad) {
554 555 556
  if (activation_grad == "none") {
    return CUBLASLT_EPILOGUE_DEFAULT;
  } else if (activation_grad == "relu_grad") {
557 558 559 560
    return CUBLASLT_EPILOGUE_DRELU;
  } else if (activation_grad == "gelu_grad") {
    return CUBLASLT_EPILOGUE_DGELU;
  } else {
561
    PADDLE_THROW(phi::errors::InvalidArgument(
562 563 564 565 566 567 568
        "The activation_grad attribute of fused_gemm_epilogue op should "
        "be one of {\"none\", \"relu\", \"gelu\"}. But received %s."
        "But received activation_grad=%s.",
        activation_grad));
  }
}

569
template <typename T, typename DXT, typename DYT, bool TransX, bool TransY>
570 571 572 573 574 575 576 577 578 579 580 581
void ComputeFusedGemmEpilogueBackwardImpl(const phi::GPUContext& dev_ctx,
                                          const phi::DenseTensor* dout,
                                          const phi::DenseTensor* x,
                                          const phi::DenseTensor* y,
                                          const phi::DenseTensor* reserve_space,
                                          int64_t M,
                                          int64_t N,
                                          int64_t K,
                                          const std::string activation_grad,
                                          phi::DenseTensor* dx,
                                          phi::DenseTensor* dy,
                                          phi::DenseTensor* dbias,
582 583
                                          bool use_addto_dx,
                                          bool use_addto_dy) {
584
  using MT = typename phi::dtype::MPTypeTrait<T>::Type;
S
sneaxiy 已提交
585 586 587 588
  constexpr bool kIsValidDataType =
      (std::is_same<DXT, T>::value || std::is_same<DXT, MT>::value) &&
      (std::is_same<DYT, T>::value || std::is_same<DYT, MT>::value);
  static_assert(kIsValidDataType, "Invalid data type");
589

590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
  using Trait = FusedGEMMGradTrait<TransX, TransY>;

  cudaDataType_t mat_type = phi::backends::gpu::ToCudaDataType<T>();
  cudaDataType_t scale_type = phi::backends::gpu::ToCudaDataType<MT>();
  cublasComputeType_t compute_type = CUBLAS_COMPUTE_32F;
  if (std::is_same<T, double>::value) {
    compute_type = CUBLAS_COMPUTE_64F;
  }

  cublasLtHandle_t lt_handle = dev_ctx.cublaslt_handle();
  // NOTE(zengjinle): I do not know whether the 4MB workspace size is
  // "enough". I just followed the settings from the NVIDIA MLPerf BERT code.
  size_t workspace_size = static_cast<size_t>(4) * 1024 * 1024;
  const cublasLtMatmulAlgo_t* algo = nullptr;
  cudaStream_t stream = dev_ctx.stream();

  MT alpha = static_cast<MT>(1.0);
607 608
  MT beta_dx = use_addto_dx ? static_cast<MT>(1.0) : static_cast<MT>(0.0);
  MT beta_dy = use_addto_dy ? static_cast<MT>(1.0) : static_cast<MT>(0.0);
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627

  cublasLtMatrixLayout_t dout_desc = nullptr, dout_trans_desc = nullptr;
  cublasLtMatrixLayout_t x_desc = nullptr, x_trans_desc = nullptr;
  cublasLtMatrixLayout_t y_desc = nullptr, y_trans_desc = nullptr;
  cublasLtMatrixLayout_t dx_desc = nullptr, dy_desc = nullptr;
  cublasLtMatmulDesc_t dx_operation_desc = nullptr, dy_operation_desc = nullptr;

  DEFINE_PADDLE_SCOPE_GUARD([&] {
    auto descs = {dout_desc,
                  dout_trans_desc,
                  x_desc,
                  x_trans_desc,
                  y_desc,
                  y_trans_desc,
                  dx_desc,
                  dy_desc};
    for (auto desc : descs) {
      if (desc) {
        PADDLE_ENFORCE_GPU_SUCCESS(
628
            phi::dynload::cublasLtMatrixLayoutDestroy(desc));
629 630 631 632 633
      }
    }

    if (dx_operation_desc) {
      PADDLE_ENFORCE_GPU_SUCCESS(
634
          phi::dynload::cublasLtMatmulDescDestroy(dx_operation_desc));
635 636 637 638
    }

    if (dy_operation_desc) {
      PADDLE_ENFORCE_GPU_SUCCESS(
639
          phi::dynload::cublasLtMatmulDescDestroy(dy_operation_desc));
640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
    }
  });

  auto x_row = TransX ? K : M;
  auto x_col = TransX ? M : K;
  auto y_row = TransY ? N : K;
  auto y_col = TransY ? K : N;
  auto z_row = TransX ? N : M;
  auto z_col = TransX ? M : N;

  // dx = func(dout, y)
  if (dx) {
    constexpr auto kXGradAIsDZ = (Trait::kXGradA == FusedGEMMGradInType::kDZ);
    cublasLtMatrixLayout_t *dx_dout_desc, *dx_y_desc;

    if (TransX) {
      dx_dout_desc = &dout_trans_desc;
657
      PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
658 659 660
          dx_dout_desc, mat_type, z_row, z_col, z_row));
    } else {
      dx_dout_desc = &dout_desc;
661
      PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
662 663 664 665
          dx_dout_desc, mat_type, z_col, z_row, z_col));
    }

    dx_y_desc = &y_trans_desc;
666
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
667 668 669 670 671 672 673
        dx_y_desc, mat_type, y_col, y_row, y_col));

    auto& a_desc = kXGradAIsDZ ? (*dx_dout_desc) : (*dx_y_desc);
    auto& b_desc = kXGradAIsDZ ? (*dx_y_desc) : (*dx_dout_desc);
    auto a_trans = BoolToCuBlasEnum(Trait::kXGradATrans);
    auto b_trans = BoolToCuBlasEnum(Trait::kXGradBTrans);

674
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
675 676 677 678 679
        &dx_desc,
        phi::backends::gpu::ToCudaDataType<DXT>(),
        x_col,
        x_row,
        x_col));
680

681
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescCreate(
682
        &dx_operation_desc, compute_type, scale_type));
683 684 685 686 687 688 689 690 691 692
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dx_operation_desc,
        CUBLASLT_MATMUL_DESC_TRANSB,
        &a_trans,
        sizeof(a_trans)));
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dx_operation_desc,
        CUBLASLT_MATMUL_DESC_TRANSA,
        &b_trans,
        sizeof(b_trans)));
693 694 695

    cublasLtEpilogue_t epiloque_func_for_dx =
        GetEpilogueGradType(activation_grad);
696 697 698 699 700
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dx_operation_desc,
        CUBLASLT_MATMUL_DESC_EPILOGUE,
        &epiloque_func_for_dx,
        sizeof(epiloque_func_for_dx)));
701 702 703

    if (activation_grad != "none") {
      auto* aux_data = reserve_space->data();
704 705 706 707 708
      PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
          dx_operation_desc,
          CUBLASLT_MATMUL_DESC_EPILOGUE_AUX_POINTER,
          &aux_data,
          sizeof(aux_data)));
709
      int64_t aux_ld = TransX ? M : K;
710 711 712 713 714
      PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
          dx_operation_desc,
          CUBLASLT_MATMUL_DESC_EPILOGUE_AUX_LD,
          &aux_ld,
          sizeof(aux_ld)));
715 716
    }

717
    auto dx_workspace = memory_utils::Alloc(
718 719 720 721
        dev_ctx.GetPlace(),
        workspace_size,
        phi::Stream(reinterpret_cast<phi::StreamId>(dev_ctx.stream())));

722
    auto* dx_data = dev_ctx.Alloc<DXT>(dx, dx->numel() * sizeof(DXT));
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    const auto* y_data = y->data<T>();
    const auto* dout_data = dout->data<T>();
    const auto* a_data = kXGradAIsDZ ? dout_data : y_data;
    const auto* b_data = kXGradAIsDZ ? y_data : dout_data;

    auto algo =
        GemmEpilogueAlgoCache::Instance().GetGemmAlgo(lt_handle,
                                                      dx_operation_desc,
                                                      b_desc,
                                                      a_desc,
                                                      dx_desc,
                                                      &alpha,
                                                      &beta_dx,
                                                      b_data,
                                                      a_data,
                                                      dx_data,
                                                      stream,
                                                      dx_workspace->ptr(),
                                                      workspace_size);

743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmul(lt_handle,
                                                            dx_operation_desc,
                                                            &alpha,
                                                            b_data,
                                                            b_desc,
                                                            a_data,
                                                            a_desc,
                                                            &beta_dx,
                                                            dx_data,
                                                            dx_desc,
                                                            dx_data,
                                                            dx_desc,
                                                            algo,
                                                            dx_workspace->ptr(),
                                                            workspace_size,
                                                            stream));
759 760 761 762 763 764 765 766 767 768
  }

  // dy = func(dout, x)
  if (dy) {
    constexpr auto kYGradAIsDZ = (Trait::kYGradA == FusedGEMMGradInType::kDZ);

    cublasLtMatrixLayout_t *dy_dout_desc = nullptr, *dy_x_desc = nullptr;
    if (TransX) {
      dy_dout_desc = &dout_trans_desc;
      if (dout_trans_desc == nullptr) {
769 770
        PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
            dy_dout_desc, mat_type, z_row, z_col, z_row));
771 772 773 774
      }
    } else {
      dy_dout_desc = &dout_desc;
      if (dout_desc == nullptr) {
775 776
        PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
            dy_dout_desc, mat_type, z_col, z_row, z_col));
777 778 779 780
      }
    }

    dy_x_desc = &x_trans_desc;
781
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
782 783 784 785 786 787 788
        dy_x_desc, mat_type, x_col, x_row, x_col));

    auto& a_desc = kYGradAIsDZ ? (*dy_dout_desc) : (*dy_x_desc);
    auto& b_desc = kYGradAIsDZ ? (*dy_x_desc) : (*dy_dout_desc);
    auto a_trans = BoolToCuBlasEnum(Trait::kYGradATrans);
    auto b_trans = BoolToCuBlasEnum(Trait::kYGradBTrans);

789
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatrixLayoutCreate(
790 791 792 793 794
        &dy_desc,
        phi::backends::gpu::ToCudaDataType<DYT>(),
        y_col,
        y_row,
        y_col));
795

796
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescCreate(
797 798
        &dy_operation_desc, compute_type, scale_type));

799 800 801 802 803 804 805 806 807 808
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dy_operation_desc,
        CUBLASLT_MATMUL_DESC_TRANSB,
        &a_trans,
        sizeof(a_trans)));
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dy_operation_desc,
        CUBLASLT_MATMUL_DESC_TRANSA,
        &b_trans,
        sizeof(b_trans)));
809 810 811 812 813 814 815 816 817 818 819 820

    cublasLtEpilogue_t epiloque_func_for_dy;
    if (dbias == nullptr) {
      epiloque_func_for_dy = CUBLASLT_EPILOGUE_DEFAULT;
    } else {
      if (TransY) {
        epiloque_func_for_dy = CUBLASLT_EPILOGUE_BGRADB;
      } else {
        epiloque_func_for_dy = CUBLASLT_EPILOGUE_BGRADA;
      }
    }

821 822 823 824 825
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
        dy_operation_desc,
        CUBLASLT_MATMUL_DESC_EPILOGUE,
        &epiloque_func_for_dy,
        sizeof(epiloque_func_for_dy)));
826 827

    if (dbias) {
828 829
      auto* dbias_data =
          dev_ctx.Alloc<DYT>(dbias, dbias->numel() * sizeof(DYT));
830 831 832 833 834
      PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmulDescSetAttribute(
          dy_operation_desc,
          CUBLASLT_MATMUL_DESC_BIAS_POINTER,
          &dbias_data,
          sizeof(dbias_data)));
835 836
    }

837
    auto dy_workspace = memory_utils::Alloc(
838 839 840
        dev_ctx.GetPlace(),
        workspace_size,
        phi::Stream(reinterpret_cast<phi::StreamId>(dev_ctx.stream())));
841
    auto* dy_data = dev_ctx.Alloc<DYT>(dy, dy->numel() * sizeof(DYT));
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861
    const auto* dout_data = dout->data<T>();
    const auto* x_data = x->data<T>();
    const auto* a_data = kYGradAIsDZ ? dout_data : x_data;
    const auto* b_data = kYGradAIsDZ ? x_data : dout_data;

    auto algo =
        GemmEpilogueAlgoCache::Instance().GetGemmAlgo(lt_handle,
                                                      dy_operation_desc,
                                                      b_desc,
                                                      a_desc,
                                                      dy_desc,
                                                      &alpha,
                                                      &beta_dy,
                                                      b_data,
                                                      a_data,
                                                      dy_data,
                                                      stream,
                                                      dy_workspace->ptr(),
                                                      workspace_size);

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
    PADDLE_ENFORCE_GPU_SUCCESS(phi::dynload::cublasLtMatmul(lt_handle,
                                                            dy_operation_desc,
                                                            &alpha,
                                                            b_data,
                                                            b_desc,
                                                            a_data,
                                                            a_desc,
                                                            &beta_dy,
                                                            dy_data,
                                                            dy_desc,
                                                            dy_data,
                                                            dy_desc,
                                                            algo,
                                                            dy_workspace->ptr(),
                                                            workspace_size,
                                                            stream));
878 879 880
  }
}

881
template <typename T, typename DXT = T, typename DYT = T>
882 883 884 885 886 887 888 889 890 891 892 893 894 895
void ComputeFusedGemmEpilogueBackward(const phi::GPUContext& dev_ctx,
                                      const phi::DenseTensor* dout,
                                      const phi::DenseTensor* x,
                                      const phi::DenseTensor* y,
                                      const phi::DenseTensor* reserve_space,
                                      int64_t M,
                                      int64_t N,
                                      int64_t K,
                                      bool trans_x,
                                      bool trans_y,
                                      const std::string& activation_grad,
                                      phi::DenseTensor* dx,
                                      phi::DenseTensor* dy,
                                      phi::DenseTensor* dbias,
896 897
                                      bool use_addto_dx = false,
                                      bool use_addto_dy = false) {
898 899 900 901 902 903
  VLOG(10) << "M=" << M << ", K=" << K << ", N=" << N << ", trans_x=" << trans_x
           << ", trans_y=" << trans_y
           << ", activation_grad=" << activation_grad;

  if (trans_x) {
    if (trans_y) {
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
      ComputeFusedGemmEpilogueBackwardImpl<T, DXT, DYT, true, true>(
          dev_ctx,
          dout,
          x,
          y,
          reserve_space,
          M,
          N,
          K,
          activation_grad,
          dx,
          dy,
          dbias,
          use_addto_dx,
          use_addto_dy);
919
    } else {
920 921 922 923 924 925 926 927 928 929 930 931 932 933 934
      ComputeFusedGemmEpilogueBackwardImpl<T, DXT, DYT, true, false>(
          dev_ctx,
          dout,
          x,
          y,
          reserve_space,
          M,
          N,
          K,
          activation_grad,
          dx,
          dy,
          dbias,
          use_addto_dx,
          use_addto_dy);
935 936 937
    }
  } else {
    if (trans_y) {
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
      ComputeFusedGemmEpilogueBackwardImpl<T, DXT, DYT, false, true>(
          dev_ctx,
          dout,
          x,
          y,
          reserve_space,
          M,
          N,
          K,
          activation_grad,
          dx,
          dy,
          dbias,
          use_addto_dx,
          use_addto_dy);
953
    } else {
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
      ComputeFusedGemmEpilogueBackwardImpl<T, DXT, DYT, false, false>(
          dev_ctx,
          dout,
          x,
          y,
          reserve_space,
          M,
          N,
          K,
          activation_grad,
          dx,
          dy,
          dbias,
          use_addto_dx,
          use_addto_dy);
969 970 971 972
    }
  }
}

973 974
}  // namespace funcs
}  // namespace phi
975
#endif
976
#endif