Attention, Scaled: How Tokens Resolve Each Other
Attention is a database lookup with no index: every token asks a question, every other token offers a key, and the answers are blended values weighted by similarity. Once you see it that way, the formula stops looking like notation and starts looking like a design you could have written yourself. This lesson derives the mechanism from the lookup, explains the two easy-to-skip scaling choices, and shows what changes when attention becomes causal, cross-attention, or windowed.
The Lookup, Made Formal
Each hidden state is projected three times. The query vector says what this position is looking for, the key vector says what this position can answer, and the value vector is the payload that gets returned. A dot product between one query and every key scores compatibility; a softmax turns those scores into a distribution that sums to one; a weighted sum of values produces the output. Nothing in the definition cares about distance, so a pronoun can attach to a noun hundreds of tokens earlier at no extra cost.
Two properties follow directly. The operation is permutation-equivariant â shuffle the input and the outputs shuffle the same way â so order must come from somewhere else. And because the weights sum to one, the output is a convex combination of value vectors, which bounds its magnitude and keeps deep stacks numerically stable.
Why Divide by the Square Root of d
Raw dot products grow with dimension. If query and key entries are independent with unit variance, their product has variance equal to the key dimension, so for a width of 4,096 the typical score is around 64 â large enough that softmax saturates and gradients vanish. Dividing by the square root of the key dimension rescales the variance back to one, keeping logits in the range where softmax still differentiates. Skip the scaling in a small model and training often appears to work; skip it in a wide one and the run dies in the first thousand steps.
The second, quieter choice is masking. Softmax must ignore certain positions entirely â padding on the right, future tokens during training â and the standard trick is to add a large negative constant to the forbidden logits before normalization, which drives their probability to effectively zero while keeping the computation differentiable.
import math
import torch
import torch.nn.functional as F
def scaled_dot_product(q, k, v, mask=None, dropout=0.0):
d_k = q.size(-1)
scores = q @ k.transpose(-2, -1) / math.sqrt(d_k)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
weights = F.softmax(scores, dim=-1)
if dropout:
weights = F.dropout(weights, p=dropout)
return weights @ v, weights
batch, seq, width, heads = 2, 12, 64, 8
q = torch.randn(batch, heads, seq, width // heads)
k = torch.randn(batch, heads, seq, width // heads)
v = torch.randn(batch, heads, seq, width // heads)
out, w = scaled_dot_product(q, k, v)
print(out.shape, w.shape) # torch.Size([2, 8, 12, 8]) torch.Size([2, 8, 12, 12])
print(w.sum(-1)[0, 0, :3]) # rows of ones
Print the weight matrix once and the mechanism becomes concrete: each row is a distribution over positions, and each column shows how often a position is consulted.
What Multiple Heads Are For
A single attention pattern per layer is a bottleneck, so the model projects the width into several subspaces and runs one lookup in each. Because each head has its own query, key, and value projections, heads can specialize without competing â empirically, some heads track the previous token, some resolve coreference, some attend to syntactic heads, and a few appear to suppress irrelevant positions entirely. Concatenating the heads and applying an output projection merges their reports back into the residual stream.
Specialization is learned, not assigned, and it is fragile: ablate one attention head and a specific behavior degrades while others barely notice. That observation is the foundation of mechanistic interpretability work, and it also explains why pruning heads from a trained model hurts more than training a narrower model from scratch.
import torch.nn as nn
class MultiHeadAttention(nn.Module):
def __init__(self, width, heads, dropout=0.0):
super().__init__()
assert width % heads == 0
self.heads = heads
self.d = width // heads
self.qkv = nn.Linear(width, 3 * width)
self.out = nn.Linear(width, width)
self.drop = nn.Dropout(dropout)
def forward(self, x, mask=None):
b, t, w = x.shape
q, k, v = self.qkv(x).chunk(3, dim=-1)
def split(tns):
return tns.view(b, t, self.heads, self.d).transpose(1, 2)
q, k, v = split(q), split(k), split(v)
scores = (q @ k.transpose(-2, -1)) / (self.d ** 0.5)
if mask is not None:
scores = scores.masked_fill(mask == 0, float("-inf"))
y = self.drop(scores.softmax(-1)) @ v
y = y.transpose(1, 2).reshape(b, t, w)
return self.out(y)
mha = MultiHeadAttention(width=512, heads=16)
print(mha(torch.randn(4, 32, 512)).shape) # torch.Size([4, 32, 512])
Four Variants You Will Meet
The same core appears with different visibility rules, and each rule encodes a task assumption. Self-attention lets every position see every position in the same sequence, which suits classification. Causal self-attention restricts each position to itself and everything earlier, which is required for autoregressive generation and also makes training cheap because future tokens are never leaked. Cross-attention draws queries from one sequence and keys and values from another, which is how a decoder reads a source sentence or how a text model conditions on an image. Local or sliding-window attention limits each token to a neighborhood, trading recall for linear cost.
| Variant | Who sees whom | Cost per layer | Typical use |
|---|---|---|---|
| Self (bidirectional) | All positions in the sequence | Quadratic in length | Encoders, classifiers, retrieval |
| Causal (masked) | Self and earlier positions | Quadratic, incremental decode | Autoregressive LLMs |
| Cross | Queries from target, keys from source | Linear in source length | Translation, image conditioning |
| Sliding window | Fixed neighborhood around each token | Linear in length | Long documents, on-device models |
| Grouped or multi-query | Shared keys and values across heads | Lower memory bandwidth at decode | Fast inference stacks |
The Quadratic Wall and How People Climb It
Full attention reads a length-by-length matrix for every head in every layer, so doubling context quadruples that work. Prompt prefill tolerates it; a 200,000-token document does not. The industry response has been layered. FlashAttention avoids materializing the matrix by tiling the computation in fast on-chip memory, cutting both time and peak memory without changing results. Sparse and windowed patterns reduce the number of pairs outright. Linear and kernel-approximation methods replace softmax similarity with a cheaper surrogate, usually at some accuracy cost. Finally, some architectures sidestep attention for most layers and reserve it for a few mixing points.
For engineering purposes, measure before you restructure: most production latency problems come from decode bandwidth and batching, not from prefill arithmetic, and prompt caching removes repeated attention over a shared prefix entirely.
Inspecting Attention Before You Guess
When a model misuses a fact, look rather than speculate. Extracting the weights for one head on one sentence tells you whether the model linked the right tokens, whether the link is spread across many positions, or whether the head is doing something unrelated to your hypothesis. The script below prints the strongest attended pair per head for a short prompt.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
name = "gpt2"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name, output_attentions=True)
model.eval()
text = "The trophy did not fit in the suitcase because it was too big."
ids = tok(text, return_tensors="pt")
with torch.no_grad():
result = model(**ids)
tokens = tok.convert_ids_to_tokens(ids["input_ids"][0])
att = result.attentions[-1][0] # last layer, batch 0
heads, seq, _ = att.shape
for h in range(min(heads, 4)):
row = att[h, 6] # the word "it"
top = torch.topk(row, 3)
print(h, [(tokens[i], round(float(s), 3)) for s, i in zip(top.values, top.indices)])
Read the output as evidence: if the head consistently points at the antecedent rather than the suitcase, the model has resolved the reference; if it points everywhere equally, the head is not the one carrying that decision.
đĄRule of thumb for masking
Best Practices
- Divide logits by the square root of the key dimension before softmax in any hand-written attention
- Keep a causal mask whenever training a decoder, otherwise validation loss will look impossibly good
- Inspect per-head weights on a concrete sentence before concluding that a model lacks a capability
- Prefer fused kernels such as scaled dot-product attention and FlashAttention over naive matmul loops
- When context grows, check prompt caching and prefill strategy before changing the architecture
Key Takeaways
- Attention is an unindexed lookup: queries meet keys, softmax weights values
- Scaling by the square root of key width keeps logits in softmax's useful range
- Multi-head projections let one layer run several independent routing patterns
- Causal, cross, and windowed variants differ only in which pairs are allowed to interact
- Cost grows quadratically with length, which fused kernels and sparse patterns exist to fix