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.
Twelve short steps, from why kernels exist to a working one. Each builds on the last.
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)
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.
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.
Data climbs a hierarchy on its way to the cores. The further it sits, the bigger and slower it is.
Almost every GPU optimization comes down to this: do more work in the top rows, and touch the bottom row less.
You program in logical units. The hardware maps each one onto physical silicon, and that mapping is the whole game.
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:
LDG Warp 0 loads A[0..31]LDG Warp 1 loads A[32..63]LDG Both warps load their slice of BFADD Warp 0 adds 32 pairs in one instructionFADD Warp 1 adds 32 pairs in one instructionSTG Both warps store C back to VRAMSix warp instructions for the whole vector. Each FADD does 32 additions at once.
Each SM has 128 cores but keeps up to ~1,536 threads ready. Why so many?
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.
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:
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.
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, ...
Llama 3.2 1B's vectors have 2,048 numbers, so with 1,024 threads every thread handles exactly two.
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.
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.
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:
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;
}
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
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();
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.
Two choices in this kernel look lazy, but they're deliberate.
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.
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.
GPU time per token for all RMSNorm calls, eager PyTorch vs the fused kernel, on the L4.
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.
FlashAttention, written in CUDA. My first attention kernel was 2.5× slower than PyTorch. Here's how it ended up faster, and why it runs 16K tokens where PyTorch runs out of memory.