CourseTransformers: From Attention to Trained, Served and Interpreted Models · Module 2: Self-Attention Mechanics · part 14 of 111
Part 14 · Module 2: Self-Attention Mechanics

Lesson 2: The scaling factor, derived, measured and removed

20 min read·
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".

VIT AT ABOUT 8B PARAMETERS, LEARNING RATE 1E-3 loss falls as normal logits grow over 50,000 weights almost one-hot loss rises in 2,000 steps fix: LayerNorm on q and k 1e-3 stays stable
Dehghani et al. (2023, cited): attention logits (amber) grew past 50,000, weights went almost one-hot and the loss rose (red); LayerNorm on queries and keys kept 1e-3 stable (green).

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.

python
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 5 on the author's Mac.
python
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 = 11 and set_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.

python
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=None keeps Lesson 1's behaviour; any number multiplies the scores instead, so scale=1.0 removes 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).
THE SECOND A OF MAYA, HEAD WIDTH 4 raw scores 1.93 0.31 -0.70 0.31 divided by 2 M 0.46 a 0.21 y 0.12 a 0.21 not divided M 0.68 a 0.13 a 0.13
Maya's row 3 from Lesson 1: dividing the raw scores by 2 gives M 0.46 of the weight (green), skipping the division gives 0.68 (red), so the factor matters even at width 4.

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.

python
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_row is row 3 before any division.
  • The loop runs the head with the factor (None) and without (1.0).
ONE SCORE AT HEAD WIDTH D q1 k1 + q2 k2 + q3 k3 + ... + q_d k_d each product: mean 0, variance 1 score = sum of d terms
A score is a sum of d products, one per slot (blue); when entries have mean 0 and variance 1, each product does too, and the sum is the score (amber).

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.

TYPICAL RAW SCORE SIZE: SQRT(D) d = 4 std 2 d = 16 std 4 d = 64 std 8 d = 256 std 16 d = 1,024 std 32
Variances of independent terms add, so a raw score has variance d and a typical size of sqrt(d): 2 at width 4, 32 at width 1,024 (arithmetic).

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).

raw score variance d / sqrt(d) divided variance d / d variance 1 at every width dividing by c divides the variance by c squared
Dividing a score by sqrt(d) divides its variance by d, so the scaled scores have variance 1 whatever the head width (green).

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.

python
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.randn draws 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.
4,096 RANDOM PAIRS PER WIDTH, MEASURED HERE width d predicted raw var scaled var 4 4 4.2 1.039 16 16 15.8 0.989 64 64 64.5 1.008 256 256 263.1 1.028 1,024 1,024 1,058.2 1.033
Measured here: raw score variance tracks the prediction d at every width (amber), and after dividing by sqrt(d) it stays between 0.99 and 1.04 (green).

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.

LARGEST SCORE AMONG 4,096 d = 4 4.75 9.5 d = 16 4.41 17.6 d = 64 3.77 30.2 d = 256 4.18 66.9 d = 1,024 3.47 111.0 scaled raw
The largest raw score grows from 9.5 to 111.0 with width (red), while the largest scaled score stays between 3.5 and 4.8 (green), measured here.

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.

WHAT THE ARGUMENT ASSUMES mean 0 no offset independent q and k unrelated variance 1 unit entries d x Var(q) x Var(k) if only variance 1 is dropped Section 4: training breaks the other two
The derivation needs mean 0, independence and unit variance (blue); without unit variance the rule becomes d x Var(q) x Var(k) (amber), and trained models break the other two.

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.

python
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_attention divides 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.
LARGEST WEIGHT IN A ROW OF 32 KEYS, WIDTH 256 / sqrt(d) 0.136 / d (bug) 0.035 uniform 0.031 check against PyTorch prints False: caught
Dividing by d instead of sqrt(d) flattens a head to 0.035 on its best key, barely above uniform 0.031 (grey), and the comparison with PyTorch catches the bug (red).

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.

