How Large Language Models Work — Part 2: The Attention Mechanism
This is Part 2 of a five-part series on the internal mechanics of large language models. Part 1 covered tokenization, embeddings, and positional encoding. Part 2 derives the self-attention mechanism from first principles, covers multi-head attention, and examines the KV cache.
The Problem Attention Solves
At the end of Part 1, we had a matrix , which was a one d-dimensional vector per token, encoding both semantic identity and position. The first transformer layer receives this matrix and must do something critical: allow each token to incorporate information from every other token in the sequence before passing its updated representation to the feed-forward network.
This is the problem that self-attention solves. Earlier sequence models such as LSTMs and GRUs processed tokens sequentially, which meant that a word at position 1 had to wait for its influence to propagate through every intermediate hidden state to reach position 512. Long-range dependencies were difficult to learn because the gradient had to flow through hundreds of recurrent steps. Attention eliminates this bottleneck entirely by allowing any token to attend directly to any other token in a single operation, regardless of distance.
Queries, Keys, and Values
The first step of self-attention is to project each token’s embedding into three separate representations using learned weight matrices:where are learned projection matrices, and is the dimension of the query and key space (typically where is the number of attention heads, more on that shortly).
The resulting matrices are called the Query, Key, and Value matrices respectively.
The intuition behind this decomposition is often explained through an analogy: think of each token’s query vector as a question it is asking (“what context do I need?”), each token’s key vector as an advertisement of its content (“here is what I contain”), and each token’s value vector as the actual information it contributes when attended to (“here is what I give you if you attend to me”). The query-key interaction determines how much each token attends to every other; the values are what actually gets aggregated.
Scaled Dot-Product Attention
Given , , and , the attention output is computed as:Let’s unpack this step by step.
Step 1 — Dot products: is a matrix of raw attention scores. Entry is the dot product between the query vector of token and the key vector of token :A high dot product means token finds token highly relevant. This is the mechanism through which, for example, a pronoun “she” can attend strongly to the noun “Alice” it refers to three sentences earlier.
Step 2 — Scaling: The dot products are divided by . Without this scaling, when is large, the dot products grow large in magnitude, pushing the softmax into regions where gradients become vanishingly small — a variant of the vanishing gradient problem. The factor keeps the variance of the dot products approximately constant regardless of model dimensionality.
Step 3 — Causal masking (decoder-only models): In autoregressive models like GPT, token must not attend to any token meaning that it cannot look into the future. Before applying softmax, a mask is added:The values become zero after softmax, effectively zeroing out future positions.
Step 4 — Softmax: Each row of the masked score matrix is passed through softmax:The resulting matrix is the attention weight matrix. Each row sums to 1 and can be interpreted as a probability distribution over the sequence: the probability that token attends to each position.
Step 5 — Value aggregation: The output for token is a weighted sum of all value vectors:In matrix form: . Each output vector is a contextualised representation of its token, so that the same word “bank” will produce a different output vector in “river bank” versus “central bank” because its attention weights will be distributed differently across the surrounding context.

Multi-Head Attention
A single attention head computes one set of query-key-value interactions. But different aspects of meaning may require different attention patterns simultaneously: a token might need to attend to its syntactic head, its semantic antecedent, and its positional neighbours all at once. Multi-head attention runs attention operations in parallel: where are per-head projection matrices, each head operates in a dimensional subspace, and is a final output projection that mixes the concatenated heads back into the full -dimensional space.
In GPT-3, and , so each head operates in a dimensional subspace. The 96 heads learn to specialize: empirical work in mechanistic interpretability has identified heads that track syntactic subject-verb agreement, heads that copy tokens from earlier in context, heads that attend to the most recent noun phrase, and heads that implement induction — recognizing when a pattern seen earlier in the context is repeating.
The computational cost of full self-attention is , or quadratic in sequence length. For a 128K-token context window, the attention matrix alone has billion entries, making naive computation prohibitively expensive. Efficient attention variants such as Flash Attention, Sparse Attention, Sliding Window Attention address this scaling problem, which we’ll cover in Part 3 alongside the full transformer block.
The KV Cache
During inference, a decoder-only model generates one token at a time. At step , the model processes the full sequence and predicts . Without optimization, this would require recomputing the key and value matrices for all previous tokens at every step so thar cost grows as per generation.
The KV cache eliminates this redundancy. Since the key and value representations of tokens do not change between steps (they depend only on those tokens’ positions and embeddings, which are fixed once generated), they can be cached in memory and reused. At step , only the new token’s , , need to be computed; the cached and matrices from previous steps are concatenated and the attention is computed against the full cached sequence.
This reduces per-step inference cost from to in attention computation, but at the cost of memory. A KV cache for a 128K-token context with 96 heads, 128 layers, and FP16 precision occupies on the order of tens of gigabytes. Managing KV cache memory is one of the primary challenges in deploying frontier models efficiently at scale. It is why inference hardware for long-context models requires far more VRAM than a naive parameter count would suggest.
What Attention Actually Learns
It is tempting to describe attention as a mechanism that “understands” language. It is more precise, and more useful for engineering purposes, to say that attention is a differentiable, content-based memory retrieval system. The model learns, through gradient descent on the next-token prediction objective, to configure its , , matrices such that the right values get retrieved for the right queries.
The mechanism has no built-in notion of syntax, coreference, or meaning. All of that emerges from training dynamics or from the statistical regularities of billions of documents. Understanding this distinction is important for debugging model failures: when an LLM makes a coreference error or loses track of a constraint stated early in a long context, the failure mode is almost always traceable to attention weights that were distributed incorrectly, either because the training distribution underrepresented that pattern, or because the KV cache compression strategy discarded the relevant context.
Conclusion
Self-attention is the architectural innovation that made modern LLMs possible. By allowing every token to attend directly to every other token in a single parallelisable matrix operation, it solves the long-range dependency problem that defeated earlier sequential architectures. Multi-head attention extends this by learning multiple independent attention patterns simultaneously, while the KV cache makes autoregressive inference tractable at scale.
Part 3 will take the attention output and trace it through the rest of the transformer block: the feed-forward network, layer normalisation, residual connections, and the architectural choices (decoder-only versus encoder-decoder) that distinguish GPT-style models from BERT-style ones.


