Skip to content
Cerebellum

Kernel optimization

Kernel optimization and H100s in pictures. Matrix multiply and fused softmax.

Suhaas5 min read

I'm post-training a custom model for kernel optimization. In one experiment I trained on test-time refinements. I tried checking the quality of refinements but realized I was completely ill-equipped to do so. I made some visualizations to help me wrap my mind around a lot of this stuff. I'll use as few words as possible.

GPU (H100)

HBM380 GBL2 cache50 MBSMs1323.35 TB/sShared memory / L1up to 227 KB of a 256 KB L1managed by the hardwareone SM,opened upwarp schedulerregisters,64K per SMCUDA cores,128 per SMtensor cores,4 per SMfour quadrantsper SM

All the parts in an H100 do one of two main things: (1) store memory (2) do arithmetic. Tensor cores and CUDA cores do arithmetic, everything else is memory. In order to compute large operations quickly (like computing the next token), memory needs to be moved from memory stores to the cores as efficiently as possible. That is what kernels are for. A summary of the parts:

  • High Bandwidth Memory (HBM3): the GPU's main memory, 80 GB. Data moves in and out at up to 3.35 TB/s.
  • L2 cache: 50 MB of the most recently used HBM data. Managed by hardware.
  • Streaming Multiprocessor (SM): like a mini GPU. Contains CUDA cores, tensor cores, and shared memory. 132 total, each with 128 CUDA cores, 4 tensor cores, and up to 227 KB of shared memory.
  • Shared memory: the memory of an SM. Can be used by any thread in the same block.
  • Register: values a thread is working on right now. Up to 255 per thread.
  • Tensor core: multiplies small matrices and does nothing else. 528 total, 989 TFLOPS at 16-bit.
  • CUDA core: does one ordinary operation at a time (add, multiply, exp, compare), so it runs everything that is not a matrix multiply. 16,896 total, 67 TFLOPS at 32-bit.
  • Warp: the GPU runs threads in packs of 32 called warps. All 32 do the same instruction at the same moment.
Coresper SM4 tensor128 CUDARegistersper SM256 KB~33 TB/sShared memoryper SM227 KB3.35 TB/sHBM3whole GPU80 GBwidths: log scale
Levels of memory. Sizes are NVIDIA's for the H100 SXM.

The smaller and closer to the cores a memory store is, the faster it is to move data to the cores.

  • HBM3 to an SM: 3.35 TB/s (slow)
  • Shared memory to registers: about 33 TB/s (fast)

Kernel

A very simple kernel: adding two arrays, then multiplying by a number.

Your program, on the CPUc = (a + b) * kadd<<<4, 4>>>(a, b, t);mul<<<4, 4>>>(t, k, c);The kernels, on the GPUvoid add(a, b, t) { i = blockIdx.x * blockDim.x + threadIdx.x; t[i] = a[i] + b[i];}void mul(t, k, c) { i = ...; // the same c[i] = t[i] * k;}in HBMabcin HBMaddblock 00123block 10123block 20123block 30123tmulblock 00123block 10123block 20123block 30123

Your program wants c = (a + b) × k, for two arrays of 16 numbers that are already in the GPU's memory. The CPU does not do the arithmetic. It launches kernels, and for each one asks for 16 threads: 4 blocks of 4. (Real launches use far bigger numbers; these are small so they fit in the picture.)

Now the realer example of generating next token during inference. Every row is a kernel the CPU launches.

Your program, on the CPUnext = model(tokens)what that line doesKernels launched on the GPUone launch per operationlook up the tokens' vectorsgathernormalizenormattention: make queries, keys, valuesmatmulattention: score every pair of tokensmatmulattention: turn scores into weightssoftmaxattention: mix the valuesmatmulattention: project the resultmatmuladd to what came inaddnormalizenormMLP: expandmatmulMLP: activationgeluMLP: contractmatmuladd to what came inaddnormalizenormscore every word in the vocabularymatmulturn scores into probabilitiessoftmaxpick onesampleone layera model repeatsthis for everylayer it hasmatmuls are nearlyall the arithmetic

17 launches for one pass. Press Play, or click a row.

A model launches hundreds of kernels for one token.

Matrix Multiplication

These steps follow Simon Boehm's walkthrough. The first one changes no arithmetic at all, only which thread computes which element.

Recall that threads run in warps: packs of 32 that do the same instruction at the same moment.

ABCwritten×=One warp8 of its 32 threadsneighbours godown a column of CA as it lies in memory, row after rowB as it lies in memorya row apart: 8 transactions

Neighbouring threads compute elements one below the other in C. At each step of the dot product they all want the same element of B, and eight elements of A that sit a whole row apart in memory. Every load is its own transaction.

On his A6000, that change alone took memory throughput from 15 GB/s to 110 GB/s.

The rest is the same idea each time: fetch data from far away once, then reuse it as many times as possible from somewhere close.

HBMA, B, CABShared memoryunusedRegistersone thread'sC tile1 per threadevery operand, every timeLoads per element of CK = length of the dot productfrom HBM2Kfrom shared0

Every thread computes one element of C and loads every operand from HBM itself: two loads per multiply, K multiplies per element.

Fused Softmax

Softmax does almost no arithmetic per element, so its speed is set by how many times the data crosses to HBM and back.

HBMxM × Nrow maxMx − maxM × NexpM × Nrow sumMyM × NOn an SM5 kernelsmaxx − maxexpsum÷ sumElements moved5MN + 2Mread3MN + 2Mwritten

Softmax as five library calls. Each one is its own kernel: it reads its inputs from HBM, does one cheap operation, and writes the whole result back for the next to read again. For an M × N input that is 5MN + 2M elements read and 3MN + 2M written.

Nothing here made the arithmetic faster. It's all about moving the data better.

Refs

  • kernels
  • gpu