News

日本語 · English · 中文

[Local LLMs Today] Part 3: Prefill and Decode – How LLMs Read and Write Text

LLM inference is divided into "prefill," which reads all inputs and generates the first token, and "decode," which generates tokens one by one from the second token onward. This article explains step-by-step the mechanisms of tokenization, embeddings, Transformer layers, Q, K, and V attention, and KV cache, which retains only the K and V values.

Hello. This is Ichiro Minato from blueqat. In this series, "The Current State of Local LLMs," Episode 1 covered the overall picture of local LLMs, and Episode 2 discussed the foundations of open weights, quantization, and VRAM. If you haven't read them yet, please check them out first.

This time, we will finally dive into the details. The theme is "Prefill and Decode." When an LLM returns text, the processing is actually divided into two stages. The former is prefill, and the latter is decode. While these two appear similar, the computations occurring within them are quite different. And when you want to speed up local LLMs or run them smoothly on your own PC, understanding these two separately is the starting point.

Those who have read Episodes 1 and 2 are likely already familiar with the overall picture of "downloading model weights and running them locally," as well as the concept that "weights are quantized and loaded onto VRAM." As a continuation of that, we will now walk through what happens at the moment inference actually runs, step by step. I will explain the terminology carefully so that even newcomers can follow along, so please rest assured.

This content is based on a video I presented. Although I have rewritten it in the first person as an article, for those who would like to hear the original presentation, please see below.

YouTube "The Key to Local LLM Acceleration: Explaining the Difference Between Prefill and Decode"

Inference is divided into two stages

Prefill: Reading the entire input and outputting the first token

First, let's look at prefill. Prefill is the stage where the model reads the input text to the end, understands the context, and predicts the first token (a unit equivalent to a word). For example, let's say you input "What is the capital of Japan?" This text is passed to the model, computations are performed internally, and the first token emerges. Up to this point is prefill.

The key point is that the entire input text is processed collectively. The longer the sentence, the more data needs to be read. In this stage, the passed text is converted into large computational data and sent to the GPU to perform calculations to understand the massive context. Therefore, the computational load on the GPU becomes extremely high. The bottleneck of prefill is precisely this computation. It involves using GPU cores to their fullest to compute the relationships within the entire input at once. This is the nature of prefill.

Let me add a supplementary explanation for the term "bottleneck." A bottleneck refers to the part of the overall flow that takes the most time. It points to the area where the entire process cannot be sped up unless improvements are made there. In prefill, the computation itself is that bottleneck.

Also, there is one more important aspect of this stage: the content calculated during prefill can be reused in the subsequent decode stage. This reuse mechanism is called KV cache, which is the central topic of this article.

Inference is divided into two stages: Prefill and Decode
Inference is divided into two stages: Prefill and Decode

Decode: Starting from the second token, generating one by one

Once the first token is output, the next stage is decode. In decode, the subsequent text is generated one token at a time, such as the second token, the third token, and so on.

To describe what is happening here accurately, it proceeds as follows: Based on the context including what has been generated up to that point, the next single token is predicted. To do this, the immediately preceding token is passed as input. At this time, the KV cache calculated and saved during prefill is reused. This means there is no need to recalculate the entire context from scratch; only a small additional calculation for the newly arrived token is required.

In other words, in decode, the computation itself is minimal. On the other hand, the massive weight data of the model must be read out for every token generation. Therefore, the bottleneck of decode is not computation, but memory readout, specifically memory bandwidth.

What is crucial here is that the weights themselves are fixed, and they are merely being read out each time. What is being reused in decode is the KV cache, not the weights. The weights are not being retrained or rewritten. The weights are fixed data that are repeatedly read from memory. The speed of this readout determines the speed of decode.

Prefill is computation-centric, leveraging GPU computational power. Decode is readout-centric, relying on memory bandwidth. Even though both are encompassed by the term "inference," what determines the speed is completely different.

Therefore, when discussing local LLM performance, different metrics are often used separately, such as tokens per second for prefill and tokens per second for decode. Whether you want to shorten the time until the first word appears or speed up the generation of the second word and beyond determines which metrics to look at and where to optimize.

What happens during Prefill
What happens during Prefill

What is happening inside

From here, I will explain step by step what specifically happens during prefill. It gets a bit detailed, but if you grasp the flow, that is sufficient.

First, we write a question. This is raw text. It looks like normal sentences such as "The capital of Japan is" or "I want to make this kind of omelet." The work begins to convert this raw text into a form that the model can handle.

The first step is tokenization (tokenizing). The text is divided into units called tokens, and each is assigned an ID. There are several algorithms for where to split the text. Splitting character by character would result in a very large number of tokens, so it is more efficient to split into cohesive units. For example, it might split by words like "Japan" and "capital," or there might be a difference in whether "artificial intelligence" is split into "artificial" and "intelligence" or treated as a single token. This depends on the algorithm. In any case, dividing text into tokens and assigning IDs to each is the first step.

Next is embedding (embedding vectors). The assigned IDs are converted into vectors, which are sequences of numbers with magnitude and direction. Unlike tokenization, which has algorithms, embedding becomes the work of AI at this point, using neural network weights to convert IDs into vectors. This results in a matrix where vectors for each token are aligned. This becomes the input matrix and serves as the input for prefill.

Once the input matrix is ready, we enter the core computational logic of the Transformer. The Transformer has a layered structure, stacked layer by layer. For example, it might be composed of 32 layers (I will explain using 32 layers as an example here). Passing through these layers sequentially constitutes the main computation.

In each layer, the Q·K·V calculation is performed first. Q stands for Query, representing the question. K stands for Key, representing the target information to search. V stands for Value, representing the content of that information. Using these, attention (importance within the context) is calculated. It determines numerically which token should pay attention to which other token and to what extent.

After the context calculation, there is knowledge addition. This occurs in the part called the Feed-Forward Network (FFN), where the knowledge held by the model is added to the vector. While attention handles "what is important in the context," you can think of FFN as the part that "adds knowledge."

Then, the output is fed into the next layer, where the same calculation is repeated. However, even though it is a repetition, the weights of each layer are all different, so calculations are performed separately for each layer. This process is passed through for 32 layers.

Finally, some vector, that is, a sequence of numbers, emerges. This vector is multiplied by the vocabulary matrix to calculate which token to select. This selection process is called sampling. This is how the first token is determined.

To summarize: Tokenize to create IDs, convert to vectors via embedding, repeat Q·K·V calculations, attention, and knowledge addition via FFN for the number of layers, and finally predict the next token. This is the content of prefill. Reading the text, understanding it, and outputting the first word—this series of flows is performed as a heavy computational process.

KV Cache: The reason for keeping only K and V

This is the core of this article. Q·K·V calculations are performed in each of the 32 layers, and the results accumulate layer by layer. Among these, what remains for reuse in the subsequent decode stage is the KV Cache. The K and V for each layer are saved in the GPU's VRAM.

Why are K and V kept, but Q is not? This is a common point of confusion, so I will explain it carefully.

Q represents the Query, i.e., "what is being searched for now." This changes every time a new token arrives. If a different question comes, the content being searched also changes, so past Qs cannot be reused as is. For a new token, Q must be recalculated.

On the other hand, K and V are information about the context up to that point. The content "there is such information in this context" does not change for the existing parts even if one new token is added. Therefore, they can be kept and reused.

So, when a new token arrives, how is the KV Cache updated? This is another point to grasp accurately. The K and V calculated for the new token are appended to the back of the KV Cache. They are not added to the existing cache values. The image is that since the context extends by one token, new K and V for that amount are appended to the end. This addition occurs for each layer.

Thus, in the decode stage, Q is calculated for the newly arrived token, K and V for that token are calculated and appended to the back of the cache, and attention is calculated by combining it with the existing cache. Since most of the K and V have already been calculated, only the differential needs to be computed. Therefore, decode requires much lighter processing compared to prefill.

However, although it is light, it is still necessary to read out the model weights each time. A huge amount of data is being read from memory to generate a single word. This leads back to the earlier point that the speed of decode is determined not by computation, but by memory readout speed.

Here, let's also confirm that the KV Cache is saved in VRAM. Since it saves context, it amounts to a considerable size. In Episode 2, we calculated that the KV cache per token for Qwen3.8-27B is approximately 64KB. As the context becomes longer, the cache increases accordingly. The VRAM capacity must be considered not only for weights but also for this KV cache.

KV Cache: Keeping only K and V, appending new amounts to the back
KV Cache: Keeping only K and V, appending new amounts to the back

Next time

In next episode's Episode 4, we will take this discussion one step further and look more concretely at what determines speed. Keeping in mind that the bottlenecks differ between prefill and decode, you will be able to see which parts of your own machine are effective. Whether it is GPU computational power, memory bandwidth, or capacity. The reasons why speed varies across environments even for the same model should become visible there.

Additionally, inference engines are responsible for such optimizations. There are inference engines like Strata, SGLang, and vLLM, which optimize weight loading and calculation order to change the speed of the same model. I cover how to read Strata benchmarks in detail in How to Read Strata Benchmarks, so please check that out as well. Next time, I will continue to explain carefully what these inference engines are doing and how to identify the factors that determine speed.

This time was a bit long, but if you can remember the two stages of prefill and decode separately, and keep in mind that the computational domains used in each are different, I would be happy. Thank you for reading.

Next episode: Episode 4: What Determines Speed――Bandwidth, Inference Engines, MoE, and Placement

This article was translated from the Japanese original. 日本語で読む

← Latest articles