Case Study: Matrix Multiplication in CUDA

Chapter 8 — from 1% of peak to nearly half, one measured step at a time

What you will learn

  • Why matrix multiplication can be compute-bound, while most kernels are memory-bound
  • Five versions of SGEMM, each fixing the limit the previous one hit
  • Shared-memory tiling and register tiling, and how they raise arithmetic intensity
  • How your kernel compares with cuBLAS, and when to use a library instead

Matrix multiplication is the core of deep learning, simulation and much of scientific computing, and the classic exercise for everything in this course. This chapter follows the path of Simon Boehm's well-known worklog How to Optimize a CUDA Matmul Kernel, rewritten for this course and tested on Turing and Ampere GPUs. All five kernels are in one program, so you can run and compare them.

The problem

Compute C = A × B for square N × N single-precision matrices stored row by row. Each of the N² outputs is a dot product of length N, so the work is 2N³ floating-point operations. For N = 2048 that is 17.2 GFLOP. The inputs and output are only 48 MB, but every element of A and B is used N times. With perfect reuse, the arithmetic intensity is about N/6 FLOP per byte, far above the balance point of any GPU (Chapter 7). Matmul can be compute-bound, but only if the kernel actually reuses data on chip. Every step below is about that reuse.

1. Naive: one thread per output

Each thread computes one element of C. This version maps threadIdx.x to the row, which looks harmless. But the 32 threads of a warp then have consecutive rows, and they read A[row * N + k], addresses N floats apart. That is the strided pattern from Chapter 7.

2. Coalesced: swap the indices

Map threadIdx.x to the column instead. Now a warp's threads all read the same A[row * N + k] (a broadcast, one transaction) and consecutive B[k * N + col] (coalesced). The code changes by two lines and typically runs several times faster. It is still memory-bound: every multiply-add loads two floats from global memory or cache.

3. Shared-memory tiling

ABCone block computesthe green tile of Cstep t: load tile t of A'srow band and of B's columnband into shared memoryEach loaded value is used by 32 threads of the block, so device-memory traffic drops by a factor of 32.Highlighted: the tiles loaded at step 1. The block steps along k until the full dot product is done.
A block walks a tile of A along its rows and a tile of B down its columns, accumulating the product of each pair.

A block of 32 × 32 threads computes a 32 × 32 tile of C. It steps along k in chunks of 32: all threads cooperatively load one 32 × 32 tile of A and one of B into shared memory, synchronize, each thread does 32 multiply-adds from shared memory, and they synchronize again before the next tile. Each value loaded from device memory is now used 32 times. This is the same pattern as the stencil in Chapter 3, but here the reuse is large and regular, which is where shared memory pays off.

4. 1D register tiling

Version 3 is no longer limited by device memory, but by shared memory: every multiply-add still needs two shared-memory loads. The fix is the same idea one level down. Let each thread compute several outputs and keep values it reuses in registers. In this version each thread computes 8 outputs in a column of C. For each k, it loads one value of B into a register and uses it for all 8 outputs, so shared-memory loads per multiply-add drop from 2 to about 1.1. Blocks now cover 64 × 64 tiles of C with 512 threads.

5. 2D register tiling

Take it further: each thread computes an 8 × 8 block of outputs. Per k step it loads 8 values of A and 8 values of B into registers and does 64 multiply-adds with them, an outer product. That is 16 shared-memory loads for 64 multiply-adds. A block of 256 threads now covers a 128 × 128 tile of C. Each thread holds 64 accumulators plus 16 operands in registers, which lowers occupancy. As Chapter 4 said, that is the right trade here: the instruction-level parallelism of 64 independent accumulators hides latency better than more warps would.

sgemm.cu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
#include <cstdio>
#include <cstdlib>
#include <cmath>

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

// All kernels compute C = A * B for N x N row-major matrices. N must be a multiple of 128.

// 1. Naive: threadIdx.x -> row, so a warp reads A with a stride of N floats.
__global__ void sgemmNaive(const float *A, const float *B, float *C, int N) {
    int row = blockIdx.x * 32 + threadIdx.x;
    int col = blockIdx.y * 32 + threadIdx.y;
    float acc = 0.0f;
    for (int k = 0; k < N; k++) acc += A[row * N + k] * B[k * N + col];
    C[row * N + col] = acc;
}

// 2. Coalesced: threadIdx.x -> column. A is broadcast, B and C are coalesced.
__global__ void sgemmCoalesced(const float *A, const float *B, float *C, int N) {
    int row = blockIdx.y * 32 + threadIdx.y;
    int col = blockIdx.x * 32 + threadIdx.x;
    float acc = 0.0f;
    for (int k = 0; k < N; k++) acc += A[row * N + k] * B[k * N + col];
    C[row * N + col] = acc;
}

