LLM Architecture
By Ludovico Bessi, Senior ML Engineer at Google ¡ Updated
The decoder-only transformer, seen through the lens of what it costs to run.
The Big Picture
Nearly every production LLM â GPT, Llama, Mistral, Qwen, Gemma, DeepSeek â is a decoder-only transformer. Text is split into tokens, each token becomes a vector, the vectors pass through a stack of identical blocks, and the final vector at the last position is turned into a probability distribution over the next token.
tokens â embedding â [ block Ă L ] â final norm â LM head â next-token probabilities
block = x + Attention(Norm(x)) â x + FFN(Norm(x))
From an inference point of view, the questions that matter for each component are: how many parameters does it hold, how many FLOPs does it cost per token, and what state does it leave behind?
Tokens and Embeddings
A tokenizer (usually byte-pair encoding) maps text to integer IDs from a vocabulary of roughly 32K to 256K entries. The embedding table maps each ID to a vector of size d_model (4096 for Llama 2 7B and Llama 3 8B, 8192 for 70B-class models).
The embedding table and the output projection (the LM head) are each vocab Ă d_model parameters. With a 128K vocabulary and d_model = 4096, that is about 0.5B parameters each â a meaningful slice of a small model. A larger vocabulary means fewer tokens per sentence (less decode work) but a bigger, slower LM head.
The Transformer Block
Each block has two sub-layers, each wrapped in a residual connection and a normalization layer. Modern models normalize before each sub-layer (pre-norm) and usually use RMSNorm, which is cheaper than LayerNorm and works as well.
Self-Attention
For each token, attention computes three projections: a query (what am I looking for?), a key (what do I contain?) and a value (what do I pass on?). Each token's output is a weighted average of the values of earlier tokens, weighted by how well its query matches their keys:
Attention(Q, K, V) = softmax(Q Káľ / âd_head + causal_mask) V
The causal mask stops a token from looking at future tokens, which is what makes the model generative.
Attention is split into h heads, each with dimension d_head = d_model / h (typically 128). Heads let the model attend to different things at once. The projection weights are W_Q, W_K, W_V and an output projection W_O.
Two facts matter enormously for inference:
- The keys and values of past tokens never change. Once computed, they can be stored and reused for every future token. That store is the KV cache.
- Attention cost grows with sequence length. Over a full sequence of length
n, attention is O(n²) in compute. During decode, each new token attends to allnprevious tokens, so per-token cost grows linearly as the answer gets longer.
Grouped-Query and Multi-Query Attention
In classic multi-head attention (MHA), every query head has its own key and value head. Multi-query attention (MQA) shares a single key/value head across all query heads; grouped-query attention (GQA) shares each key/value head across a group of query heads. Llama 2 70B and Llama 3 use GQA with 8 KV heads.
This barely affects quality but shrinks the KV cache by the group factor (4Ă to 8Ă is common). It is the single most important architectural decision for serving cost, and it must be made at training time. Details are in Attention Optimizations.
Positional Information: RoPE
Attention by itself has no notion of order. Most current models use rotary position embeddings (RoPE), which rotate query and key vectors by an angle that depends on position. The dot product between a query and a key then depends on their relative distance. RoPE is applied to keys before they enter the KV cache, and techniques to extend context length (position interpolation, NTK-aware scaling, YaRN) work by adjusting these rotation frequencies.
The Feed-Forward Network
After attention, each token passes independently through a feed-forward network (FFN). Modern models use a gated variant, SwiGLU:
FFN(x) = W_down ¡ ( SiLU(W_gate ¡ x) â (W_up ¡ x) )
The hidden size is typically about 2.7â3.5Ă d_model. The FFN holds roughly two-thirds of a dense model's parameters, so it dominates the weight memory you read on every decode step.
Mixture of Experts
A Mixture-of-Experts (MoE) layer replaces the single FFN with many expert FFNs and a router that sends each token to a few of them (for example, 2 of 8 in Mixtral 8x7B). Total parameters grow, but the parameters used per token stay small. For inference this is a mixed blessing: FLOPs per token drop, but all experts must still sit in memory, and at small batch sizes each step may touch many different experts.
Where the Parameters and FLOPs Go
For a dense model with N parameters, a forward pass costs about 2N FLOPs per token (one multiply and one add per weight). Attention adds a term that grows with context length: roughly 2 Ă n_layers Ă n_ctx Ă d_model FLOPs per token for the score and value computations.
| Model | Layers | d_model | Heads (Q / KV) | Parameters |
|---|---|---|---|---|
| Llama 2 7B | 32 | 4096 | 32 / 32 | 6.7B |
| Llama 3 8B | 32 | 4096 | 32 / 8 | 8.0B |
| Llama 2 70B | 80 | 8192 | 64 / 8 | 69B |
At short contexts the weights dominate everything. At long contexts (tens of thousands of tokens), attention over the KV cache starts to dominate both FLOPs and memory traffic.
The Generation Loop
kv_cache = prefill(prompt) # one pass over all prompt tokens
token = sample(logits_of_last_position)
while token != EOS and len(output) < max_tokens:
logits, kv_cache = forward(token, kv_cache) # one new token, reuses the cache
token = sample(logits)
The final step, sampling, turns logits into a token: greedy (take the max), temperature scaling, top-k, or top-p (nucleus) sampling. Sampling is cheap, but it matters for techniques like speculative decoding, which must preserve the sampling distribution exactly.
What This Means for Inference
- Weights set the floor on memory and on per-token latency: you read all of them every decode step.
- The KV cache is per-request state that grows with context. Its size is set by layers, KV heads and head dimension â architectural choices.
- Attention is the only part whose cost depends on context length; everything else is per-token constant.
- The FFN is the bulk of the weights; MoE trades memory for fewer FLOPs per token.
Key Takeaways
- Production LLMs are decoder-only transformers: embeddings, a stack of attention + FFN blocks, and an LM head.
- A dense model costs about 2N FLOPs per generated token, plus an attention term that grows with context.
- Keys and values of past tokens are reusable, which is why the KV cache exists.
- GQA/MQA shrink the KV cache several-fold and are decided at training time.
- MoE lowers FLOPs per token but not memory footprint.