ENTROPY OF A ROW OVER 32 KEYS 0 one key 3.47 all 32 keys effective keys = exp(entropy): 1 to 32
Entropy measures how spread a row is: 0 when one key takes everything (red), log 32 = 3.47 when all 32 share equally (green); its exponential counts effective keys.

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.

python
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

  • entropy applies 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() fills s.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.
EFFECTIVE KEYS OUT OF 32, MEAN OF 1,000 ROWS d = 4 21.85 11.92 d = 16 20.83 3.70 d = 64 20.72 1.84 d = 256 20.47 1.33 d = 1,024 20.51 1.15 with the factor without
With the factor a row averages about 20.5 effective keys at every width (green); without it the count falls from 11.92 to 1.15, a near argmax (red), measured here.

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.

dL/ds_i = a_i x ( g_i - sum_j a_j g_j ) a_i near 0 the product is near 0 a_i near 1 g_i is the average: gap near 0 g_i: what the loss wants from key i
The gradient on score i is its weight times its gap from the weighted average, so a weight near 0 or near 1 sends almost nothing back (red): a saturated row stops learning.

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.

MEAN |GRADIENT| ON THE SCORES (X 1E-2) d = 4 2.68 2.40 d = 16 2.67 1.65 d = 64 2.70 0.922 d = 256 2.67 0.453 d = 1,024 2.67 0.238 with the factor without
The mean gradient on the scores stays at 2.7e-2 with the factor (green) and falls to 2.4e-3 without it at width 1,024, 11 times smaller (red), measured here.

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 OVER 0.99 ON ONE KEY, WITHOUT THE FACTOR d = 4 0% d = 16 3% d = 64 24% d = 256 55% d = 1,024 73% with the factor: 0% at every width
Without the factor the share of rows with over 0.99 on one key climbs to 73% at width 1,024 (red); with it, no row is stuck (green), measured here.

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.

MAYA'S ROW 3, SCORES DIVIDED BY T T = 0.05 M 1.00 T = 0.25 M 0.92 T = 1 M 0.46 T = 4 M 0.30 T = 16 M 0.26
Dividing Maya's scores by a temperature T moves M's share (amber) from 1.00 at T = 0.05 through 0.46 at T = 1 to 0.26 at T = 16, nearly uniform.

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.

python
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

  • row is 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 OF MAYA'S ROW (OUT OF 4) 1 2 3 4 T=0.05 T=0.5 T=1 T=16 3.55
As the temperature rises, Maya's row goes smoothly from 1.00 effective key (a lookup) to 4.00 (a plain average), with 3.55 at T = 1, measured here.

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.

delete / sqrt(d) width 64 T = 1/8 = 0.125 M gets 0.997 Maya's row 3 a wide head without the factor starts 8 times sharper
Removing the factor at width 64 is the same as a temperature of 1/8, which turns Maya's row into 0.997 on M (red): a near-lookup before any training.

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.

attention temperature divides q.k scores decides what a head reads sampling temperature divides output logits decides the next token (M11) same arithmetic, different place
Attention temperature works inside a head on query-key scores (amber); sampling temperature, in Module 11, works on the output logits (blue).

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.

python
%pip install -q transformers==5.19.0
python
from 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 rows

Code walkthrough

  • fresh has GPT-2's configuration with new random weights (from_config). scale_attn_weights is True: GPT-2 divides by the square root of 64.
  • second finds 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 in qkv.
  • split, view and transpose give 12 heads of width 64; raw keeps 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.
python
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.
GPT-2 SMALL, SCALED SCORE VARIANCE BY LAYER 0 1 2 3 4 5 6 7 8 9 10 11 1 24.2 trained 2.5 to 24.2 fresh 0.06 to 0.14
Inside GPT-2 small the scaled score variance is about 0.1 at a fresh initialisation (grey) and 2.5 to 24.2 after training (amber), far from the derivation's 1 (green), measured here.

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.

RAW SCORE VARIANCE: MEASURED AGAINST PREDICTED layer 0 683 143 layer 3 771 1,363 layer 4 1,551 1,271 layer 11 355 100 measured d x Var(q) x Var(k)
In trained GPT-2 the independence formula (grey) misses the measured raw variance (amber) by up to 4.8 times, too low in layers 0 and 11 and too high in layer 3, because q and k share their input.

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.

