Skip to content
ImagineWorld

Attention from First Principles

node_idnode-book_building-frontier-llm-from-scratch_chapter-07-attention-from-first-principles
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleAttention from First Principles
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Attention from First Principles

Section titled “Chapter 7 — Attention from First Principles”

Part III — The Transformer

The bigram model of Chapter 4 failed for one reason: a token could see only its immediate predecessor. Real language needs each position to draw on any earlier position — the subject agreeing with a verb ten words later, a pronoun resolving to a name in the previous sentence. Attention is the mechanism that makes this possible, and it is the single idea that defines the transformer. This chapter derives it from scratch, implements it in a few lines, and adds the causal mask that makes it a language model. Everything in Part IV is a refinement of what you build here.

Think of each token as needing to retrieve information from the others. It broadcasts a query describing what it is looking for; every token offers a key advertising what it contains; and wherever a query and a key match, the querying token pulls in that token’s value. Attention is this soft, differentiable dictionary lookup: instead of retrieving one entry, each token retrieves a weighted blend of all values, with weights set by how well its query matches each key. Because the matching is learned and content-dependent, the model decides for itself which positions should talk to which — a routing network with no fixed wiring.

Concretely, we project the input into three matrices — queries Q, keys K, and values V — and compute the attention output with one formula:

Attention(Q,K,V)=softmax ⁣(QK⊤/dk)V.\mathrm{Attention}(Q, K, V) = \mathrm{softmax}\!\left( Q K^\top / \sqrt{d_k} \right) V.

Read it left to right. Q Kᵀ is a matrix of dot products: entry (i, j) measures how much query i matches key j. Dividing by √dₖ keeps those scores from growing with dimension (more on this below). The softmax turns each row into attention weights that sum to one. Multiplying by V replaces each position with the weighted average of all values. The whole thing is two matrix multiplies and a softmax — and it is differentiable, so the projections are learned by gradient descent. In code it is almost a transcription of the formula:

import torch, math
import torch.nn.functional as F
def attention(q, k, v, mask=None):
# q, k, v: (B, T, d_k)
d_k = q.size(-1)
scores = (q @ k.transpose(-2, -1)) / math.sqrt(d_k) # (B, T, T)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = scores.softmax(dim=-1) # (B, T, T): rows sum to 1
return weights @ v # (B, T, d_k)

Python — attention.py: scaled dot-product attention

Why divide by the square root of the head dimension

Section titled “Why divide by the square root of the head dimension”

The scaling is not cosmetic. If query and key components are roughly independent with unit variance, their dot product over dₖ dimensions has variance dₖ and therefore a standard deviation of √dₖ. Without correction, large dimensions produce large scores, the softmax saturates into a near one-hot distribution, and its gradient vanishes — the model cannot learn. Dividing by √dₖ restores unit-scale scores and keeps the softmax in its well-behaved regime. It is a tiny term with outsized importance for trainability.

As written, every position attends to every other — including future ones. For a language model that is cheating: predicting token t must not depend on tokens after t, or the model trivially copies the answer. The fix is a causal mask that forbids attending to the future by setting those scores to -∞ before the softmax, which drives their weights to zero. The mask is a lower-triangular matrix of ones; Figure 7.1 shows the pattern.

[!visual-conversion] Grid figure, PDF 082 (printed 84), titled “Causal attention mask (T = 6)”. The y-axis reads “queries →” and the x-axis “keys (attended-to position) →”. Its legend reads: filled = “attend (key ≤ query)”, empty = “blocked (future): score → −∞”. A note beside it reads: “Each query row attends only to itself and earlier keys, so token t never sees the future it must predict.”

Causal attention mask (T = 6) ■ attend (key ≤ query) □ blocked (future): score → −∞
keys (attended-to position) →
1 2 3 4 5 6
queries → 1 ■ □ □ □ □ □
2 ■ ■ □ □ □ □
3 ■ ■ ■ □ □ □
4 ■ ■ ■ ■ □ □
5 ■ ■ ■ ■ ■ □
6 ■ ■ ■ ■ ■ ■

Figure 7.1. The causal mask. Row i (query) may attend only to columns j ≤ i (itself and earlier keys); the upper triangle is set to -∞ before the softmax so future positions receive zero weight.

Putting the projections, the scaling, and the mask together gives a complete single-head causal self-attention layer — the atom of a GPT:

import torch.nn as nn
class CausalSelfAttention(nn.Module):
def __init__(self, d_model):
super().__init__()
self.q = nn.Linear(d_model, d_model, bias=False)
self.k = nn.Linear(d_model, d_model, bias=False)
self.v = nn.Linear(d_model, d_model, bias=False)
self.proj = nn.Linear(d_model, d_model, bias=False)
def forward(self, x): # x: (B, T, d_model)
B, T, C = x.shape
q, k, v = self.q(x), self.k(x), self.v(x)
scores = (q @ k.transpose(-2, -1)) / math.sqrt(C)
mask = torch.tril(torch.ones(T, T, device=x.device)) # lower-triangular
scores = scores.masked_fill(mask == 0, float("-inf"))
att = scores.softmax(dim=-1)
return self.proj(att @ v) # (B, T, d_model)

Python — attention.py: single-head causal self-attention

This layer already does something the bigram model never could: position t can pull information from any earlier position, weighted by learned relevance. Train a stack of these and the model can track agreement, resolve references, and copy from far back in the context.

In practice: use the fused kernel Real code rarely materializes the full (T, T) score matrix as above, because it costs memory quadratic in sequence length. PyTorch’s F.scaled_dot_product_attention(q, k, v, is_causal=True) computes the identical result with a fused, memory-efficient kernel (FlashAttention), and is what we use from the next chapter onward. The explicit version above is for understanding; the fused version is for running. We dissect FlashAttention itself in Chapter 14.

The single-head version above is for understanding; the version real GPTs run is multi-head and batched, and it is worth seeing in full. Here is nanoGPT’s actual CausalSelfAttention, reproduced. It packs the query, key, and value projections of all heads into one matrix multiply, reshapes the result into separate heads, runs the fused causal kernel, and re-assembles — the production shape of everything this chapter derived:

class CausalSelfAttention(nn.Module):
def __init__(self, config):
super().__init__()
assert config.n_embd % config.n_head == 0
# q, k, v projections for all heads, batched into one matrix
self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd,
bias=config.bias)
self.c_proj = nn.Linear(config.n_embd, config.n_embd,
bias=config.bias)
self.n_head = config.n_head
self.n_embd = config.n_embd
def forward(self, x):
B, T, C = x.size() # batch, sequence, embedding dim
# one matmul yields q, k, v for every head, then split
q, k, v = self.c_attn(x).split(self.n_embd, dim=2)
k = k.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
q = q.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
v = v.view(B, T, self.n_head, C // self.n_head).transpose(1, 2)
# fused flash-attention kernel, causal mask applied internally
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
y = y.transpose(1, 2).contiguous().view(B, T, C) # merge heads
return self.c_proj(y)

Python — karpathy/nanoGPT · model.py: CausalSelfAttention (reproduced, MIT licence)

Two things distinguish this from the teaching version, and both are pure engineering. First, the single c_attn projection of width 3 · n_embd computes the queries, keys, and values for every head in one matrix multiply, which is far more efficient on a GPU than three separate projections; the .split then carves them apart. Second, the view/transpose dance reshapes the flat (B, T, C) tensor into (B,

n_head, T, head_dim) so that scaled_dot_product_attention processes all heads at once, applying the causal mask internally through its is_causal=True flag rather than building an explicit triangular matrix. (We have omitted only nanoGPT’s dropout plumbing for brevity; the structure is otherwise exact.) The original transformer paper introduced the scaled dot-product attention and the √dₖ scaling this code rests on; nanoGPT is where that mathematics becomes forty lines you can run.

One head can attend in only one way at a time. Language needs several relationships tracked at once — syntax here, coreference there — which is why real models run many attention heads in parallel. That, the feed-forward network, and the normalization that holds a deep stack together are the subject of the next chapter, where the single layer becomes a complete transformer block.

7.4 Worked Example: Attention on a Toy Sequence

Section titled “7.4 Worked Example: Attention on a Toy Sequence”

The mechanics of attention are easiest to trust when you watch them run on numbers small enough to follow. Take three tokens, each already projected to query, key, and value vectors. Attention asks, for each query, how much it should listen to every key, and then mixes the values accordingly:

import math
def attention(Q, K, V, mask=None):
scores = Q @ K.transpose(-2, -1) / math.sqrt(Q.size(-1))
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = F.softmax(scores, dim=-1)
return weights @ V # [T, d_v] mixed by attention

Python — attn/sdpa.py: scaled dot-product attention

Trace one query. Its dot product with each key produces a raw score; dividing by the square root of the head dimension keeps those scores from growing with dimension and saturating the softmax. The softmax turns the three scores into weights that sum to one — say 0.7, 0.2, 0.1 — and the output is that weighted blend of the three value vectors, 70% the first, 20% the second, 10% the third. Every position computes its own blend in parallel. This is the entire operation; everything else in the chapter — multiple heads, causal masking, the projections — is scaffolding around these five lines.

The same operation that makes attention powerful makes it expensive. Forming the score matrix compares every query against every key, which for a sequence of length T is T² dot products; the memory to hold that matrix is likewise quadratic. At 1,000 tokens this is a million entries per head, an afterthought; at 100,000 tokens it is ten billion, and it dominates both compute and memory.

This single quadratic is the gravitational center of an enormous amount of later engineering. It is why the KV cache (Section 27.2) exists, why FlashAttention reorganizes the computation to avoid materializing the full matrix, why Multi-Head Latent Attention (Chapter 12) compresses what is stored, and why the entire linear-attention and state-space frontier of Chapter 37 seeks to escape the T² term altogether. Understanding attention’s cost is therefore not a footnote but a prerequisite for understanding half the architectural decisions in the rest of the book.

Attention is a weighted average, computed pairwise Each token’s output is a softmax-weighted blend of all tokens’ values. That pairwise weighting is the source of both its modeling power and its quadratic cost — the trade-off that drives most of modern architecture research.

7.6 Grouped-Query and Multi-Query Attention

Section titled “7.6 Grouped-Query and Multi-Query Attention”

The KV-cache cost of Section 7.5 prompted the first wave of attention variants, all aimed at storing fewer keys and values. Standard multi-head attention gives every query head its own key and value head, so the cache scales with the head count. Multi-query attention takes the extreme opposite: all query heads share a single key and value head, shrinking the cache by the full head-count factor at a small cost in quality. Grouped-query attention is the pragmatic middle — query heads are divided into groups, and each group shares one key/value head:

# n_heads query heads, n_kv_heads < n_heads key/value heads
k = k.repeat_interleave(n_heads // n_kv_heads, dim=1)
v = v.repeat_interleave(n_heads // n_kv_heads, dim=1)
# now attention runs with n_heads queries over shared K/V

Python — attn/gqa.py: query heads share K/V within groups

The trade is straightforward: fewer key/value heads means a smaller cache and faster decoding, at a quality cost that grows as the sharing becomes more aggressive. Grouped-query attention, with a handful of key/value heads serving many query heads, captures most of the cache savings while preserving most of the quality, which is why it became the standard in the Llama family and many others. It is worth seeing as the conceptual predecessor to Multi-Head Latent Attention (Chapter 12): both attack the KV cache, but where GQA reduces the number of stored key/value heads, MLA instead compresses what is stored into a shared latent — a different and, at long context, more aggressive answer to the same problem Section 7.5 posed.

Fewer KV heads, smaller cache Multi-query and grouped-query attention let many query heads share a few key/value heads, shrinking the KV cache at a modest quality cost. GQA is the common default; MLA (Chapter 12) is the alternative that compresses rather than shares.

When researchers inspect a trained model’s attention heads — visualizing which tokens each head attends to — a striking thing emerges: many heads have specialized into interpretable, nameable roles. Attention is not an inscrutable blur but, in part, a collection of recognizable functions the model discovered on its own.

Several recurring types appear. Some heads are positional, reliably attending to the previous token or a fixed offset. Some are syntactic, linking grammatically related words — a verb to its subject, a pronoun to its antecedent. Most consequentially, some are induction heads: they find an earlier occurrence of the current token and attend to whatever followed it, implementing a copy-and-continue pattern that turns out to be a central mechanism behind in-context learning (Section 4.4) — the model’s ability to pick up a pattern from the prompt and extend it. Not every head is so legible; many are redundant or resist interpretation, which is part of why grouped-query attention and pruning (Sections 7.6 and 26.9) can remove capacity without much loss. Still, the fact that attention heads specialize into discoverable roles is both a window into how the model actually computes and the empirical foundation of the mechanistic interpretability program (Section 43.8). Reading a model’s attention patterns is, quite literally, watching some of its reasoning happen.

Heads specialize into legible roles Inspecting attention reveals positional heads, syntactic heads, and induction heads that copy-and-continue — the latter a key mechanism of in-context learning. Not all heads are interpretable, but enough are that attention patterns offer a real window into the model’s computation.