// 3. Shared-memory tiling: each value loaded from device memory is used 32 times.
__global__ void sgemmShared(const float *A, const float *B, float *C, int N) {
    __shared__ float As[32][32], Bs[32][32];
    int tx = threadIdx.x, ty = threadIdx.y;
    int row = blockIdx.y * 32 + ty, col = blockIdx.x * 32 + tx;
    float acc = 0.0f;
    for (int t = 0; t < N; t += 32) {
        As[ty][tx] = A[row * N + t + tx];
        Bs[ty][tx] = B[(t + ty) * N + col];
        __syncthreads();
        for (int k = 0; k < 32; k++) acc += As[ty][k] * Bs[k][tx];
        __syncthreads();
    }
    C[row * N + col] = acc;
}

// 4. 1D register tiling: each thread computes TM = 8 outputs in a column. 64x64 tile, 512 threads.
template <int BM, int BN, int BK, int TM>
__global__ void sgemm1D(const float *A, const float *B, float *C, int N) {
    __shared__ float As[BM * BK], Bs[BK * BN];
    const int threadCol = threadIdx.x % BN, threadRow = threadIdx.x / BN;
    A += blockIdx.y * BM * N;                       // move to this block's row band
    B += blockIdx.x * BN;                           // and column band
    C += blockIdx.y * BM * N + blockIdx.x * BN;
    const int aRow = threadIdx.x / BK, aCol = threadIdx.x % BK;    // BM*BK == threads: one load each
    const int bRow = threadIdx.x / BN, bCol = threadIdx.x % BN;    // BK*BN == threads: one load each

    float acc[TM] = {0.0f};
    for (int t = 0; t < N; t += BK) {
        As[aRow * BK + aCol] = A[aRow * N + aCol];
        Bs[bRow * BN + bCol] = B[bRow * N + bCol];
        __syncthreads();
        A += BK;
        B += BK * N;
        for (int k = 0; k < BK; k++) {
            float b = Bs[k * BN + threadCol];            // loaded once, used TM times
            for (int r = 0; r < TM; r++) acc[r] += As[(threadRow * TM + r) * BK + k] * b;
        }
        __syncthreads();
    }
    for (int r = 0; r < TM; r++) C[(threadRow * TM + r) * N + threadCol] = acc[r];
}

// 5. 2D register tiling: each thread computes a TM x TN = 8x8 block. 128x128 tile, 256 threads.
template <int BM, int BN, int BK, int TM, int TN>
__global__ void sgemm2D(const float *A, const float *B, float *C, int N) {
    constexpr int THREADS = (BM / TM) * (BN / TN);
    __shared__ float As[BM * BK], Bs[BK * BN];
    const int threadCol = threadIdx.x % (BN / TN), threadRow = threadIdx.x / (BN / TN);
    A += blockIdx.y * BM * N;
    B += blockIdx.x * BN;
    C += blockIdx.y * BM * N + blockIdx.x * BN;
    const int aRow = threadIdx.x / BK, aCol = threadIdx.x % BK, aStride = THREADS / BK;
    const int bRow = threadIdx.x / BN, bCol = threadIdx.x % BN, bStride = THREADS / BN;

    float acc[TM][TN] = {{0.0f}};
    float regA[TM], regB[TN];
    for (int t = 0; t < N; t += BK) {
        for (int o = 0; o < BM; o += aStride) As[(aRow + o) * BK + aCol] = A[(aRow + o) * N + aCol];
        for (int o = 0; o < BK; o += bStride) Bs[(bRow + o) * BN + bCol] = B[(bRow + o) * N + bCol];
        __syncthreads();
        A += BK;
        B += BK * N;
        for (int k = 0; k < BK; k++) {
            for (int i = 0; i < TM; i++) regA[i] = As[(threadRow * TM + i) * BK + k];
            for (int j = 0; j < TN; j++) regB[j] = Bs[k * BN + threadCol * TN + j];
            for (int i = 0; i < TM; i++)                 // outer product: 64 FMAs from 16 loads
                for (int j = 0; j < TN; j++) acc[i][j] += regA[i] * regB[j];
        }
        __syncthreads();
    }
    for (int i = 0; i < TM; i++)
        for (int j = 0; j < TN; j++) C[(threadRow * TM + i) * N + threadCol * TN + j] = acc[i][j];
}

