November 25, 2026
Why is LLM inference hard?
When I first heard about inference engines, like vLLM, I wondered what makes inference so challenging. That’s why I decided to learn more about LLM inference from a systems perspective. If you already know how transformers work, then this is a fun topic to explore. In case you don’t, I recommend watching this awesome YouTube video by 3Blue1Brown. In this blog post you’ll learn about KV cache, paged attention, continuous batching and flash attention. Let’s get started!
Attention Revisited
Let’s briefly recap what happens in the attention layer when an LLM is prompted with something like “Edsger Dijkstra was a dutch computer scientist who”. First, the keys and the queries are calculated from token embeddings and the attention scores are derived as follows:
For simplicity, we consider only a single head. The first forward pass, called prefill, processes the whole prompt at once and fills in the entire attention matrix. From then on, in the decode phase, each new token adds just a single row.
We now know how much “made” attends to each earlier token, we use these scores to take a weighted sum of the value vectors, and update the embedding for “made”.
With attention revisited, let’s take a look at some of the systems challenged involved.
KV cache
LLMs generate one token at a time. At every decode step, the keys and the values of all earlier tokens, whether they came from the prompt or were generated, are exactly the same as in the previous step. Recomputing them would be wasted work. So inference engines compute them once, store them, and reuse them in every later step. This is the KV cache.
But LLMs don’t know in advance how many tokens they will generate when prompted. How are we gonna know the amount of space needed for the KV cache in that case? We can assume we know the maximum sequence length, and reserve all that space, but if the generated sequence happens to be much shorter, we’ve wasted GPU memory, a scarce resource! This is what is known as internal fragmentation. Moreover, inference engines serve many requests at once, each with its own cache. Requests finish at different times and leave gaps in memory. The total free space may be enough for a new request, but not in one contiguous piece. This creates external fragmentation!
Paged attention
To alleviate these problems, inference engines borrow an idea from operating systems. Remember that in an OS, each process assumes it has a large, contiguous memory starting at address 0, and the OS maps these virtual addresses to physical memory, which can be scattered anywhere.
Paged attention applies the same idea to the KV cache. The cache is split into small fixed-size blocks (for example 16 tokens each). Each request sees a contiguous sequence of logical blocks, and a block table maps each one to a physical block wherever there is space. Blocks are allocated only when needed, so we don’t need to know the maximum length in advance, and the blocks don’t have to be next to each other. The attention computation is modified to follow the block table when it reads keys and values.
We briefly said that inference engines run multiple requests at a time. Next let’s understand why that is the case, and what are the ways around it.
Static and continuous batching
LLMs can be hundreds of gigabytes in size, and at every decode step, each weight has to be read from GPU memory into the compute cores. But GPUs are much better at doing math than at moving data. For instance, a H100 can do roughly 1000 TFLOPs but can read only 3.3 TB/s from memory, meaning that in the time it takes to read a single byte, it can do around 300 floating-point operations!
Now consider a single request. Every weight we read is used for just one token, which is roughly one operation per byte instead of the 300 the GPU could handle. For an 8B model, reading the weights takes about 5 ms, while the actual math takes about 0.02 ms. The GPU spends almost all of its time waiting for memory instead of computing. We say that decoding is memory-bound.
Reading the weights is the expensive part, so let’s read them once and use them for many requests at the same time. This is batching. With 32 requests in a batch, a decode step reads the same weights and does 32 times more useful work, so it takes about as long as before, but produces 32 tokens instead of one.
There are two ways to batch requests. In static batching, we start with a fixed set of requests and keep running decode steps until all of them are finished, then start the next batch. The problem is that requests don’t finish at the same time. The ones that finish early leave their slots empty until the longest request is done, and the requests waiting in the queue can’t start. In continuous batching, the batch is re-evaluated after every decode step: as soon as a request finishes, it is replaced by one from the queue, so no slot sits idle.
There is a catch, though. The weights are shared by all requests in the batch, but the KV cache is not, since every request has its own. So the batch size is limited by how much GPU memory is left for KV caches, and with continuous batching, caches are constantly allocated and freed as requests come and go. This is exactly why the memory management of paged attention matters.
Memory traffic turns out to matter inside the attention computation itself during prefill, which brings us to flash attention.
Flash attention
In the naive implementation of attention, the following four steps are run separately:
- the score matrix is calculated: \(S = \dfrac{QK^\top}{\sqrt{d}}\)
- masking is applied, so that a token cannot attend to the tokens after it: \(S_{ij} = -\infty\) for \(j > i\)
- softmax is applied to each row to normalize the scores between 0 and 1: \(P_{ij} = \dfrac{e^{S_{ij}}}{\sum_k e^{S_{ik}}}\)
- the attention scores are used to update the value embeddings: \(O = PV\)
Each steps runs a separate GPU kernel and writes out the results to GPU memory (HBM) and next steps read them back from HBM to the faster SRAM in GPU to do the computations. There are several problems here. For starters HBM is much slower than SRAM and the computations done in between, for instance masking and softmax, are not computationally intensive so we are once again bounded by the memory!
Redrawn after Figure 1 of the FlashAttention paper by Dao et al.
SRAM is roughly 10 times faster than HBM, but about a thousand times smaller. Not only that, but also score matrix is N×N, which is quadratic in size, and consumes a large amounts of memory! The question is if we can do the same computation, without materializing the N×N matrix and not moving data out of SRAM. That’s the idea behind Flash Attention. It computes everything in a single fused kernel, working on small tiles of Q, K and V that fit in SRAM, and updates a running state as each tile arrives. In the end, it produces exactly the same output as standard attention, without ever writing the N×N matrix to HBM.
Redrawn after Figure 1 of the FlashAttention paper by Dao et al.
Let’s go through the steps in detail. The only tricky part is how the softmax is computed in this new setting, so let’s start there.
Softmax turns a row of scores \(s_1, \dots, s_N\) into weights that are positive and add up to 1:
\[ p_j = \frac{e^{s_j}}{\sum_{k=1}^{N} e^{s_k}} \]
The problem is that the exponential grows very fast. In 16-bit floating point, the largest representable number is 65504, and \(e^{12} \approx 162755\) is already too big, so a score of 12 gives inf, and the result becomes NaN. The standard fix is to subtract the largest score from every score before taking the exponential:
\[ m = \max_{j} s_j, \qquad p_j = \frac{e^{s_j - m}}{\sum_{k=1}^{N} e^{s_k - m}} \]
This doesn’t change the result, because the factor \(e^{-m}\) appears in both the numerator and the denominator and cancels out:
\[ \frac{e^{s_j - m}}{\sum_k e^{s_k - m}} = \frac{e^{-m}\, e^{s_j}}{e^{-m} \sum_k e^{s_k}} = \frac{e^{s_j}}{\sum_k e^{s_k}} \]
But now the largest exponent is \(e^{0} = 1\) and all the others are smaller, so nothing can overflow, and the denominator is at least 1, so we never divide by zero.
To compute \(p_j\) we need \(m\) and the sum \(\sum_k e^{s_k - m}\) over the whole row, and then the output of the row is \(o = \sum_j p_j v_j\). Flash attention never sees the whole row at once. looking at the picture, in the outer loop only one block of \(K^\top\) is in SRAM at a time, so we only see a small piece of each row of scores.
The idea is to keep a small running state for each row (each query), and update it every time a new block of keys arrives. Let’s introduce some notation and look at how this can be done more rigorously:
- \(m\): the largest score seen so far,
- \(\ell\): the running sum of \(e^{s_k - m}\),
- \(\tilde{o}\): the running weighted sum of the values, \(\sum_k e^{s_k - m}\, v_k\), which is not divided by anything yet.
Before any block, \(m^{(0)} = -\infty\), \(\ell^{(0)} = 0\) and \(\tilde{o}^{(0)} = 0\). When the \(t\)-th block of keys \(\mathcal{B}_t\) arrives, with scores \(s_k\) and values \(v_k\) for \(k \in \mathcal{B}_t\), we update:
\[ \begin{aligned} m^{(t)} &= \max\Big(m^{(t-1)},\ \max_{k \in \mathcal{B}_t} s_k\Big) \\ \ell^{(t)} &= e^{\,m^{(t-1)} - m^{(t)}}\, \ell^{(t-1)} + \sum_{k \in \mathcal{B}_t} e^{\,s_k - m^{(t)}} \\ \tilde{o}^{(t)} &= e^{\,m^{(t-1)} - m^{(t)}}\, \tilde{o}^{(t-1)} + \sum_{k \in \mathcal{B}_t} e^{\,s_k - m^{(t)}}\, v_k \end{aligned} \]
Let’s see what the update does. The new block may contain a score that is larger than anything we’ve seen, so the maximum changes from \(m^{(t-1)}\) to \(m^{(t)}\). Everything we accumulated so far was computed relative to the old maximum. The factor \(e^{m^{(t-1)} - m^{(t)}}\) rescales it so that it is relative to the new maximum. If the maximum doesn’t change, the factor is \(e^0 = 1\), and we simply add the new terms. You can see that after every block, the running state is exactly what the stable softmax would have computed on the keys seen so far.
After the last block \(T\), we divide once:
\[ o = \frac{\tilde{o}^{(T)}}{\ell^{(T)}} \]
Here \(o\) is the output vector for a single query, in other words one row of \(O = PV\). In our earlier example, the row for “made” is what we use to update its embedding. It is the same output that standard attention gives. After the last block we have seen every key in the row, so \(m^{(T)}\) is the true maximum \(m\), and the division gives us:
\[ o = \frac{\tilde{o}^{(T)}}{\ell^{(T)}} = \frac{\sum_k e^{s_k - m}\, v_k}{\sum_k e^{s_k - m}} = \sum_k p_k\, v_k \]
So the same math is done as before, but the \(N \times N\) matrices are never written to or read from HBM. The memory used drops from \(O(N^2)\) to \(O(N)\), and since HBM was the bottleneck, the whole thing is faster, even though the number of operations is the same.
Summary
In this blog post, we briefly explained some of the systems challenges involved in LLM inference and gained a little bit of insight into how they internally work. If you are interested in this topic, I recommend checking the following resources:
- Mini-SGLang: a compact implementation of SGLang in about 5,000 lines of Python.
- tiny-vllm: an inference engine in C++ and CUDA, with a course that walks you through building it from scratch.
- tiny-llm: a hands-on course for systems engineers who want to understand LLM inference end to end.