Lesson 2: The scaling factor, derived, measured and removed
Module 2 · Lesson 2 · About 45 minutes · Needs: Module 2, Lesson 1 (naive_attention, the Maya trace); Module 1, Lesson 2 (the copy race)The situation
Sol 404 at Aurora Station. Kofi Mensah is reading tinyformer/attention.py line by line. He stops at scores / math.sqrt(q.shape[-1]). "Every line in this lab earns its place with a test. What does this one do, and what breaks without it?"
This lesson answers with a derivation checked in code, measurements on random and trained heads, and a training run without the line. If you met the factor in the ai-engineering course (Module 6, Lesson 1), here you test it.
A real case, first
On 10 February 2023 Mostafa Dehghani and colleagues at Google Research published "Scaling Vision Transformers to 22 Billion Parameters" (arXiv:2302.05442). Scaling up, they "observed divergent training loss after a few thousand steps", for models of "around 8B parameters". The cause: "extremely large values in attention logits, which lead to (almost one-hot) attention weights with near-zero entropy".
Their Appendix B gives the detail. At learning rate 1e-3 the loss first fell, "but within 2000 steps the loss steadily increased", and without normalisation the logits "quickly grow to over 50000 in magnitude". The fix was LayerNorm on queries and keys before the dot product, and the authors say that with it "the higher 1e-3 learning rate remains stable". Their formula keeps the 1/sqrt(d) factor. This lesson shows why that factor controls scores at the start, and why it cannot stop them growing later.
What you will be able to do
- Derive why raw scores have variance d and check it in code.
- Measure softmax saturation as entropy and as a shrinking gradient.
- Treat the factor as a softmax temperature and predict its effect.
- Measure score variance inside GPT-2, fresh and trained.
- Train the same model with and without the factor and read the gap.
1. The variance argument (Essential)
Without this one line a model can start training with its attention already frozen. Knowing where it comes from tells you when it matters. Paste the torch setup cell and shared block 1.
import torch
DEVICE = "cuda" if torch.cuda.is_available() else "cpu" # every lesson runs on "cpu"; a GPU is optional
torch.manual_seed(11) # the course seed (see course-guide/06)
print("torch", torch.__version__, "| device", DEVICE, "| CPU threads", torch.get_num_threads())Code walkthrough
- The course's torch setup cell. It printed
torch 2.14.1 | device cpu | CPU threads 5on the author's Mac.
import random
import torch
COURSE_DATE = "2026-10-09" # versions, model names and prices checked on this day
SEED = 11 # every generator in the course starts from this seed
SNAPSHOT_SOL = 400 # the corpus is the station record up to sol 399
def set_seed(seed=SEED):
"""Seed Python and PyTorch so a cell gives the same numbers every run."""
random.seed(seed)
torch.manual_seed(seed)
set_seed()
print("torch", torch.__version__, "| threads", torch.get_num_threads())Code walkthrough
- Shared block 1, as written:
SEED = 11andset_seed().
To remove the factor you need a switch. naive_attention gains a scale argument, the same one PyTorch's scaled_dot_product_attention has.
import math
import torch.nn.functional as F
def naive_attention(q, k, v, mask=None, return_weights=False, scale=None):
"""Lesson 1's naive_attention plus one switch: scale=None divides by sqrt(d_head), as before;
any other number multiplies the scores by that number instead (scale=1.0 means no scaling)."""
scores = q @ k.transpose(-2, -1)
scores = scores * (1 / math.sqrt(q.shape[-1]) if scale is None else scale)
if mask is not None:
scores = scores.masked_fill(~mask, float("-inf"))
weights = scores.softmax(dim=-1)
out = weights @ v
return (out, weights) if return_weights else out
set_seed()
q, k, v = (torch.randn(2, 4, 16, 64) for _ in range(3))
for s in [None, 1.0]:
diff = (naive_attention(q, k, v, scale=s) - F.scaled_dot_product_attention(q, k, v, scale=s)).abs().max()
print(f"scale={s}: largest difference from PyTorch {diff.item():.1e}")Code walkthrough
scale=Nonekeeps Lesson 1's behaviour; any number multiplies the scores instead, soscale=1.0removes the factor.- PyTorch's documentation (version 2.14, checked October 2026) gives the same rule:
scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale. Both settings match it (4.8e-07 and 9.5e-07).
Start with Maya. In Lesson 1 the head width was 4, so the factor was 2. The second a's raw scores are [1.93, 0.31, -0.70, 0.31]. Divided by 2 they give M a weight of 0.46; undivided, 0.68. Even at width 4 the factor changes what the head reads.
ids = torch.tensor([[32, 45, 68, 45]]) # "Maya", exactly as in Lesson 1
set_seed()
embed = torch.nn.Embedding(69, 8)
W_q, W_k, W_v = (torch.randn(8, 4) / 8 ** 0.5 for _ in range(3))
with torch.no_grad():
q, k, v = (embed(ids) @ W for W in (W_q, W_k, W_v))
mask = torch.ones(4, 4, dtype=torch.bool).tril()
raw_row = (q @ k.transpose(-2, -1))[0, 3] # the second 'a' scoring M, a, y, a
print("raw scores, row 3: ", [round(s, 2) for s in raw_row.tolist()])
for s, name in [(None, "divided by 2"), (1.0, "not divided")]:
_, w = naive_attention(q, k, v, mask, return_weights=True, scale=s)
print(f"weights, {name}:", [round(x, 2) for x in w[0, 3].tolist()])Code walkthrough
- The first six lines rebuild Lesson 1's trace with the same seed.
raw_rowis row 3 before any division. - The loop runs the head with the factor (
None) and without (1.0).
Why the square root of the width? One score is a sum of d products, one per slot. Suppose each query and key entry has mean 0 and variance 1 (variance measures spread: the average squared distance from the mean). Then each product also has mean 0 and variance 1.
When independent numbers are added, their variances add. So a raw score has variance d, and its typical size, the standard deviation, is the square root of d: 2 at width 4, 8 at width 64, 32 at width 1,024 (arithmetic). Vaswani and colleagues give exactly this in a footnote to "Attention Is All You Need" (2017).
Dividing a number by c divides its variance by c squared. Divide the score by the square root of d and its variance becomes d / d = 1, at every width. That is the whole job of the factor: the scores start the same size whatever the head width.
g = torch.Generator().manual_seed(SEED)
print(f"{'d':>5} {'mean':>6} {'var raw':>8} {'var scaled':>11} {'max|raw|':>9} {'max|scaled|':>12}")
for d in [4, 16, 64, 256, 1024]:
q = torch.randn(4096, d, generator=g) # 4,096 queries: mean 0, variance 1, independent
k = torch.randn(4096, d, generator=g) # 4,096 keys, drawn the same way
raw = (q * k).sum(-1) # one dot product per row
scaled = raw / math.sqrt(d)
print(f"{d:5d} {raw.mean():6.2f} {raw.var():8.1f} {scaled.var():11.3f} "
f"{raw.abs().max():9.1f} {scaled.abs().max():12.2f}")Code walkthrough
torch.randndraws exactly what the derivation assumes: independent entries, mean 0, variance 1.(q * k).sum(-1)is 4,096 dot products. The table prints their mean and variance, raw and scaled, and the largest absolute value of each.
Measured here: raw variance 4.2 to 1,058.2 against predictions of 4 to 1,024; scaled, between 0.99 and 1.04. The derivation holds.
The largest score matters most, because the softmax reacts to the biggest gap. Raw, it grows from 9.5 to 111.0. Scaled, it stays between 3.5 and 4.8. A gap of 111 makes e to the 111, about 1.6e48 (arithmetic): no other key gets any weight.
The argument rests on three assumptions: mean 0, independent entries, variance 1. Drop only the last and the rule becomes d x Var(q) x Var(k), which the exercise tests. Section 4 shows a trained model breaks the other two.
Break it: divide by d instead of sqrt(d)
Dividing by the width itself is an easy slip, and nothing crashes.
def wrong_divisor_attention(q, k, v):
scores = q @ k.transpose(-2, -1) / q.shape[-1] # the bug: d instead of sqrt(d)
return scores.softmax(-1) @ v, scores.softmax(-1)
g = torch.Generator().manual_seed(SEED)
q, k, v = (torch.randn(1, 32, 256, generator=g) for _ in range(3)) # 32 positions, head width 256
_, good = naive_attention(q, k, v, return_weights=True)
bad_out, bad = wrong_divisor_attention(q, k, v)
print("largest weight, sqrt(d):", round(good[0, -1].max().item(), 3), "| d:", round(bad[0, -1].max().item(), 3),
"| uniform would be", round(1 / 32, 3))
print("matches PyTorch:", torch.allclose(bad_out, F.scaled_dot_product_attention(q, k, v), atol=1e-5))Code walkthrough
wrong_divisor_attentiondivides by the width, so the score variance becomes 1/256. The prints compare the last row's largest weight, then run the lab's check against PyTorch.
The broken head's largest weight is 0.035, barely above uniform 0.031; the correct one reaches 0.136. The check against PyTorch prints False: the existing test catches it.
2. Softmax saturation, entropy and gradients (Essential)
Big scores do more than sharpen a row: they stop it learning. You need one number for how spread out a row is, and one for how much gradient gets through.
That first number is entropy: minus the sum of each weight times its logarithm. A row on one key has entropy 0. A row spread evenly over 32 keys has log 32 = 3.47 (arithmetic). Its exponential, the effective number of keys, reads more naturally: 1 for one key, 32 for all 32.
def entropy(w):
"""Entropy of each attention row in nats: 0 for one-hot, log(n) for uniform over n keys."""
return -(w * w.clamp_min(1e-12).log()).sum(-1)
g = torch.Generator().manual_seed(SEED)
target = torch.randn(32, generator=g) # stands in for "what the next layer wants"
print("uniform entropy log(32) =", round(math.log(32), 3))
for d in [4, 16, 64, 256, 1024]:
q = torch.randn(1000, d, generator=g) # 1,000 query rows
k = torch.randn(1000, 32, d, generator=g) # each row scores 32 keys
raw = (k @ q.unsqueeze(-1)).squeeze(-1) # (1000, 32) raw scores
for name, s in [("scaled", raw / math.sqrt(d)), ("raw", raw)]:
s = s.clone().requires_grad_()
w = s.softmax(-1)
(w * target).sum().backward() # gradient of a fixed downstream loss
print(f"d={d:4d} {name:6} entropy {entropy(w).mean():.3f} effective keys {entropy(w).exp().mean():5.2f}"
f" rows > 0.99 {(w.max(-1).values > 0.99).float().mean():.3f} |grad| {s.grad.abs().mean():.2e}")Code walkthrough
entropyapplies the definition;clamp_min(1e-12)avoids the logarithm of 0.- Each width gets 1,000 rows of 32 keys (the copy task's length), with and without the factor.
(w * target).sum()is a stand-in loss, a fixed demand from the rest of the network;backward()fillss.grad, the gradient on each score.- The print gives entropy, effective keys, the share of rows over 0.99 on one key, and the mean gradient.
With the factor, entropy stays near 3.01 (about 20.5 effective keys) at every width. Without it, entropy falls from 2.29 at width 4 to 0.112 at width 1,024: 1.15 effective keys. That is softmax saturation: the softmax has become an argmax.
Why does saturation stop learning? The gradient on score i is its weight a_i times the gap between what the loss wants from key i and the weighted average. Near 0, the weight kills it; near 1, key i is the average, so the gap vanishes.
Measured: the mean gradient on the scores stays at 2.7e-2 with the factor. Without it, it falls to 9.2e-3 at width 64 and 2.4e-3 at width 1,024, 11 times smaller. This is what Vaswani and colleagues meant by "regions where it has extremely small gradients".
Rows stuck on one key: none with the factor; without it, 24% at width 64 and 73% at 1,024. They chose their key by chance, before training, and get almost no signal to change it.
3. Softmax temperature and sharpness (Essential)
The factor is one setting of a more general dial. Seeing the dial lets you predict any scale's effect, including deleting the line.
Divide the scores by a number T before the softmax. T is the temperature. Small T exaggerates gaps; large T flattens them. On Maya's row, T = 0.05 gives [1.0, 0.0, 0.0, 0.0]; T = 1 gives Lesson 1's [0.463, 0.206, 0.125, 0.206]; T = 16 gives nearly 0.25 each.
row = raw_row / 2 # Maya's row 3, scaled as in Lesson 1
print("scaled scores:", [round(s, 2) for s in row.tolist()])
print(f"{'T':>6} weights (M, a, y, a) entropy effective keys")
for T in [0.05, 0.125, 0.25, 0.5, 1, 2, 4, 16]:
w = (row / T).softmax(-1)
h = entropy(w)
print(f"{T:6} {[round(x, 3) for x in w.tolist()]!s:30} {h:7.3f} {h.exp():6.2f}")
print("dropping the factor at width 64 is T =", 1 / math.sqrt(64))Code walkthrough
rowis Maya's row 3 after Lesson 1's division by 2. Each temperature divides it before the softmax.- The last line is the temperature you choose by deleting the factor at width 64.
Effective keys climb from 1.00 at T = 0.05 through 3.55 at T = 1 to 4.00 at T = 16, the most four keys allow. Temperature moves a row smoothly between a hard lookup and a plain average.
Deleting the factor multiplies the scores by the square root of d, a temperature of 1 over the square root of d: at width 64, T = 0.125. Maya's row at that temperature is 0.997 on M. Without the factor, a wide head starts life sharpened 8 times.
Module 11 has another temperature: sampling temperature divides the output logits before a token is drawn. Same arithmetic, different place: one decides what a head reads, the other how adventurous generation is.
4. Score variance inside trained models (Recommended)
The derivation assumed unit variance and independence. A trained model promises neither, so measure GPT-2 small, the course's reference model, fresh and trained.
%pip install -q transformers==5.19.0from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
REF = "openai-community/gpt2" # the course's reference model: GPT-2 small, MIT licence
tok = AutoTokenizer.from_pretrained(REF)
trained = AutoModelForCausalLM.from_pretrained(REF, attn_implementation="eager").eval()
set_seed()
fresh = AutoModelForCausalLM.from_config(AutoConfig.from_pretrained(REF), attn_implementation="eager").eval()
print("scale_attn_weights:", trained.config.scale_attn_weights, "| head width:", trained.config.n_embd // trained.config.n_head)
text = "Log 4821, sol 212. Maya Lindqvist repaired the oxygen recycler. Maya Lindqvist"
ids = tok(text, return_tensors="pt")["input_ids"]
T = ids.shape[1]
second = [i for i, t in enumerate(ids[0].tolist()) if tok.decode([t]) == " Maya"][1]
def score_stats(model):
"""Per layer: raw q.k variance, the independence prediction, scaled variance, entropy of the second ' Maya'."""
qkv = {}
hooks = [b.attn.c_attn.register_forward_hook(lambda m, i, o, l=l: qkv.__setitem__(l, o[0]))
for l, b in enumerate(model.transformer.h)]
with torch.no_grad():
run = model(ids, output_attentions=True)
for h in hooks:
h.remove()
causal = torch.ones(T, T, dtype=torch.bool).tril()
rows = []
for l in range(12):
q, k, _ = (t.view(T, 12, 64).transpose(0, 1) for t in qkv[l].split(768, -1)) # (heads, T, 64)
raw = (q @ k.transpose(-2, -1))[:, causal] # allowed cells only
rows.append((l, raw.var().item(), (64 * q.var() * k.var()).item(), raw.var().item() / 64,
entropy(run.attentions[l][0, :, second]).mean().item()))
return rowsCode walkthrough
freshhas GPT-2's configuration with new random weights (from_config).scale_attn_weightsisTrue: GPT-2 divides by the square root of 64.secondfinds the second' Maya'of Lesson 1's log line (position 17).- GPT-2 makes q, k and v in one layer,
c_attn. A forward hook is a function PyTorch calls with a layer's output; here it stores it inqkv. split,viewandtransposegive 12 heads of width 64;rawkeeps the causal cells. Each row holds raw variance, the prediction 64 x Var(q) x Var(k), scaled variance, and the second Maya's entropy averaged over heads.
print(f"second ' Maya' at position {second}: uniform entropy log({second + 1}) = {math.log(second + 1):.2f}")
print(f"{'layer':>5} {'raw var':>8} {'predicted':>9} {'scaled var':>10} {'entropy':>8} | fresh: {'scaled var':>10} {'entropy':>8}")
for (l, rv, pv, sv, h), (_, _, _, fsv, fh) in zip(score_stats(trained), score_stats(fresh)):
print(f"{l:5d} {rv:8.0f} {pv:9.0f} {sv:10.1f} {h:8.2f} | {fsv:10.3f} {fh:8.2f}")Code walkthrough
- One line per layer: the trained model's four numbers, then the fresh model's scaled variance and entropy side by side.
Fresh, GPT-2's scaled scores have variance 0.06 to 0.14: small initial weights make small queries and keys. Trained, it is 2.5 to 24.2. Training sharpened attention on purpose.
The independence formula also fails. In layer 0 the raw variance is 683 against a prediction of 143; in layer 11, 355 against 100; in layer 3 the error flips, 771 against 1,363. Queries and keys are both made from the same token vectors, so they are not independent.
The second Maya's row shows it. Uniform over 18 positions is 2.89; fresh heads sit at 2.85 to 2.88, trained heads at 1.05 to 2.32. The factor sets the start; Module 6 measures growth that runs away, as in ViT-22B.
5. Training with and without the factor (Recommended)
Measurements predict; training decides. Train the same model twice, one switch apart, on Module 1's copy task.
from typing import NamedTuple
class TaskData(NamedTuple):
name: str
vocab_size: int
inputs: torch.Tensor # (n, T) token ids
targets: torch.Tensor # (n, T) the next token at every position
mask: torch.Tensor # (n, T) 1 where the answer is scored, 0 elsewhere
def _shift(name, vocab, seq, scored_from):
inputs, targets = seq[:, :-1], seq[:, 1:]
mask = torch.zeros_like(inputs)
mask[:, scored_from:] = 1
return TaskData(name, vocab, inputs, targets, mask)
def make_task(name, n=4096, length=16, vocab=32, seed=SEED):
"""copy, reverse or induction. Token 0 is the separator; content tokens are 1 to vocab - 1."""
g = torch.Generator().manual_seed(seed)
body = torch.randint(1, vocab, (n, length), generator=g)
sep = torch.zeros(n, 1, dtype=torch.long)
if name == "copy":
seq = torch.cat([body, sep, body], dim=1)
elif name == "reverse":
seq = torch.cat([body, sep, body.flip(1)], dim=1)
elif name == "induction": # random tokens, then the same random tokens again
seq = torch.cat([body, body], dim=1)
return _shift(name, vocab, seq, scored_from=length)
TASKS = {name: make_task(name) for name in ["copy", "reverse", "induction"]}
for t in TASKS.values():
print(t.name, tuple(t.inputs.shape), "scored positions per row:", int(t.mask[0].sum()))Code walkthrough
- Shared block 9, as written.
copyis 16 random tokens, a separator, the same 16 again; only the second half is scored. It printedcopy (4096, 32) scored positions per row: 16.
ScaleLab is two pre-norm blocks with one head of width 128, so the factor is about 11.3. Wide heads are where it matters. The scale switch is the only difference between twin runs.
import torch.nn as nn
class OneHeadBlock(nn.Module):
"""Pre-norm block with one wide attention head and a feed-forward layer."""
def __init__(self, d, scale, qk_std):
super().__init__()
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
self.qkv, self.out = nn.Linear(d, 3 * d, bias=False), nn.Linear(d, d, bias=False)
self.ff = nn.Sequential(nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d))
self.scale = scale
if qk_std: # None keeps PyTorch's default initialisation
nn.init.normal_(self.qkv.weight, std=qk_std)
def forward(self, x):
q, k, v = self.qkv(self.norm1(x)).chunk(3, dim=-1)
causal = torch.ones(x.shape[1], x.shape[1], dtype=torch.bool).tril()
a, self.weights = naive_attention(q, k, v, causal, return_weights=True, scale=self.scale)
x = x + self.out(a)
return x + self.ff(self.norm2(x))
class ScaleLab(nn.Module):
def __init__(self, scale, qk_std, vocab=32, d=128, layers=2, context=32):
super().__init__()
self.embed, self.pos = nn.Embedding(vocab, d), nn.Embedding(context, d)
self.blocks = nn.ModuleList(OneHeadBlock(d, scale, qk_std) for _ in range(layers))
self.head = nn.Sequential(nn.LayerNorm(d), nn.Linear(d, vocab))
def forward(self, ids):
x = self.embed(ids) + self.pos(torch.arange(ids.shape[1]))
for block in self.blocks:
x = block(x)
return self.head(x)Code walkthrough
OneHeadBlocknormalises, makes q, k and v with onenn.Linear, runsnaive_attentionwith itsscale, adds the result back, then does the same with a feed-forward layer. Module 3 builds the real block.qk_std = 128 ** -0.5gives queries and keys variance about 1, the derivation's case;Nonekeeps PyTorch's default, about a third of that.self.weightskeeps the last weights for reading entropy.ScaleLabadds embeddings, two blocks and an output layer.
import time
def train_once(scale, qk_std, seed, task=TASKS["copy"], steps=150, n_valid=512):
set_seed(seed)
model, g = ScaleLab(scale, qk_std), torch.Generator().manual_seed(seed)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
xv, yv, mv = (t[-n_valid:] for t in (task.inputs, task.targets, task.mask))
with torch.no_grad():
model(xv[:64])
h0 = sum(entropy(b.weights).mean().item() for b in model.blocks) / 2 # mean row entropy at the start
curve = []
for step in range(1, steps + 1):
i = torch.randint(0, len(task.inputs) - n_valid, (64,), generator=g)
losses = F.cross_entropy(model(task.inputs[i]).flatten(0, 1), task.targets[i].flatten(), reduction="none")
loss = (losses * task.mask[i].flatten()).sum() / task.mask[i].sum()
opt.zero_grad(); loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
if step % 10 == 0:
with torch.no_grad():
right = (model(xv).argmax(-1) == yv).float()
curve.append((step, (right * mv).sum().item() / mv.sum().item()))
first = next((s for s, a in curve if a >= 0.95), None)
return first, dict(curve)[30], h0
t0 = time.perf_counter()
for init, qk_std in [("unit-variance", 128 ** -0.5), ("PyTorch default", None)]:
for scale, name in [(None, "with 1/sqrt(d)"), (1.0, "without")]:
runs = [train_once(scale, qk_std, seed) for seed in (11, 12, 13)]
print(f"{init:16} {name:15} steps to 95%: {[r[0] for r in runs]} acc at step 30: "
f"{[round(r[1], 2) for r in runs]} entropy at start: {runs[0][2]:.2f}")
print(f"12 runs in {time.perf_counter() - t0:.0f} s")Code walkthrough
train_onceis Module 1's race loop, shortened: AdamW, 64 rows a step, loss on the copied half, clipping at 1.0, held-out accuracy every 10 steps.h0is the mean row entropy before training.- It returns the first step at 95% accuracy, the accuracy at step 30, and
h0. The loops make 12 runs: two starts, with and without the factor, three seeds. They took 20 to 24 s over two runs on the author's Mac; allow up to four times that on a free Colab CPU.
From the unit-variance start the factor wins on every seed. With it, all three runs pass 95% at step 30. Without it they need 70, 70 and 90 steps, and at step 30 sit at 0.28, 0.41 and 0.71. All 12 runs reach 95% in the end: on this small task the factor buys speed.
From PyTorch's default start the gap shrinks: 40, 40 and 30 steps with the factor, 60, 40 and 30 without. Small weights make small scores, leaving the factor less to correct.
The cause is visible before step 1: mean row entropy 2.19 with the factor, 0.28 without. The unscaled model begins saturated and spends dozens of steps escaping. Three seeds is a small noise floor, and Kofi would want that said.
In production
PyTorch's attention divides by the square root of the head width by default (documentation for version 2.14, checked October 2026). The factor protects the start of training only. For growth during training, ViT-22B added QK-norm, LayerNorm on queries and keys before the dot product, keeping the factor. Shuangfei Zhai and colleagues (2023, arXiv:2303.06296) report that "low attention entropy is accompanied by high training instability". Module 3 builds QK-norm; Module 6 tracks entropy during training.
What you added to tinyformer-lab
- A
scaleargument onnaive_attention, matching PyTorch's, with a check forscale=1.0and the default. - An
entropyhelper for attention rows, used again in Modules 6 and 14. score_stats, a per-layer score-variance report for GPT-2.- The with-and-without training experiment. It stays in this lesson: the module lab keeps one seeded experiment,
experiments/m02_kv_heads.py.
Check yourself
- Raw scores at head width 256 have what standard deviation, and why?
- A head's rows have entropy 0.11 over 32 keys. What is happening to its gradients?
- You delete the factor at width 64. What temperature have you chosen?
- GPT-2's trained scaled variance is 24.2 in layer 4. Does that mean the factor is broken?
- Why did the factor matter less from PyTorch's default start?
- 16: 256 unit-variance products add to variance 256.
- They are tiny: near one-hot rows (1.12 effective keys) pass almost no gradient back.
- T = 1/8 = 0.125.
- No. The factor fixes the starting scale; training sharpened attention on purpose.
- Small weights gave modest raw scores (start entropy 0.86 without the factor), so dividing changed less.
Exercise
The general rule is Var(q · k) = d x Var(q) x Var(k), for independent entries with mean 0. Predict each measured variance below before running. Then look at the last case, where keys are built from queries, and explain the miss.
def predicted_var(d, var_q, var_k):
"""Var(q . k) when all entries are independent with mean 0."""
return d * var_q * var_k
g = torch.Generator().manual_seed(SEED)
for d, sq, sk in [(64, 1.0, 1.0), (64, 0.5, 2.0), (128, 0.3, 0.3), (16, 3.0, 1.0)]:
q = torch.randn(20000, d, generator=g) * sq ** 0.5 # entries with variance sq
k = torch.randn(20000, d, generator=g) * sk ** 0.5 # entries with variance sk
measured = (q * k).sum(-1).var().item()
assert abs(measured / predicted_var(d, sq, sk) - 1) < 0.05, (d, sq, sk, measured)
print(f"d={d:3d} var_q={sq} var_k={sk}: measured {measured:7.2f}, predicted {predicted_var(d, sq, sk):7.2f}")
q = torch.randn(20000, 64, generator=g)
k = 0.8 * q + 0.6 * torch.randn(20000, 64, generator=g) # keys correlated with queries, variance still 1
ratio = (q * k).sum(-1).var().item() / predicted_var(64, 1.0, 1.0)
assert ratio > 1.5, "correlated q and k should break the formula"
print(f"correlated: measured / predicted = {ratio:.2f}; check passed")Code walkthrough
- The loop scales
randnby the square root of each variance and asserts the measurement is within 5% ofpredicted_var. - The last case makes each key 0.8 of its query plus noise: variance still 1, but not independent. The formula undershoots (1.63 times). Work out why: the average of q to the fourth power is 3, not 1.
Key terms
| Term | Meaning |
|---|---|
| Variance | Average squared distance from the mean; a raw score's variance is d at unit-variance start |
| Scaling factor | 1/sqrt(d_head), which makes the scores' variance 1 whatever the head width |
| Entropy | Minus the sum of w log w over a row: 0 for one key, log n for n equal keys |
| Effective number of keys | exp(entropy): how many keys a row really averages |
| Softmax saturation | A row so close to one-hot that almost no gradient reaches its scores |
| Temperature | A number the scores are divided by before the softmax; small sharpens, large flattens |
| QK-norm | Normalising queries and keys before the dot product, to bound scores during training |
Sources
- Mostafa Dehghani, Josip Djolonga, Basil Mustafa, Piotr Padlewski, Jonathan Heek et al. (Google Research), "Scaling Vision Transformers to 22 Billion Parameters", 2023, section 2 and Appendix B. https://arxiv.org/abs/2302.05442
- Ashish Vaswani et al., "Attention Is All You Need", 2017, Section 3.2.1 and footnote 4. https://arxiv.org/abs/1706.03762
- Shuangfei Zhai, Tatiana Likhomanenko, Etai Littwin et al., "Stabilizing Transformer Training by Preventing Attention Entropy Collapse", 2023. https://arxiv.org/abs/2303.06296
- PyTorch,
torch.nn.functional.scaled_dot_product_attention, documentation for version 2.14, checked October 2026. https://docs.pytorch.org/docs/2.14/generated/torch.nn.functional.scaled_dot_product_attention.html