int main() {
    const int N = 2048;
    const size_t bytes = (size_t)N * N * sizeof(float);
    float *hA = (float *)malloc(bytes), *hB = (float *)malloc(bytes), *hC = (float *)malloc(bytes);
    unsigned int seed = 42;
    auto rnd = [&]() { seed = seed * 1664525u + 1013904223u; return ((seed >> 8) & 0xFFFF) / 32768.0f - 1.0f; };
    for (size_t i = 0; i < (size_t)N * N; i++) { hA[i] = rnd(); hB[i] = rnd(); }

    // CPU reference for 256 sampled entries (a full CPU matmul would take too long).
    const int samples = 256;
    int sr[samples], sc[samples]; double ref[samples];
    for (int s = 0; s < samples; s++) {
        sr[s] = (s * 977) % N; sc[s] = (s * 1453 + 11) % N;
        double acc = 0.0;
        for (int k = 0; k < N; k++) acc += (double)hA[(size_t)sr[s] * N + k] * hB[(size_t)k * N + sc[s]];
        ref[s] = acc;
    }

    float *A, *B, *C;
    CUDA_CHECK(cudaMalloc(&A, bytes)); CUDA_CHECK(cudaMalloc(&B, bytes)); CUDA_CHECK(cudaMalloc(&C, bytes));
    CUDA_CHECK(cudaMemcpy(A, hA, bytes, cudaMemcpyHostToDevice));
    CUDA_CHECK(cudaMemcpy(B, hB, bytes, cudaMemcpyHostToDevice));

    const char *names[] = {"1 naive", "2 coalesced", "3 shared tiling", "4 1D reg tiling", "5 2D reg tiling"};
    cudaEvent_t a, b;
    CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b));
    bool ok = true;
    for (int v = 0; v < 5; v++) {
        auto run = [&]() {
            if (v == 0) sgemmNaive<<<dim3(N / 32, N / 32), dim3(32, 32)>>>(A, B, C, N);
            if (v == 1) sgemmCoalesced<<<dim3(N / 32, N / 32), dim3(32, 32)>>>(A, B, C, N);
            if (v == 2) sgemmShared<<<dim3(N / 32, N / 32), dim3(32, 32)>>>(A, B, C, N);
            if (v == 3) sgemm1D<64, 64, 8, 8><<<dim3(N / 64, N / 64), 512>>>(A, B, C, N);
            if (v == 4) sgemm2D<128, 128, 8, 8, 8><<<dim3(N / 128, N / 128), 256>>>(A, B, C, N);
        };
        CUDA_CHECK(cudaMemset(C, 0, bytes));
        run();                                        // warm-up, and the result we check
        CUDA_CHECK(cudaGetLastError());
        CUDA_CHECK(cudaMemcpy(hC, C, bytes, cudaMemcpyDeviceToHost));
        int errors = 0;
        for (int s = 0; s < samples; s++)
            if (fabs(hC[(size_t)sr[s] * N + sc[s]] - ref[s]) > 1e-3 * (1.0 + fabs(ref[s]))) errors++;

        const int reps = 5;
        CUDA_CHECK(cudaEventRecord(a));
        for (int r = 0; r < reps; r++) run();
        CUDA_CHECK(cudaEventRecord(b));
        CUDA_CHECK(cudaEventSynchronize(b));
        float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b));
        ms /= reps;
        printf("%-16s %8.2f ms  %7.0f GFLOP/s  errors: %d\n", names[v], ms, 2.0 * N * N * N / ms / 1e6, errors);
        ok = ok && errors == 0;
    }
    printf(ok ? "PASS\n" : "FAIL\n");
    CUDA_CHECK(cudaFree(A)); CUDA_CHECK(cudaFree(B)); CUDA_CHECK(cudaFree(C));
    free(hA); free(hB); free(hC);
    return 0;
}

Results

Measured with the program above at N = 2048:

KernelRTX 3070 LaptopSpeedup vs. previousWhat changed
1 naive143 GFLOP/s—one thread per output
2 coalesced964 GFLOP/s6.7×threadIdx.x → column
3 shared tiling1,281 GFLOP/s1.3×32× reuse of each loaded value
4 1D register tiling4,009 GFLOP/s3.1×8 outputs per thread
5 2D register tiling6,932 GFLOP/s1.7×8 × 8 outputs per thread

From naive to 2D register tiling is a 48× speedup. The RTX 3070 Laptop GPU peaks at roughly 16 TFLOP/s FP32 at full boost clock, less under sustained laptop power limits, so kernel 5 reaches close to half of peak. Your numbers will differ, but the pattern holds on every GPU: coalescing and tiling fix memory traffic, and register tiling turns a memory-bound kernel into a compute-bound one.

Going further

