cuDNN vs cuBLAS performance on GEMMs

What is the performance on cuDNN vs cuBLAS on unfused gemms?
Does cuDNN use cuBLAS internatlly?


When trying to benchmark a set of gemms cuDNN performs much worse than cuBLAS. I created the following to benchmark scripts to measure the kernel runtime of batched gemms. Did I miss something that explains the slow performance of cuDNN in

// benchmark_cublas.cc

#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>
#include <vector>

#include "third_party/gpus/cuda/include/cublas_v2.h"
#include "third_party/gpus/cuda/include/cuda_runtime.h"
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "third_party/gpus/cuda/include/driver_types.h"
#include "third_party/gpus/cuda/include/library_types.h"

#define CHECK_CUDA(call)                                               \
  do {                                                                 \
    cudaError_t err = call;                                            \
    if (err != cudaSuccess) {                                          \
      fprintf(stderr, "CUDA Error at %s:%d: %s\n", __FILE__, __LINE__, \
              cudaGetErrorString(err));                                \
      exit(EXIT_FAILURE);                                              \
    }                                                                  \
  } while (0)

#define CHECK_CUBLAS(call)                                                \
  do {                                                                    \
    cublasStatus_t status = call;                                         \
    if (status != CUBLAS_STATUS_SUCCESS) {                                \
      fprintf(stderr,                                                     \
              "cuBLAS Error at %s:%d\n"                                   \
              "Error code: %d, Message: %s\n",                            \
              __FILE__, __LINE__, status, cublasGetStatusString(status)); \
      exit(EXIT_FAILURE);                                                 \
    }                                                                     \
  } while (0)

// Structure to hold benchmark configurations
struct BenchmarkConfig {
  std::string category;
  int batch_size;
  int M, K, N;
};

const std::vector<BenchmarkConfig> benchmark_configs = {
    {"LLM Inference (Token Gen, FFN-up)", 1, 1, 5120, 17920},
    {"LLM Inference (Token Gen, FFN-down)", 1, 1, 17920, 5120},
    {"LLM Inference (Prompt Proc, Attn)", 1, 1024, 5120, 5120},
    {"LLM Inference (Small Batch, Attn)", 4, 1, 5120, 5120},
    {"LLM Training (FFN-up)", 16, 4096, 5120, 17920},
    {"LLM Training (FFN-down)", 16, 4096, 17920, 5120},
    {"LLM Training (Attn QKV)", 8, 8192, 5120, 5120},
    {"Vision Training (Early CNN)", 128, 3136, 128, 256},
    {"Vision Training (Deep CNN)", 128, 196, 512, 1024},
    {"Vision Training (ViT FFN)", 64, 256, 1024, 4096},
    {"Hardware Stress (Small & Batched)", 256, 128, 128, 128},
    {"Hardware Stress (Power-of-Two)", 128, 1024, 1024, 1024},
    {"Hardware Stress (Awkward Dims)", 128, 1025, 1023, 1025},
    {"Hardware Stress (Skinny GEMM)", 1, 65536, 128, 65536},
    {"Hardware Stress (Fat GEMM)", 256, 64, 16384, 64},
};

enum DataType { FP32, BF16 };

