fused_gemm_epilogue_op.h 10.5 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
#if defined(PADDLE_WITH_CUDA) && CUDA_VERSION >= 11060
19
#include <cuda_runtime_api.h>
20

21 22 23
#include <algorithm>
#include <mutex>
#include <unordered_map>
24

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

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;

47 48 49 50 51 52 53 54 55 56 57 58 59
  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) {
60 61
    if (search_times_ <= 0) return nullptr;

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

79 80 81 82 83
    cublasLtMatmulPreference_t preference;
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulPreferenceCreate(&preference));
    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulPreferenceSetAttribute(
84 85 86 87
            preference,
            CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES,
            &workspace_size,
            sizeof(workspace_size)));
88 89 90 91 92 93

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

    PADDLE_ENFORCE_GT(
106 107
        returned_results,
        0,
108 109 110 111 112 113 114 115 116 117 118 119
        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(
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
          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);
136 137 138 139
      if (status != CUBLAS_STATUS_SUCCESS) {
        t = -1;
        warmup_algo_idx += 1;
        if (warmup_algo_idx == requested_algo_count_) {
140 141 142
          PADDLE_THROW(platform::errors::Unavailable(
              "No GEMM epilogue algorithm support!"));
        }
143 144
      }
    }
145

146 147 148 149 150 151 152 153 154 155
    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));

156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
        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);
173 174 175 176 177 178 179 180 181

        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;
182 183 184
        }
      }

185 186 187 188 189
      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;
      }
190 191
    }

192 193 194 195 196 197 198 199 200 201 202 203
    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";
204

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

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

221 222
  void HashMatmulDesc_(cublasLtMatmulDesc_t desc,
                       int64_t *seed,
223 224 225 226 227 228 229
                       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(
230 231 232 233
            desc,
            CUBLASLT_MATMUL_DESC_TRANSA,
            &trans_a,
            sizeof(trans_a),
234 235 236 237 238
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_a));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulDescGetAttribute(
239 240 241 242
            desc,
            CUBLASLT_MATMUL_DESC_TRANSB,
            &trans_b,
            sizeof(trans_b),
243 244 245 246 247
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(trans_b));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatmulDescGetAttribute(
248 249 250 251
            desc,
            CUBLASLT_MATMUL_DESC_EPILOGUE,
            &epilogue,
            sizeof(epilogue),
252 253 254 255
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(epilogue));
  }

256 257
  void HashMatrixLayoutDesc_(cublasLtMatrixLayout_t desc,
                             int64_t *seed,
258 259 260 261 262 263 264 265 266
                             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(
267 268 269 270
            desc,
            CUBLASLT_MATRIX_LAYOUT_TYPE,
            &dtype,
            sizeof(dtype),
271 272 273 274 275
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(dtype));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
276 277 278 279
            desc,
            CUBLASLT_MATRIX_LAYOUT_BATCH_COUNT,
            &batch,
            sizeof(batch),
280 281 282 283 284
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(batch));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
285 286 287 288
            desc,
            CUBLASLT_MATRIX_LAYOUT_ROWS,
            &row,
            sizeof(row),
289 290 291 292 293
            &size_to_write));
    HashValue_(seed, hash_fn, static_cast<int64_t>(row));

    PADDLE_ENFORCE_GPU_SUCCESS(
        platform::dynload::cublasLtMatrixLayoutGetAttribute(
294 295 296 297
            desc,
            CUBLASLT_MATRIX_LAYOUT_COLS,
            &col,
            sizeof(col),
298 299 300 301 302 303 304 305 306 307
            &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(
308 309 310 311 312
            desc,
            CUBLASLT_MATRIX_LAYOUT_STRIDED_BATCH_OFFSET,
            &batch_offset,
            sizeof(batch_offset),
            &size_to_write));
313 314 315
    HashValue_(seed, hash_fn, static_cast<int64_t>(batch_offset));
  }

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

}  // namespace operators
}  // namespace paddle
325
#endif