The Basics of Transformer Inference Transformer inference requires a KV cache to cut generation complexity from O(n^2) on the feedforward network and O(n^3) on attention down to O(n) and O(n^2) respectively, according to Part 7 of the "How To Scale Your Model" scaling book. The article states that inference splits into two distinct tasks, prefill and generation, and introduces latency metrics absent from training, specifically Time To First Token (TTFT) and per-token latency. The piece notes that throughput per chip remains critical for cost and TTFT but does not necessarily improve individual user experience, citing llama.cpp running on a laptop as a single-user, low-latency case. Part 7 of How To Scale Your Model https://jax-ml.github.io/scaling-book Part 6: Training LLaMA ../applied-training | Part 8: Serving LLaMA ../applied-inference Performing inference on a Transformer can be very different from training. Partly this is because inference adds a new factor to consider: latency. In this section, we will go all the way from sampling a single new token from a model to efficiently scaling a large Transformer across many slices of accelerators as part of an inference engine. So you’ve trained a Transformer, and you want to use it to generate some new sequences. At the end of the day, benchmark scores going up and loss curves going down are only proxies for whether something interesting is going to happen once the rubber hits the road Sampling is conceptually simple. We put a sequence in and our favorite Transformer will spit out $\log p \text{next token} i \vert \text{previous tokens} $, i.e. log-probabilities for all possible next tokens. We can sample from this distribution and obtain a new token. Append this token and repeat this process and we obtain a sequence of tokens which is a continuation of the prompt. We have just described the naive implementation of Transformer sampling, and while it works, we never do it in practice because we are re-processing the entire sequence every time we generate a token. This algorithm is $O n^2 $ on the FFW and $O n^3 $ on the attention mechanism to generate $n$ tokens How do we avoid this? Instead of doing the full forward pass every time, it turns out we can save some intermediate activations from each forward pass that let us avoid re-processing previous tokens. Specifically, since a given token only attends to previous tokens during dot-product attention, we can simply write each token’s key and value projections into a new data structure called a KV cache . Once we’ve saved these key/value projections for past tokens, future tokens can simply compute their $q i \cdot k j$ products without performing any new FLOPs on the earlier tokens. Amazing With this in mind, inference has two key parts: