Open the WaytoAGI knowledge base on Feishu · 100M+ visits, open to everyone →
WaytoAGI

Knowledge Base · Learning paths

How LLM Inference Works: A First-Principles Breakdown

This guide breaks down the entire LLM inference pipeline from first principles: tokenization, embeddings, attention mechanisms, the prefill and decode phases, KV cache, and quantization. It explains why the first token is slow, why subsequent tokens are much faster, and the different GPU bottlenecks in each phase.

LLM inferencehow LLMs worklarge language model inferencetransformer inferenceKV cache

Translated from Chinese by AI. Spotted an issue? Use the feedback button.

🔗 Original source: https://x.com/akshay_pachaar/status/2050941458614751327

A first-principles walkthrough of what actually happens between entering a prompt and receiving a streamed response: tokenization, embeddings, attention, the prefill/decode split, KV caching, and quantization.

You type a prompt. A few hundred milliseconds later, text starts streaming back to you, one token at a time. It looks simple. It is anything but.

Between your keystroke and the first token appearing, your request passes through one of the most finely tuned processing pipelines in modern computing. And here is the most counterintuitive part: to answer you, the model actually performs two completely different kinds of work within the same request, on the same GPU—and each has an entirely different bottleneck.

Once you understand this, you will never look at a generate() call the same way again.

The Mental Model

At its core, an LLM is a neural network that predicts the next token. Just one token at a time. It then appends that token to your prompt and predicts the next one. And repeats.

That is it. That is essentially the entire loop.

The interesting questions are: how exactly does it predict the next token? And why does the second token arrive so much faster than the first token?

Step 1: Your Text Becomes Numbers

A neural network does not “read” English. It processes vectors. So the first thing that happens when a prompt enters the system is tokenization: splitting the text into chunks and assigning each chunk an integer ID.

Most modern LLMs use a method called Byte Pair Encoding. The basic idea is to start with raw characters, then repeatedly merge the most frequent adjacent pairs until you have a vocabulary of roughly 50,000 entries. A common word like the might take up just one token, while a less common word like unhappiness might be split into pieces such as un + happi + ness.

python
prompt = "How does inference work?"
ids = tokenizer.encode(prompt)

# ids -> [2437, 1374, 32278, 670, 30]

The importance of this step is often underestimated. Languages underrepresented in the tokenizer’s training data tend to get split into more pieces, which means more tokens, higher costs, and slower responses for the same sentence.

Step 2: Each Token Becomes a Vector

Each integer ID is then used to look up a row in a huge matrix called the embedding table. If the model has a vocabulary of 50K tokens and a hidden dimension of 4096, this table has the shape [50000, 4096]. Retrieve a row, and you have a vector.

python

# embedding_table has shape [vocab_size, hidden_dim]
vectors = embedding_table[ids]   # shape: [num_tokens, 4096]

These vectors are not random. During training, the model continually adjusts their positions so that tokens with similar meanings sit closer together in this 4096-dimensional space. king and queen will be relatively close; python and snake might be close along one direction, while python and javascript are close along another.

The embedding layer is also where positional information is introduced, because attention itself does not know which token comes before or after another. Modern models typically use schemes such as RoPE, which encode position by rotating vectors according to each token’s position in the sequence.

Step Three: Attention Layers

Now the real computation begins. Your sequence of vectors is passed through a stack of transformer layers—typically at least 32—one after another. Each layer roughly does two things:

  1. Exchanges information between tokens through self-attention.

  2. Further processes information within each token through a feed-forward network.

Self-attention is the part most worth understanding in depth. For each token, the layer uses three sets of learned weight matrices to generate three new vectors:

python

# x is the input to this layer, shape [num_tokens, hidden_dim]
Q = x @ Wq # queries
K = x @ Wk # keys
V = x @ Wv # values

Each token now has three different “perspectives.” The key operation is this: each token uses its query to match against other tokens’ keys. The stronger the match, the more it takes in from the other token’s value.

python

# scores: how much each token attends to every other token
raw     = Q @ K.T
scaled  = raw / sqrt(hidden_dim) # keeps softmax stable
weights = softmax(scaled) # one row per token, sums to 1
attention_output  = weights @ V

The diagram below provides an intuitive view of this process:

That is the magic of attention. A token actively determines what context it needs, then searches the entire sequence for the information most useful to it. Stack 32 layers of this mechanism, and the model can track references spanning thousands of tokens.

After attention, each token’s vector also passes through a small, two-layer feed-forward network. This is actually where much of the model’s “knowledge” resides. Attention moves information around; the feed-forward network processes it.

Step Four: Predicting the Next Token

At the final layer, the model takes the vector at the last position, projects it back to the size of the full vocabulary, and applies softmax to produce a probability distribution over all possible next tokens. Sampling from this distribution gives you the first generated token.

Now comes the really interesting part.

The Two Phases Few People Explain Properly

Generating a 200-token response is not one uniform task. It actually consists of two tasks with completely different underlying behavior.

Phase One: Prefill

When you submit a prompt, the model must first process all your input tokens before it can start generating. The good news is that this step can happen in parallel. Every token’s Q, K, and V are computed simultaneously, and attention takes the form of a large-scale matrix-by-matrix multiplication.

GPUs excel at this. Matrix multiplication is their bread and butter. So the bottleneck in this phase is raw compute throughput: GPU utilization is often very high as it performs mathematical operations as quickly as possible.

The most important metric in this phase is Time to First Token (TTFT): that silent wait before the first words begin to appear on your screen.

python

# Prefill: process the whole prompt in one shot
hidden = embed(prompt_tokens) + positions
for layer in model.layers:
    Q, K, V = project(hidden)             # for ALL tokens at once
    hidden  = attention(Q, K, V) + hidden
    hidden  = feedforward(hidden) + hidden
    cache_kv(layer, K, V)                 # save for later
first_token = sample(project_to_vocab(hidden[-1]))

Phase Two: Decode

Once the first token is produced, the model switches modes. To generate the 51st token, for example, it only needs to compute Q, K, and V for this one token. What about the previous 50 tokens? Their K and V values haven't changed at all, so recomputing them would be a complete waste.

The model therefore enters a loop like this, processing one token at a time:

python

# Decode: one token per iteration
token = first_token
steps = 0
while token != STOP and steps < MAX_STEPS:
    x = embed(token) + position(steps)
    for layer in model.layers:
        q, k, v = project(x)
        K_all, V_all = caches[layer].append(k, v) # cached history + new
        x = layer.forward(q, K_all, V_all, x)  # attention + FFN, residuals
    token = sample(project_to_vocab(x))
    steps += 1
    yield token

Notice what has changed here. Previously, a "query matrix" was multiplied by a "key matrix"; now, a "query vector" is multiplied by an "entire key matrix." The amount of computation drops dramatically.

But to perform this small amount of computation, the GPU still has to fetch every layer's weight matrices, along with all the cached K and V values, from GPU memory. The bottleneck therefore flips: the chip isn't short on compute power—it is simply stuck waiting for memory to deliver the next batch of data.

This is why decode is memory-bound, while prefill is compute-bound. It is the same model running on the same hardware, yet the performance characteristics are completely different.

The most important metric at this stage is Inter-Token Latency (ITL): the time interval between two consecutive tokens being streamed out. The lower the ITL, the faster the model feels.

KV Cache: The Key Optimization That Makes All of This Practical

That append_to_cache line above is actually doing the most critical work. Without it, generating a 1,000-token response would require the model to recompute attention over the entire, continually growing sequence at every step. The computational complexity would quickly spiral out of control, making generation unacceptably slow.

With a KV cache, the K and V matrices only need to be computed once and can then be reused. The basic structure looks like this:

python

# One KVCache per transformer layer 
class KVCache:
    def __init__(self):
        self.K = None # all keys seen so far,   shape [tokens, dim]
        self.V = None # all values seen so far, shape [tokens, dim]

    def append(self, k_new, v_new):
        if self.K is None:
            self.K, self.V = k_new, v_new # first token
        else:
            self.K = concat([self.K, k_new], axis=token_axis)
            self.V = concat([self.V, v_new], axis=token_axis)
        return self.K, self.V # full history so far

The speedup is substantial. For long-form text generation, a 5× speedup—or more—is common. But the cost is equally real: this cache must remain in GPU memory, and it keeps growing with the token count. Each layer needs to maintain its own set of K and V tensors. For a 13B model, a rough estimate puts the additional cache required for each new token at about 1 MB. With a 4K-token context, the cache alone consumes roughly 4 GB of GPU memory.

This is why long contexts are always slow and expensive. It is not that the model lacks “brainpower”—it is that the cache no longer fits.

To address this problem, the industry has developed some clever optimizations: quantizing the cache to INT8 or INT4; discarding old tokens outside a sliding window; sharing K and V across multiple attention heads (grouped-query attention); or managing the cache like an operating system manages memory pages (PagedAttention, the key technique behind vLLM).

Frontier Research: Shrinking the Cache Itself

Quantization and paging treat the cache as a given cost to be managed. The V4 series that DeepSeek previewed in late 2025 takes a more aggressive approach: redesigning the attention mechanism itself to make the cache smaller from the outset.

Its hybrid approach combines two types of compressed attention mechanisms: one leans sparse, the other dense, and both operate on highly compressed KV streams. According to the V4-Pro report, at a context length of one million tokens, its cache is approximately 10% the size of its predecessor’s, while its compute per token is about 27% of the previous generation’s.

The point is not just that particular architecture, but the broader trend: the KV cache has become a central bottleneck that the entire field is working to optimize. When attention itself is being redesigned just to reduce the cache, you know the constraints have shifted.

If you want to understand where long-context inference is heading, this section is well worth reading. The full technical report is here:

Quantization: Trading Bits for Speed

Training requires high precision. Inference does not necessarily need it.

Most production deployments use FP16 or BF16 rather than FP32. This halves GPU memory usage and typically also roughly doubles throughput on Tensor Cores. More aggressive deployments go further, quantizing weights to INT8 or even INT4.

The math is straightforward. A model with 7 billion parameters requires approximately:

  • FP32: 28 GB

  • FP16: 14 GB

  • INT8: 7 GB

  • INT4: 3.5 GB

That last figure is precisely why a 7B model can run on a laptop GPU. Techniques such as GPTQ and AWQ choose different scaling factors for different channels to minimize the impact of this lossy compression on model quality. When done well, INT4 scores less than one percentage point below the original model on most benchmarks.

Putting It All Together

Here is the complete journey of a prompt, from start to finish:

  1. Tokenize. Text becomes integer IDs.

  2. Embed. IDs become vectors, with positional information incorporated along the way.

  3. Prefill. Every layer processes all input tokens in parallel. This phase is compute-bound. The KV cache is built here, and the first output token is produced.

  4. Decode loop. For each subsequent token: project Q only for the new token, perform attention over the cached K and V, pass through the feed-forward network, and sample; then append the new K and V to the cache. This phase is memory-bound.

  5. Detokenize. Token IDs are mapped back to characters and streamed to your screen.

Modern serving frameworks such as vLLM, TensorRT-LLM, and Text Generation Inference wrap this core loop in an entire layer of engineering optimizations. These include continuous batching (interleaving tokens from multiple users on the same GPU), speculative decoding (a smaller model drafts tokens, then a larger model verifies them), and sophisticated memory management techniques. This is how a single GPU can serve dozens of concurrent users.

How This Should Change Your Perspective

Once you have the full picture, a few practical insights follow:

  • Long prompts primarily increase TTFT, while long outputs primarily increase ITL. They put pressure on different bottlenecks. Prioritize optimizing the one your users actually notice.

  • Context length is never free. It does more than increase computation; it also expands the KV cache and limits the batch size you can use.

  • Quantization is one of the highest-impact knobs you can turn. In many scenarios, moving from FP16 to INT8 can cut latency in half with almost no loss in quality.

  • GPU utilization can be misleading. A model that maxes out the GPU during prefill is not necessarily fast during decoding. Utilization during decoding might be only 30%. In that case, the problem is not “insufficient compute,” but “memory is too slow” or “the cache is too large.”

Transformer architecture tends to attract the most attention, but the make-or-break factors in real-world inference performance often lie in seemingly “boring” engineering details: memory layout, cache management, and bit width. The real art is squeezing the most output from the hardware you have.

The next time someone tells you “the model is slow,” your first question should be: Is it slow to start, or slow to stream its output?

If you enjoyed this article, let me know in the comments.

That will tell me I should keep making more content like this.