ENTROPY OF THE SECOND ' MAYA' ROW, BY LAYER 0 1 2 3 4 5 6 7 8 9 10 11 uniform 2.89; fresh 2.85 to 2.88 1.05
Fresh GPT-2 heads read the second ' Maya' almost uniformly (2.85 to 2.88 against 2.89, grey); trained heads sit at 1.05 to 2.32 (amber): training sharpens attention on purpose.

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.

python
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. copy is 16 random tokens, a separator, the same 16 again; only the second half is scored. It printed copy (4096, 32) scored positions per row: 16.
copy task 16 + sep + 16 ScaleLab 2 blocks, 1 head head width 128 scale=None / sqrt(128) scale=1.0 no factor same seed, same batches, 150 steps, 3 seeds each
The experiment: the same two-block, one-head model (blue) on Module 1's copy task, trained with the factor (green) and without it (red), everything else identical.

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.

python
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

  • OneHeadBlock normalises, makes q, k and v with one nn.Linear, runs naive_attention with its scale, adds the result back, then does the same with a feed-forward layer. Module 3 builds the real block.
  • qk_std = 128 ** -0.5 gives queries and keys variance about 1, the derivation's case; None keeps PyTorch's default, about a third of that.
  • self.weights keeps the last weights for reading entropy. ScaleLab adds embeddings, two blocks and an output layer.
python
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_once is 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. h0 is 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.
UNIT-VARIANCE START: STEPS TO 95% ACCURACY seed 11 30 70 seed 12 30 70 seed 13 30 90 with the factor without
From a unit-variance start every seed reaches 95% copy accuracy at step 30 with the factor (green) and needs 70 to 90 steps without it (red), measured here.

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.

PYTORCH DEFAULT START: STEPS TO 95% ACCURACY seed 11 40 60 seed 12 40 40 seed 13 30 30 with the factor without
From PyTorch's smaller default start the gap mostly closes: 30 to 40 steps with the factor (green), 30 to 60 without (red), because raw scores were already modest.

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.

MEAN ROW ENTROPY BEFORE TRAINING, UNIT-VARIANCE START with the factor 2.19 without 0.28 the unscaled model is born saturated
Before step 1 the model with the factor has mean row entropy 2.19 (green) and the one without has 0.28 (red), so the slow start is visible before training begins.

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

x q k LayerNorm LayerNorm q.k / sqrt(d) then softmax normalised q and k cannot grow without bound
QK-norm, as in ViT-22B (cited): queries and keys pass through LayerNorm (green) before the scaled dot product, so the scores stay bounded as the weights grow in training.

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 scale argument on naive_attention, matching PyTorch's, with a check for scale=1.0 and the default.
  • An entropy helper 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

  1. Raw scores at head width 256 have what standard deviation, and why?
  2. A head's rows have entropy 0.11 over 32 keys. What is happening to its gradients?
  3. You delete the factor at width 64. What temperature have you chosen?
  4. GPT-2's trained scaled variance is 24.2 in layer 4. Does that mean the factor is broken?
  5. Why did the factor matter less from PyTorch's default start?
  1. 16: 256 unit-variance products add to variance 256.
  2. They are tiny: near one-hot rows (1.12 effective keys) pass almost no gradient back.
  3. T = 1/8 = 0.125.
  4. No. The factor fixes the starting scale; training sharpened attention on purpose.
  5. 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.

python
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 randn by the square root of each variance and asserts the measurement is within 5% of predicted_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

TermMeaning
VarianceAverage squared distance from the mean; a raw score's variance is d at unit-variance start
Scaling factor1/sqrt(d_head), which makes the scores' variance 1 whatever the head width
EntropyMinus the sum of w log w over a row: 0 for one key, log n for n equal keys
Effective number of keysexp(entropy): how many keys a row really averages
Softmax saturationA row so close to one-hot that almost no gradient reaches its scores
TemperatureA number the scores are divided by before the softmax; small sharpens, large flattens
QK-normNormalising 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