Skip to content
Skip to lesson
Back to Topics
LearnGPU Systems & LLM InferenceGEMM From Naive CUDA to Tensor Cores
HardInference Optimization13 min read

GEMM From Naive CUDA to Tensor Cores

The same output can be numerically right and still come from the wrong addresses. Follow one product from a scalar thread to a Tensor Core tile.

On this page

Which thread should own output C1,0C_{1,0}? One scalar thread can compute it, four neighboring outputs can share one thread's registers, or a 32-lane warp can feed a whole 16×1616 \times 16 tile to Tensor Cores. The math C=ABC = AB never changes, yet global memory sectors, on-chip reuse, and rounding behavior shift dramatically at every rung of the ladder.

We build row-major multiplication (A[M,K]B[K,N]→C[M,N]A_{[M,K]} B_{[K,N]} \to C_{[M,N]}, the α=1,β=0\alpha=1, \beta=0 GEMM case with 2MNK2MNK FLOPs) across five stages in gemm_lab.cu: strided scalar -> coalesced scalar -> shared-memory tiled -> 2D register-blocked -> WMMA Tensor Cores, then examine how Ampere cp.async, Hopper TMA/WGMMA, and Blackwell tcgen05 pipeline data movement ahead of math.

A 2 by 3 matrix A highlights row 1, negative 1, 3, 2. A 3 by 2 matrix B highlights column 0, 2, 1, 3. The three aligned products sum to 7, shown in a solid green C row 1 column 0 cell.
Row-major GEMM pairs row ii of AA with column jj of BB across KK steps (2MNK2MNK FLOPs total). For a square FP32 matrix of size nn, ideal unique-byte intensity is n/6n/6 FLOP/B (682.7 FLOP/B at n=4096n=4096), whereas naive scalar code demands only 2/8=0.252 / 8 = 0.25 FLOP/B per thread.

Stage 1: Scalar strided vs. coalesced warps

Assign one thread to each output Cr,c=∑k=0K−1Ar,kBk,cC_{r,c} = \sum_{k=0}^{K-1} A_{r,k} B_{k,c}. CUDA linearizes threadIdx.x first across warp lanes 0..31. Mapping row = blockIdx.x * blockDim.x + threadIdx.x makes adjacent lanes step down rows of AA and CC with stride KK and NN. Simply swapping threadIdx.x to own col transforms memory coalescing without altering a single FLOP:[1]

gemm_scalar_coalesced.cu
__global__ void gemm_scalar_coalesced(const float* A, const float* B, float* C,
                                      int M, int N, int K) {
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    if (row >= M || col >= N) return;

    float acc = 0.0f;
    for (int k = 0; k < K; ++k) acc += A[row * K + k] * B[k * N + col];
    C[row * N + col] = acc;
}

At M=32,N=K=64M=32, N=K=64, swapping from a 16x16 strided block to a 32x8 coalesced block cuts warp-0's requested 32-byte sectors across k=0 loads and the final C store from 33 sectors (16 A, 1 B, 16 C) down to 9 sectors (1 broadcast A, 4 contiguous B, 4 contiguous C), a 3.67x reduction.

Aligned FP32 warp sector layout for M=32, N=K=64: 16x16 strided lanes split rows by 256 bytes, requesting 16 A, 1 B, and 16 C sectors (33 total); 32x8 coalesced lanes pack row 0 contiguously, requesting 1 broadcast A sector, 4 B sectors, and 4 C sectors (9 total). Five lane byte-offset triples (L0, L1, L8, L16, L31) and sector split bars are shown.
Assigning threadIdx.x to col lets all 32 warp lanes broadcast one element of AA (1 sector) and coalesce 32 adjacent columns of BB and CC (4 sectors each), cutting 33 sectors to 9.

Stage 2: Shared-memory tiling and bank analysis

Coalescing merges warp requests, yet every thread still reloads AA and BB from global/L2 memory on every step. Staging a 16×1616 \times 16 panel of AA and BB in __shared__ memory reuses each loaded float 16 times across the block, raising panel operand intensity 16x from 0.25 to 4.0 FLOP/B (8,192 FLOPs/2,048 B8{,}192\text{ FLOPs} / 2{,}048\text{ B}):

