Kernels and FlashAttention

Topics Covered

What a Kernel Is

Kernels as the unit of GPU work

The memory hierarchy

Arithmetic intensity at the kernel level

Launch overhead

Where time goes in a decode step

Who writes kernels

Threads, warps and blocks

Tiles are the core design choice

Specialized matrix units

Bandwidth numbers to remember

Reading a kernel name in a profile

Why this matters for serving engineers

Every operation a model performs on a GPU, from a matrix multiply to a softmax, runs as a kernel: a small program launched across thousands of GPU threads. The speed of inference depends heavily on how well these kernels use the hardware. This lesson explains what kernels are and why memory movement dominates their cost, how kernel fusion removes wasted trips to memory, how FlashAttention restructured attention to avoid materializing huge intermediate matrices, how decode attention kernels differ from prefill ones, and how engineers choose and tune kernels in practice. This first section builds the mental model.

Kernels as the unit of GPU work

A GPU does not run a model as one program. The framework breaks each layer into a sequence of operations, and each operation is dispatched as a kernel. A kernel launch tells the GPU to run the same function on a grid of thread blocks, each block handling a tile of the data. A transformer layer at inference might launch a dozen or more kernels: normalization, the query, key and value projections, rotary embedding, attention, the output projection, a residual add, another normalization, and the feed forward projections with their activation. A 32 layer model can therefore launch several hundred kernels per forward pass.

The memory hierarchy

GPUs have a hierarchy of memory with very different speeds. High bandwidth memory, or HBM, holds the weights and KV cache; an H100 has 80 gigabytes of it with roughly 3.35 terabytes per second of bandwidth. Each streaming multiprocessor has a small amount of fast on chip shared memory and registers, about 228 kilobytes of shared memory per multiprocessor on an H100, with bandwidth an order of magnitude higher than HBM. A kernel reads its inputs from HBM into on chip memory, computes, and writes results back to HBM. Data that stays on chip between steps is cheap; data that makes a round trip to HBM is expensive.

A kernel pulls data from big, slow HBM into small, fast on chip memory, computes and writes back. The round trips cost the most.

Arithmetic intensity at the kernel level

Lesson five introduced arithmetic intensity, the ratio of operations to bytes moved, for the model as a whole. The same idea applies to each kernel. A large matrix multiply reads two matrices and performs many multiply adds per element, so its intensity is high and it can approach peak compute. An elementwise operation such as adding a bias or applying an activation reads each element once, does one operation and writes it back, so its intensity is tiny and it is limited entirely by memory bandwidth. A softmax over a row reads the row, computes a maximum, exponentials and a sum, and writes it back, again mostly memory bound. Most non matrix operations in a transformer are memory bound.

Launch overhead

Each kernel launch costs a few microseconds of CPU and driver time before the GPU starts work. For large prefill passes this is negligible compared with the work itself. For decode at small batch, where each kernel may finish in tens of microseconds, hundreds of launches per step add up to a significant share of step time. This is why decode benefits from techniques that reduce launch count, such as fusion and CUDA graphs, which record a whole sequence of launches once and replay it with a single call.

Where time goes in a decode step

Profiling a decode step at small batch typically shows most time in the matrix multiplies that read weights, a meaningful share in attention reading the KV cache, and the rest spread across small elementwise kernels and launch gaps. As the batch grows, the matrix multiplies become more compute efficient, while attention grows with the total cached tokens across sequences, since each sequence must read its own cache. For long contexts, attention can become the largest single cost. Knowing this breakdown tells you where kernel work pays off.

Who writes kernels

Most engineers never write a kernel. Vendor libraries such as cuBLAS provide matrix multiplies; libraries such as FlashAttention, FlashInfer and the kernels inside vLLM, SGLang and TensorRT LLM provide attention and fused operations. Tools such as Triton let engineers write kernels in Python like code that compiles to efficient GPU programs, and compilers such as torch.compile generate fused kernels automatically. Understanding what kernels do helps you choose engine options, read profiles and recognize when a slow step comes from a missing optimized kernel rather than from the model itself.

Threads, warps and blocks

A kernel runs as a grid of thread blocks. Each block contains hundreds of threads, grouped into warps of 32 threads that execute the same instruction together. Blocks are assigned to streaming multiprocessors, and an H100 has 132 of them. A multiprocessor can host several blocks at once if they fit in its registers and shared memory, and it switches between warps to hide memory latency: while one warp waits for data from HBM, another computes. The fraction of the possible warps that are actually resident is called occupancy. Good kernels keep enough warps in flight to hide latency while giving each one enough registers and shared memory to work efficiently.

Tiles are the core design choice

Almost every efficient kernel works on tiles: rectangular pieces of the data sized so that a block can load them into shared memory or registers, compute on them repeatedly and write results once. A matrix multiply kernel loads a tile of each input matrix, multiplies them, accumulates the result and moves to the next pair of tiles. The choice of tile size balances reuse, which favors large tiles, against resource limits, which favor small ones. Much of the craft of kernel engineering lies in picking tile shapes that match the hardware, the data type and the problem size.

Specialized matrix units

Modern GPUs include tensor cores, specialized units that multiply small matrices in a single instruction at much higher throughput than ordinary arithmetic. An H100 delivers roughly 990 trillion dense BF16 operations per second through its tensor cores, compared with a small fraction of that from general purpose units. Kernels that do not use tensor cores for matrix work leave most of the compute capacity untouched. Tensor cores support specific data types and shapes, which is one reason new quantization formats need new kernels before they run fast.

A multiprocessor juggles many warps. While one waits on memory, another computes, so the hardware stays busy.

Bandwidth numbers to remember

A few numbers anchor kernel reasoning. An H100 reads HBM at about 3.35 terabytes per second, so streaming a 140 gigabyte set of weights, such as a 70 billion parameter model in BF16 split over two GPUs, takes roughly 21 milliseconds per GPU half. Shared memory bandwidth is roughly ten times higher, and registers faster still. A kernel that reaches 80 to 90 percent of HBM bandwidth on a memory bound operation is considered excellent. When a profile shows a memory bound kernel at 30 percent of peak bandwidth, there is usually a better kernel or configuration available.

Reading a kernel name in a profile

Kernel names in profiles look cryptic but carry useful hints. Names containing gemm or matmul are matrix multiplies, often with tile shapes and data types encoded in the name. Names containing flash, fmha or paged_attention are attention kernels. Names containing rms_norm, silu, rotary or fused are the glue operations. Names with a generic prefix from the framework, such as an elementwise or vectorized kernel, often mean an operation is running on a default path without an engine specific optimization. Learning to recognize these patterns makes it quick to tell, at a glance, whether a step is dominated by the right kernels or by unexpected ones.

Why this matters for serving engineers

Serving engineers make decisions every week that depend on kernels without naming them: which engine version to run, whether to quantize, which GPU to buy, whether to enable a long context mode. Each decision changes which kernels run and how efficiently. A working model of kernels, memory traffic and launch overhead lets you predict the effect of these choices instead of discovering it after deployment.

Inference speed is mostly memory movement

Apart from large matrix multiplies, most kernels in a transformer are limited by how fast they move data between HBM and the chip. Good kernels move less data.