fused_gemm_epilogue_op.h 10.6 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
#ifdef PADDLE_WITH_CUDA

20
#include <cuda_runtime_api.h>
21 22 23
#include "cuda.h"  // NOLINT

#if CUDA_VERSION >= 11060
24

25 26 27
#include <algorithm>
#include <mutex>
#include <unordered_map>
28

29 30
#include "gflags/gflags.h"
#include "paddle/fluid/platform/dynload/cublasLt.h"
31
#include "paddle/fluid/platform/enforce.h"
32
#include "paddle/fluid/platform/float16.h"
33
#include "paddle/utils/optional.h"
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

DECLARE_int64(cublaslt_exhaustive_search_times);

namespace paddle {
namespace operators {

class GemmEpilogueAlgoCache {
 public:
  static GemmEpilogueAlgoCache &Instance() {
    static GemmEpilogueAlgoCache instance(
        FLAGS_cublaslt_exhaustive_search_times);
    return instance;
  }

  GemmEpilogueAlgoCache(GemmEpilogueAlgoCache const &) = delete;
  void operator=(GemmEpilogueAlgoCache const &) = delete;

51 52 53 54 55 56 57 58 59 60 61 62 63
  cublasLtMatmulAlgo_t *GetGemmAlgo(cublasLtHandle_t lt_handle,
                                    cublasLtMatmulDesc_t op_desc,
                                    cublasLtMatrixLayout_t a_desc,
                                    cublasLtMatrixLayout_t b_desc,
                                    cublasLtMatrixLayout_t c_desc,
                                    const void *alpha,
                                    const void *beta,
                                    const void *a,
                                    const void *b,
                                    void *c,
                                    cudaStream_t stream,
                                    void *workspace,
                                    size_t workspace_size) {
64 65
    if (search_times_ <= 0) return nullptr;

66 67 68 69 70 71 72 73 74 75 76
    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_);
77
      auto it = map_.find(seed);
78
      if (it != map_.end()) {
79
        return &(it->second);
80 81 82
      }
    }

83 84 85 86 87
    cublasLtMatmulPreference_t preference;
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulPreferenceCreate(&preference));
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulPreferenceSetAttribute(
88 89 90 91
            preference,
            CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES,
            &workspace_size,
            sizeof(workspace_size)));
92 93 94 95 96 97

    int returned_results = 0;
    std::vector<cublasLtMatmulHeuristicResult_t> heuristic_results(
        requested_algo_count_);
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulAlgoGetHeuristic(
98 99 100 101 102 103 104 105 106
            lt_handle,
            op_desc,
            a_desc,
            b_desc,
            c_desc,
            c_desc,
            preference,
            requested_algo_count_,
            heuristic_results.data(),
107 108 109
            &returned_results));

    PADDLE_ENFORCE_GT(
110 111
        returned_results,
        0,
112 113 114 115 116 117 118 119 120 121 122 123
        platform::errors::Unavailable("No GEMM epilogue algorithm support!"));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulPreferenceDestroy(preference));

    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++) {
      cublasStatus_t status = platform::dynload::cublasLtMatmul(
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
          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);
140 141 142 143
      if (status != CUBLAS_STATUS_SUCCESS) {
        t = -1;
        warmup_algo_idx += 1;
        if (warmup_algo_idx == requested_algo_count_) {
144 145 146
          PADDLE_THROW(platform::errors::Unavailable(
              "No GEMM epilogue algorithm support!"));
        }
147 148
      }
    }
149

150 151 152 153 154 155 156 157 158 159
    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));

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        cublasStatus_t status =
            platform::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);
177 178 179 180 181 182 183 184 185

        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;
186 187 188
        }
      }

189 190 191 192 193
      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;
      }
194 195
    }

196 197 198 199 200 201 202 203 204 205 206 207
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventDestroy(start_event));
    PADDLE_ENFORCE_GPU_SUCCESS(cudaEventDestroy(stop_event));

    if (best_algo_idx == -1) {
      PADDLE_THROW(
          platform::errors::Unavailable("No GEMM epilogue algorithm support!"));
    }

    ret = heuristic_results[best_algo_idx].algo;

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

209 210 211 212
    std::lock_guard<std::mutex> lock(cache_mutex_);
    auto &algo_in_map = map_[seed];
    algo_in_map = ret;
    return &algo_in_map;
213 214 215 216 217 218 219 220 221 222 223 224
  }

 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_;

225 226
  void HashMatmulDesc_(cublasLtMatmulDesc_t desc,
                       int64_t *seed,
227 228 229 230 231 232 233
                       const std::hash<int64_t> &hash_fn) {
    size_t size_to_write;
    int trans_a, trans_b;
    uint32_t epilogue;

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulDescGetAttribute(
234 235 236 237
            desc,
            CUBLASLT_MATMUL_DESC_TRANSA,
            &trans_a,
            sizeof(trans_a),
238 239 240 241 242
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_a));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulDescGetAttribute(
243 244 245 246
            desc,
            CUBLASLT_MATMUL_DESC_TRANSB,
            &trans_b,
            sizeof(trans_b),
247 248 249 250 251
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_b));

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

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

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

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

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
289 290 291 292
            desc,
            CUBLASLT_MATRIX_LAYOUT_ROWS,
            &row,
            sizeof(row),
293 294 295 296 297
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(row));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
298 299 300 301
            desc,
            CUBLASLT_MATRIX_LAYOUT_COLS,
            &col,
            sizeof(col),
302 303 304 305 306 307 308 309 310 311
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(col));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
            desc, CUBLASLT_MATRIX_LAYOUT_LD, &ld, sizeof(ld), &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(ld));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
312 313 314 315 316
            desc,
            CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET,
            &batch_offset,
            sizeof(batch_offset),
            &size_to_write));
317 318 319
    HashValue_(seed, hash_fn, static_cast<int64_t>(batch_offset));
  }

320 321
  void HashValue_(int64_t *seed,
                  const std::hash<int64_t> &hash_fn,
322 323 324 325 326 327 328
                  int64_t value) {
    *seed ^= hash_fn(value) + 0x9e3779b9 + (*seed << 6) + (*seed >> 2);
  }
};

}  // namespace operators
}  // namespace paddle
329 330

#endif
331
#endif