gemm_shared.cu
constexpr int TILE = 16;

__global__ void gemm_shared(const float* A, const float* B, float* C, int M, int N, int K) {
    __shared__ float As[TILE][TILE], Bs[TILE][TILE];
    int row = blockIdx.y * TILE + threadIdx.y, col = blockIdx.x * TILE + threadIdx.x;
    float acc = 0.0f;

    for (int k0 = 0; k0 < K; k0 += TILE) {
        int ak = k0 + threadIdx.x, bk = k0 + threadIdx.y;
        As[threadIdx.y][threadIdx.x] = (row < M && ak < K) ? A[row * K + ak] : 0.0f;
        Bs[threadIdx.y][threadIdx.x] = (bk < K && col < N) ? B[bk * N + col] : 0.0f;
        __syncthreads();  // RAW barrier: all loads visible before reads.
#pragma unroll
        for (int k = 0; k < TILE; ++k) acc += As[threadIdx.y][k] * Bs[k][threadIdx.x];
        __syncthreads();  // WAR barrier: all reads done before next panel overwrites.
    }
    if (row < M && col < N) C[row * N + col] = acc;
}
16x16 shared-memory tile reuse and two-barrier K-panel loop. Top schematic shows As (16x16, 1,024 B) times Bs (16x16, 1,024 B) producing C (16x16), where one As row value serves 16 outputs and one Bs column value serves 16 outputs, delivering 8,192 FLOPs from 2,048 operand bytes (4.0 FLOP/B). Bottom timeline shows the four-step K-panel loop (Stage with OOB zero-fill, RAW barrier, 16 FMAs, WAR barrier) with the edge-thread rule aligned beneath.
Cooperative 16×1616\times 16 staging delivers 8,192 FLOPs from 2,048 operand bytes (4.0 FLOP/B). Out-of-range edge threads must still load valid partner entries, zero-fill invalid entries, and hit both barriers before skipping their final C store.

Check shared-memory bank conflicts before swizzling

NVIDIA shared memory maps 4-byte words across 32 banks via bank=(byte_addr/4) mod 32\text{bank} = (\text{byte\_addr}/4) \bmod 32.[1] In gemm_shared's 16×1616 \times 16 block, a 32-lane warp spans two rows: lanes 0..15 broadcast As[0][k], lanes 16..31 broadcast As[1][k], and Bs[k][tx] hits 16 distinct banks conflict-free! A 32-way conflict arises only when 32 lanes read distinct rows down a stride-32 column (32*lane + k), which padding to [32][33] or XOR swizzling (col ^ row) resolves to 1 service group (note that col ^ row permutes vector order on row 1 to [1, 0, 3, 2], so producers and vectorized consumers must agree on the swizzle):

broadcast_or_conflict.py
def service_groups(words):
    banks = {}
    for w in words:
        banks.setdefault(w % 32, set()).add(w)
    return max(len(v) for v in banks.values())