The worklog that inspired this chapter continues with steps that each add 10–30%:

  • Vectorized loads (float4) for global and shared memory, with A stored transposed in shared memory so that register loads are vectorized too.
  • Autotuning the tile sizes BM, BN, BK, TM, TN per GPU.
  • Warp tiling: an extra level between block and thread tiles that matches how warps share registers and shared-memory bandwidth.
  • Double buffering: loading the next tile while computing the current one.

Beyond FP32, modern GPUs have Tensor Cores: units that multiply small matrix tiles in FP16, BF16, TF32 or FP8 at many times the FP32 rate. They are programmed through the WMMA API, PTX mma instructions, or libraries such as CUTLASS.

Use a library in production

cuBLAS is NVIDIA's tuned BLAS library. It picks the best kernel for your GPU and matrix shape and uses Tensor Cores when allowed. For plain matmul in production code, call it:

cublas_sgemm.cu
12345678910111213141516
#include <cublas_v2.h>
// Build: nvcc -O3 cublas_sgemm.cu -lcublas

cublasHandle_t handle;
cublasCreate(&handle);
const float alpha = 1.0f, beta = 0.0f;

// cuBLAS uses column-major storage. For row-major A, B, C, compute C^T = B^T * A^T,
// which is the same memory layout, by swapping the operands:
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N,
            N, N, N, &alpha,
            d_B, N,          // "A" for cuBLAS
            d_A, N,          // "B" for cuBLAS
            &beta, d_C, N);

cublasDestroy(handle);

On large FP32 matrices, cuBLAS typically reaches 70–90% of the GPU's peak. Simon Boehm's worklog reached about 94% of cuBLAS on an A6000 with all the steps above, so hand-written kernels can come close, but it takes work for each GPU. Write your own when you need to fuse the multiplication with other operations, such as a bias, an activation or a custom epilogue, or use CUTLASS, which gives you cuBLAS-level building blocks with hooks for fusion.

The site's playground compiles single files with a fixed set of flags, so the cuBLAS example above is meant for your own machine.

Summary

  • Matmul has high potential arithmetic intensity, but a kernel only reaches it by reusing data on chip.
  • Coalescing is the first fix: make threadIdx.x walk along rows of B and C.
  • Shared-memory tiling cuts device-memory traffic by the tile width.
  • Register tiling cuts shared-memory traffic in the same way, and makes the kernel compute-bound.
  • Lower occupancy with more independent work per thread is often faster.
  • Use cuBLAS or CUTLASS in production; write your own to learn, or to fuse operations.

Exercises

1. Count the traffic. For N = 2048, how many bytes does kernel 2 load from A and B in total (ignoring caches), and how many does kernel 3 load?

Solution

Kernel 2: each of the N² threads loads N values of A and N of B: 2N³ × 4 bytes = 68.7 GB. Kernel 3: each block loads (N / 32) tiles of A and of B, 2 × 32 × 32 × 4 bytes each, and there are (N / 32)² blocks: 2N³ / 32 × 4 bytes = 2.1 GB. Caches make kernel 2's real traffic lower than 68.7 GB, which is why it is not 32 times slower than kernel 3.

2. Arbitrary sizes. The kernels require N to be a multiple of 128. What would you change in kernel 3 to support any N?

Solution

Round the grid up, and guard the loads and the store: load 0.0f into the tile when the row or column is out of range, keep both __syncthreads() calls outside any condition, and only write C when row < N && col < N. Zeros in the padding don't change the dot products.

3. Tile size. Try kernel 5 with TM = TN = 4 (and a 64 × 64 block tile). Is it faster or slower? Why?

Solution

Usually slower. With 4 × 4 outputs per thread, each k step does 16 FMAs from 8 shared loads, a ratio of 2 instead of 4, so shared-memory bandwidth limits the kernel again. Larger thread tiles help until register pressure causes spills or occupancy drops too far. Check registers with -Xptxas -v.

Check your understanding

Why does kernel 2 read A "as a broadcast"?

All 32 threads of a warp have the same row and the same k in each iteration, so they read the same A element. The hardware serves it with one transaction for the whole warp.

Kernel 5 has lower occupancy than kernel 3. Why is it faster?

Each thread has 64 independent accumulators, so it always has instructions ready to issue. That instruction-level parallelism hides latency, and each loaded value is reused many times from registers.

Further reading & credits

The chapter order and topic coverage of this course draw on the OLCF / NERSC CUDA Training Series, the NVIDIA Accelerated Computing Hub CUDA C++ tutorial, the GPU MODE lectures (Apache-2.0) and Simon Boehm's CUDA matrix multiplication worklog (code MIT). The text and example programs on this page are original and were tested on NVIDIA Turing and Ampere GPUs.

You have finished the course. Try the challenges to practice, or experiment with any example in the playground.