Skip to main content

LLM inference kernels

Optimizing an LLM LayerNorm Kernel in Rust

Published 7 min 49 sMeasured on NVIDIA L4

What this video shows

About this walkthrough

A correct GPU kernel can still waste most of the threads it launches. This Rust lab turns a serial row-wise LayerNorm starter into a block-per-row kernel in which the threads cooperate. The walkthrough covers shared-memory reductions, a synchronization requirement when scratch storage is reused, and exclusive ownership of the output. The matching 4,096-row kernel changes from 2.04 ms to 52.58 microseconds in one captured pair, with both versions passing correctness.

Read along

Transcript

Select a time to play the video from that chapter.

0:00Learn LayerNorm in Rust

A correct GPU kernel can still leave most of its threads with no useful work. Let's see how that happens in a Rust LayerNorm kernel, and fix it in GPUFlight. We'll read the task, give each row to a whole block, and compare the actual profiling results.

0:19What does LayerNorm do?

Layer normalization, or LayerNorm, adjusts a row of features using that row's own mean and variance. It appears in many neural networks, including many Transformers. First, subtract the mean to center the values. Then divide by the square root of the variance, plus a small epsilon for numerical stability. This lab focuses on that normalization step. It leaves out the optional learned scale and bias, so we can focus on the GPU work.

0:52Read the task and keep the math

Here is LayerNorm: One Block Owns One Row. Select Rust, and use the L4 for both versions. The largest case has 4,096 rows, with 1,024 values per row. The answer must stay correct across the test cases. In particular, the data has a large mean and a small spread. We calculate deviations from the mean before squaring them, to avoid losing precision. Our change is how threads share the work. We are not changing the normalization formula.

1:28Find the serial work in the starter

Look at the row index. It combines the block index and the thread index. Each valid thread gets a different row, then walks that whole row three times: mean, variance, and output. Now look at the launch. There is already one block for every row, and 256 threads per block. Most launched threads therefore get a row index outside the input and do nothing. For the largest case, only the first sixteen blocks do useful row work. That comes from reading the source and launch dimensions, not from an occupancy measurement.

2:06Profile the baseline

Before editing, run the starter and open its profiling session. In Kernels, expand the LayerNorm kernel to see its launches and memory statistics. We'll compare the launch with 4,096 blocks and 256 threads per block. That identifies the same large input in both versions. Keep kernel duration separate from the total lab runtime. The lab harness also performs setup, checks, and other work.

2:38Edit 1: a block owns a row

First, use the block index as the row. Every thread in that block now agrees on which row it owns. Add a shared array with one slot per thread. Shared memory lets threads within the same block exchange partial results. Each thread starts at its own column and advances by the block size. With 1,024 columns and 256 threads, each thread handles four values per pass.

3:08Edit 2: cooperate on the mean

Each thread first sums its own values and stores that partial sum in the shared array. Then all threads meet at a barrier. A reduction combines those partial results. Here, pairs are added in a tree. The stride halves each round, until slot zero holds the row sum. Notice that the synchronization is outside the condition. All threads must reach the barrier, even when only some threads perform an addition. Divide the total by the number of columns to get the mean.

3:41Edit 3: preserve the mean, then reduce variance

This next barrier matters. Every thread must finish reading the mean before anyone overwrites the shared array for the variance calculation. Without it, a fast thread could replace slot zero while a slower thread is still reading the mean. That would be a race. Now subtract the mean, square each deviation, and sum each thread's share. We use the same reduction pattern again to combine the variance. The math stays deliberately in two stages. A shortcut based on the average of squared values can lose precision when the mean is large and the spread is small.

4:21Edit 4: normalize separate columns

Finally, calculate the inverse standard deviation and normalize the columns in parallel. Each thread writes only its own columns. That is the safety argument for this unchecked output access: the indices are valid, and no two threads write the same element. The launch still uses 256 threads per block. This example's shared array is sized for that choice. Changing the block size also means revisiting the storage and reduction assumptions.

4:55Verify correctness and compare

Run the complete optimized kernel, then check correctness before interpreting performance. Both versions pass correctness, and the optimized version also passes the lab's speed target. Select the baseline and optimized Rust runs, and open Compare. Both use NVIDIA L4 GPUs, the same row sizes, and the same normalization formula. The saved source snapshots show exactly what changed. The 7.92× score compares against the harness's own reference in that run. Next, we'll compare our two submitted kernels directly in the profiler. These are different comparisons.

5:39Read the measured results

Open the optimized session, choose Kernels, and expand layernorm rows. Match the large launch by its grid and block dimensions. The starter took 2.04 ms. The optimized kernel took 52.58 µs. That is about 97% less kernel time in this captured pair. It is not an end-to-end model speedup or a repeated benchmark. Achieved occupancy rises from 47.8% to 93.9%. Occupancy measures active warps relative to a hardware limit. A warp is a group of thirty-two threads. Higher occupancy alone does not prove that those threads are doing useful work.

6:27Connect the counters to the code

Expand the launch for hardware counters. SM throughput rises from 0.7% to 66.1%. SM means streaming multiprocessor: the GPU hardware that runs thread blocks. This is consistent with better use of the processing hardware here. The baseline's sampled stalls are dominated by memory waits. The optimized profile also shows barriers and shared-memory waits. These percentages describe the collected samples, not the fraction of time we saved. We still read the row for the mean, again for the variance, and again for the output. The shared array holds partial sums, not a cache of the input row. The improvement comes from sharing the work and changing the access pattern. Each change also has costs, so correctness and matching measurements come first.

7:24Try the Rust lab

Rust does not remove the need to understand the GPU execution model. Thread ownership, memory access, and synchronization still determine how the kernel behaves. Try this lab in GPUFlight. Read the code, make one clear change, and use the profiler to check what happened. Thanks for watching!

Measure it yourself

Run the same experiment on a real GPU

Edit the kernel in your browser, run it on managed hardware, and read the profile the video walks through.

Run the LayerNorm lab