k = 3
shown_a = [(lane // 16) * 16 + k for lane in range(32)]
shown_b = [k * 16 + lane % 16 for lane in range(32)]
col_32 = [32 * lane + k for lane in range(32)]
pad_33 = [33 * lane + k for lane in range(32)]
xor_full = [32 * row + (k ^ row) for row in range(32)]
print("service groups (shown A, B, stride-32, pad-33, XOR):",
      [service_groups(x) for x in (shown_a, shown_b, col_32, pad_33, xor_full)])
Output
service groups (shown A, B, stride-32, pad-33, XOR): [1, 1, 32, 1, 1]
Shared-memory bank layout across a 32-lane warp at k=3. Top strip shows 16x16 block conflict-free broadcasts (As[ty][3] broadcasts banks 3 and 19; Bs[3][tx] spans banks 16..31 twice in 1 wave). Left bank grids compare rows r0..r3 and columns k0..k3 across Stride-32 tile[32][32] (all rows hit bank 3, 32-way conflict), Pad [32][33] (banks 3, 4, 5, 6), and Full XOR k^r (banks 3, 2, 1, 0; physical row 1 order 1, 0, 3, 2). Right horizontal bar chart shows bank service waves dropping from 32 (Stride-32) and 4 (Grouped XOR) to 1 (Pad 33 and Full XOR).
The 16×1616\times 16 block broadcasts A and reads B conflict-free. Stride-32 column reads serialize 32-way; stride-33 padding or full-row XOR eliminates the conflict.

Stage 3: Register blocking (2D thread tiles)

In gemm_shared, each thread still issues two shared loads (8 B) per FMA (2 FLOPs = 0.25 FLOP/B at the shared-memory interface). Register blocking gives each thread an RM×RNR_M \times R_N output sub-tile in registers. Computing 1×41 \times 4 outputs per thread lets one loaded As[ty][k] feed four FMAs (0.40 FLOP/B per thread, 6.4 FLOP/B per 16×6416 \times 64 block panel); an 8×88 \times 8 register tile loads 16 floats (64 B) for 64 FMAs (128 FLOPs = 2.0 FLOP/B, an 8x shared-load reduction):

gemm_register_blocked.cu
float acc[4] = {0.0f, 0.0f, 0.0f, 0.0f};
#pragma unroll
for (int k = 0; k < TILE; ++k) {
    float a = As[threadIdx.y][k];
#pragma unroll
    for (int j = 0; j < 4; ++j) acc[j] += a * Bs[k][threadIdx.x + j * TILE];
}
16x64 register output tile ownership and per-thread operand-reuse comparison. Top view splits the 16x64 C block into four 16x16 sub-tiles (+0, +16, +32, +48), highlighting row 2 and the four cells owned by thread (tx=1, ty=2) at columns 1, 17, 33, and 49. Bottom left traces per-k register reuse: one As[2, k] float pairs with four Bs floats into four accumulators (5 floats = 20 bytes for 8 FLOPs = 0.40 FLOP/B). Bottom right compares per-thread SMEM intensity across 1x1 (0.25), 1x4 (0.40), and 8x8 (2.00 FLOP/B).
Giving each thread four horizontal outputs reuses each As load across four FMAs (0.40 FLOP/B); an 8×88\times 8 register tile lifts per-thread SMEM intensity to 2.0 FLOP/B at the cost of higher register pressure.

Higher register counts can lower occupancy, yet pipelined CUTLASS GEMMs routinely trade occupancy for larger register tiles and deeper latency hiding.[2]

Stage 4: Tensor Cores (WMMA) and mixed-precision rounding

Instead of scalar FMAs, Tensor Cores execute warp-collective matrix multiply-accumulates D=AB+CD = AB + C. Using CUDA's WMMA API for FP16 inputs and FP32 accumulation, all 32 warp lanes cooperate on one 16×16×1616 \times 16 \times 16 tile per mma_sync:[3][4]

gemm_wmma_aligned.cu
__global__ void gemm_wmma_aligned(const half* A, const half* B, float* C, int M, int N, int K) {
#if defined(__CUDA_ARCH__) && __CUDA_ARCH__ < 700
    asm("trap;");
#else
    using namespace nvcuda;
    int row = blockIdx.y * 16, col = blockIdx.x * 16;
    wmma::fragment<wmma::accumulator, 16, 16, 16, float> c_frag;
    wmma::fill_fragment(c_frag, 0.0f);
    for (int k0 = 0; k0 < K; k0 += 16) {
        wmma::fragment<wmma::matrix_a, 16, 16, 16, half, wmma::row_major> a_frag;
        wmma::fragment<wmma::matrix_b, 16, 16, 16, half, wmma::row_major> b_frag;
        wmma::load_matrix_sync(a_frag, A + row * K + k0, K);
        wmma::load_matrix_sync(b_frag, B + k0 * N + col, N);
        wmma::mma_sync(c_frag, a_frag, b_frag, c_frag);
    }
    wmma::store_matrix_sync(C + row * N + col, c_frag, N, wmma::mem_row_major);
#endif
}

Respect three strict WMMA rules: (1) all 32 warp lanes must participate unconditionally, (2) base pointers need 32-byte alignment and leading dimensions must be multiples of 8 (FP16) or 4 (FP32), and (3) load_matrix_sync/store_matrix_sync have no element masks, so pad ragged shapes to multiples of 16 (or stage guarded shared tiles) and remember that fragment tags (row_major vs. col_major) declare layout rather than transposing bytes.

Zero-padded 16x16 GEMM tiling for 73x61x67 padded to 80x64x80: A becomes 5x5 tiles, B becomes 5x4 tiles, and C becomes 5x4 tiles cropped back to 73x61. For tile (bm=4, bn=3), four full K=16 panels precede tail panel p4 where only 9x3 of A and 3x13 of B are nonzero. Padding increases total GEMM FLOPs from 596,702 to 819,200 (+37.3%, versus +11.6% at 257x263x251).
Padding 73×61×6773\times 61\times 67 to 80×64×8080\times 64\times 80 inflates executed work by 37.3%; always report useful TFLOP/s using logical 2MNK2MNK separately from padded work.

Two-reference precision testing

Above 1,024, adjacent IEEE FP16 numbers sit 1.0 apart (ϵFP16=2−10\epsilon_{\text{FP16}} = 2^{-10}), so FP16 accumulation drops 1024.0 + 0.25 -> 1024.0 while FP32 accumulation preserves 1024.25.[5][6] Yet FP32 accumulation can never recover precision already lost when FP32 inputs cast to FP16. Always test mixed-precision kernels against two references: Reference 1 (cast inputs to FP16, then FP64 dot product) isolates kernel math bugs, while Reference 2 (original FP32 inputs in FP64) measures input quantization loss.

two_references_after_cancellation.py
import numpy as np

assert float(np.float16(1024.0 + 0.25)) == 1024.0
assert float(np.float32(1024.0 + 0.25)) == 1024.25

a = np.array([1.0001, 1.0], dtype=np.float32)
b = np.array([1.0, -1.0], dtype=np.float32)
aq = a.astype(np.float16)  # Rounds [1.0001, 1.0] -> [1.0, 1.0]
orig_ref = float(a.astype(np.float64) @ b.astype(np.float64))
rounded_ref = float(aq.astype(np.float64) @ b.astype(np.float64))
cand = float(aq.astype(np.float32) @ b.astype(np.float32))
print(f"Ref1 (rounded inputs)={rounded_ref:.8f}, arithmetic err={abs(cand - rounded_ref):.8f}")
print(f"Ref2 (original FP32) ={orig_ref:.8f}, relative err={abs(cand - orig_ref) / abs(orig_ref):.0%}")
Output
Ref1 (rounded inputs)=0.00000000, arithmetic err=0.00000000
Ref2 (original FP32) =0.00010002, relative err=100%
FP16 quantization spacing around 1,024 and two-reference error separation. Top calibrated number line from 1023.0 to 1025.0 shows FP16 ULP doubling from 0.5 below 1,024 to 1.0 above 1,024 (versus FP32 spacing near 1.2e-4): subtracting 0.375 snaps to 1023.5 while adding 0.25 snaps back to 1024.0. Bottom cancellation comparison for A=[1.0001, 1], B=[1, -1]^T contrasts Reference 2 (Original FP64 dot product 0.00010002, 100% relative error against candidate) with Reference 1 (rounded FP16 inputs [1, 1] giving 0.0, exact pass within 5e-3 / 2e-3 FP32 tolerance).
Separating Reference 1 (rounded FP16 inputs) from Reference 2 (original FP32 inputs) prevents blaming a bug-free Tensor Core kernel for input-quantization cancellation.

Roofline knees and CPU index verification

For an output tile BM×BNB_M \times B_N with ss-byte inputs, panel-load intensity is 2BMBN/[s(BM+BN)]2 B_M B_N / [s(B_M + B_N)], climbing from 0.25 (scalar) to 4.0 (shared 16×1616\times 16), 6.4 (register 16×6416\times 64), 8.0 (WMMA FP16 16×1616\times 16), and 85.3 FLOP/B (128×256128\times 256 FP16 block tile). Compare those against A100 80GB SXM HBM roofline knees (2,039 GB/s HBM2e, 19.5 TFLOP/s FP32, 312 TFLOP/s dense FP16): KneeFP32≈9.56 FLOP/B\text{Knee}_{\text{FP32}} \approx 9.56\text{ FLOP/B} and KneeTC≈153.0 FLOP/B\text{Knee}_{\text{TC}} \approx 153.0\text{ FLOP/B}.[7][8]

A100 80GB SXM hardware roofline on calibrated log-log axes alongside nominal panel-load intensity ratios. Left log-log roofline draws the 2,039 GB/s HBM bandwidth slope meeting the FP32 ceiling at knee (9.56 FLOP/B, 19.5 TFLOP/s) and the dense FP16 Tensor Core ceiling at knee (153.0 FLOP/B, 312 TFLOP/s). Right horizontal bar chart compares nominal panel-load ratios across Scalar (0.25), Shared (4.0), Register 1x4 (6.4), and WMMA (8.0 FLOP/B).
A100 80GB SXM HBM roofline knees (9.56 FLOP/B for FP32, 153.0 FLOP/B for dense FP16) beside nominal panel-load ratios; measure actual DRAM traffic in Nsight Compute to locate L2 reuse.

Run gemm_index_check.py on CPU to verify all five stages' index maps and padding/crop geometry before compiling assets/gemm_lab.cu on GPU (with compute-sanitizer and ncu as covered in the profiling lab):[9][10]

gemm-index-check.py
import runpy

runpy.run_path("assets/gemm_index_check.py", run_name="__main__")
Output
PASS 6 shapes: scalar ownership, shared/register indices, padding/crop
first-warp sectors (A, B, C): strided=(16, 1, 16), coalesced=(1, 4, 4)
CPU integer shapes only; no CUDA, floating-point, barrier, or speed validation.

Stage 5: Asynchronous pipelines (cp.async, TMA, WGMMA, and Blackwell tcgen05)

Synchronous kernels stall compute while fetching the next KK-panel. Double-buffered async main loops overlap loading tile t+1t+1 into slot (t+1) mod 2(t+1)\bmod 2 while Tensor Cores compute tile tt from slot t mod 2t\bmod 2: copy completion makes a slot readable, and consumer completion (not MMA issue) makes it safe to overwrite.

Asynchronous tile-stage ownership lifecycle, double-buffered Slot 0 and Slot 1 overlap Gantt timeline, and GPU async hardware progression. Top ribbon shows the six phases: 01 Acquire, 02 Issue copy, 03 Wait read, 04 MMA compute, 05 Wait done, and 06 Release. Center Gantt timeline shows Slot 0 computing tile t while Slot 1 asynchronously copies tile t+1, then swapping roles across the Phase 05 guard barrier (preventing early-release races). Bottom strip tracks Pre-Ampere register staging, Ampere cp.async, Hopper TMA plus WGMMA, and Blackwell tcgen05 plus TMEM.
Async tile ownership enforces six phases across double-buffered slots, scaling from Pre-Ampere register staging through Ampere `cp.async`, Hopper TMA + WGMMA, and Blackwell `tcgen05` + TMEM.
GenerationData movementMatrix engineKey architectural shift
Pre-AmpereGMEM →\to Regs →\to SMEMVolta/Turing WMMASynchronous loads burn registers and stall on __syncthreads()
Ampere (CC 8.0)cp.async (LDGSTS) GMEM →\to SMEMmma.sync + ldmatrixBypasses registers; multistage async pipelines
Hopper (CC 9.0)[11]TMA descriptor-based 2D/5D async copyWGMMA (128-thread warpgroup)Single-thread TMA issue with bounds fill + warp specialization
Blackwell (CC 10.0)[12]TMA + 2-CTA multicasttcgen05 + dedicated TMEMAccumulators move out of registers into Tensor Memory

In production, benchmark against cuBLAS or CUTLASS/CuTe (cutlass_profiler) before maintaining a custom GEMM, matching precision, layout, and shapes.[13]

Failure signatureLikely causeFirst fix
Wrong bottom/right edge valuesMissing bounds guard or output cropTest 31×29×3731\times 29\times 37; zero-fill input tails
Shared kernel hangs on odd shapesConditional __syncthreads()Keep cooperative loads & barriers outside output guards
Transposed outputLayout tag disagrees with memory stridesMatch row_major/col_major tags to physical layout
WMMA illegal accessUnaligned pointer/stride or unpadded tailEnforce 32B alignment and multiples of 16
Async copy matches sync speedAlignment fallback or missing overlapCheck SASS for LDGSTS/TMA and inspect stall counters
Check your understanding

Mastery Check

Check each question as you go, or answer all of them and check together. Score 75% or higher to complete this lesson.

0 of 6 answered
1.A block has 16 threads in x and 2 in y. At fixed k, each thread loads FP32 B[k, 1 + threadIdx.x] where column 0 is 32-byte aligned. Which column does lane 1 read, and how many 32-byte sectors does the warp request?
2.One thread computes a 2x6 register tile, loading 2 FP32 values from A and 6 from B per k step. What is its per-thread operand intensity?
3.In row 6 of a shared tile, logical column c sits at physical column c XOR 6. Reading physical columns 0..3 returns [9, 4, 7, 1]. Which vector gives logical columns 4..7 in order?
4.A mixed-precision GEMM casts inputs to FP16 (spacing 0.5 near 640) and accumulates in FP32. Adding float16(640.375) * 1 and 0.0625 yields which FP32 sum?
5.In a 16x16 tiled GEMM with M=18, N=8, K=32, the thread for out-of-bounds C[19, 2] also maps to in-bounds B[3, 2]. How must it handle panel loads and barriers?
6.Two warp groups consume shared slot P: copy finishes at step 2, Group 1 runs async MMA steps 3..9, Group 2 runs steps 5..7, and slot Q finishes copying at step 11. When can a new copy overwrite P?

6 questions remaining.

References

CUDA C++ Best Practices Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/

Efficient GEMM in CUDA

NVIDIA CUTLASS Team · 2026 · NVIDIA CUTLASS Documentation

https://docs.nvidia.com/cutlass/latest/media/docs/cpp/efficient_gemm.html

Programming Tensor Cores in CUDA 9

Appleyard, J., & Yokim, S. · 2017 · NVIDIA Technical Blog

https://developer.nvidia.com/blog/programming-tensor-cores-cuda-9/

C/C++ Language Extensions

NVIDIA · 2026

https://docs.nvidia.com/cuda/cuda-programming-guide/05-appendices/cpp-language-extensions.html

Parallel Thread Execution ISA

NVIDIA · 2026

https://docs.nvidia.com/cuda/parallel-thread-execution/

Python struct: Interpret Bytes as Packed Binary Data

Python Software Foundation · 2026

https://docs.python.org/3/library/struct.html

Roofline: An Insightful Visual Performance Model for Multicore Architectures

Williams, S., Waterman, A., & Patterson, D. · 2009

https://doi.org/10.1145/1498765.1498785

NVIDIA A100 Specifications

NVIDIA · 2026

https://www.nvidia.com/en-us/data-center/a100/

CUDA Toolkit 13.0 Release Notes

NVIDIA · 2025

https://docs.nvidia.com/cuda/archive/13.0.0/cuda-toolkit-release-notes/index.html

Nsight Compute Profiling Guide

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/nsight-compute/ProfilingGuide/

NVIDIA Hopper Tuning Guide

NVIDIA · 2026

https://docs.nvidia.com/cuda/hopper-tuning-guide/index.html

PTX ISA: Fifth-Generation TensorCore Instructions

NVIDIA · 2026

https://docs.nvidia.com/cuda/parallel-thread-execution/#tensorcore-5th-generation-instructions

CUTLASS and CuTe Documentation

NVIDIA · 2026 · Official documentation

https://docs.nvidia.com/cutlass/latest/overview.html

Discussion

Questions and insights from fellow learners.

Discussion loads when you reach this section.