void run_benchmark(cublasHandle_t handle, const BenchmarkConfig& config,
                   DataType dtype, float compute_capability) {
  std::string dtype_name;
  cudaDataType_t a_type, b_type, c_type;
  cublasComputeType_t compute_type;
  size_t a_size, b_size, c_size;

  switch (dtype) {
    case FP32:
      dtype_name = "FP32";
      a_type = CUDA_R_32F;
      b_type = CUDA_R_32F;
      c_type = CUDA_R_32F;
      compute_type = CUBLAS_COMPUTE_32F;
      a_size = sizeof(float);
      b_size = sizeof(float);
      c_size = sizeof(float);
      break;
    case BF16:
      if (compute_capability < 8.0f) {
        std::cout << "  - Skipping BF16: Not supported on this GPU (CC < 8.0)"
                  << std::endl;
        return;
      }
      dtype_name = "BF16";
      a_type = CUDA_R_16BF;
      b_type = CUDA_R_16BF;
      c_type = CUDA_R_16BF;
      compute_type = CUBLAS_COMPUTE_32F;
      a_size = sizeof(__nv_bfloat16);
      b_size = sizeof(__nv_bfloat16);
      c_size = sizeof(__nv_bfloat16);
      break;
  }

  int64_t b = config.batch_size;
  int64_t m = config.M;
  int64_t k = config.K;
  int64_t n = config.N;

  std::vector<void*> h_A_array(b);
  std::vector<void*> h_B_array(b);
  std::vector<void*> h_C_array(b);
  void **d_A_array, **d_B_array, **d_C_array;
  CHECK_CUDA(cudaMalloc(&d_A_array, b * sizeof(void*)));
  CHECK_CUDA(cudaMalloc(&d_B_array, b * sizeof(void*)));
  CHECK_CUDA(cudaMalloc(&d_C_array, b * sizeof(void*)));
  for (int i = 0; i < b; ++i) {
    CHECK_CUDA(cudaMalloc(&h_A_array[i], m * k * a_size));
    CHECK_CUDA(cudaMalloc(&h_B_array[i], k * n * b_size));
    CHECK_CUDA(cudaMalloc(&h_C_array[i], m * n * c_size));
  }

  CHECK_CUDA(cudaMemcpy(d_A_array, h_A_array.data(), b * sizeof(void*),
                        cudaMemcpyHostToDevice));
  CHECK_CUDA(cudaMemcpy(d_B_array, h_B_array.data(), b * sizeof(void*),
                        cudaMemcpyHostToDevice));
  CHECK_CUDA(cudaMemcpy(d_C_array, h_C_array.data(), b * sizeof(void*),
                        cudaMemcpyHostToDevice));

  float alpha = 1.0f;
  float beta = 0.0f;

  int lda = m;
  int ldb = k;
  int ldc = m;

  int warmup_iterations = 15;
  for (int i = 0; i < warmup_iterations; ++i) {
    CHECK_CUBLAS(cublasGemmBatchedEx(
        handle, CUBLAS_OP_N, CUBLAS_OP_N, m, n, k, &alpha,
        const_cast<const void**>(d_A_array), a_type, lda,
        const_cast<const void**>(d_B_array), b_type, ldb, &beta, d_C_array,
        c_type, ldc, b, compute_type, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  }
  CHECK_CUDA(cudaDeviceSynchronize());

  int iterations = 100;
  cudaEvent_t start, stop;
  CHECK_CUDA(cudaEventCreate(&start));
  CHECK_CUDA(cudaEventCreate(&stop));
  CHECK_CUDA(cudaEventRecord(start));
  for (int i = 0; i < iterations; ++i) {
    CHECK_CUBLAS(cublasGemmBatchedEx(
        handle, CUBLAS_OP_N, CUBLAS_OP_N, m, n, k, &alpha,
        const_cast<const void**>(d_A_array), a_type, lda,
        const_cast<const void**>(d_B_array), b_type, ldb, &beta, d_C_array,
        c_type, ldc, b, compute_type, CUBLAS_GEMM_DEFAULT_TENSOR_OP));
  }
  CHECK_CUDA(cudaEventRecord(stop));
  CHECK_CUDA(cudaEventSynchronize(stop));

  float milliseconds = 0;
  CHECK_CUDA(cudaEventElapsedTime(&milliseconds, start, stop));
  std::cout << "  - " << std::left << std::setw(6) << dtype_name << ": "
            << std::fixed << std::setprecision(0) << milliseconds << " ms"
            << std::endl;

  CHECK_CUDA(cudaEventDestroy(start));
  CHECK_CUDA(cudaEventDestroy(stop));
  for (int i = 0; i < b; ++i) {
    CHECK_CUDA(cudaFree(h_A_array[i]));
    CHECK_CUDA(cudaFree(h_B_array[i]));
    CHECK_CUDA(cudaFree(h_C_array[i]));
  }
  CHECK_CUDA(cudaFree(d_A_array));
  CHECK_CUDA(cudaFree(d_B_array));
  CHECK_CUDA(cudaFree(d_C_array));
}

int main() {
  int deviceId;
  CHECK_CUDA(cudaGetDevice(&deviceId));

  cudaDeviceProp prop;
  CHECK_CUDA(cudaGetDeviceProperties(&prop, deviceId));

  std::cout << "GPU: " << prop.name << std::endl;
  std::cout << "Compute Capability: " << prop.major << "." << prop.minor
            << std::endl;
  std::cout << "----------------------------------------" << std::endl;

  cublasHandle_t handle;
  CHECK_CUBLAS(cublasCreate(&handle));
  CHECK_CUBLAS(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH));
  float compute_capability = prop.major + prop.minor / 10.0f;
  for (const auto& config : benchmark_configs) {
    std::cout << "Benchmarking Category: " << config.category
              << " | Shape: (B=" << config.batch_size << ", M=" << config.M
              << ", K=" << config.K << ", N=" << config.N << ")" << std::endl;

    try {
      run_benchmark(handle, config, FP32, compute_capability);
      run_benchmark(handle, config, BF16, compute_capability);
    } catch (const std::exception& e) {
      std::cerr << "Caught an exception: " << std::endl;
    }
  }

  CHECK_CUBLAS(cublasDestroy(handle));

  return 0;
}
//benchmark_cudnn.cc

#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include "base/init_google.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend/graph_helpers.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend/graph_interface.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend/graph_properties.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend_ExecutionPlan.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend_Heuristics.h"
#include "third_party/cudnn_frontend/include/cudnn_frontend_utils.h"
#include "third_party/gpus/cuda/include/cuda.h"
#include "third_party/gpus/cuda/include/cuda_runtime.h"
#include "third_party/gpus/cuda/include/cuda_runtime_api.h"
#include "third_party/gpus/cuda/include/driver_types.h"
#include "third_party/gpus/cudnn/cudnn.h"
#include "third_party/gpus/cudnn/cudnn_cnn.h"
#include "third_party/gpus/cudnn/cudnn_graph.h"
#include "third_party/gpus/cudnn/cudnn_ops.h"

namespace fe = cudnn_frontend;

#define CHECK_CUDA(call)                                               \
  do {                                                                 \
    cudaError_t err = call;                                            \
    if (err != cudaSuccess) {                                          \
      fprintf(stderr, "CUDA Error at %s:%d: %s\n", __FILE__, __LINE__, \
              cudaGetErrorString(err));                                \
      exit(EXIT_FAILURE);                                              \
    }                                                                  \
  } while (0)

#define CHECK_CUDNN_FE(call)                                           \
  do {                                                                 \
    cudnn_frontend::error_t err = call;                                \
    if (err.is_bad()) {                                                \
      fprintf(stderr, "cuDNN Frontend Error at %s:%d: %s\n", __FILE__, \
              __LINE__, err.get_message().c_str());                    \
      exit(EXIT_FAILURE);                                              \
    }                                                                  \
  } while (0)

struct BenchmarkConfig {
  std::string category;
  int batch_size;
  int M, K, N;
};

const std::vector<BenchmarkConfig> benchmark_configs = {
    {"LLM Inference (Token Gen, FFN-up)", 1, 1, 5120, 17920},
    {"LLM Inference (Token Gen, FFN-down)", 1, 1, 17920, 5120},
    {"LLM Inference (Prompt Proc, Attn)", 1, 1024, 5120, 5120},
    {"LLM Inference (Small Batch, Attn)", 4, 1, 5120, 5120},
    {"LLM Training (FFN-up)", 16, 4096, 5120, 17920},
    {"LLM Training (FFN-down)", 16, 4096, 17920, 5120},
    {"LLM Training (Attn QKV)", 8, 8192, 5120, 5120},
    {"Vision Training (Early CNN)", 128, 3136, 128, 256},
    {"Vision Training (Deep CNN)", 128, 196, 512, 1024},
    {"Vision Training (ViT FFN)", 64, 256, 1024, 4096},
    {"Hardware Stress (Small & Batched)", 256, 128, 128, 128},
    {"Hardware Stress (Power-of-Two)", 128, 1024, 1024, 1024},
    {"Hardware Stress (Awkward Dims)", 128, 1025, 1023, 1025},
    {"Hardware Stress (Skinny GEMM)", 1, 65536, 128, 65536},
    {"Hardware Stress (Fat GEMM)", 256, 64, 16384, 64},
};

enum DataType { FP32, BF16 };

void run_benchmark(cudnnHandle_t handle, const BenchmarkConfig& config,
                   DataType dtype, float compute_capability) {
  std::string dtype_name;
  cudnnDataType_t cudnn_dtype;
  cudnn_frontend::DataType_t fe_dtype;
  size_t type_size;

  switch (dtype) {
    case FP32:
      dtype_name = "FP32";
      cudnn_dtype = CUDNN_DATA_FLOAT;
      fe_dtype = cudnn_frontend::DataType_t::FLOAT;
      type_size = sizeof(float);
      break;
    case BF16:
      if (compute_capability < 8.0f) {
        std::cout << "  - Skipping BF16: Not supported on this GPU (CC < 8.0)"
                  << std::endl;
        return;
      }
      dtype_name = "BF16";
      cudnn_dtype = CUDNN_DATA_BFLOAT16;
      fe_dtype = cudnn_frontend::DataType_t::BFLOAT16;
      type_size = sizeof(__nv_bfloat16);
      break;
  }

  int64_t b = config.batch_size;
  int64_t m = config.M;
  int64_t k = config.K;
  int64_t n = config.N;

  void *d_A, *d_B, *d_C;
  CHECK_CUDA(cudaMalloc(&d_A, b * m * k * type_size));
  CHECK_CUDA(cudaMalloc(&d_B, b * k * n * type_size));
  CHECK_CUDA(cudaMalloc(&d_C, b * m * n * type_size));

  try {
    auto graph = std::make_shared<cudnn_frontend::graph::Graph>();
    graph->set_io_data_type(fe_dtype)
        .set_intermediate_data_type(fe_dtype)
        .set_compute_data_type(cudnn_frontend::DataType_t::FLOAT);

    auto A = graph->tensor(cudnn_frontend::graph::Tensor_attributes()
                               .set_name("A")
                               .set_dim({b, m, k})
                               .set_stride({m * k, k, 1})
                               .set_uid(1)
                               .set_data_type(fe_dtype));
    auto B = graph->tensor(cudnn_frontend::graph::Tensor_attributes()
                               .set_name("B")
                               .set_dim({b, k, n})
                               .set_stride({k * n, n, 1})
                               .set_uid(2)
                               .set_data_type(fe_dtype));

    auto matmul_attributes =
        cudnn_frontend::graph::Matmul_attributes().set_compute_data_type(
            cudnn_frontend::DataType_t::FLOAT);
    auto C = graph->matmul(A, B, matmul_attributes);
    C->set_name("C_out").set_output(true).set_data_type(fe_dtype).set_uid(3);

    CHECK_CUDNN_FE(graph->validate());
    CHECK_CUDNN_FE(graph->build_operation_graph(handle));

    CHECK_CUDNN_FE(
        graph->create_execution_plans({fe::HeurMode_t::B, fe::HeurMode_t::A}));
    CHECK_CUDNN_FE(
        graph->build_plans(handle, cudnn_frontend::BuildPlanPolicy_t::ALL));

    void* d_workspace = nullptr;
    int64_t workspace_size = 0;
    CHECK_CUDNN_FE(graph->get_workspace_size(workspace_size));
    if (workspace_size > 0) {
      CHECK_CUDA(cudaMalloc(&d_workspace, workspace_size));
    }

    std::unordered_map<
        std::shared_ptr<cudnn_frontend::graph::Tensor_attributes>, void*>
        variant_pack = {{A, d_A}, {B, d_B}, {C, d_C}};

    std::cout << "  - Autotuning... (This may take a while)" << std::endl;
    CHECK_CUDNN_FE(graph->autotune(handle, variant_pack, d_workspace));

    std::string plan_name;
    CHECK_CUDNN_FE(graph->get_plan_name(plan_name));
    std::cout << "  - Best plan found: " << plan_name << ". Now benchmarking."
              << std::endl;

    int warmup_iterations = 15;
    for (int i = 0; i < warmup_iterations; ++i) {
      CHECK_CUDNN_FE(graph->execute(handle, variant_pack, d_workspace));
    }
    CHECK_CUDA(cudaDeviceSynchronize());

    int iterations = 100;
    cudaEvent_t start, stop;
    CHECK_CUDA(cudaEventCreate(&start));
    CHECK_CUDA(cudaEventCreate(&stop));

    CHECK_CUDA(cudaEventRecord(start));
    for (int i = 0; i < iterations; ++i) {
      CHECK_CUDNN_FE(graph->execute(handle, variant_pack, d_workspace));
    }
    CHECK_CUDA(cudaEventRecord(stop));
    CHECK_CUDA(cudaEventSynchronize(stop));

    float milliseconds = 0;
    CHECK_CUDA(cudaEventElapsedTime(&milliseconds, start, stop));

    std::cout << "  - " << std::left << std::setw(6) << dtype_name << ": "
              << std::fixed << std::setprecision(0) << milliseconds << " ms"
              << std::endl;

    if (d_workspace) CHECK_CUDA(cudaFree(d_workspace));
    CHECK_CUDA(cudaEventDestroy(start));
    CHECK_CUDA(cudaEventDestroy(stop));

  } catch (const cudnn_frontend::error& exception_object) {
    std::cerr << "cuDNN Frontend Exception at " << __FILE__ << ":" << __LINE__
              << ": " << std::endl;
    cudaError_t last_err = cudaGetLastError();
    if (last_err != cudaSuccess) {
      std::cerr << "Last CUDA Error after cuDNN Frontend Exception: "
                << cudaGetErrorString(last_err) << std::endl;
    }
  }

  CHECK_CUDA(cudaFree(d_A));
  CHECK_CUDA(cudaFree(d_B));
  CHECK_CUDA(cudaFree(d_C));
}

int main(int argc, char* argv[]) {
  InitGoogle(argv[0], &argc, &argv, /*remove_flags=*/true);

  int deviceId;
  CHECK_CUDA(cudaGetDevice(&deviceId));

  cudaDeviceProp prop;
  CHECK_CUDA(cudaGetDeviceProperties(&prop, deviceId));

  std::cout << "GPU: " << prop.name << std::endl;
  std::cout << "Compute Capability: " << prop.major << "." << prop.minor
            << std::endl;
  std::cout << "----------------------------------------" << std::endl;

  cudnnHandle_t handle;
  cudnnCreate(&handle);

  float compute_capability = prop.major + prop.minor / 10.0f;

  for (const auto& config : benchmark_configs) {
    std::cout << "Benchmarking Category: " << config.category
              << " | Shape: (B=" << config.batch_size << ", M=" << config.M
              << ", K=" << config.K << ", N=" << config.N << ")" << std::endl;

    run_benchmark(handle, config, FP32, compute_capability);
    run_benchmark(handle, config, BF16, compute_capability);
  }

  cudnnDestroy(handle);

  return 0;
}