Inference from scratch · Part 3

Writing my first CUDA kernel.

Part 2 ended with the GPU idle 70% of the time, waiting for Python to hand it the next operation. One big reason: PyTorch runs every small step as its own GPU program, a kernel. So I wrote my own: one kernel that does RMSNorm's eight steps in one go.

7.2× faster
RMSNorm: 0.57 → 0.08 ms per token
8 → 1 kernels
GPU launches per RMSNorm call
130 → 225 GB/s
memory throughput achieved

The path

Twelve short steps, from why kernels exist to a working one. Each builds on the last.

  1. 01Why write a kernel at all
  2. 02The chip: 58 small processors
  3. 03Memory: closer is faster
  4. 04What you write vs what runs it
  5. 05A warp at work
  6. 06Hiding latency
  7. 07Why blocks cap at 1,024 threads
  8. 08More data than threads: loop
  9. 09How blocks get scheduled
  10. 10The kernel: fused RMSNorm
  11. 11Where data lives
  12. 12The result
Step 01

Why write your own kernel?

RMSNorm normalizes each token's vector. In PyTorch it's three short lines. On the GPU, it's eight separate kernels.

# the model's RMSNorm, run 33 times per token
variance = x.to(torch.float32).pow(2).mean(-1, keepdim=True)
x_normed = x * torch.rsqrt(variance + eps)
return weight * x_normed.to(input_dtype)
Eager PyTorch: 8 kernels, each reading and writing GPU memory
to fp32
pow
mean
+ eps
rsqrt
× x
to bf16
× w
GPU memory (VRAM): 8 round trips
Fused CUDA kernel: 1 kernel, everything in between stays on-chip
fused RMSNormsquare, sum, rsqrt, scale, weight: all in registers
↓ read x once↑ write y once
GPU memory (VRAM): 1 read, 1 write

Each launch costs the CPU tens of microseconds, often longer than the GPU takes to do the math. With 33 RMSNorm calls per token, that's about 260 launches just for normalization. Fusing them is the textbook first step.

Step 02

The chip: 58 small processors

A GPU isn't one big processor. The NVIDIA L4 these experiments ran on is 58 Streaming Multiprocessors (SMs). Each has 128 cores, its own registers and its own shared memory: 7,424 cores in all.

The 58 SMs of the L4. Everything a kernel does happens on these.

Step 03

Memory: closer is faster

Data climbs a hierarchy on its way to the cores. The further it sits, the bigger and slower it is.

Registersprivate to each thread · ~1 cycle
Shared memory / L1on each SM, shared by a block · ~20 cycles
L2 cacheshared by all 58 SMs
VRAM · 24 GB~300 GB/s · a load costs ~200 cycles

Almost every GPU optimization comes down to this: do more work in the top rows, and touch the bottom row less.

Step 04

What you write vs what runs it

You program in logical units. The hardware maps each one onto physical silicon, and that mapping is the whole game.

You writeThe hardware runs it on
Kernelone function, run thousands of times, each with its own ID
→
The whole GPUa scheduler hands its blocks out to SMs
Blocka team of up to 1,024 threads that can cooperate
→
One SMa block lives entirely on one SM
Threadyou write the code from its point of view
→
A lane in a warpthreads run in groups of 32, on CUDA cores
Step 05

A warp at work

You write code for one thread, but an SM runs threads in warps of 32: one instruction, 32 threads, 32 different values. Adding two vectors of 64 numbers takes exactly 2 warps. Step through it:

Warp 0lanes 0–31
A
B
C
Warp 1lanes 32–63
A
B
C
  1. LDG Warp 0 loads A[0..31]
  2. LDG Warp 1 loads A[32..63]
  3. LDG Both warps load their slice of B
  4. FADD Warp 0 adds 32 pairs in one instruction
  5. FADD Warp 1 adds 32 pairs in one instruction
  6. STG Both warps store C back to VRAM

Six warp instructions for the whole vector. Each FADD does 32 additions at once.

Step 06

Hiding latency: more threads than cores

Each SM has 128 cores but keeps up to ~1,536 threads ready. Why so many?

128cores per SM
~1,536threads resident per SM

A load from VRAM takes ~200 cycles. Instead of stalling, the SM switches its cores to another warp that's ready. The switch is free: every thread's registers already sit in the SM's register file, so there's nothing to save or restore.

Step 07

Why a block caps at 1,024 threads

Threads in a block cooperate through shared memory and a barrier, __syncthreads(), where every thread waits until all of them arrive. That only works if the whole block fits on one SM at once.

A good way to see why the cap matters. Imagine a block of 4,096 threads on an SM that holds ~1,536:

  1. The SM loads the first 1,536 threads, and they run until the barrier.
  2. They all pause there, waiting for the other 2,560.
  3. But those can't start: the SM is full of paused threads.
  4. Nobody can move. Permanent deadlock.

A block has to fit on one SM all at once. Capping it at 1,024 threads, under the SM's limit, means a whole block can always be resident together, so the barrier can always be satisfied.

