Transformers and Attention Questions
The transformer architecture behind modern language models. Covers queries, keys and values, scaled dot-product and multi-head attention (including why scores are scaled and worked numeric examples), masking, positional encoding (sinusoidal, learned, relative with bucketed biases, rotary, and 2D schemes for image patches), encoder-only, decoder-only and encoder-decoder variants, residual connections, layer normalization placement and the feed-forward block, parameter, memory and compute accounting, why transformers scale better than recurrent models, efficient and long-context attention variants (sparse, local window with global tokens, hashing-based, linear, low-rank, FlashAttention, multi-query), and what attention heads learn and what raw attention weights do and do not explain. Includes implementing attention and its components from scratch. Distributed training, serving and quantization, fine-tuning, pretraining objectives, and general optimizer practice are covered elsewhere.
What is the position-wise feed-forward network in a Transformer block for? Describe its dimensions and activations, and how it contributes to capacity and non-linearity compared with attention.
Sample Answer
The idea
Attention decides which tokens to read from and mixes their information into each position. The position-wise feed-forward network (FFN) then takes each position's mixed vector and processes it on its own, with the same small two-layer neural network applied to every position and no information passing between positions. "Position-wise" means exactly that: one shared set of weights, applied to each token vector independently. The FFN is where the block gets most of its non-linearity and a large share of its parameters. Its input and output are the token's slot in the residual stream, the running vector each token carries from layer to layer, to which every sub-layer adds its output.
Dimensions and activation
For a token vector x of length d_model:
FFN(x)=W2ϕ(W1x+b1)+b2- W_1 has shape d_ff by d_model: it expands the vector from d_model to d_ff numbers. The original Transformer used d_model = 512 and d_ff = 2048, a 4x expansion, and 4x is still a common convention.
- phi is the activation, a non-linear function applied to each of the d_ff numbers separately. The original used ReLU (zero out negatives); GELU (a smooth version) is common now.
- W_2 has shape d_model by d_ff: it projects back down, so the output can be added to the residual stream.
Applied to a whole sequence, the input has shape (batch, N, d_model), each of the N positions is multiplied by the same matrices, and the output has the same shape. A gated variant (for example SwiGLU: one projection of x goes through a smooth activation and is multiplied element by element by a second projection of x, the gate, before the final projection down) uses three matrices instead of two. To keep the parameter count about equal, the hidden width h must satisfy 3 x d_model x h = 2 x d_model x 4 d_model, so h = 8 d_model / 3, which is 2730.67 for d_model = 1024 and is rounded to 2731 (shown in the last checks below).
Why it is there: what attention cannot do
Attention, for a fixed set of attention weights, is just a weighted average of value vectors, which is linear in the values. The only non-linearity inside it is the softmax that picks those weights. Stack attention layers with nothing else and the model can route and average information but has little ability to compute new features from a token's mixed vector. Concretely, every output of an attention layer is a weighted sum of value vectors, and each value vector is a fixed linear function of a token's input, so apart from the choice of weights the layer can only take weighted combinations of linear functions of the inputs. A feature such as "how different are these two numbers" (|a - b|) is not a linear function of a and b: a linear map with f(1,0) = 1 and f(0,1) = 1 must give f(1,1) = 2, but |1 - 1| = 0. The last check below builds that feature with two ReLU units, which a hidden layer with a non-linearity can do. The FFN supplies that: a wide hidden layer with a non-linearity between two matrices can represent much richer functions of each token than any single matrix.
The non-linearity is the essential part. Without phi, the two matrices collapse into one, so the width d_ff adds nothing. Two terms the checks use: the rank of a matrix is the number of independent directions its outputs can span, so a map from d numbers to d numbers has rank at most d however wide the middle is; a function f is affine if f(a + b) + f(0) = f(a) + f(b) for all a and b, which every linear map satisfies and so does a linear map plus a fixed bias vector, so a function that fails the test is genuinely non-linear; and permutation-equivariant means reordering the input tokens reorders the outputs in the same way, which holds when every token is processed by the same function independently. The program below checks these on small tensors (it also confirms a token is processed alone, and builds |a - b| from two ReLU units): the FFN is position-wise (permuting tokens permutes the outputs), two linear layers without an activation equal a single d_model by d_model layer, attention-style averaging is linear in the values while the FFN with its activation is not affine (and the same two layers without the activation are), and the parameter counts of the standard and gated forms at d_model = 1024.
import torch, torch.nn as nn
torch.set_num_threads(1)
torch.manual_seed(0)
d, ff, T = 8, 32, 5
ffn = nn.Sequential(nn.Linear(d, ff), nn.GELU(), nn.Linear(ff, d))
x = torch.randn(1, T, d)
# 1) position-wise: permuting the tokens permutes the outputs the same way
perm = torch.tensor([3, 0, 4, 1, 2])
print("same weights applied to every token (permutation-equivariant):",
torch.allclose(ffn(x)[:, perm], ffn(x[:, perm]), atol=1e-6))
print("token 0 alone equals token 0 inside the sequence:", torch.allclose(ffn(x[:, :1]), ffn(x)[:, :1], atol=1e-6))
# 2) without the activation, two linear layers collapse into one matrix
l1, l2 = nn.Linear(d, ff), nn.Linear(ff, d)
W = l2.weight @ l1.weight # (d, d)
b = l2.weight @ l1.bias + l2.bias # (d,)
print("linear-linear equals one (d x d) layer:", torch.allclose(l2(l1(x)), x @ W.T + b, atol=1e-5))
print("rank of the collapsed matrix:", torch.linalg.matrix_rank(W).item(), "; at most d =", d, "even though the hidden width is", ff)
# 3) attention with fixed weights is linear in the values; the FFN is not
A = torch.softmax(torch.randn(T, T), dim=-1) # fixed mixing weights
v1, v2 = torch.randn(T, d), torch.randn(T, d)
print("attention mix linear in V:", torch.allclose(A @ (v1 + v2), A @ v1 + A @ v2, atol=1e-5))
def gap(f):
# zero for any linear or affine map; nonzero when f has a non-linearity
return (f(v1 + v2) + f(torch.zeros(T, d)) - f(v1) - f(v2)).abs().max().item()
print("FFN with GELU, f(a+b)+f(0) - f(a) - f(b) is zero:", gap(ffn) < 1e-5)
print("same two layers without the activation, same test:", gap(lambda t: l2(l1(t))) < 1e-5)
# 4) parameter counts: standard vs gated (three matrices) FFN at d=1024
D = 1024
std = 2 * D * 4 * D
hid = round(2 * 4 * D / 3)
print("standard FFN weights (4d hidden):", std)
print("gated FFN weights with hidden", hid, ":", 3 * D * hid)
# 5) a feature no single matrix computes: |a - b| from two numbers using two ReLU units
W1 = torch.tensor([[1.0, -1.0], [-1.0, 1.0]])
W2 = torch.tensor([[1.0, 1.0]])
pts = torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
print("two ReLU units give |a - b| at (1,0), (0,1), (1,1):", (torch.relu(pts @ W1.T) @ W2.T).squeeze(-1).tolist())
print("a linear map would give f(1,1) = f(1,0) + f(0,1) =", 1.0 + 1.0)
Output:
same weights applied to every token (permutation-equivariant): True
token 0 alone equals token 0 inside the sequence: True
linear-linear equals one (d x d) layer: True
rank of the collapsed matrix: 8 ; at most d = 8 even though the hidden width is 32
attention mix linear in V: True
FFN with GELU, f(a+b)+f(0) - f(a) - f(b) is zero: False
same two layers without the activation, same test: True
standard FFN weights (4d hidden): 8388608
gated FFN weights with hidden 2731 : 8389632
two ReLU units give |a - b| at (1,0), (0,1), (1,1): [1.0, 1.0, 0.0]
a linear map would give f(1,1) = f(1,0) + f(0,1) = 2.0
The first two lines show that the FFN treats every position alike and in isolation: a token gets the same output whether or not the other tokens are present, so nothing passes between positions. The next two lines show the collapse without an activation: the hidden width of 32 cannot raise the rank above 8. The following three lines show that the fixed-weight attention mix is linear in the values (True), that the FFN with GELU fails the affine test (False), and that the same two matrices without the activation pass it (True), so the failure comes from the activation and not from the bias terms. The next two lines show the standard FFN with 8,388,608 weights per layer and the gated form with 8,389,632, about the same. The final two lines show |a - b| computed by two ReLU units: 1, 1 and 0 at the three points, where any linear map would have to give 2 at (1, 1).
Capacity, and what it does not do
- The FFN holds the larger share of a block's parameters (with a 4x expansion, twice as many weights as the four attention matrices), so it is where most of the per-layer capacity sits.
- It does no mixing across positions. Anything that needs information from another token must have arrived through attention first. That division of labour (attention moves information, FFN transforms it) is why the two alternate.
- Its cost per token is fixed and does not depend on sequence length, unlike attention's N by N score matrix.
Common mistakes
- Calling the FFN "another attention layer" or saying it mixes positions.
- Forgetting that the width expansion only helps because of the activation between the matrices.
- Saying the FFN is the only non-linearity: the softmax, layer norm and (in gated forms) the multiplicative gate are also non-linear.
Running the code
Install: pip install torch. Save the program to a file and run it with python. It uses a fixed seed.
Self-attention costs O(n^2) in time and memory. Explain why, then lay out the main ways to reduce that cost for long sequences and the accuracy trade-off of each.
Sample Answer
Why attention is O(n^2)
For a sequence of n tokens, each head has queries Q and keys K, each n by d_k (d_k is the size of one head). The score matrix is Q times K transposed, shape n by n: every query is compared with every key, and each comparison is a dot product costing d_k multiply-adds. So the time is n times n times d_k, i.e. O(n^2 d). The softmax normalizes each row over all n keys, so a row cannot be finished until all n scores exist, and the weighted sum with V (n by d_k) costs another n^2 d_k. If the n by n matrix is stored, memory is O(n^2) per head, and backpropagation needs it again. Doubling the length quadruples both.
The main ways to cut the cost, with their trade-offs
| Method | Idea | Cost | Exact? | What you give up |
|---|---|---|---|---|
| Tiled exact kernel (FlashAttention idea) | compute attention block by block with a running ("online") softmax, never storing n by n | time still O(n^2 d), memory O(n) | yes | nothing in accuracy; does not reduce FLOPs (floating-point operations, the count of arithmetic steps) |
| Local / sliding window | each token attends only to the w tokens on each side | O(n w d) | no | direct access to far tokens; information must hop across layers |
| Sparse patterns (strided, global tokens, block) | window plus a few designated global tokens (positions every token can read and that can read every token) or strided positions (every s-th token, to reach far) | about O(n w d) | no | whatever the pattern misses; global tokens are a hand-chosen bottleneck |
| Low-rank projection | project keys and values from length n down to a fixed length k (so the n by n table is replaced by an n by k one) | O(n k d) | no | the rank of the attention map (roughly, how many independent patterns it can express) is capped by k; awkward for causal generation |
| Linear (kernel) attention | replace softmax(QK^T) with a feature-map product (a feature map is a function applied to each query and key so that their similarity becomes a plain dot product) so the product can be reordered: first K^T V (d by d), then Q times that | O(n d^2) | no | the sharp, peaky behaviour of softmax; quality drops on tasks needing precise lookup |
| Retrieval or chunk-and-summarize | split into chunks, attend to retrieved or summarized parts | depends | no | recall depends on the retriever or summarizer |
The rows run from exact to increasingly approximate; the order to try them in is under "How to choose". Orthogonal but often confused: multi-query attention (all heads share one set of keys and values) and grouped-query attention (groups of heads share one) shrink the key-value cache that decoding reads, not the n^2 score computation.
The online softmax on four numbers
Softmax needs the sum over all keys, which seems to force all scores to exist at once. The trick is to keep a running maximum m, a running denominator l and a running numerator, and to rescale the old totals by exp(old m - new m) whenever a later tile raises the maximum; subtracting the maximum is the usual guard against overflow, and the rescaling keeps every earlier tile consistent with it, which is why the result is exact. Here is one query with four given scores and values, processed two keys at a time.
import numpy as np
# One query, four keys, one number per value. Scores are given directly.
scores = np.array([1.0, 3.0, 2.0, 5.0])
values = np.array([10.0, 20.0, 30.0, 40.0])
p = np.exp(scores - scores.max())
print("full softmax-weighted value:", round(float((p / p.sum()) @ values), 4))
# Online version: two tiles of two keys; keep a running max m, denominator l and numerator acc.
m, l, acc = -np.inf, 0.0, 0.0
for tile in (slice(0, 2), slice(2, 4)):
s, v = scores[tile], values[tile]
m_new = max(m, s.max())
scale = np.exp(m - m_new) # shrinks what was accumulated under the old max
e = np.exp(s - m_new)
l = l * scale + e.sum()
acc = acc * scale + e @ v
m = m_new
print(f"after keys {tile.start}-{tile.stop - 1}: max m = {m:.1f}, scale = {scale:.4f}, denominator l = {l:.4f}, numerator = {acc:.4f}")
print("tiled result acc / l:", round(float(acc / l), 4))
Output:
full softmax-weighted value: 36.8806
after keys 0-1: max m = 3.0, scale = 0.0000, denominator l = 1.1353, numerator = 21.3534
after keys 2-3: max m = 5.0, scale = 0.1353, denominator l = 1.2034, numerator = 44.3835
tiled result acc / l: 36.8806
Reading it: after the first tile the maximum is 3 and there was nothing to rescale (the scale printed for it is exp(-inf) = 0, which just wipes the empty start). The second tile contains a score of 5, which raises the maximum from 3 to 5, so the old denominator and numerator are multiplied by exp(3 - 5) = 0.1353 before the new terms are added; every term is again measured against the new maximum. That rescaling is why the final acc / l is exactly the full softmax-weighted value, while only two scores were held at a time.
Code: one exact and two approximate methods
On a synthetic 64-token input with d_k = 16, the program (1) implements tiled attention with an online softmax and checks it equals full attention, (2) implements a window mask, and (3) implements linear attention with the feature map elu(x) + 1, checking that the reordered computation equals the quadratic-order one. It reports relative error (the length of the difference between an approximation's output and full attention's output, divided by the length of full attention's output: 0 means identical, 1 means the error is as large as the output itself, and above 1 means the approximation is further from the right answer than an all-zero output would be) on two inputs: a random one with no locality, and one built as a random walk, so neighbouring tokens are similar and nearby keys get large scores. "Attention mass inside window" is the average share of each row's softmax weight that falls inside the window. A last block repeats the comparison on 20 other seeds and prints the median error, so no conclusion rests on one draw.
import torch
import torch.nn.functional as F
torch.set_num_threads(1)
torch.manual_seed(0)
n, d, blk = 64, 16, 16
q, k, v = (torch.randn(n, d) for _ in range(3))
full = F.softmax(q @ k.T / d ** 0.5, dim=-1) @ v
# 1. Exact: tiled attention with an online softmax (the FlashAttention idea), never builds n x n.
def tiled(q, k, v, blk):
out = torch.zeros_like(q)
m = torch.full((n, 1), float("-inf")) # running max of scores
l = torch.zeros(n, 1) # running softmax denominator
for s in range(0, n, blk):
sc = q @ k[s:s + blk].T / d ** 0.5 # only an n x blk tile at a time
m_new = torch.maximum(m, sc.amax(dim=-1, keepdim=True))
p = torch.exp(sc - m_new)
scale = torch.exp(m - m_new)
l = l * scale + p.sum(dim=-1, keepdim=True)
out = out * scale + p @ v[s:s + blk]
m = m_new
return out / l
print("tiled == full (exact):", torch.allclose(tiled(q, k, v, blk), full, atol=1e-5))
# 2. Approximate: sliding window of w keys on each side.
def window(q, k, v, w):
idx = torch.arange(n)
allowed = (idx[:, None] - idx[None, :]).abs() <= w
sc = (q @ k.T / d ** 0.5).masked_fill(~allowed, float("-inf"))
return F.softmax(sc, dim=-1) @ v, int(allowed.sum())
# 3. Approximate: kernelized linear attention with feature map phi(x) = elu(x) + 1.
def linear(q, k, v):
pq, pk = F.elu(q) + 1, F.elu(k) + 1
kv = pk.T @ v # (d, d), cost O(n d^2)
z = pq @ pk.sum(dim=0, keepdim=True).T
return (pq @ kv) / z
pq, pk = F.elu(q) + 1, F.elu(k) + 1
quad = ((pq @ pk.T) @ v) / (pq @ pk.T).sum(dim=-1, keepdim=True)
print("linear (reordered) == linear (quadratic order):", torch.allclose(linear(q, k, v), quad, atol=1e-5))
def rel_err(a, ref):
return ((a - ref).norm() / ref.norm()).item()
def report(name, q, k, v):
ref = F.softmax(q @ k.T / d ** 0.5, dim=-1) @ v
print(f"--- {name} input (full attention scores computed: {n * n})")
print(f"tiled : scores per tile {n * blk}, relative error {rel_err(tiled(q, k, v, blk), ref):.4f}")
idx = torch.arange(n)
p = F.softmax(q @ k.T / d ** 0.5, dim=-1)
for w in (4, 16):
out, cnt = window(q, k, v, w)
mass = (p * ((idx[:, None] - idx[None, :]).abs() <= w)).sum(-1).mean().item()
print(f"window w={w:<2}: scores computed {cnt}, attention mass inside window {mass:.2f}, relative error {rel_err(out, ref):.4f}")
print(f"linear : state size {d * d} numbers, relative error {rel_err(linear(q, k, v), ref):.4f}")
report("random", q, k, v)
x = torch.randn(n, d).cumsum(0) # a random walk: neighbouring tokens are similar
x = x / x.norm(dim=-1, keepdim=True) * 6.0
report("local", x, x, v)
# Same comparison over 20 seeds (median relative error), so no conclusion rests on one draw.
def trial(seed):
g = torch.Generator().manual_seed(seed)
qq, kk, vv = (torch.randn(n, d, generator=g) for _ in range(3))
xx = torch.randn(n, d, generator=g).cumsum(0)
xx = xx / xx.norm(dim=-1, keepdim=True) * 6.0
row = []
for a, b in ((qq, kk), (xx, xx)):
ref = F.softmax(a @ b.T / d ** 0.5, dim=-1) @ vv
row += [rel_err(window(a, b, vv, w)[0], ref) for w in (4, 16)] + [rel_err(linear(a, b, vv), ref)]
return row
rows = torch.tensor([trial(s) for s in range(20)])
med = rows.median(dim=0).values
print("--- median relative error over 20 seeds")
print(f"random: window w=4 {med[0]:.2f}, window w=16 {med[1]:.2f}, linear {med[2]:.2f}")
print(f"local : window w=4 {med[3]:.2f}, window w=16 {med[4]:.2f}, linear {med[5]:.2f}")
print(f"local window w=16 beats random window w=16 in {(rows[:, 4] < rows[:, 1]).sum().item()} of 20 seeds")
Output:
tiled == full (exact): True
linear (reordered) == linear (quadratic order): True
--- random input (full attention scores computed: 4096)
tiled : scores per tile 1024, relative error 0.0000
window w=4 : scores computed 556, attention mass inside window 0.14, relative error 1.8768
window w=16: scores computed 1840, attention mass inside window 0.45, relative error 1.0044
linear : state size 256 numbers, relative error 0.6690
--- local input (full attention scores computed: 4096)
tiled : scores per tile 1024, relative error 0.0000
window w=4 : scores computed 556, attention mass inside window 0.54, relative error 0.7136
window w=16: scores computed 1840, attention mass inside window 0.93, relative error 0.1056
linear : state size 256 numbers, relative error 0.7717
--- median relative error over 20 seeds
random: window w=4 2.18, window w=16 1.11, linear 0.74
local : window w=4 0.84, window w=16 0.21, linear 0.82
local window w=16 beats random window w=16 in 20 of 20 seeds
Reading it:
- The tiled method matches full attention (error 0.0000) while holding only n by 16 scores at a time (1,024 instead of 4,096).
- A window helps when the attention is local. On the random input a window is a poor stand-in: with w = 4 it captures only 0.14 of the weight and the error is 1.8768 on this draw; the median over 20 seeds is 2.18 for w = 4 and 1.11 for w = 16. On the local input w = 16 captures 0.93 of the weight and the error falls to 0.1056 on this draw (median 0.21 over 20 seeds, and lower than the random-input w = 16 error in all 20), while computing 1,840 of the 4,096 scores.
- Errors above 1 on the random input come from a simple effect: full attention averages many unrelated random value vectors, which shrinks its output, while a narrow window averages only a few, which gives a longer vector that points elsewhere. Real text is usually far more local than random numbers, so the local input is the nearer picture, and only your own data can say how local your task is.
- Linear attention here has error 0.6690 on the random input and 0.7717 on the local one (medians over 20 seeds: 0.74 and 0.82): softmax and the feature map produce different weight shapes. These are untrained random projections on synthetic inputs, so the numbers measure how far a cheaper layer's output is from softmax attention's, not task quality. In practice a model with linear attention is trained as it is, and the fair comparison is its accuracy on your task against the full-attention model. What the numbers do show is that each approximation has an assumption about the attention pattern, not a ranking of methods. Measure on your task.
How to choose
Commit to this order: first use the exact tiled kernel and fix the memory problem without any accuracy loss. If FLOPs or length still do not fit, use a window plus global tokens when the task is mostly local (documents, code), and retrieval when relevant information is sparse. Consider linear or low-rank layers only if you can validate the quality loss on your own evaluation. What flips it: tasks that need exact copy or lookup from far away push you back toward full attention with more hardware, or retrieval.
Common mistakes
- Calling FlashAttention an approximation; it is exact and removes memory, not FLOPs.
- Expecting a window of w to give a receptive field (how far back a token's output can depend on, directly or through layers) of w; stacking L layers lets information travel about L times w.
- Ignoring that generation uses a growing cache: sparse patterns must also bound the cache.
Running the code
Save the program as demo.py and run python demo.py. The output above was produced with Python 3.12, numpy 2.1.3 and torch 2.5.1 (CPU). The seed is fixed in the program.
Explain relative positional encodings as used in T5 and Transformer-XL. What are the memory and compute costs, how do bucketed and exact relative distances differ, and how do they affect generalization to longer sequences?
Sample Answer
Direct answer
Absolute positional encodings tell each token "you are at index 17". Relative encodings instead let the attention score between a query at position i and a key at position j depend on the offset between them ("the key is 3 tokens behind me"). Sign convention for the whole answer: the T5 formula and the code write the offset as j - i (key minus query), so a key 3 tokens behind is -3, while the Transformer-XL paper writes the same quantity as i - j, so the same key is +3. They are the same information with opposite signs; only the sign convention differs. T5 does this with a learned scalar per head and per distance bucket that is added to the attention logit (the raw score before softmax; a logit is a score before it is turned into a probability). Transformer-XL does it with a fixed sinusoidal encoding of the offset (a vector of sines and cosines of the offset at several frequencies, as in the original Transformer, which needs no learned parameters), projected by its own weight matrix and combined with two learned global bias vectors, which splits the score into four terms; it also reuses cached hidden states from the previous segment so that offsets reach beyond one segment. Both avoid adding a position vector to the input embeddings, both make the model care about distance rather than index, and both can be run at lengths longer than seen in training, with limits that differ. If time is short, the T5 bucket idea and the point that the score depends on distance matter most; know the four Transformer-XL terms at the level of what each one answers.
T5: bucketed learned bias
For head h, query position i and key position j:
scoreh(i,j)=dhqi⋅kj+bh[bucket(j−i)]Here q_i and k_j are the query and key vectors, d_h is the per-head key width, and b_h is a table of learned scalars, one per bucket, for head h. The T5 paper states that each relative position embedding is simply a scalar added to the corresponding logit, that 32 embeddings are used with ranges that grow logarithmically up to an offset of 128, that all larger offsets share one embedding, and that the parameters are shared across all layers while each head in a layer learns its own. Nothing is added to the token embeddings.
A bucket function maps distances to ids: nearby distances get their own bucket, farther distances share buckets whose width grows with distance (resolution matters more up close), and everything beyond the maximum distance falls in the last bucket. In a bidirectional encoder (one in which every token may look both left and right) the buckets are split between keys behind and keys ahead; in a causal decoder (which generates text left to right, so each token sees only earlier ones) only the look-back side is used.
Worked by hand with the causal settings used below (32 buckets, maximum distance 128): distances below 16 get their own bucket, so distance 7 is bucket 7. For distance 32: 16 + int(log(32/16) / log(128/16) x 16) = 16 + int(0.333 x 16) = 16 + int(5.33) = 21. For 64: 16 + int(log(4) / log(8) x 16) = 16 + int(10.67) = 26. For 127: 16 + int(0.996 x 16) = 16 + 15 = 31, and anything from 128 up is clipped to 31. That is the logarithmic spacing: each doubling of distance moves the bucket by about 5.3, so close distances stay distinguishable and far ones share buckets. The exact boundaries below (exact buckets for the nearest distances, a logarithmic spacing after that) are one common way to implement it; the paper fixes only the 32 and the 128.
Transformer-XL: sinusoidal relative terms and recurrence
Transformer-XL splits the long text into segments of length L and caches the previous segment's hidden states (the per-token vectors its layers produced, treated as constants: no gradient flows back into them) as memory of length M, a design called segment-level recurrence, so each query attends to M + L keys. With absolute encodings that would confuse positions, since the same index appears in each segment, so it rewrites the score between query i and key j in terms of the offset i - j:
Ai,j=(a)qi⊤Wk,Exj+(b)qi⊤Wk,RRi−j+(c)u⊤Wk,Exj+(d)v⊤Wk,RRi−jSymbols: q_i is the query, x_j the key token's representation, R_{i-j} the sinusoidal encoding of the offset (fixed, no learned parameters), W_{k,E} the key projection for content and W_{k,R} a separate key projection for the position encoding, and u and v are learned vectors that do not depend on the query position. Term (a) is content-to-content, (b) content-to-offset, (c) a global content bias (how much this kind of token is worth attending to), (d) a global offset bias (how much this distance is worth attending to). T5 keeps only a distance-dependent scalar, roughly the role of (d), and drops the rest. What makes (b) and (d) relative is that they depend on the position pair only through R_{i-j}: two different query-key pairs with the same offset get exactly the same (d) value for a given head, whatever their absolute positions, whereas (b) additionally depends on the query's content.
Costs and bucketing, computed
The program prints the bucket ids for sample distances, how many buckets get used, and the memory and compute accounting. The tensor-size lines assume 12 heads, 32 buckets and 2 bytes per entry. The Transformer-XL lines assume width 512, 8 heads, segment 128 and memory 512.
import numpy as np
def bucket(rel, num_buckets=32, max_distance=128, bidirectional=True):
"""Map relative position rel = key_pos - query_pos to a bucket id (T5-style scheme)."""
rel = np.asarray(rel)
out = np.zeros_like(rel)
if bidirectional:
num_buckets //= 2
out = out + (rel > 0) * num_buckets # keys to the right use the upper half
dist = np.abs(rel)
else:
dist = np.maximum(-rel, 0) # causal: only look back; future clipped to 0
max_exact = num_buckets // 2 # small distances get one bucket each
large = max_exact + (np.log(np.maximum(dist, 1) / max_exact) / np.log(max_distance / max_exact)
* (num_buckets - max_exact)).astype(int)
large = np.minimum(large, num_buckets - 1) # beyond max_distance: last bucket
return out + np.where(dist < max_exact, dist, large)
d = np.array([0, 1, 7, 8, 9, 12, 16, 32, 64, 127, 128, 500, 5000])
print("distance (keys behind the query):", d.tolist())
print("causal bucket ids :", bucket(-d, bidirectional=False).tolist())
print("bidirectional, behind :", bucket(-d).tolist())
print("bidirectional, ahead :", bucket(d).tolist())
for name, bi in (("causal", False), ("bidirectional", True)):
ids = bucket(np.arange(-3000, 3001), bidirectional=bi)
print(f"{name}: distinct buckets used over distances -3000..3000 = {len(set(ids.tolist()))}")
far = bucket(-np.arange(128, 3001), bidirectional=False)
print("causal: distinct buckets for distances 128..3000 =", len(set(far.tolist())))
# Cost accounting.
H, nb = 12, 32
print("\nT5-style bias parameters (shared by all layers):", H * nb)
for n in (512, 4096, 32768):
print(f"n={n:6d}: bias tensor H x n x n = {H*n*n:,} entries = {H*n*n*2/2**20:,.0f} MiB at 2 bytes")
# Transformer-XL style term cost: segment length L attends to memory M + L keys.
d_model, L, M = 512, 128, 512
print("\nExtra position-key projection per layer (d x d):", d_model * d_model, "weights")
dh = d_model // 8
print("score entries per head per layer:", L * (L + M))
print("multiply-adds for one score term (content term a, or position term b) per head:", L * (L + M) * dh)
print("relative encodings R needed per layer: one per distance 0..", L + M - 1, "=", L + M, "vectors of width", d_model)
Output:
distance (keys behind the query): [0, 1, 7, 8, 9, 12, 16, 32, 64, 127, 128, 500, 5000]
causal bucket ids : [0, 1, 7, 8, 9, 12, 16, 21, 26, 31, 31, 31, 31]
bidirectional, behind : [0, 1, 7, 8, 8, 9, 10, 12, 14, 15, 15, 15, 15]
bidirectional, ahead : [0, 17, 23, 24, 24, 25, 26, 28, 30, 31, 31, 31, 31]
causal: distinct buckets used over distances -3000..3000 = 32
bidirectional: distinct buckets used over distances -3000..3000 = 31
causal: distinct buckets for distances 128..3000 = 1
T5-style bias parameters (shared by all layers): 384
n= 512: bias tensor H x n x n = 3,145,728 entries = 6 MiB at 2 bytes
n= 4096: bias tensor H x n x n = 201,326,592 entries = 384 MiB at 2 bytes
n= 32768: bias tensor H x n x n = 12,884,901,888 entries = 24,576 MiB at 2 bytes
Extra position-key projection per layer (d x d): 262144 weights
score entries per head per layer: 81920
multiply-adds for one score term (content term a, or position term b) per head: 5242880
relative encodings R needed per layer: one per distance 0.. 639 = 640 vectors of width 512
Reading it:
- Bucketing: distances 0 to 15 get their own causal bucket, then spacing grows, and every distance from 128 on lands in bucket 31 (one bucket for all 128 to 3000, as printed). Bidirectional uses half the buckets per side, so each side has its own exact buckets only up to distance 7, and 31 distinct ids occur rather than 32 because id 16, which would mean "ahead by zero", is never produced: an offset of zero is counted on the behind side (id 0). Exact-distance schemes such as clipped relative embeddings (a table with one learned vector per distance up to a clip value, proposed in an earlier relative-position paper by Shaw and colleagues) keep full resolution below the clip and share one embedding beyond it; bucketing gives up resolution at large distances to cover a long range with few parameters.
- T5 parameters: 12 heads x 32 buckets = 384 numbers, shared across layers, versus 12 x 4,096 x 4,096 = 201,326,592 bias entries (384 MiB at 2 bytes) if the full bias tensor is materialized for a 4,096-token sequence and 24,576 MiB at 32,768 tokens. The bias is cheap in parameters and expensive only if materialized, that is, built as a full dense tensor in memory; a fused kernel (one GPU program that does the whole attention computation tile by tile) that supports it can generate the bias block by block instead.
- Transformer-XL: one extra d by d projection per layer (262,144 weights), 640 relative encodings (distances 0 to 639) per layer, and position terms (b) and (d) that cost about as much as the content term (a): 5,242,880 multiply-adds per head for (a) alone. Attention is 128 x 640 = 81,920 entries per head per layer, linear in memory length M rather than quadratic in total context.
Generalization to longer sequences
| T5 buckets | Transformer-XL | |
|---|---|---|
| Distance information | Exact nearby, coarse far, none beyond 128 | Exact at every distance, from fixed sinusoids |
| What can go wrong when longer than training | Within one layer, distances beyond the cap share one bias, so that layer's bias cannot tell a token 200 away from one 2,000 away; later layers can build sensitivity to larger offsets by combining local information from earlier layers, as the T5 paper notes | The learned weights W_{k,R}, u, v were fit on offsets seen in training; the paper reports good results with longer attention at evaluation than in training, but this has to be measured per model: evaluate at several lengths past the training length, and read a flat or falling perplexity curve as extrapolation working and a rising one as it failing |
| Positions beyond training length | No new parameters needed: any offset maps to a bucket | R is defined for any offset |
| Long-range reach | Whatever the sequence length allows (a single layer is insensitive to distance beyond 128) | Memory extends context by up to segment length times layers |
Pitfalls
- Saying T5 bias is a "position embedding added to the input". It is a per-head scalar on the logits.
- Forgetting that the bucketed bias is shared across layers in T5 but each head has its own table.
- Claiming either method extrapolates indefinitely; measure perplexity as a function of length beyond the training length. Perplexity is the exponential of the average negative log-likelihood per token; lower means the model finds the text less surprising.
Explain self-attention in a Transformer: what queries, keys and values are, how the output is computed from them, why the scores are scaled, and what shapes flow through the computation for a batch of sequences.
Sample Answer
The idea in plain words
Self-attention lets every token in a sequence build its new representation as a weighted average of information from all the tokens in the same sequence (including itself). The weights are not fixed: they are computed from the content of the tokens. Each token asks a question (its query), every token advertises what it holds (its key), and the token with a good match contributes more of its payload (its value). A token here is one unit of input text, such as a word or word piece, already turned into a vector of numbers (an embedding).
The mechanism, in order
Start with an input matrix X holding one row per token. For one sequence with n tokens and model width d_model, X has shape (n, d_model).
- Project. Three learned weight matrices turn X into queries, keys and values: Q = X W_Q, K = X W_K, V = X W_V. W_Q and W_K have shape (d_model, d_k) and W_V has shape (d_model, d_v), so Q and K are (n, d_k) and V is (n, d_v). The matrices W_Q, W_K, W_V are learned during training. Row i of Q is the question token i asks, row j of K is how token j can be matched, row j of V is what token j hands over if it is selected.
- Score. Take the dot product of every query with every key: scores = Q K^T, shape (n, n). Entry (i, j) says how well token j answers token i.
- Scale. Divide by the square root of d_k (explained below).
- Softmax. A softmax turns a row of raw numbers into positive weights that sum to 1. Applying it along each row gives the attention weights, shape (n, n).
- Mix. Multiply the weights by V: output = weights V, shape (n, d_v). Output row i is the weighted average of the value rows, using row i of the weights.
Here Q, K, V are the matrices above, d_k is the width of one key vector, and the softmax is taken over the last axis (over the keys).
A two-token example you can do on paper
Take two tokens with one-hot inputs, queries and keys equal to the inputs, and values that stretch feature 1 by 2 and feature 2 by 4. Then Q = K = X, V = [[2, 0], [0, 4]], and the score of token 0 on itself is 1 / 1.4142 = 0.7071 while its score on token 1 is 0. The softmax of (0.7071, 0) is e^0.7071 / (e^0.7071 + 1) = 2.028 / 3.028, about 0.6698, and 0.3302 for the other token, so output row 0 is about 0.6698 x (2, 0) + 0.3302 x (0, 4) = (1.34, 1.32). The program below checks it and also shows, for a softmax over three scores, how fast the gradient dies as one score pulls ahead.
import numpy as np
# Two tokens, width 2, key width 2, hand-set matrices so every number can be checked by hand.
X = np.array([[1.0, 0.0],
[0.0, 1.0]])
Wq = Wk = np.eye(2) # queries and keys are just the inputs
Wv = np.array([[2.0, 0.0],
[0.0, 4.0]]) # values stretch the two features by 2 and 4
Q, K, V = X @ Wq, X @ Wk, X @ Wv
scores = Q @ K.T / np.sqrt(2)
e = np.exp(scores)
weights = e / e.sum(axis=1, keepdims=True)
out = weights @ V
np.set_printoptions(precision=4, suppress=True)
print("V\n", V)
print("scores\n", scores)
print("weights\n", weights)
print("output row 0:", out[0])
# Why saturation stalls learning: for softmax, d p_i / d s_i = p_i * (1 - p_i).
for gap in (0, 2, 10, 30):
s = np.array([float(gap), 0.0, 0.0])
p = np.exp(s - s.max()) / np.exp(s - s.max()).sum()
print(f"score gap {gap:2d}: largest weight {p[0]:.6f} its gradient p*(1-p) = {p[0] * (1 - p[0]):.2e}")
Output:
V
[[2. 0.]
[0. 4.]]
scores
[[0.7071 0. ]
[0. 0.7071]]
weights
[[0.6698 0.3302]
[0.3302 0.6698]]
output row 0: [1.3395 1.321 ]
score gap 0: largest weight 0.333333 its gradient p*(1-p) = 2.22e-01
score gap 2: largest weight 0.786986 its gradient p*(1-p) = 1.68e-01
score gap 10: largest weight 0.999909 its gradient p*(1-p) = 9.08e-05
score gap 30: largest weight 1.000000 its gradient p*(1-p) = 1.87e-13
The last four lines are the saturation effect in numbers: with no gap the largest weight is 0.33 and nudging its score still changes it noticeably (gradient 0.22); with a gap of 10 the weight is 0.9999 and the same nudge changes it by only about 9e-5.
Worked example: three tokens, run in code
The program below uses three tokens of width 4, a key width of 2, and a fixed seed. The projection matrices are random (drawn by torch.randn and scaled by 0.7), so the printed scores cannot be derived by hand; what you can check by hand is the rule that each weights row sums to 1 and the output is the weights times V, as in the two-token example above. It prints the scores, the weights, the output and a check against PyTorch's reference function. Then it repeats the computation for a batch to show the shapes, shows why the scaling is needed, and counts the memory of the score matrix.
import torch
import torch.nn.functional as F
torch.set_num_threads(1)
torch.manual_seed(0)
# Part 1: three tokens, model width 4, one head, written out step by step.
x = torch.tensor([[1.0, 0.0, 1.0, 0.0],
[0.0, 2.0, 0.0, 2.0],
[1.0, 1.0, 1.0, 1.0]]) # (n=3, d_model=4)
Wq = torch.randn(4, 2) * 0.7 # (d_model, d_k=2)
Wk = torch.randn(4, 2) * 0.7
Wv = torch.randn(4, 2) * 0.7
Q, K, V = x @ Wq, x @ Wk, x @ Wv # each (3, 2)
scores = Q @ K.T / (2 ** 0.5) # (3, 3), divided by sqrt(d_k)
weights = torch.softmax(scores, dim=-1) # each row sums to 1
out = weights @ V # (3, 2)
print("scores\n", scores.round(decimals=3))
print("weights\n", weights.round(decimals=3))
print("row sums", weights.sum(-1).round(decimals=3))
print("output\n", out.round(decimals=3))
ref = F.scaled_dot_product_attention(Q[None], K[None], V[None])[0]
print("matches PyTorch reference:", torch.allclose(out, ref, atol=1e-6))
# Part 2: shapes for a batch of 2 sequences, length 5, d_model 16, d_k 8.
B, n, d_model, d_k = 2, 5, 16, 8
X = torch.randn(B, n, d_model)
Wq, Wk, Wv = (torch.randn(d_model, d_k) for _ in range(3))
Q, K, V = X @ Wq, X @ Wk, X @ Wv
S = Q @ K.transpose(-2, -1) / d_k ** 0.5
A = torch.softmax(S, -1)
O = A @ V
print("X", tuple(X.shape), "Q/K/V", tuple(Q.shape), "scores", tuple(S.shape),
"weights", tuple(A.shape), "output", tuple(O.shape))
# Part 3: why divide by sqrt(d_k). q and k have unit-variance entries.
for d in (4, 64, 1024):
q = torch.randn(20000, d)
k = torch.randn(20000, d)
raw = (q * k).sum(-1)
print(f"d_k={d:5d} std of q.k = {raw.std():7.3f} after scaling = {(raw / d ** 0.5).std():5.3f}")
d = 1024
q, K_ = torch.randn(d), torch.randn(8, d)
for name, s in (("unscaled", K_ @ q), ("scaled", K_ @ q / d ** 0.5)):
print(name, "largest weight over 8 keys:", round(torch.softmax(s, 0).max().item(), 3))
# Part 4: memory of the score matrix, float32 = 4 bytes, one layer.
for n_ in (1024, 4096):
heads = 16
print(f"n={n_}: scores per sequence = {heads * n_ * n_ * 4 / 2**20:.0f} MiB")
Output:
scores
tensor([[-0.6580, -0.8850, -1.1000],
[ 2.6180, 4.6980, 4.9670],
[ 0.6510, 1.4640, 1.3830]])
weights
tensor([[0.4100, 0.3270, 0.2630],
[0.0510, 0.4110, 0.5380],
[0.1870, 0.4230, 0.3900]])
row sums tensor([1., 1., 1.])
output
tensor([[-0.0620, 0.3910],
[-0.0350, 0.0560],
[-0.0380, 0.1050]])
matches PyTorch reference: True
X (2, 5, 16) Q/K/V (2, 5, 8) scores (2, 5, 5) weights (2, 5, 5) output (2, 5, 8)
d_k= 4 std of q.k = 1.993 after scaling = 0.997
d_k= 64 std of q.k = 8.084 after scaling = 1.010
d_k= 1024 std of q.k = 31.864 after scaling = 0.996
unscaled largest weight over 8 keys: 1.0
scaled largest weight over 8 keys: 0.403
n=1024: scores per sequence = 64 MiB
n=4096: scores per sequence = 1024 MiB
Reading the first block: token 2 (the second row) puts a weight of 0.051 on token 1 and 0.538 on token 3, so its output is dominated by the values of tokens 2 and 3. Each row of weights sums to 1, so the output is a convex combination of the value rows (a weighted average with non-negative weights that sum to 1, so it always lies between the value rows).
Shapes for a batch of sequences
A batch adds a leading axis B, and every matrix product acts on the last two axes. In the run above: X is (2, 5, 16), Q, K and V are (2, 5, 8), the scores and weights are (2, 5, 5) (one n by n table per sequence), and the output is (2, 5, 8). With several heads there is one more axis, giving (B, heads, n, n) for the scores.
Why the scores are scaled
If the entries of a query and a key are independent with mean 0 and variance 1 (variance is the average squared distance from the mean, and the standard deviation is its square root, the typical size of the spread), their dot product is a sum of d_k such products and has variance d_k, so its standard deviation is the square root of d_k. The Part 3 loop draws 20,000 random query/key pairs for each width and measures the spread of their dot products. The printout confirms the argument: the standard deviation of q.k is about 2 at d_k=4, about 8 at d_k=64 and about 32 at d_k=1024, and dividing by the square root of d_k brings each back to about 1. Without scaling, large d_k pushes the scores far apart, and the softmax saturates: one weight is almost 1 and the rest almost 0, a row that is nearly one-hot (all the weight on a single entry). In the 8-key example (one random query of width 1024 against 8 random keys) the largest weight prints as 1.0 (to three decimals) unscaled, against 0.403 scaled. A saturated softmax has a gradient with respect to the scores (how much the weights move when a score is nudged) that is close to zero, because for the largest weight p that gradient is p(1 - p); the saturation demo above printed 9e-5 for a score gap of 10 over three scores, so training signals reaching the query and key matrices vanish and learning stalls. A row this peaked also makes the output almost a copy of one value row, so changing how strongly the model attends to that token barely changes anything: it is already at weight 1. The divisor is the key width per head, d_k, not the model width.
Why several heads, and what attention maps do and do not show
One softmax produces one set of weights per token, so a token that needs information from two different places has to blend them in a single average. Multi-head attention runs several attention computations in parallel, each in its own smaller subspace (a lower-width projection of the token vector) with its own W_Q, W_K, W_V, and concatenates the results, so each head can pick different tokens. That is the reason to have several; which relations a given head ends up capturing is learned and has to be inspected, not assumed.
Common mistakes when reading an attention map (the weights table):
- Treating a high weight as an explanation. The weight says where the value was read from, but the value vectors differ in size and content, and later layers mix everything again, so a large weight is not proof that the token caused the output.
- Reading one head or one layer as "the model's focus". Each head is one of many, and weights after the first layer apply to already mixed representations, not to the original words.
- Forgetting that rows sum to 1 over the keys, not columns: the column of a token does not sum to 1.
Time and memory in the sequence length
The score matrix has n x n entries, each a dot product of length d_k. So one layer costs on the order of n squared times d in time and stores n squared weights per head. With 16 heads in float32 (4 bytes per number), the run above gives 64 MiB per sequence per layer at n=1024 and 1024 MiB at n=4096: quadrupling n multiplies the memory by 16. That quadratic growth is what the efficient-attention variants try to avoid: methods that compute only some of the n by n scores (for example, between nearby tokens only) or avoid storing the whole table. The projections cost on the order of n times d_model squared, which dominates when n is small relative to d_model.
Trade-offs and pitfalls
- Attention has no notion of order by itself: shuffle the input rows and the output rows are shuffled the same way. Position information must therefore be put into the inputs (for example as a position vector added to each token embedding) or into the scores.
- In a decoder, a causal mask (minus infinity added to the scores of later positions, same mechanism as the padding mask) must stop tokens from reading later tokens.
- Padding tokens (filler tokens added to short sequences so that every sequence in a batch has the same length) must be masked out of the keys: adding minus infinity to their scores before the softmax makes their weights exactly 0. Otherwise they take weight.
- A missing scale on a wide head saturates the softmax, as the example shows, and a saturated softmax passes almost no gradient back to the query and key matrices.
Compare locality-sensitive-hashing attention with fixed sparse patterns and sliding-window attention. How does each reduce memory and compute, and what are the weaknesses?
Sample Answer
Direct answer
Position-based patterns are the safer first choice: Longformer and BigBird combine sliding windows with global tokens, and some open models use sliding-window layers. LSH attention was introduced with Reformer (a long-sequence Transformer design) and has seen much less adoption in published designs, so read it here as the instructive content-based contrast, not as the practical default. All three cut the cost of full attention (every query scoring every key, O(n^2) scores) by letting each query look at only a small set of keys. They differ in how the set is chosen. A sliding window and a fixed sparse pattern choose it by position, before seeing any data, so they are cheap and predictable but blind to content. Locality-sensitive hashing (LSH) attention chooses it by content: queries and keys that point in similar directions land in the same hash bucket and attend within it, so it can reach distant tokens that matter, at the cost of randomness, unbalanced buckets and an awkward fit with causal masking.
How each reduces compute and memory
- Sliding-window attention. Query
iattends to keysjwith|i-j| <= w(or only the past w). Scores: about n(2w+1) instead of n^2; the key/value cache for generation holds only the last w entries. Information travels beyond w by stacking layers, one window per layer. - Fixed sparse patterns (a combination chosen in advance, for example a local band plus a strided set of columns every s positions, or a set of global tokens). Scores: n(local + n/s) with a stride; the choice of stride and window gives sub-quadratic cost, for example about n times the square root of n when s is about the square root of n. Distant tokens are reachable in two hops through the strided columns.
- LSH attention. A hash bucket is a label such that similar vectors usually get the same label. The labels come from random hyperplanes (random directions in the vector space; a hyperplane is the flat surface at right angles to one direction, and which side of it a vector falls on is the kind of yes/no answer a hash is built from). In angular LSH you project each vector onto several random directions, list the projections together with their negatives, and the bucket is the position of the largest entry in that list (the argmax). Vectors with a small angle between them tend to have the same argmax. A hand-traceable version is in the program: two directions, (1, 0) and (0, 1), give four buckets. Point A = (3, 1) projects to [3, 1], with negatives [-3, -1]; the largest of [3, 1, -3, -1] is the first entry, bucket 0. Point B = (2.5, 0.8), a slightly different vector, also lands in bucket 0. Point C = (-3, -1), pointing the opposite way, gets bucket 2, and D = (0.5, 4), pointing elsewhere, gets bucket 1. Reformer-style implementations use shared query/key vectors (the same projection produces queries and keys) so that "similar query and key" is symmetric, sort tokens by bucket, cut the sorted order into equal chunks, and attend within each chunk and its neighbour. Cost per round: sorting O(n log n) plus n times the chunk work; several independent rounds with different hashes are combined to reduce the chance that two similar vectors are split apart.
What the program shows
The program uses synthetic shared query/key vectors (1024 tokens, width 32, 16 clusters, norm 4) in two layouts: cluster members scattered at random positions, and cluster members in contiguous blocks. It reports how much of the full softmax weight lies on the allowed keys ("softmax mass captured"), at roughly matched key budgets: about 112 to 124 keys per query in the first group of rows, and about 286 to 309 in the second. The budgets are close but not identical, and the four-round LSH row has about 8 percent more keys than the wider window (309 against 286). That extra does not account for its large lead, but the comparison is not exactly equal.
How to read the number: full attention would capture 1.000 by definition. A pattern that picked keys with no regard to content would capture roughly its share of the keys, 112 of 1024, about 0.11. So 0.12 for a window on scattered clusters is barely better than chance, and 0.6 means the allowed keys carry about three fifths of the weight the full softmax would use. A good enough value for a real model cannot be read from this toy; it would have to be checked against the model's own quality. This is a synthetic measurement of how much weight a pattern can see, not a model-quality result.
Two hashing variants are compared on purpose. The row "LSH 16 buckets" lets every query attend to everything in its whole bucket, whose size varies. The row "sorted chunks of 64" is what a sort-and-chunk implementation actually computes (sort tokens by bucket, cut into chunks of 64, attend to your own chunk and the previous one), and the cost count at the bottom refers to that second version.
import numpy as np
n, d, n_clusters = 1024, 32, 16
def make_data(seed, contiguous):
"""Keys form 16 topic clusters (shared Q=K, as in LSH attention). Cluster labels are either scattered at
random positions or laid out as 16 contiguous blocks of 64 positions."""
rng = np.random.default_rng(seed)
centers = rng.standard_normal((n_clusters, d)) * 1.5
labels = np.arange(n) // (n // n_clusters) if contiguous else rng.integers(0, n_clusters, n)
x = centers[labels] + rng.standard_normal((n, d)) * 0.5
return x / np.linalg.norm(x, axis=1, keepdims=True) * 4.0 # norm 4 so the softmax is reasonably peaked
def lsh_buckets(x, n_buckets, seed):
R = np.random.default_rng(seed).standard_normal((d, n_buckets // 2))
h = x @ R
return np.argmax(np.concatenate([h, -h], axis=1), axis=1) # angular LSH: bucket = argmax of [xR, -xR]
def allowed_lsh(x, n_buckets, rounds, seed):
A = np.zeros((n, n), bool)
for r in range(rounds):
b = lsh_buckets(x, n_buckets, seed * 100 + r)
A |= b[:, None] == b[None, :]
return A
def allowed_lsh_chunked(x, n_buckets, seed, c=64):
"""What the sort-and-chunk implementation really attends to: sort tokens by bucket, cut into chunks of c,
each chunk sees itself and the previous chunk (so a big bucket is cut up and a small one is padded out)."""
b = lsh_buckets(x, n_buckets, seed * 100)
order = np.argsort(b, kind="stable")
chunk = np.empty(n, int); chunk[order] = np.arange(n) // c
return (chunk[:, None] == chunk[None, :]) | (chunk[:, None] - 1 == chunk[None, :])
def allowed_window(w):
i = np.arange(n); return np.abs(i[:, None] - i[None, :]) <= w
def allowed_fixed(local, stride):
i = np.arange(n); A = np.abs(i[:, None] - i[None, :]) <= local
return A | ((i[None, :] % stride) == 0) # plus a strided set of columns every `stride` positions
def mass_captured(x, A):
S = x @ x.T / np.sqrt(d)
W = np.exp(S - S.max(1, keepdims=True)); W /= W.sum(1, keepdims=True)
return float((W * A).sum(1).mean()), float(A.sum(1).mean())
configs = [("sliding window, +-57", lambda x, s: allowed_window(57)),
("fixed: local +-16 and every 12th column", lambda x, s: allowed_fixed(16, 12)),
("LSH 16 buckets, 1 round", lambda x, s: allowed_lsh(x, 16, 1, s)),
("LSH sorted chunks of 64, 1 round", lambda x, s: allowed_lsh_chunked(x, 16, s)),
("sliding window, +-154", lambda x, s: allowed_window(154)),
("LSH 16 buckets, 4 rounds", lambda x, s: allowed_lsh(x, 16, 4, s))]
for contiguous in [False, True]:
print(f"\nsynthetic shared-QK keys, n={n}, d={d}, 16 clusters, "
+ ("laid out in contiguous blocks" if contiguous else "scattered at random positions") + "; mean of 5 data seeds")
print("method keys/query softmax mass captured (full attention = 1.000)")
for name, fn in configs:
res = [mass_captured(make_data(s, contiguous), fn(make_data(s, contiguous), s)) for s in range(5)]
print(f"{name:40s} {np.mean([r[1] for r in res]):9.1f} {np.mean([r[0] for r in res]):.3f}")
# a hand-traceable hash: 2 random directions r1 = (1, 0) and r2 = (0, 1); bucket = argmax of [x.r1, x.r2, -x.r1, -x.r2]
pts = {"A": (3.0, 1.0), "B": (2.5, 0.8), "C": (-3.0, -1.0), "D": (0.5, 4.0)}
Rd = np.array([[1.0, 0.0], [0.0, 1.0]])
for name, p in pts.items():
h2 = np.array(p) @ Rd
print(f"point {name} {p}: projections {h2.tolist()} and negatives {(-h2).tolist()} -> bucket {int(np.argmax(np.concatenate([h2, -h2])))}")
# cost of the sort-and-chunk implementation (counted, not timed): chunks of size c attend to themselves and the previous chunk
c = 64
print(f"\nsorted-chunk LSH: {n // c} chunks of {c}; score computations per round = {n // c * c * 2 * c} vs {n * n} dense")
x = make_data(0, False)
sizes = np.bincount(lsh_buckets(x, 16, 0), minlength=16)
print("bucket sizes with 16 buckets (ideal 64 each):", sizes.min(), "to", sizes.max())
Output:
synthetic shared-QK keys, n=1024, d=32, 16 clusters, scattered at random positions; mean of 5 data seeds
method keys/query softmax mass captured (full attention = 1.000)
sliding window, +-57 111.8 0.116
fixed: local +-16 and every 12th column 116.0 0.120
LSH 16 buckets, 1 round 114.6 0.308
LSH sorted chunks of 64, 1 round 124.0 0.255
sliding window, +-154 285.7 0.285
LSH 16 buckets, 4 rounds 309.1 0.599
synthetic shared-QK keys, n=1024, d=32, 16 clusters, laid out in contiguous blocks; mean of 5 data seeds
method keys/query softmax mass captured (full attention = 1.000)
sliding window, +-57 111.8 0.454
fixed: local +-16 and every 12th column 116.0 0.265
LSH 16 buckets, 1 round 112.1 0.306
LSH sorted chunks of 64, 1 round 124.0 0.296
sliding window, +-154 285.7 0.558
LSH 16 buckets, 4 rounds 306.5 0.595
point A (3.0, 1.0): projections [3.0, 1.0] and negatives [-3.0, -1.0] -> bucket 0
point B (2.5, 0.8): projections [2.5, 0.8] and negatives [-2.5, -0.8] -> bucket 0
point C (-3.0, -1.0): projections [-3.0, -1.0] and negatives [3.0, 1.0] -> bucket 2
point D (0.5, 4.0): projections [0.5, 4.0] and negatives [-0.5, -4.0] -> bucket 1
sorted-chunk LSH: 16 chunks of 64; score computations per round = 131072 vs 1048576 dense
bucket sizes with 16 buckets (ideal 64 each): 4 to 316
Reading it:
- Scattered clusters (content unrelated to position). At about 115 keys per query, LSH with one round and whole buckets captures 0.308 of the softmax mass, against 0.116 for the window and 0.120 for the fixed pattern, which are both close to the chance level of about 0.11. The sorted-chunk version, which is the one whose cost is counted below (124 keys per query), captures 0.255: cutting buckets into equal chunks costs some of the mass but stays well above the window. At about 300 keys, four LSH rounds capture 0.599 against 0.285 for the window.
- Contiguous clusters (content tied to position). The ranking changes: at about 112 keys the window captures 0.454 and one LSH round 0.306 (0.296 sorted-chunk); at about 300 keys the window captures 0.558 and four LSH rounds 0.595. When related tokens are already adjacent, as local structure in text often is, the window loses little or nothing to hashing and is much simpler. This is why the scattered-cluster win for LSH is not a recommendation: it describes a layout where related tokens are far apart, and real long-context models usually rely on windows and global tokens.
- Fixed pattern. Its strided columns help little here (0.265 contiguous, 0.120 scattered) because they are content-blind: they sample positions, not related tokens.
- Balance. With 16 buckets the largest bucket held 316 tokens and the smallest 4 in one draw, against an ideal of 64. Sorted-chunk implementations force equal chunk sizes, which cuts a large bucket into pieces and pads a small one, so some similar tokens end up in different chunks; the sorted-chunk rows above include that effect.
- Cost count. Chunks of 64, each attending to itself and the previous chunk, compute 131072 scores per round against 1048576 for dense attention at n = 1024 (a counted figure, not a timing). Real cost also includes sorting and moving data, which this count leaves out.
Weaknesses
| Method | Main weaknesses |
|---|---|
| Sliding window | No access beyond the window in one layer; distant facts need many layers; good at local syntax, poor at retrieval from far away |
| Fixed sparse pattern | Content-blind; needs pattern-specific kernels (hand-written GPU routines for that exact sparsity layout); the pattern was designed for a data layout (for example image rows) and transfers poorly |
| LSH | Approximate: similar vectors can fall in different buckets (more rounds fix this at linear cost in rounds); unbalanced buckets; the sort and gather are memory-bound (limited by how fast data can be moved, not by arithmetic) and awkward on accelerators (GPUs and TPUs, which are fastest on regular, contiguous work); a gather is a read from scattered memory locations; causal masking (blocking keys that come later in the text) must use the original positions after sorting; and shared query/key projections (one matrix producing both) restrict what the model can express |
Which to reach for first
Start with a sliding window plus a few global tokens: it is simple, predictable, has no random component, and works with a small key-value cache. Add a content-based mechanism such as LSH only when related tokens are known to be far apart and the window demonstrably misses them, and expect to pay for the extra engineering. Many real systems combine a window with a few global or retrieval links instead of choosing one method.
Common mistakes
- Comparing methods at different key budgets, which favours whichever looks at more keys. (In the tables above the budgets are matched only to within about 11 percent.)
- Claiming LSH "approximates full attention" without saying it approximates the large-weight keys only, and only when they are close in angle.
- Judging by asymptotics: for moderate n, the sorting and irregular memory access of LSH can outweigh the saved scores.
Unlock Full Question Bank
Get access to all 32 Transformers and Attention interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.