On this page
Which thread should own output ? One scalar thread can compute it, four neighboring outputs can share one thread's registers, or a 32-lane warp can feed a whole tile to Tensor Cores. The math never changes, yet global memory sectors, on-chip reuse, and rounding behavior shift dramatically at every rung of the ladder.
We build row-major matrix multiplication (, the GEMM case with 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.

Stage 1: Scalar strided vs. coalesced warps
Assign one thread to each output . 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 and with stride and . Simply swapping threadIdx.x to own col transforms memory coalescing without altering a single FLOP:[1]
__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 , 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.

threadIdx.x to col lets all 32 warp lanes broadcast one element of (1 sector) and coalesce 32 adjacent columns of and (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 and from global/L2 memory on every step. Staging a panel of and 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 ():
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;
}
C store.Check shared-memory bank conflicts before swizzling
NVIDIA shared memory maps 4-byte words across 32 banks via .[1] In gemm_shared's 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):
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)])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).](https://assets.leetllm.com/v1/55ebf457f69d/fundamentals/gemm-naive-cuda-tensor-cores/illustrations/_generated/bank_broadcast_layout_dark.png)
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 output sub-tile in registers. Computing outputs per thread lets one loaded As[ty][k] feed four FMAs (0.40 FLOP/B per thread, 6.4 FLOP/B per block panel); an register tile loads 16 floats (64 B) for 64 FMAs (128 FLOPs = 2.0 FLOP/B, an 8x shared-load reduction):
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).](https://assets.leetllm.com/v1/91bdd5cedfc7/fundamentals/gemm-naive-cuda-tensor-cores/illustrations/_generated/register_output_tile_dark.png)
As load across four FMAs (0.40 FLOP/B); an 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 . Using CUDA's WMMA API for FP16 inputs and FP32 accumulation, all 32 warp lanes cooperate on one tile per mma_sync:[3][4]
__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.

Two-reference precision testing
Above 1,024, adjacent IEEE FP16 numbers sit 1.0 apart (), 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.
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%}")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).](https://assets.leetllm.com/v1/52cabf415c2e/fundamentals/gemm-naive-cuda-tensor-cores/illustrations/_generated/rounding_two_references_dark.png)
Roofline knees and CPU index verification
For an output tile with -byte inputs, panel-load intensity is , climbing from 0.25 (scalar) to 4.0 (shared ), 6.4 (register ), 8.0 (WMMA FP16 ), and 85.3 FLOP/B ( 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): and .[7][8]

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]
import runpy
runpy.run_path("assets/gemm_index_check.py", run_name="__main__")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 -panel. Double-buffered async main loops overlap loading tile into slot while Tensor Cores compute tile from slot : copy completion makes a slot readable, and consumer completion (not MMA issue) makes it safe to overwrite.

| Generation | Data movement | Matrix engine | Key architectural shift |
|---|---|---|---|
| Pre-Ampere | GMEM Regs SMEM | Volta/Turing WMMA | Synchronous loads burn registers and stall on __syncthreads() |
| Ampere (CC 8.0) | cp.async (LDGSTS) GMEM SMEM | mma.sync + ldmatrix | Bypasses registers; multistage async pipelines |
| Hopper (CC 9.0)[11] | TMA descriptor-based 2D/5D async copy | WGMMA (128-thread warpgroup) | Single-thread TMA issue with bounds fill + warp specialization |
| Blackwell (CC 10.0)[12] | TMA + 2-CTA multicast | tcgen05 + dedicated TMEM | Accumulators 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 signature | Likely cause | First fix |
|---|---|---|
| Wrong bottom/right edge values | Missing bounds guard or output crop | Test ; zero-fill input tails |
| Shared kernel hangs on odd shapes | Conditional __syncthreads() | Keep cooperative loads & barriers outside output guards |
| Transposed output | Layout tag disagrees with memory strides | Match row_major/col_major tags to physical layout |
| WMMA illegal access | Unaligned pointer/stride or unpadded tail | Enforce 32B alignment and multiples of 16 |
| Async copy matches sync speed | Alignment fallback or missing overlap | Check SASS for LDGSTS/TMA and inspect stall counters |