Step 08

More data than threads? Loop.

A block has at most 1,024 threads, but a row can be longer. You don't ask for more threads; each thread walks the row in strides of the block size.

for (int i = threadIdx.x; i < N; i += blockDim.x)
    // thread 0 handles 0, 1024, 2048, ...
    // thread 1 handles 1, 1025, 2049, ...
pass 1 · elements 0–1,023
pass 2 · elements 1,024–2,047

Llama 3.2 1B's vectors have 2,048 numbers, so with 1,024 threads every thread handles exactly two.

Step 09

How blocks get scheduled

Launch 2,048 blocks of 1,024 threads on 58 SMs. A block that big uses most of an SM's ~1,536-thread budget, so one fits per SM: the GPU's own scheduler fills all 58, and the rest wait in a hardware queue. The moment an SM finishes a block, it pulls the next one, with no CPU involved.

1,990blocks waiting

Smaller blocks can share an SM, several at a time. Either way, a big grid is the goal, not a problem: it keeps every SM busy until the job is done.

Step 10

The kernel: fused RMSNorm

Everything above, in one kernel. One block per token, 1,024 threads per block, two numbers per thread (Step 08). Four phases, all in one launch:

Phase 1

Each thread squares its own numbers

Every thread reads its two values from VRAM and keeps a running sum of squares in a private register.

float local_sum = 0.0f;
for (int i = tid; i < N; i += blockDim.x) {
    float val = x[i];
    local_sum += val * val;
}
Phase 2

1,024 partial sums become one

Registers are private, so the sums travel in three hops. Inside each warp, threads pass values straight between registers with __shfl_down_sync, collapsing 32 sums to one in 5 steps. Each warp's result goes into shared memory. Then one warp reduces those 32 into the final total.

// 1 · within each warp: 32 lanes → 1 (5 steps)
for (int offset = 16; offset > 0; offset /= 2)
    val += __shfl_down_sync(0xffffffff, val, offset);
// 2 · each warp's lane 0 hands off via shared memory
if (lane == 0) shared[warp_id] = val;
__syncthreads();
// 3 · warp 0 reduces the 32 warp sums the same way
Phase 3

One thread does the final math

Thread 0 computes the scale factor once and shares it through shared memory, so all 1,024 threads can use it. rsqrtf is a single hardware instruction, and __syncthreads() makes sure no thread races ahead before it's written.

if (tid == 0) rstd = rsqrtf(total_sum / N + eps);
__syncthreads();
Phase 4

Scale, weight, write once

Every thread normalizes its two values, multiplies by the learned weight, and writes the result back to VRAM. That's the only write in the whole kernel.

for (int i = tid; i < N; i += blockDim.x)
    y[i] = (x[i] * rstd) * weight[i];

One honest detail: while generating, there's only one new token, so this kernel launches a single block and uses 1 of the 58 SMs. It still wins, because the real cost was eight launches and eight trips to memory, not the math.

Step 11

Where data lives is the optimization

Two choices in this kernel look lazy, but they're deliberate.

The weights

Left in VRAM, on purpose

Copying the weights into shared memory would cost an extra loop. Instead each thread reads weight[i] when it needs it. The L1 cache keeps it on-chip, so when many tokens are normalized at once, like the prompt, the other blocks read the same weights from cache instead of VRAM.

The constants

Broadcast, not loaded

Values like the vector size and epsilon arrive as kernel arguments, held in constant memory: hardware built to broadcast one value to every thread at once, with no trip to VRAM.

The fastest memory access is the one you never make.

Step 12

The result: 7.2× faster

GPU time per token for all RMSNorm calls, eager PyTorch vs the fused kernel, on the L4.

Total per token0.572 → 0.080 ms · 7.2×

Why it's faster: the data is read once and written once, instead of bouncing to VRAM eight times. The kernel pulls about 225 GB/s out of the L4's ~300 GB/s, against about 130 GB/s for the eager version.

Where it helps beyond RMSNorm: the CPU side, from Part 2. About 230 fewer kernel launches per token (264 → 33). At ~15–30 µs of Python and driver time each, that's roughly 3–7 ms less waiting per token, by my estimate. I haven't measured it end to end.

What it doesn't do: make the whole model 7× faster. RMSNorm is a small slice of each token's GPU work, roughly half a millisecond of ~12 ms, and about 500 other launches per token still go through Python one at a time. The full fix is fusing much more, and replaying the whole forward pass as one launch (CUDA Graphs). Next, the same idea goes into attention, where it matters far more.

Three rules that stuck with me

01
Map logical to physical. Blocks run on SMs; threads run as warps of 32.
02
Hide latency. Keep enough threads ready that the cores never wait on memory.
03
Keep data close. Registers, then shared memory, then VRAM. Every kernel is a negotiation between these three.
Prefer slides? CUDA on the metalThe 20-slide talk this page is based on, with every phase of the kernel traced on the silicon.