Math Mapgenerated 2026-10-25 · a354234
PUBLIC BUILD

Grokking, From the Characters Up

A self-contained course for the Map of Math project: why small neural networks trained on finite algebra rediscover representation theory, math first. Prerequisites: group basics (§3 of elliptic-curves.md); the Legendre symbol is met again from quadratic-reciprocity.md. Canonical connections graph: the map’s lens files.


How this doc fits the map

This is the study side of the training-dynamics track (R26_training_dynamics/). Every chapter ends in a lab, and every lab is a real record in the repo. A lab is either a scored run, which you read against the chapter, or an open probe, which the chapter prepares you to seal. The course does not score anything. Where a chapter and a record disagree, the record wins and the chapter is fixed.

ch subject lab record state (2026-09-28)
1 Characters: the Fourier basis of a finite group run 037, multiplicative characters mod 113 scored, confirmed
2 Networks from scratch: perceptron, MLP, backpropagation by hand a tiny network on Z/7 addition — exercise, no record yet no record yet
3 Embeddings and attention: the one-layer transformer, piece by piece 037’s control arm (a + b mod 113) scored with 037
4 Training dynamics: gradient descent, weight decay, plateaus as singular values, the edge of stability P-027 (staircase as spectral readout), P-028 (edge of stability); animations/learning-curves.html open
5 Grokking: memorization against circuit; watching the circuit form before the jump run 037’s loss curves and grokking steps scored
6 Product groups: the Chinese Remainder Theorem inside an embedding P-031 (units of Z/561); P-030 (pseudoprimes as error fingerprint; 561 is the first Carmichael number) open
7 Non-abelian groups: irreducible representations and S5 grok.table_task takes S5’s 120 × 120 table; no probe yet none
8 Curves as spectra: double descent, scaling laws, which learning curves read out an eigenvalue P-029 (double descent), P-035 (curve shapes); animations/learning-curves.html open

How to use a chapter: read one section, then do its exercises by hand before moving on. The calculations are kept small on purpose, because the pattern is the point.


Chapter 1 — Characters: How a Finite Group Hears Itself

1.1 The clock and its waves

A character of ℤ/n\mathbb{Z}/n is a way of placing the clock onto the unit circle that respects addition. There are exactly nn of them, and that one fact is the whole engine of this course.

Start with the clock ℤ/n={0,1,…,n−1}\mathbb{Z}/n = \{0, 1, \dots, n-1\}, added mod nn. Write ω=e2πi/n\omega = e^{2\pi i/n} for the first nn-th root of unity.

Definition. A character of ℤ/n\mathbb{Z}/n is a map χ\chi from ℤ/n\mathbb{Z}/n to the nonzero complex numbers with

χ(a+b)=χ(a)χ(b)for all a,b∈ℤ/n.\chi(a+b) = \chi(a)\,\chi(b) \quad \text{for all } a, b \in \mathbb{Z}/n.

Theorem 1.1. The characters of ℤ/n\mathbb{Z}/n are exactly the nn maps

χk(a)=ωka=e2πika/n,k=0,1,…,n−1.\chi_k(a) = \omega^{ka} = e^{2\pi i k a / n}, \qquad k = 0, 1, \dots, n-1.

Proof. A character is fixed by its value on 1, since χ(a)=χ(1)a\chi(a) = \chi(1)^a. Also χ(1)n=χ(n)=χ(0)=1\chi(1)^n = \chi(n) = \chi(0) = 1, so χ(1)\chi(1) is an nn-th root of unity, one of ω0,…,ωn−1\omega^0, \dots, \omega^{n-1}. Each choice gives a character (Exercise 4). ∎

Picture χk\chi_k as a hand that moves kk notches around the circle for every tick of the clock. χ0\chi_0 never moves. χ1\chi_1 goes round once as aa runs from 00 to n−1n-1, and χk\chi_k goes round kk times. The number kk is the frequency, the same word as in music.

The real form. A network stores real numbers, not complex ones. Splitting ωka\omega^{ka} into its real and imaginary parts gives the pair

(cos⁡(2πka/n),sin⁡(2πka/n)).\bigl(\cos(2\pi k a/n),\ \sin(2\pi k a/n)\bigr).

So “the network learned frequency kk” means that two coordinates somewhere in its embedding of the token aa hold this pair. Section 1.6 puts that sentence to work.

1.2 Orthogonality and the Fourier transform

Distinct characters are orthogonal, so any function on the clock splits into frequencies in exactly one way. That split is the discrete Fourier transform.

Theorem 1.2 (orthogonality).

1n∑a=0n−1χj(a)χk(a)¯={1j=k0j≠k\frac{1}{n}\sum_{a=0}^{n-1} \chi_j(a)\,\overline{\chi_k(a)} = \begin{cases} 1 & j = k \\ 0 & j \neq k \end{cases}

Proof. The sum is ∑aza\sum_a z^a with z=ωj−kz = \omega^{j-k}. If j=kj = k then z=1z = 1 and the sum is nn. Otherwise z≠1z \neq 1 but zn=1z^n = 1, and the geometric series gives (zn−1)/(z−1)=0(z^n - 1)/(z - 1) = 0. ∎

So the nn characters form an orthonormal basis for functions on ℤ/n\mathbb{Z}/n. The coordinates of ff in that basis are its Fourier coefficients:

f̂(k)=1n∑af(a)χk(a)¯,f(a)=∑kf̂(k)χk(a).\hat f(k) = \frac{1}{n}\sum_{a} f(a)\,\overline{\chi_k(a)}, \qquad f(a) = \sum_{k} \hat f(k)\,\chi_k(a).

The energy is shared out exactly (Parseval):

∑k|f̂(k)|2=1n∑a|f(a)|2.\sum_k |\hat f(k)|^2 = \frac{1}{n}\sum_a |f(a)|^2.

Worked by hand: n = 5

Take f=(1,1,0,0,0)f = (1, 1, 0, 0, 0), a bump on the first two hours. Then f̂(k)=(1+ω−k)/5\hat f(k) = (1 + \omega^{-k})/5, and since |1+eiθ|=2|cos⁡(θ/2)||1 + e^{i\theta}| = 2|\cos(\theta/2)|,

|f̂(k)|=25|cos⁡(πk/5)|.|\hat f(k)| = \tfrac{2}{5}\,\bigl|\cos(\pi k/5)\bigr|.

kk cos⁡(πk/5)\cos(\pi k/5) |f̂(k)|\lvert\hat f(k)\rvert squared
0 1 0.4000 0.1600
1 0.8090 0.3236 0.1047
2 0.3090 0.1236 0.0153
3 −0.3090 0.1236 0.0153
4 −0.8090 0.3236 0.1047

The squares sum to 0.4000, and the right side of Parseval is 2/5=0.42/5 = 0.4. It balances.

Notice two things: - The mass sits at low frequency, because a bump two hours wide is smooth on a five-hour clock. - kk and n−kn - k have the same size, because ff is real. Frequency kk and frequency −k-k are the cos/sin pair of Section 1.1 seen twice.

Every real embedding in this course has that symmetry. That is why run 037 folds frequencies into conjugate-pair bins, {k,n−k}\{k, n-k\}, and counts 56 of them.

1.3 Why characters diagonalize addition

In the character basis, adding two clock readings becomes multiplying two numbers on the circle. A network that learns characters has turned a lookup table into one multiplication and one comparison.

Convolution. For functions on ℤ/n\mathbb{Z}/n, define (f*g)(c)=∑af(a)g(c−a)(f * g)(c) = \sum_a f(a)\, g(c - a). With the normalization of Section 1.2,

f*ĝ(k)=nf̂(k)ĝ(k).\widehat{f * g}(k) = n\,\hat f(k)\,\hat g(k).

Proof. Expand the sum, substitute b=c−ab = c - a, and use χk(a+b)=χk(a)χk(b)\chi_k(a + b) = \chi_k(a)\chi_k(b) to split the double sum into a product. ∎

Here is why this matters. The answer to “a+ba + b” is the point mass at a+ba + b, which is the convolution of the point masses at aa and at bb. So the Fourier transform turns the addition table into pointwise multiplication, one frequency at a time. That is what “diagonalize” means.

The angle-addition trick. Suppose a network holds the cos and sin of 2πka/n2\pi ka/n for its input aa, and the same for bb. It can then form

cos⁡2πk(a+b)n=cos⁡2πkancos⁡2πkbn−sin⁡2πkansin⁡2πkbn,\cos\frac{2\pi k(a+b)}{n} = \cos\frac{2\pi k a}{n}\cos\frac{2\pi k b}{n} - \sin\frac{2\pi k a}{n}\sin\frac{2\pi k b}{n},

and likewise the sine. This is χk(a)χk(b)=χk(a+b)\chi_k(a)\chi_k(b) = \chi_k(a + b) written in real numbers. It needs products of inputs, and those come from the nonlinear layer; Chapter 2 shows how.

The readout: interference. To pick the answer cc, score every candidate by how well it lines up with a+ba + b, summed over a few frequencies k1,…,kKk_1, \dots, k_K:

logit(c)=∑i=1Kcos⁡2πki(a+b−c)n.\text{logit}(c) = \sum_{i=1}^{K} \cos\frac{2\pi k_i\,(a+b-c)}{n}.

At c=a+bc = a + b every term is 1, so the score is KK. Anywhere else the cosines point in different directions and partly cancel. One frequency gives a correct but blunt peak, with near neighbours scoring almost as high. Several frequencies interfere until one spike stands alone. Exercise 5 finds a case where the cancellation is perfect. The explorer in animations/learning-curves.html draws exactly this sum.

1.4 The other clock: multiplication

The nonzero residues mod a prime pp form a second clock, with p−1p - 1 hours, and multiplication runs it. Its characters are the Dirichlet characters. They are periodic in a different coordinate, the discrete log.

Theorem 1.3. For pp prime, the group (ℤ/p)×(\mathbb{Z}/p)^\times of nonzero residues under multiplication is cyclic of order p−1p - 1.

Proof sketch. A polynomial of degree dd has at most dd roots mod pp, so for every dd dividing p−1p - 1, at most dd elements satisfy xd=1x^d = 1. A counting argument over element orders then forces an element of order exactly p−1p - 1. ∎

An element gg of order p−1p - 1 is a primitive root. Every nonzero aa is a power of gg, a=gja = g^j. The exponent j=ind⁡g(a)j = \operatorname{ind}_g(a) is the discrete log of aa, defined mod p−1p - 1. The key identity is

ind⁡g(ab)=ind⁡g(a)+ind⁡g(b)(modp−1).\operatorname{ind}_g(ab) = \operatorname{ind}_g(a) + \operatorname{ind}_g(b) \;(\mathrm{mod}\;p-1).

The discrete log turns the multiplicative clock into the additive clock ℤ/(p−1)\mathbb{Z}/(p - 1), and everything in Sections 1.1 to 1.3 then carries over.

Worked by hand: p = 7, g = 3

The powers of 3 mod 7 are 30=13^0 = 1, 31=33^1 = 3, 32=23^2 = 2, 33=63^3 = 6, 34=43^4 = 4, 35=53^5 = 5, and 36=13^6 = 1 closes the loop.

aa 1 2 3 4 5 6
ind⁡3(a)\operatorname{ind}_3(a) 0 2 1 4 5 3

Check: 2×4=8=12 \times 4 = 8 = 1 mod 7, and ind⁡2+ind⁡4=6=0\operatorname{ind} 2 + \operatorname{ind} 4 = 6 = 0 mod 6, which is ind⁡1\operatorname{ind} 1. It works.

Read the table in ordinary order and the logs jump around: 0, 2, 1, 4, 5, 3. That scrambling is the whole difficulty. A pattern that is periodic in the log looks like noise when you list a=1,2,3,…a = 1, 2, 3, \dots

Dirichlet characters. The characters of (ℤ/p)×(\mathbb{Z}/p)^\times are

χk(a)=e2πikind⁡g(a)/(p−1),k=0,…,p−2.\chi_k(a) = e^{2\pi i\,k\,\operatorname{ind}_g(a)/(p-1)}, \qquad k = 0, \dots, p-2.

The order of χk\chi_k is (p−1)/gcd⁡(k,p−1)(p - 1)/\gcd(k, p - 1). Changing the primitive root multiplies every frequency kk by a unit mod p−1p - 1. That relabels the characters but leaves each order unchanged.

The Legendre symbol lives here. Take k=(p−1)/2k = (p - 1)/2. Then χ(a)=(−1)ind⁡a\chi(a) = (-1)^{\operatorname{ind} a}, which is +1+1 exactly when aa is a square mod pp. For p=7p = 7 the squares are 1, 2 and 4, and their logs 0, 2 and 4 are the even ones. This is the only character of order 2, and it does not depend on the choice of gg. Quadratic reciprocity is a theorem about this one character (see quadratic-reciprocity.md).

1.5 When the clocks meet: Gauss sums

Look at a nontrivial multiplicative character through additive eyes, on ℤ/p\mathbb{Z}/p, and it is spread perfectly evenly over all nonzero frequencies. The two clocks are as incompatible as two bases can be, and one short proof shows it.

The residues mod pp carry both clocks at once: addition on all of ℤ/p\mathbb{Z}/p, and multiplication on the nonzero part. The Gauss sum of a multiplicative character χ\chi pairs it against the first additive character:

τ(χ)=∑a=1p−1χ(a)e2πia/p.\tau(\chi) = \sum_{a=1}^{p-1} \chi(a)\, e^{2\pi i a/p}.

Theorem 1.4. If χ\chi is not the trivial character, then |τ(χ)|=p|\tau(\chi)| = \sqrt p.

Proof. Expand |τ|2|\tau|^2 as a double sum over aa and bb, and substitute a=bca = bc (as aa runs over the nonzero residues, so does cc):

|τ|2=∑b∑cχ(c)e2πib(c−1)/p=∑cχ(c)∑b=1p−1e2πib(c−1)/p.|\tau|^2 = \sum_{b}\sum_{c} \chi(c)\, e^{2\pi i\, b(c-1)/p} = \sum_{c} \chi(c) \sum_{b=1}^{p-1} e^{2\pi i\, b(c-1)/p}.

The inner sum is p−1p - 1 when c=1c = 1 and −1-1 otherwise, because the full sum over all bb, including 00, vanishes. So |τ|2=(p−1)−∑c≠1χ(c)|\tau|^2 = (p - 1) - \sum_{c\neq1} \chi(c). The values of a nontrivial character sum to zero over the group (Theorem 1.2 with j=0j = 0), so ∑c≠1χ(c)=−χ(1)=−1\sum_{c\neq1} \chi(c) = -\chi(1) = -1. That leaves |τ|2=p|\tau|^2 = p. ∎

What it means. Replace e2πia/pe^{2\pi ia/p} by e2πika/pe^{2\pi ika/p} for any k≠0k \neq 0 and you get χ(k)¯τ(χ)\overline{\chi(k)}\,\tau(\chi), which has the same size p\sqrt p. So extend χ\chi to all of ℤ/p\mathbb{Z}/p by setting χ(0)=0\chi(0) = 0. Its Fourier transform, taken at length pp, then has exactly equal magnitude at every nonzero frequency and zero at frequency 0. Additive analysis sees none of the multiplicative structure; all it sees is perfect flatness.

Worked by hand: p = 5, the Legendre symbol

The squares mod 5 are 1 and 4, so χ=(+1,−1,−1,+1)\chi = (+1, -1, -1, +1) on a=1,2,3,4a = 1, 2, 3, 4. With ζ=e2πi/5\zeta = e^{2\pi i/5},

τ=ζ−ζ2−ζ3+ζ4=2cos⁡72∘−2cos⁡144∘.\tau = \zeta - \zeta^2 - \zeta^3 + \zeta^4 = 2\cos 72^\circ - 2\cos 144^\circ.

Now 2cos⁡72∘=0.6182\cos 72^\circ = 0.618 and −2cos⁡144∘=1.618-2\cos 144^\circ = 1.618, which are φ−1\varphi - 1 and φ\varphi, where φ\varphi is the golden ratio. The sum is 2φ−1=2.236=52\varphi - 1 = 2.236 = \sqrt 5. The theorem and the pentagon’s golden ratio appear in a single line.

The fine print, which matters in the lab. Theorem 1.4 describes the length-pp transform over ℤ/p\mathbb{Z}/p, with the zero slot included. A network trained on a×ba \times b has tokens only for 1,…,p−11, \dots, p-1. Run 037 therefore read those tokens with a length-(p−1)(p-1) transform in ordinary order. That transform is not the character transform of any group law on the tokens, so the theorem says nothing exact about it. Section 1.6 shows what the difference costs.

1.6 Lab: what a network found

The record is lab/runs/037-grokking-multiplicative-characters.md, scored confirmed on 2026-09-28. Run 037 trained a one-layer transformer on a×ba \times b mod 113 and found Dirichlet characters in the discrete-log coordinate of Section 1.4.

The setup: - Two tasks, three seeds each. The control is a+ba + b mod 113, which should reproduce the published additive result (Nanda et al. 2023, as cited in the record). The main task is a×ba \times b on the 112 nonzero residues. - The network and training. One layer, 4 heads, dmodel=128d_\text{model} = 128. It trained on 30% of the table, with weight decay 1.0, AdamW and full batch. - Every seed grokked. On the multiplicative task, test accuracy reached 0.99 at steps 10,900, 12,300 and 23,200, long after training accuracy did (step 200). - The measurement. The analysis took each learned embedding and measured the share of its non-DC power in the top 10 of 56 conjugate-pair bins, in two orderings: ordinary (a=1,2,3,…a = 1, 2, 3, \dots) and discrete log (primitive root g=3g = 3).

Task and ordering Transform Top-10 share Section that explains it
Addition, ordinary order length 113 0.956 to 0.966 (3 seeds) 1.3: characters of ℤ/113\mathbb{Z}/113
Multiplication, discrete-log order length 112 0.949 to 0.970 (3 seeds) 1.4: Dirichlet characters
Multiplication, ordinary order length 112 0.231 to 0.270 (3 seeds) 1.4: the scrambling (see below)
Gaussian noise (floor) either 0.202 none
Reference: one exact Dirichlet character, ordinary order length 112 0.344 (mean over kk) 1.4
Reference: span of three characters, ordinary order length 112 0.275 (range 0.239–0.301) 1.4
Reference: one exact character, zero slot added length 113 0.179 exactly =10/56= 10/56 1.5: Gauss sums

Read the table with the chapter in hand: - Addition. The addition network is the angle-addition circuit of Section 1.3: a handful of frequencies carry nearly all of its structure. - Multiplication in discrete-log order. The multiplication network is the same circuit after the change of coordinates in Section 1.4. The tokens arrive in ordinary order, so it could not have seen the discrete log directly; it built that coordinate itself. - Multiplication in ordinary order. It reads almost like noise, but not quite (1.14–1.34× the floor). The reference rows say why. The record’s post-hoc reference, which is not part of the sealed test, reads a perfect multiplicative embedding under the same length-112 transform. One character reads 0.344 and a three-character span 0.275, both above the noise floor. A character indexed by value and transformed additively is a mismatched-coordinate object, not a structureless one. The trained seeds sit inside or just below the three-character range. - Where Gauss sums apply. Only the last row is Section 1.5’s theorem. Add the zero slot and transform at length 113, and a single character comes out exactly flat, at 10/56=0.17910/56 = 0.179. That is lower than noise, because a flat spectrum has none of the order-statistic surplus that noise has.

Loose threads, recorded in 037 as unsealed observations and not part of the verdict: - The Legendre symbol (frequency 56, order 2) carried 11% of the power in one seed and almost none in the other two. The seeds show no stable preference. - Character order. There was no preference for low-order characters: full-order characters took 53 to 66% of the power in every seed. - Odd characters. All three seeds leaned toward odd characters, those with χ(−1)=−1\chi(-1) = -1, by growing margins (odd share 0.536, 0.661, 0.763; noise gives 0.505). Since −1=g56-1 = g^{56}, a character is odd exactly when its frequency kk is odd. Nobody has explained this yet.

That last thread is an open question with your name on it (Exercise 11).

Exercises

One star is routine, two stars need an idea, and three stars are proofs to rebuild without looking. Do the hand exercises with a pencil and a table of cosines; that is where the patterns stick.

  1. ★ Write the 4 × 4 character table of ℤ/4\mathbb{Z}/4 (its entries are 1,i,−1,−i1, i, -1, -i). Check by hand that rows 1 and 3 are orthogonal.
  2. ★ Redo the n=5n = 5 computation of Section 1.2 for f=(1,0,1,0,0)f = (1, 0, 1, 0, 0). Where does the mass sit now, and why? Check Parseval.
  3. ★ Find the smallest primitive root mod 11 and build its discrete-log table. Circle the squares mod 11 and confirm that their logs are the even ones.
  4. ★★ Fill in the “each choice works” step of Theorem 1.1: show that χ(a)=ζa\chi(a) = \zeta^a is well defined on ℤ/n\mathbb{Z}/n when ζn=1\zeta^n = 1.
  5. ★★ The perfect-interference exercise. On ℤ/7\mathbb{Z}/7, compute logit(d)=∑cos⁡(2πkd/7)\text{logit}(d) = \sum \cos(2\pi k d/7) for d=0,…,6d = 0, \dots, 6 with the frequencies {1}\{1\}, then {1,3}\{1, 3\}, then {1,2,3}\{1, 2, 3\}. Record the margin between d=0d = 0 and the best wrong answer each time. The last case has a surprise; explain it with Theorem 1.2.
  6. ★★ Compute the Gauss sum of the Legendre symbol mod 3 exactly, then mod 7. In the second case, show τ2=−7\tau^2 = -7 without using decimals.
  7. ★★ Prove that the order of a Dirichlet character does not depend on the primitive root chosen, and that the Legendre symbol’s frequency (p−1)/2(p - 1)/2 never moves.
  8. ★★★ Rebuild the proof of Theorem 1.4 from memory.
  9. ★★★ Using χ(−1)\chi(-1), show that the quadratic Gauss sum is real when p≡1p \equiv 1 mod 4 and purely imaginary when p≡3p \equiv 3 mod 4. (Which sign it has is a different, famous story: it took Gauss years.)
  10. Computational. Plot the Legendre symbol mod 113 twice: in ordinary order, then in discrete-log order with g=3g = 3. Describe each picture in one sentence. Take the top-10 share of each under a length-112 transform. Then take it again under a length-113 transform with the zero slot added, and compare all four numbers with the table in Section 1.6. (grok.analyse in R26_training_dynamics/ does the reading.)
  11. Computational, open. Run 037’s seeds leaned toward odd characters. Propose one reason why a network trained on a×ba \times b mod 113 might prefer χ(−1)=−1\chi(-1) = -1, and one experiment that would test it. If the experiment is worth running, it becomes a probe in the training-dynamics block, with a sealed prediction written before any compute.

Hints. - (3) Try 2, and check that its order is 10, not 2 or 5. - (5) With the frequencies {1,2,3}\{1, 2, 3\}, add the conjugates 4, 5 and 6 and use orthogonality. - (6) Mod 3 the answer is i3i\sqrt3. - (9) Conjugate τ\tau and substitute a→−aa \to -a. - (10) The length-113 reading of the Legendre symbol should come out at exactly 10/5610/56. Why?

Summary and bridge to Chapter 2

A finite cyclic group has exactly as many characters as elements. They are orthogonal, and in their basis the group operation becomes multiplication on the circle.

Next. This chapter assumed a network can multiply two cosines. Chapter 2 builds that ability from nothing: a perceptron, then a two-layer network, then backpropagation worked by hand on a 3-neuron example. Its lab trains a tiny network on ℤ/7\mathbb{Z}/7 addition, small enough to read its weights directly, and asks whether the character table of ℤ/7\mathbb{Z}/7 appears in them.


Chapter 2 — Networks From Scratch: How a Nonlinearity Multiplies

A linear unit can add its inputs but cannot multiply them, and Chapter 1 showed that a group law, read in characters, is multiplication. This chapter builds the missing piece: a hidden layer with a nonlinearity, trained by backpropagation, which you will run once by hand.

2.1 The perceptron

A perceptron takes inputs x∈ℝdx \in \mathbb{R}^d, weights w∈ℝdw \in \mathbb{R}^d and a bias bb, and outputs

y={1w⋅x+b≥00otherwise.y = \begin{cases} 1 & w \cdot x + b \ge 0 \\ 0 & \text{otherwise.} \end{cases}

The set w⋅x+b=0w \cdot x + b = 0 is a hyperplane, and the perceptron answers one question: which side of it is xx on? A task is linearly separable when some hyperplane puts all the 1s on one side and all the 0s on the other.

The learning rule. Show the perceptron a labelled example (x,t)(x, t). If it answers correctly, do nothing. If it is wrong, move the hyperplane toward the right answer:

w←w+(t−y)x,b←b+(t−y).w \leftarrow w + (t - y)\,x, \qquad b \leftarrow b + (t - y).

On linearly separable data this rule stops after finitely many mistakes. (Exercise 1 runs it by hand on AND. The perceptron is due to Rosenblatt, 1958; citation unverified.)

Theorem 2.1. No perceptron computes XOR on {0,1}2\{0,1\}^2.

Proof. Suppose one did. Then (0,0)↦0(0,0) \mapsto 0 gives b<0b < 0. The inputs (1,0)(1,0) and (0,1)(0,1) give w1+b≥0w_1 + b \ge 0 and w2+b≥0w_2 + b \ge 0; adding them, w1+w2+b≥−b>0w_1 + w_2 + b \ge -b > 0. But (1,1)↦0(1,1) \mapsto 0 needs w1+w2+b<0w_1 + w_2 + b < 0. Contradiction. ∎

2.2 XOR is addition mod 2, and addition mod 2 is a product

XOR is not an arbitrary hard example. It is the group law of ℤ/2\mathbb{Z}/2: a⊕b=a+bmod⁡2a \oplus b = a + b \bmod 2.

Now read it in characters, as in Chapter 1. ℤ/2\mathbb{Z}/2 has two characters, and the nontrivial one is s(a)=(−1)as(a) = (-1)^a, sending 0↦+10 \mapsto +1 and 1↦−11 \mapsto -1. Section 1.3 says the group law becomes multiplication:

s(a+b)=s(a)s(b).s(a + b) = s(a)\, s(b).

So in the ±1\pm 1 encoding, XOR is the product sasbs_a s_b. Theorem 2.1 says a linear unit cannot compute it, and here is a sharper reason.

Theorem 2.2. On the four inputs (sa,sb)∈{±1}2(s_a, s_b) \in \{\pm1\}^2, the functions 11, sas_a, sbs_b and sasbs_a s_b are orthogonal. So the best linear fit to XOR, in least squares, is the zero function.

Proof. These four functions are the characters of ℤ/2×ℤ/2\mathbb{Z}/2 \times \mathbb{Z}/2, and characters of a finite abelian group are orthogonal (Theorem 1.2 applied coordinate by coordinate). Least squares projects sasbs_a s_b onto the span of 1,sa,sb1, s_a, s_b, and that projection is zero. ∎

A linear unit is not just unable to get XOR right. It cannot see XOR at all: every weight it could learn has zero correlation with the target. Multiplication has to come from somewhere else.

2.3 Two layers

Add a hidden layer: several units, each computing z=w⋅x+bz = w \cdot x + b and passing it through a nonlinear activation σ\sigma. The output is a linear combination of the hidden values. This chapter uses the ReLU,

ReLU⁡(z)=max⁡(0,z).\operatorname{ReLU}(z) = \max(0, z).

XOR with two hidden units, on {0,1}2\{0,1\}^2:

h1=ReLU⁡(x1+x2),h2=ReLU⁡(x1+x2−1),y=h1−2h2.h_1 = \operatorname{ReLU}(x_1 + x_2), \quad h_2 = \operatorname{ReLU}(x_1 + x_2 - 1), \quad y = h_1 - 2h_2.

(x1,x2)(x_1, x_2) h1h_1 h2h_2 yy
(0, 0) 0 0 0
(1, 0) 1 0 1
(0, 1) 1 0 1
(1, 1) 2 1 0

The second unit switches on only when both inputs are on, and subtracts exactly enough. A sum of ReLUs is a piecewise-linear function; each unit contributes one bend. That is all a one-hidden-layer ReLU network is (Exercise 8).

2.4 How a nonlinearity multiplies

Products come from squares. The polarization identity is

xy=14((x+y)2−(x−y)2).xy = \tfrac{1}{4}\bigl((x+y)^2 - (x-y)^2\bigr).

So two hidden units with activation σ(z)=z2\sigma(z) = z^2, one fed x+yx + y and one fed x−yx - y, compute the product exactly. A ReLU is not a square, but it can make one well enough where it is needed.

In the ±1\pm1 encoding it is exact. Since s2=1s^2 = 1, (sa+sb)2=2+2sasb(s_a + s_b)^2 = 2 + 2 s_a s_b, and |sa+sb||s_a + s_b| is 2 or 0. So

sasb=|sa+sb|−1,|u|=ReLU⁡(u)+ReLU⁡(−u).s_a s_b = |s_a + s_b| - 1, \qquad |u| = \operatorname{ReLU}(u) + \operatorname{ReLU}(-u).

Two ReLU units compute the character product of Section 2.2 exactly. Check all four inputs by hand; it takes a minute.

Back to Chapter 1. For ℤ/n\mathbb{Z}/n, the angle-addition trick of Section 1.3 needs products like cos⁡αcos⁡β\cos\alpha \cos\beta. The product-to-sum identity

cos⁡αcos⁡β=12(cos⁡(α−β)+cos⁡(α+β))\cos\alpha\cos\beta = \tfrac{1}{2}\bigl(\cos(\alpha - \beta) + \cos(\alpha + \beta)\bigr)

and polarization say the same thing: a layer that can square can multiply. That is the job the nonlinear layer does in a network that adds on a clock. Nanda et al. (arXiv:2301.05217) reverse-engineered a trained transformer and found it computing modular addition with discrete Fourier transforms and trigonometric identities. Chapter 3 finds where in the network each step happens.

2.5 Loss and gradient descent

A network with parameters θ\theta produces an output y(x;θ)y(x; \theta). A loss LL measures how wrong that output is. This chapter uses the squared loss for one example with target tt:

L=12(y−t)2.L = \tfrac{1}{2}(y - t)^2.

(Classification over nn answers uses softmax and cross-entropy instead; Chapter 3 introduces them.)

Gradient descent moves every parameter a small step downhill:

θ←θ−η∂L∂θ,\theta \leftarrow \theta - \eta\, \frac{\partial L}{\partial \theta},

where η\eta is the learning rate. Near a point, the loss changes by about −η‖∇L‖2-\eta \lVert \nabla L \rVert^2 per step. That estimate is only first-order. When the step is large, the curvature of the loss takes over, and Chapter 4 is about what happens then.

The only hard part is computing ∂L/∂θ\partial L / \partial \theta for every weight at once. Backpropagation is the chain rule, organized so that each quantity is computed once (Rumelhart, Hinton and Williams, Nature 323, 533–536, 1986, DOI 10.1038/323533a0).

2.6 Backpropagation by hand: a 3-neuron network

Two hidden ReLU units and one linear output: three neurons. Do this section with a pencil. Every number is chosen to stay exact.

The network.

z1=w11x1+w12x2+b1,z2=w21x1+w22x2+b2,z_1 = w_{11}x_1 + w_{12}x_2 + b_1, \quad z_2 = w_{21}x_1 + w_{22}x_2 + b_2, hi=ReLU⁡(zi),y=v1h1+v2h2+c,L=12(y−t)2.h_i = \operatorname{ReLU}(z_i), \quad y = v_1 h_1 + v_2 h_2 + c, \quad L = \tfrac12 (y - t)^2.

Starting weights: w11=0.5w_{11} = 0.5, w12=−0.5w_{12} = -0.5, b1=0b_1 = 0; w21=1w_{21} = 1, w22=1w_{22} = 1, b2=−0.5b_2 = -0.5; v1=1v_1 = 1, v2=−1v_2 = -1, c=0c = 0.

The example: the XOR input x=(1,0)x = (1, 0) with target t=1t = 1.

Forward pass

quantity computation value
z1z_1 0.5⋅1−0.5⋅0+00.5 \cdot 1 - 0.5 \cdot 0 + 0 0.5
h1h_1 ReLU⁡(0.5)\operatorname{ReLU}(0.5) 0.5
z2z_2 1⋅1+1⋅0−0.51 \cdot 1 + 1 \cdot 0 - 0.5 0.5
h2h_2 ReLU⁡(0.5)\operatorname{ReLU}(0.5) 0.5
yy 1⋅0.5−1⋅0.5+01 \cdot 0.5 - 1 \cdot 0.5 + 0 0
LL 12(0−1)2\tfrac12 (0 - 1)^2 0.5

Backward pass

Write δq=∂L/∂q\delta_q = \partial L / \partial q. Start at the loss and walk back, reusing each δ\delta once it is known.

step rule value
δy\delta_y y−ty - t −1
δv1,δv2\delta_{v_1}, \delta_{v_2} δyh1,δyh2\delta_y h_1,\ \delta_y h_2 −0.5, −0.5
δc\delta_c δy\delta_y −1
δh1,δh2\delta_{h_1}, \delta_{h_2} δyv1,δyv2\delta_y v_1,\ \delta_y v_2 −1, +1
δz1,δz2\delta_{z_1}, \delta_{z_2} δhi⋅ReLU⁡′(zi)\delta_{h_i} \cdot \operatorname{ReLU}'(z_i), both zi>0z_i > 0 −1, +1
δw11,δw12,δb1\delta_{w_{11}}, \delta_{w_{12}}, \delta_{b_1} δz1x1,δz1x2,δz1\delta_{z_1} x_1,\ \delta_{z_1} x_2,\ \delta_{z_1} −1, 0, −1
δw21,δw22,δb2\delta_{w_{21}}, \delta_{w_{22}}, \delta_{b_2} δz2x1,δz2x2,δz2\delta_{z_2} x_1,\ \delta_{z_2} x_2,\ \delta_{z_2} +1, 0, +1

Notice that δw12=δw22=0\delta_{w_{12}} = \delta_{w_{22}} = 0: an input that is off carries no blame.

One step, then check

Take η=0.1\eta = 0.1. The new weights are v1=1.05v_1 = 1.05, v2=−0.95v_2 = -0.95, c=0.1c = 0.1, w11=0.6w_{11} = 0.6, b1=0.1b_1 = 0.1, w21=0.9w_{21} = 0.9 and b2=−0.6b_2 = -0.6; w12w_{12} and w22w_{22} are unchanged. Run the forward pass again:

z1=0.7,h1=0.7;z2=0.3,h2=0.3;y=1.05(0.7)−0.95(0.3)+0.1=0.55.z_1 = 0.7,\ h_1 = 0.7; \quad z_2 = 0.3,\ h_2 = 0.3; \quad y = 1.05(0.7) - 0.95(0.3) + 0.1 = 0.55.

The loss falls from 0.50.5 to 12(0.45)2=0.10125\tfrac12(0.45)^2 = 0.10125.

Compare the first-order prediction. The squared gradient sums to 0.25+0.25+1+1+0+1+1+0+1=5.50.25 + 0.25 + 1 + 1 + 0 + 1 + 1 + 0 + 1 = 5.5, so the prediction is a drop of η⋅5.5=0.55\eta \cdot 5.5 = 0.55. That is more than the whole loss of 0.5. The actual drop is 0.399. A step this large leaves the region where the linear estimate holds, a first taste of Chapter 4.

The general rule

For a layer with pre-activations z(ℓ)z^{(\ell)}, weights W(ℓ)W^{(\ell)} and activation σ\sigma,

δz(ℓ)=(W(ℓ+1)⊤δz(ℓ+1))⊙σ′(z(ℓ)),∂L∂W(ℓ)=δz(ℓ)h(ℓ−1)⊤.\delta_{z^{(\ell)}} = \bigl(W^{(\ell+1)\top}\, \delta_{z^{(\ell+1)}}\bigr) \odot \sigma'\bigl(z^{(\ell)}\bigr), \qquad \frac{\partial L}{\partial W^{(\ell)}} = \delta_{z^{(\ell)}}\, h^{(\ell-1)\top}.

The table above is this rule with one hidden layer and every sum written out.

2.7 Lab: a tiny network on ℤ/7\mathbb{Z}/7 addition

No record exists for this lab. It is an exercise until someone seals it as a run, and this chapter makes no prediction about its outcome.

The network. Encode aa and bb as one-hot vectors in ℝ7\mathbb{R}^7 and concatenate them (14 inputs). Use one hidden ReLU layer and 7 output logits, trained with cross-entropy (Chapter 3) and weight decay, on part of the 49-entry table. Small is the point: the first-layer weights split into two blocks of 7 columns, one per input token, and you can print them on one page.

Reading the weights. Take the block for input aa. Each hidden unit has a row of 7 numbers, one per token. Take that row’s length-7 DFT over the token index a=0,…,6a = 0, \dots, 6. Because the row is real, fold the frequencies into the DC term and three conjugate-pair bins, {1,6}\{1, 6\}, {2,5}\{2, 5\} and {3,4}\{3, 4\}, exactly as run 037 did at length 113.

Questions this lab asks, open: - Does the table get learned at all from a fraction of 49 examples, and does test accuracy jump late, as in run 037? - After training, how is each hidden unit’s power spread over the three bins? - Do the hidden units for input aa and for input bb use the same bins? - How do the answers change with the hidden width and the weight decay?

A hand warm-up comes first (Exercise 9): identify the frequency of a given row of 7 numbers using nothing but three inner products.

Exercises

  1. ★ Run the perceptron rule by hand on AND, starting from w=(0,0)w = (0, 0), b=0b = 0, cycling through the four inputs in order. How many mistakes does it make before it stops?
  2. ★ Redo the proof of Theorem 2.1 for the ±1\pm1 encoding: no w,bw, b give sign⁡(w⋅s+b)=sasb\operatorname{sign}(w \cdot s + b) = s_a s_b on all four inputs.
  3. ★ Verify sasb=ReLU⁡(sa+sb)+ReLU⁡(−sa−sb)−1s_a s_b = \operatorname{ReLU}(s_a + s_b) + \operatorname{ReLU}(-s_a - s_b) - 1 on all four inputs. Draw it as a network with two hidden units.
  4. ★★ Using polarization, build a network with square activations that computes cos⁡αcos⁡β\cos\alpha\cos\beta from inputs cos⁡α\cos\alpha and cos⁡β\cos\beta. How many hidden units does it need?
  5. ★★ Redo the backpropagation of Section 2.6 on the input (1,1)(1, 1) with target t=0t = 0, from the same starting weights. Which weights get no gradient, and why?
  6. ★★ The dead unit. Change b2b_2 to −2-2 and redo the forward and backward passes for x=(1,0)x = (1, 0). Show that no gradient reaches w21w_{21}, w22w_{22} or b2b_2. What does that mean for training?
  7. ★★ Derive the general rule of Section 2.6 from the chain rule, for one hidden layer written in matrices.
  8. ★★★ Show that every continuous piecewise-linear function ℝ→ℝ\mathbb{R} \to \mathbb{R} with finitely many breakpoints is c0+c1x+∑iaiReLU⁡(x−pi)c_0 + c_1 x + \sum_i a_i \operatorname{ReLU}(x - p_i). Deduce that one hidden layer of ReLUs represents it exactly.
  9. ★★ Frequency by hand. A hidden unit’s row over the tokens a=0,…,6a = 0, \dots, 6 is (1.000,−0.223,−0.901,0.623,0.623,−0.901,−0.223)(1.000, -0.223, -0.901, 0.623, 0.623, -0.901, -0.223). Take its inner product with cos⁡(2πka/7)\cos(2\pi k a/7) for k=1,2,3k = 1, 2, 3, and name the frequency. Why is no sine term needed?
  10. Computational. Check the gradients of Section 2.6 by finite differences: nudge each weight by ±10−4\pm 10^{-4} and compare (L+−L−)/(2⋅10−4)(L_+ - L_-)/(2 \cdot 10^{-4}) with the table.
  11. Computational, open. Build the lab network of Section 2.7 and read its weights as described. Record what you see; the questions there are open.

Hints. - (1) Only the input (1,1)(1, 1) has target 1, so the bias must end up negative. - (5) With x=(1,1)x = (1, 1) both inputs are on, so no input carries zero blame this time. Look at the signs. - (6) ReLU⁡′(z)=0\operatorname{ReLU}'(z) = 0 for z<0z < 0. - (9) Orthogonality (Theorem 1.2): only one inner product survives, and it equals 7/27/2.

Summary and bridge to Chapter 3

A linear unit adds; a group law in characters multiplies; a nonlinear hidden layer supplies the products.

Next. The lab encodes tokens as one-hot vectors and lets the first layer learn one column per token. That column is an embedding. Chapter 3 builds the one-layer transformer of run 037 piece by piece: embeddings, attention, the MLP, and the softmax readout. Its lab reads 037’s control arm, a+bmod⁡113a + b \bmod 113, through that anatomy.

References for Chapter 2


Chapter 3 — Embeddings and Attention: The One-Layer Transformer, Piece by Piece

A one-layer transformer that adds on a clock is Chapter 1’s circuit built from learned parts. The embedding writes each token onto circles. Attention and the MLP multiply those circles together, and the unembedding sums the interference of Section 1.3. This chapter builds each part and then says plainly which parts the repo has measured: so far, only the embedding.

Sources for this chapter. Everything said here about what the attention and MLP layers compute inside a trained network comes from Nanda et al. (arXiv:2301.05217), about their own trained models. Run 037 measured none of those layers. Section 3.6 lists what the repo has and has not measured.

3.1 Tokens, embeddings and the residual stream

The input is a sequence of three tokens, aa, bb and ==, each a one-hot vector. Position 3 is where the answer is read.

The embedding. A matrix WEW_E with one column per token value sends the one-hot vector of aa to that column, a vector in ℝd\mathbb{R}^d. This is exactly Chapter 2’s first-layer block: a one-hot input picks out one column of weights, and that column is the embedding. A learned positional embedding pip_i is added, so the network can tell the first slot from the second:

xi(0)=WEti+pi.x_i^{(0)} = W_E\, t_i + p_i.

The residual stream. Each later layer reads the current vector at a position and adds its output back. The running sum is called the residual stream. Nothing is overwritten; layers communicate by writing into shared coordinates.

What Chapter 1 predicts the embedding should hold. If the network uses the angle-addition circuit, the embedding of aa must contain the pairs (cos⁡(2πka/p),sin⁡(2πka/p))\bigl(\cos(2\pi k a/p), \sin(2\pi k a/p)\bigr) for a few frequencies kk. Nanda et al. report exactly this for their mainline model: a Fourier transform along the token index of WEW_E shows significant norm at 6 frequencies, of which 5, k∈{14,35,41,42,52}k \in \{14, 35, 41, 42, 52\}, are used later in the network. They call these the key frequencies.

3.2 Attention

Attention lets the vector at one position read from the vectors at other positions. A head has three learned maps: a query WQW_Q, a key WKW_K and a value WVW_V, plus an output map WOW_O. The position reading (here, ==) forms a query; every position offers a key and a value.

A=softmax⁡i((WKxi(0))⊤WQx3(0)),head output=WO∑iAiWVxi(0).A = \operatorname{softmax}_i\!\Bigl(\bigl(W_K x_i^{(0)}\bigr)^{\!\top} W_Q\, x_3^{(0)}\Bigr), \qquad \text{head output} = W_O \sum_i A_i\, W_V x_i^{(0)}.

The softmax (Section 3.5) turns scores into weights Ai≥0A_i \ge 0 that sum to 1. Several heads run side by side and their outputs are added into the residual stream. The architecture is from Vaswani et al. (arXiv:1706.03762).

Why attention can multiply. Look at what a head computes: a weight AiA_i, which depends on the tokens, times a value WVxiW_V x_i, which also depends on the tokens. That is a product of two token-dependent quantities, the very thing Chapter 2 said a linear layer cannot make. Attention is approximately bilinear, which is a second route to products, alongside the MLP’s nonlinearity.

What Nanda et al. found in their heads (their Appendices A.1 and C.1.2–C.1.3). Attention from == to itself was negligible, so each head’s softmax runs over just two positions, aa and bb. A softmax over two items is a sigmoid of their score difference, σ(C[a]−C[b])\sigma(C[a] - C[b]). The score CC was close to a single wave, C[a]≈Fcos⁡(wka)+Gsin⁡(wka)C[a] \approx F\cos(w_k a) + G\sin(w_k a), and the sigmoid operated in a nearly linear range. So each head’s weight is roughly 0.50.5 plus a single-frequency wave in aa minus the same wave in bb. Multiplied by a value that is itself a wave, this gives degree-2 polynomials in sines and cosines of one frequency. In their model, two heads did this; the other two mainly amplified the key frequencies already in the embedding.

3.3 The MLP

After attention, the vector at position 3 passes through an MLP: a wide linear map, a ReLU, and a linear map back.

MLP=ReLU⁡(Winx(1)),x(2)=WoutMLP+x(1).\text{MLP} = \operatorname{ReLU}\bigl(W_{\text{in}}\, x^{(1)}\bigr), \qquad x^{(2)} = W_{\text{out}}\, \text{MLP} + x^{(1)}.

This is Chapter 2’s two-layer network, applied at one position. Its job in the circuit is to finish the products that Section 1.3’s angle-addition formula needs, so that cos⁡(wk(a+b))\cos\bigl(w_k(a+b)\bigr) and sin⁡(wk(a+b))\sin\bigl(w_k(a+b)\bigr) are available as linear directions.

What Nanda et al. found in their MLP (their Sections 4.2–4.3). Of 512 neurons, 433 (84.6%) had over 85% of their variance explained by a degree-2 polynomial of sines and cosines of a single key frequency. And projecting the MLP activations onto the directions the output reads gave, for each key frequency, a near-exact multiple of cos⁡(wk(a+b))\cos\bigl(w_k(a+b)\bigr) or sin⁡(wk(a+b))\sin\bigl(w_k(a+b)\bigr). The network had computed Chapter 1’s angle-addition formula in its neurons.

3.4 The unembedding: the interference sum, learned

A final matrix WUW_U maps the residual stream to one logit per candidate answer cc. In their model the skip connection around the MLP barely mattered, so the logits are approximately WLMLPW_L\,\text{MLP} with WL=WUWoutW_L = W_U W_{\text{out}}.

Now the payoff. To score candidate cc, the network needs

cos⁡(wk(a+b−c))=cos⁡(wk(a+b))cos⁡(wkc)+sin⁡(wk(a+b))sin⁡(wkc).\cos\bigl(w_k(a+b-c)\bigr) = \cos\bigl(w_k(a+b)\bigr)\cos(w_k c) + \sin\bigl(w_k(a+b)\bigr)\sin(w_k c).

This is linear in the two quantities the MLP produced, with coefficients cos⁡(wkc)\cos(w_k c) and sin⁡(wkc)\sin(w_k c) that depend only on cc. So a fixed matrix can do it: the rows of WLW_L just need to be those cosines and sines. Nanda et al. found WLW_L was approximately rank 10, one cosine and one sine direction for each of the 5 key frequencies. They also found the logits were well approximated by

logit(c)≈∑kαkcos⁡(wk(a+b−c)),\text{logit}(c) \approx \sum_{k} \alpha_k \cos\bigl(w_k(a + b - c)\bigr),

with this form explaining 95% of the logits’ variance.

This is the interference sum of Section 1.3, with learned weights αk\alpha_k in place of 1. Every term peaks at c=a+bc = a + b and the terms disagree elsewhere. Their Appendix B shows why one frequency is not enough: cos⁡(2π⋅14⋅8/113)≈0.998\cos(2\pi \cdot 14 \cdot 8/113) \approx 0.998, so frequency 14 alone nearly confuses cc with c±8c \pm 8. But cos⁡(2π⋅35⋅8/113)≈−0.990\cos(2\pi \cdot 35 \cdot 8/113) \approx -0.990, so adding frequency 35 cancels that false peak (Exercise 4 checks both by hand).

3.5 Softmax and cross-entropy

Chapter 2 deferred these. The network outputs logits ℓc\ell_c, one per answer. Softmax turns them into probabilities:

pc=eℓc∑c′eℓc′.p_c = \frac{e^{\ell_c}}{\sum_{c'} e^{\ell_{c'}}}.

Adding the same constant to every logit changes nothing, so only differences between logits matter. Cross-entropy for the correct answer c*c^\ast is

L=−log⁡pc*=log⁡(1+∑c≠c*eℓc−ℓc*).L = -\log p_{c^\ast} = \log\Bigl(1 + \sum_{c \neq c^\ast} e^{\ell_c - \ell_{c^\ast}}\Bigr).

Its gradient is simple: ∂L/∂ℓc=pc−[c=c*]\partial L / \partial \ell_c = p_c - [c = c^\ast]. It pushes every wrong logit down in proportion to its probability and the right one up by what is missing.

Tie to the interference sum. Suppose the logits are ℓc=A∑kcos⁡(wk(a+b−c))\ell_c = A \sum_k \cos\bigl(w_k(a+b-c)\bigr), a scale AA times the Section 1.3 sum, and let MM be the margin between the correct answer and the best wrong one. Every wrong logit sits at least AMAM below the right one, so

L≤log⁡(1+(p−1)e−AM).L \le \log\bigl(1 + (p - 1)\, e^{-AM}\bigr).

Two ways to lower the loss follow. Grow the scale AA, or grow the margin MM by adding frequencies that cancel false peaks. Weight decay charges for scale, so under weight decay a wider margin looks like the cheaper route. That is one reason, in this model, to expect several frequencies rather than one. It is a heuristic, not a consequence of the bound: adding a frequency also adds weight norm — a cosine and a sine direction in WLW_L, and the neurons to feed them — so weight decay charges for margin too, and the inequality above says nothing about which cost wins. Chapter 5 returns to the competition this sets up.

The same softmax appears inside attention (Section 3.2), where it weights positions instead of answers.

3.6 The whole network, and what the repo has measured

Putting the pieces together, following Nanda et al.’s Appendix A:

xi(0)=WEti+pi,x(1)=x3(0)+∑headsWOWV(∑iAixi(0)),x(2)=x(1)+WoutReLU⁡(Winx(1)),ℓ=WUx(2).x_i^{(0)} = W_E t_i + p_i, \quad x^{(1)} = x_3^{(0)} + \sum_{\text{heads}} W_O W_V \Bigl(\sum_i A_i x_i^{(0)}\Bigr), \quad x^{(2)} = x^{(1)} + W_{\text{out}} \operatorname{ReLU}\bigl(W_{\text{in}} x^{(1)}\bigr), \quad \ell = W_U x^{(2)}.

Part What it computes in the Fourier circuit Source of that claim Measured in the repo?
Embedding WEW_E cos/sin of aa at a few frequencies Nanda et al. §4.1 Yes: run 037 (Section 3.7)
Positional embedding pip_i tells slot aa from slot bb Nanda et al. App. A No
Attention heads degree-2 polynomials of one frequency; amplification Nanda et al. App. C.1.2–C.1.3 No
MLP (WinW_{\text{in}}, WoutW_{\text{out}}) cos⁡(wk(a+b))\cos(w_k(a+b)), sin⁡(wk(a+b))\sin(w_k(a+b)) as linear directions Nanda et al. §4.2–4.3 No
Unembedding WUW_U, WLW_L the interference sum over key frequencies Nanda et al. §4.2 No
Loss and accuracy the training and test curves — Yes: run 037 logs them

Read the last column carefully. Run 037 saved only WEW_E — R26_training_dynamics/emb/*.npy holds the final embedding matrix and nothing else; there is no checkpoint, no state_dict, no saved optimizer. The positional embedding, the four heads, both MLP matrices and the unembedding were never written to disk, so they are not merely unanalyzed, they are gone: the trained models no longer exist. Every claim in this chapter about attention, the MLP and the unembedding is Nanda et al.’s finding about their models, not a measurement of 037.

3.7 Lab: 037’s control arm through this anatomy

The record is lab/runs/037-grokking-multiplicative-characters.md, scored confirmed. Its control arm trained on a+bmod⁡113a + b \bmod 113 and exists to reproduce the additive result that Nanda et al. published. This lab reads that arm with Chapter 3 in hand.

Setup, side by side.

Nanda et al. mainline (their §3) Run 037 control arm (the record)
Task a+bmod⁡113a + b \bmod 113 a+bmod⁡113a + b \bmod 113 on 0,…,1120,\dots,112 (all 12,769 ordered pairs)
Layers, heads, head dimension 1 layer, 4 heads of dimension 32 1 layer, 4 heads of dimension 32 (MultiheadAttention’s embed_dim // num_heads = 128/4)
Attention implementation written out from WQ,WK,WV,WOW_Q, W_K, W_V, W_O (their App. A) torch.nn.MultiheadAttention(128, 4, bias=False) — a different parametrization, not a re-implementation of theirs: one packed in-projection rather than four named matrices, so a head’s WQWK⊤W_Q W_K^\top and WOWVW_O W_V have to be unpacked from it before anything in Sections 3.2–3.4 can be looked for
Positional embedding; causal mask learned; their App. A learned W_pos over the 3 slots; strictly upper-triangular mask, so = may attend to aa, bb and itself — their finding that =→==\to= attention is negligible (0.1–0.4%) is empirical, and nothing here forbids it
Residual width dd, MLP width 128, 512 128, 512
LayerNorm; biases; tied embed/unembed none; untied none; no biases anywhere; untied (WEW_E and WUW_U are separate parameters)
Training fraction 30% 30% — 3,831 of 12,769 pairs, 8,938 held out
Optimizer, learning rate, weight decay AdamW, 0.001, 1.0, full batch AdamW (β=0.9,0.98\beta = 0.9, 0.98), 0.001, 1.0, full batch
Seeds reported 5 (mainline plus 4) 3 (seeds 0, 1, 2); all three grokked

What 037 measured on this arm. For each seed, the final WEW_E was Fourier-transformed along the token index with a length-113 DFT over a=0,…,112a = 0, \dots, 112. Non-DC power was folded into 56 conjugate-pair bins {k,113−k}\{k, 113-k\}, and the share in the top 10 bins was recorded.

Control seed Top-10 share (length-113 DFT, 56 bins) Top bins Test accuracy 0.99 at step
0 0.9656 44, 21, 34, 26, 52 (the top 5 of the 10) 21,900
1 0.9558 26, 16, 47, 17, 34 (the top 5 of the 10) 21,600
2 0.9636 10, 3, 25, 49, 50 (the top 5 of the 10) 8,100
Gaussian floor 0.2022 (Gaussian, 113 × 128) none none

Reading it. - The embedding row of Section 3.6’s table is confirmed for 037’s own seeds. A handful of bins carry nearly all the non-DC power of WEW_E, which is what the Fourier circuit requires of the embedding. It is the only row 037 can confirm. - Which frequencies is a separate question from how many. Compare the top bins across 037’s three seeds and against Nanda et al.’s key frequencies {14,35,41,42,52}\{14, 35, 41, 42, 52\}. Their paper found different key frequencies in different seeds of the same architecture: Appendix C.2.1 (Table 3) lists four other runs of it, using k∈{2,9,19,31}k \in \{2, 9, 19, 31\}, {40,44,53}\{40, 44, 53\}, {31,45,49,52}\{31, 45, 49, 52\} and {17,32,42,51}\{17, 32, 42, 51\} — no two alike, and none equal to the mainline’s five. So a mismatch between 037 and the published set is not by itself a disagreement; agreement would be the surprise. - Everything downstream of WEW_E is unmeasured here, and cannot be recovered from what was saved. Only WEW_E was written out (R26_training_dynamics/emb/*.npy), so whether 037’s heads, neurons and WLW_L match Sections 3.2–3.4 is not merely unknown from the record — the weights that would answer it were never stored.

What an answer would require, stated as a cost rather than as a plan, and with no prediction attached:

  1. A retrain that saves every weight, not just WEW_E — the model’s whole state_dict at the end, and ideally at intervals, since Chapter 5’s question is when the circuit forms.
  2. A check that the retrained WEW_E reproduces the saved one, seed for seed, before any head or WLW_L is read. Without it a mismatch downstream cannot be told from a different model. This check is not free, and 037’s own numbers say why: the record’s only same-seed device comparison is the pair of 300-step sizing runs for seed 0 (metrics/add-transformer-s0-size100-{mps,cpu}.json), and the two agree to 10−610^{-6} at step 0 and have already diverged to 2×10−32\times10^{-3} in training loss by step 100. Identical seed, identical hyperparameters, different device, different trajectory. So the reproduction check has to be run on the same device, and even then it is a check, not an assumption — and whether it is sufficient is open, because same-device determinism on MPS has not been tested here. The measurement, its limits and the cheap check that would close the first gap are filed as N-031 (notes/mps-cpu-training-divergence.md).
  3. Unpacking MultiheadAttention into per-head WQ,WK,WV,WOW_Q, W_K, W_V, W_O, since 037’s attention is parametrized as one packed projection and Sections 3.2–3.4 are written in the four-matrix form.

Open questions. None of these has a record, and this chapter makes no prediction about any of them. - Do the frequencies in 037’s WLW_L match the frequencies in its WEW_E, seed by seed? - In 037’s attention heads, is there the same split between single-frequency heads and amplifying heads? - For the multiplicative arm, what does each layer look like in discrete-log coordinates?

Exercises

  1. ★ Write out the softmax probabilities for logits (2,0,0)(2, 0, 0) and for (12,10,10)(12, 10, 10). Why are they the same?
  2. ★ Show that a softmax over two positions with scores s0,s1s_0, s_1 equals σ(s0−s1)\sigma(s_0 - s_1) and 1−σ(s0−s1)1 - \sigma(s_0 - s_1), where σ(u)=1/(1+e−u)\sigma(u) = 1/(1 + e^{-u}).
  3. ★ Derive ∂L/∂ℓc=pc−[c=c*]\partial L / \partial \ell_c = p_c - [c = c^\ast] for cross-entropy after softmax.
  4. ★★ Checking Appendix B by hand. Compute cos⁡(2π⋅14⋅8/113)\cos(2\pi \cdot 14 \cdot 8/113) and cos⁡(2π⋅35⋅8/113)\cos(2\pi \cdot 35 \cdot 8/113). Hint: reduce 14⋅814 \cdot 8 and 35⋅835 \cdot 8 mod 113 first, and look at how close each is to 00 or to 113/2113/2.
  5. ★★ Prove the bound L≤log⁡(1+(p−1)e−AM)L \le \log\bigl(1 + (p-1)e^{-AM}\bigr) of Section 3.5. When is it an equality?
  6. ★★ Expand (0.5+γcos⁡(wa)−γcos⁡(wb))(ucos⁡(wa)+vcos⁡(wb))\bigl(0.5 + \gamma\cos(w a) - \gamma\cos(w b)\bigr)\bigl(u\cos(wa) + v\cos(wb)\bigr). Which terms are degree 2? Which of them are pieces of cos⁡(w(a+b))\cos\bigl(w(a+b)\bigr), via the product-to-sum identity?
  7. ★★ Show that if the rows of a matrix WW are cos⁡(wkc)\cos(w_k c) and sin⁡(wkc)\sin(w_k c) for c=0,…,p−1c = 0, \dots, p-1, then WW applied to (cos⁡(wks),sin⁡(wks))\bigl(\cos(w_k s), \sin(w_k s)\bigr) gives the vector cos⁡(wk(s−c))\cos\bigl(w_k(s - c)\bigr) over cc. This is the unembedding of Section 3.4.
  8. ★★★ Using Theorem 1.2, show that the logits ∑k∈Kcos⁡(wk(a+b−c))\sum_{k \in K} \cos\bigl(w_k(a+b-c)\bigr), summed over KK together with the conjugates p−kp - k, have margin exactly 2|K|+12|K| + 1 when K∪(p−K)K \cup (p - K) covers every nonzero frequency. What is that margin as a fraction of the peak?
  9. Computational. For the frequency set {14,35,41,42,52}\{14, 35, 41, 42, 52\} and p=113p = 113, compute the interference sum of Section 3.4 with all αk=1\alpha_k = 1 over d=a+b−c=0,…,112d = a + b - c = 0, \dots, 112. Report the margin, then drop one frequency at a time and report which one costs the most margin.
  10. Computational, open. Load the saved final embeddings of 037’s control arm and repeat its measurement yourself: a length-113 DFT along the token index, conjugate-pair bins, top-10 share. Check your numbers against the record. (They are not in the checkout — .gitignore excludes R26_training_dynamics/emb/, since the metrics JSON is the record and the matrices are regenerable. Regenerate them with python run037.py --task add --seeds 0 1 2 from R26_training_dynamics/, using that directory’s own venv; each seed writes emb/add-transformer-s<seed>.npy. About six minutes a seed.)

Hints. - (1) Only differences between logits matter. - (4) 14⋅8=112≡−114 \cdot 8 = 112 \equiv -1, and 35⋅8=280≡5435 \cdot 8 = 280 \equiv 54, which is close to 113/2113/2. - (8) Chapter 1, Exercise 5 is the case p=7p = 7, K={1,2,3}K = \{1, 2, 3\}.

Summary and bridge to Chapter 4

A one-layer transformer can build Chapter 1’s circuit. Its embedding writes circles, its attention and MLP multiply them, and its unembedding sums the interference.

Next. So far every network has been examined after training. Chapter 4 studies the training itself: gradient descent as a dynamical system, what weight decay does to it, why loss curves have plateaus, and what happens when the learning rate is too large. Its labs are the open probes P-027 and P-028, and animations/learning-curves.html draws both.

References for Chapter 3


Chapter 4 — Training Dynamics: Gradient Descent as a Dynamical System

Training is a map applied over and over, θ↦θ−η∇L(θ)\theta \mapsto \theta - \eta \nabla L(\theta), and the shape of a loss curve is the behaviour of that map. This chapter reads two shapes exactly. A staircase of plateaus is a spectrum being learned one mode at a time. A period-doubling cascade is what the map does when the step is too large for the curvature. Both are exact only in small models, and that boundary is where the chapter’s two labs, P-027 and P-028, begin.

4.1 Gradient descent is a map

Chapter 2 wrote one step of gradient descent. Iterate it:

θt+1=G(θt),G(θ)=θ−η∇L(θ).\theta_{t+1} = G(\theta_t), \qquad G(\theta) = \theta - \eta\,\nabla L(\theta).

This is a discrete dynamical system, and the vocabulary of dynamics applies directly.

Small η\eta makes GG track the continuous gradient flow θ̇=−∇L(θ)\dot\theta = -\nabla L(\theta), with tt steps of size η\eta corresponding to time ηt\eta t. Section 4.3 works in that limit. Section 4.4 is about what happens when η\eta is not small.

4.2 The quadratic: stable exactly when η<2/λmax\eta < 2/\lambda_{\max}

Take a quadratic loss with its minimum at the origin:

L(θ)=12θ⊤Hθ,H symmetric, eigenvalues λ1≥…≥λd>0.L(\theta) = \tfrac12\, \theta^{\top} H \theta, \qquad H \text{ symmetric, eigenvalues } \lambda_1 \ge \dots \ge \lambda_d > 0.

Then ∇L=Hθ\nabla L = H\theta, and gradient descent is linear: θt+1=(I−ηH)θt\theta_{t+1} = (I - \eta H)\,\theta_t.

Theorem 4.1. Gradient descent on this quadratic converges to 0 from every starting point if and only if η<2/λ1\eta < 2/\lambda_1.

Proof. Expand θ0\theta_0 in the eigenvectors viv_i of HH: θ0=∑icivi\theta_0 = \sum_i c_i v_i. Each component evolves on its own, ci↦(1−ηλi)cic_i \mapsto (1 - \eta\lambda_i)\,c_i, so after tt steps it is (1−ηλi)tci(1 - \eta\lambda_i)^t c_i. This goes to 0 for every cic_i exactly when |1−ηλi|<1|1 - \eta\lambda_i| < 1 for every ii, that is 0<ηλi<20 < \eta\lambda_i < 2. The binding case is the largest eigenvalue. ∎

Read the factor 1−ηλi1 - \eta\lambda_i component by component.

Step size Factor 1−ηλi1 - \eta\lambda_i What that component does
η<1/λi\eta < 1/\lambda_i between 0 and 1 shrinks monotonically
η=1/λi\eta = 1/\lambda_i exactly 0 vanishes in one step
1/λi<η<2/λi1/\lambda_i < \eta < 2/\lambda_i between −1 and 0 shrinks while flipping sign every step
η>2/λi\eta > 2/\lambda_i below −1 grows while flipping sign

The instability arrives through the sign-flipping row. At η=2/λ1\eta = 2/\lambda_1 the sharpest direction stops shrinking and starts bouncing between two sides of the valley. That bounce is the seed of Section 4.4’s period doubling. The quantity λ1\lambda_1 is called the sharpness.

Two consequences: - The slowest direction sets the speed. With η\eta just under 2/λ12/\lambda_1, the flattest direction shrinks by 1−2λd/λ11 - 2\lambda_d/\lambda_1 per step. The ratio λ1/λd\lambda_1/\lambda_d, the condition number, is the price of a curved valley. - On a quadratic the threshold is exact. On a real loss, HH changes as θ\theta moves, so 2/λ12/\lambda_1 is a moving target. Cohen, Kaur, Li, Kolter and Talwalkar (arXiv:2103.00065) report that full-batch gradient descent on neural networks typically runs with the sharpness hovering just above 2/η2/\eta, while the loss still decreases over long timescales. They call this regime the edge of stability. Theorem 4.1 says a quadratic cannot do that. Why a network can is part of what Section 4.4 and P-028 are about.

4.3 Plateaus and the singular-value staircase

The cleanest source of plateaus is a network with no nonlinearity at all. Saxe, McClelland and Ganguli (arXiv:1312.6120) found exact solutions for gradient descent in deep linear networks. This section derives the heart of it for one mode, by hand.

The setup. A two-layer linear network maps x↦W2W1xx \mapsto W_2 W_1 x. Train it with squared loss on inputs that are whitened (their covariance is the identity). Write the input-output correlation matrix of the data as its singular value decomposition, Σyx=USV⊤\Sigma_{yx} = U S V^{\top}, with singular values σ1≥σ2≥…\sigma_1 \ge \sigma_2 \ge \dots. If the weights start aligned with the singular vectors, they stay aligned, and each mode ii is carried by one scalar strength per layer, aia_i in W1W_1 and bib_i in W2W_2. The network’s strength on mode ii is the product ui=aibiu_i = a_i b_i. The modes then decouple, and the loss is, up to a constant,

L=12∑i(σi−ui)2=12∑i(σi−aibi)2.L = \tfrac12 \sum_i (\sigma_i - u_i)^2 = \tfrac12 \sum_i (\sigma_i - a_i b_i)^2.

One mode, by hand. Drop the index. Gradient flow on 12(σ−ab)2\tfrac12(\sigma - ab)^2 gives

ȧ=b(σ−ab),ḃ=a(σ−ab).\dot a = b\,(\sigma - ab), \qquad \dot b = a\,(\sigma - ab).

Note that ddt(a2−b2)=2ab(σ−ab)−2ab(σ−ab)=0\tfrac{d}{dt}(a^2 - b^2) = 2ab(\sigma - ab) - 2ab(\sigma - ab) = 0. So a2−b2a^2 - b^2 is conserved. With balanced initialisation, a=ba = b at the start, it stays balanced, and u=a2u = a^2. Then

u̇=2aȧ=2a2(σ−a2)=2u(σ−u).\dot u = 2a\dot a = 2a^2(\sigma - a^2) = 2u\,(\sigma - u).

This is the logistic equation. Separate variables with 1u(σ−u)=1σ(1u+1σ−u)\frac{1}{u(\sigma - u)} = \frac{1}{\sigma}\bigl(\frac1u + \frac{1}{\sigma - u}\bigr) and integrate from u(0)=u0u(0) = u_0:

u(t)=σ1+(σ/u0−1)e−2σt.u(t) = \frac{\sigma}{1 + (\sigma/u_0 - 1)\, e^{-2\sigma t}}.

The staircase. For small u0u_0, the mode sits near u≈0u \approx 0 for a long time, then rises to σ\sigma in a burst. It reaches half its final value at

t1/2=ln⁡(σ/u0−1)2σ≈ln⁡(σ/u0)2σ.t_{1/2} = \frac{\ln(\sigma/u_0 - 1)}{2\sigma} \approx \frac{\ln(\sigma/u_0)}{2\sigma}.

Three features follow directly: - Big modes go first. t1/2t_{1/2} falls as σ\sigma grows, so modes are learned in order of singular value. - The wait is logarithmic in the initialisation. Halving u0u_0 adds ln⁡2/(2σ)\ln 2/(2\sigma) to the wait. The plateau is time spent escaping the saddle at u=0u = 0, which is unstable but has a small gradient when uu is small. - The burst width is about 1/σ1/\sigma. The rise from 10% to 90% takes ln⁡81/(2σ)≈2.2/σ\ln 81/(2\sigma) \approx 2.2/\sigma.

The loss is a sum of one drop per mode, each of size 12σi2\tfrac12\sigma_i^2, each at its own t1/2t_{1/2}. With well-separated singular values that is a staircase: a plateau, a drop, a plateau.

How exact this is. Every word in the setup matters. The solution is exact for gradient flow on a two-layer linear network, with whitened inputs, aligned and balanced initialisation, and one mode per singular value. Nothing in the derivation used a nonlinearity, and nothing survives automatically once one is added. In a nonlinear network the modes need not decouple, the “spectrum” being learned is not the spectrum of any fixed matrix, and plateaus can have other causes.

Reading it backwards. The forward direction is a theorem in this model: a spectrum produces a staircase. The reverse question asks whether you can take a staircase from a network you did not design, read off its plateau times, and recover a spectrum. That is P-027’s open question, together with what happens when two singular values nearly coincide and their drops merge.

The Staircase panel of animations/learning-curves.html draws 12∑i(σi−ui(t))2\tfrac12\sum_i (\sigma_i - u_i(t))^2 from the formula above with three adjustable singular values.

4.4 Past the threshold: period doubling

Section 4.2 ended with the sharpest direction bouncing at η=2/λ1\eta = 2/\lambda_1. On a quadratic the bounce grows without limit. On a real loss the curvature changes as the iterate moves away, and the bounce can settle into a new attractor. The cleanest place to watch this happen is one dimension.

The model. Take the double well

f(x)=14(x2−1)2,f′(x)=x3−x,f″(x)=3x2−1.f(x) = \tfrac14 (x^2 - 1)^2, \qquad f'(x) = x^3 - x, \qquad f''(x) = 3x^2 - 1.

It has minima at x=±1x = \pm 1, with curvature f″(±1)=2f''(\pm1) = 2, and a maximum at x=0x = 0. Gradient descent is the map

gη(x)=x−η(x3−x)=(1+η)x−ηx3.g_\eta(x) = x - \eta(x^3 - x) = (1 + \eta)\,x - \eta\,x^3.

Stage 1: the threshold is exact. The minimum x=1x = 1 is a fixed point, with multiplier gη′(1)=1+η−3η=1−2ηg_\eta'(1) = 1 + \eta - 3\eta = 1 - 2\eta. It is stable when |1−2η|<1|1 - 2\eta| < 1, that is 0<η<10 < \eta < 1. Since the curvature there is 2, this is Theorem 4.1’s η<2/λ\eta < 2/\lambda exactly: 2/2=12/2 = 1. At η=1\eta = 1 the multiplier passes through −1-1, and a period-2 orbit is born around x=1x = 1: the iterate now alternates between two points on either side of the minimum.

Stage 2: each side is a unimodal map. The map gηg_\eta is an odd cubic with two critical points, at

xc=±1+η3η.x_c = \pm\sqrt{\frac{1 + \eta}{3\eta}}.

On the positive side, gηg_\eta has a single maximum at +xc+x_c, and it is quadratic there, since gη″(xc)=−6ηxc≠0g_\eta''(x_c) = -6\eta x_c \neq 0. An orbit that starts on the positive side stays on it as long as the map’s highest value does not reach past the positive zero of gηg_\eta, which is (1+η)/η\sqrt{(1+\eta)/\eta}. Compute that highest value:

gη(xc)=xc(1+η−ηxc2)=23(1+η)xc.g_\eta(x_c) = x_c\bigl(1 + \eta - \eta x_c^2\bigr) = \tfrac23(1 + \eta)\,x_c.

Setting gη(xc)=(1+η)/ηg_\eta(x_c) = \sqrt{(1+\eta)/\eta} gives 23(1+η)=3\tfrac23(1+\eta) = \sqrt3, so

ηmerge=332−1≈1.598.\eta_{\text{merge}} = \frac{3\sqrt3}{2} - 1 \approx 1.598.

Below ηmerge\eta_{\text{merge}} the two sides never mix. An orbit on the positive side sees one hump with one quadratic maximum, which is the setting of the logistic map. Above it, orbits cross zero, the two symmetric attractors merge into one, and both critical points matter at once.

Stage 3: the cascade happens before the merge. As η\eta rises past 1, the period-2 orbit itself loses stability and doubles to period 4, then 8, 16, and so on, at parameters crowding toward a limit. This is the period-doubling cascade, and Feigenbaum (“Quantitative universality for a class of nonlinear transformations,” J. Stat. Phys. 19, 25–52, 1978, DOI 10.1007/BF01020332) showed that for one-dimensional maps with a single quadratic maximum, the gaps between successive doublings shrink by a universal ratio,

δ=limk→∞ηk−ηk−1ηk+1−ηk=4.6692…,\delta = \lim_{k\to\infty} \frac{\eta_k - \eta_{k-1}}{\eta_{k+1} - \eta_k} = 4.6692\ldots,

the same number for every map in the class.

Here the whole cascade finishes inside the one-sided regime. The table below locates the superstable parameters, where the periodic orbit passes through the critical point xcx_c. They sit between successive doublings and give the cleanest estimate of δ\delta. The values were computed for this chapter by root-finding on gη2k(xc)=xcg_\eta^{2^k}(x_c) = x_c at 50-digit precision. They are not a lab record, and Exercise 10 asks you to reproduce them.

kk period 2k2^k superstable ηk\eta_k ratio ηk−ηk−1ηk+1−ηk\dfrac{\eta_k - \eta_{k-1}}{\eta_{k+1} - \eta_k}
0 1 0.500000 none
1 2 1.121320 4.3857
2 4 1.262990 4.5917
3 8 1.293843 4.6527
4 16 1.300475 4.6656
5 32 1.301896 4.6684
6 64 1.302200 4.6690
7 128 1.302266 none

The ratios climb toward 4.66924.6692, and every doubling lands near η≈1.3023\eta \approx 1.3023, well below ηmerge≈1.598\eta_{\text{merge}} \approx 1.598. Past the accumulation point the orbit is chaotic, still confined to one side, until the merge at ηmerge\eta_{\text{merge}} lets it wander over both wells.

What this settles, and what it does not. In this one-dimensional map, the edge of stability, the period-2 bounce and the whole Feigenbaum cascade are settled mathematics. They are the known result that any instrument claiming to measure “period doubling in gradient descent” must reproduce before it is trusted on anything else. What survives in high-dimensional training is open. There, many directions share the curvature budget, several can cross 2/η2/\eta at once, and the sharpness itself moves as training proceeds. Whether a doubling cascade appears at all, whether its spacing obeys δ\delta, and in what dimension any of it stops holding is P-028’s question.

The Edge-of-stability panel of animations/learning-curves.html draws the late iterates of gηg_\eta against η\eta.

4.5 Weight decay

Every run in this course trains with weight decay. Here is what it does to the dynamics.

On plain gradient descent. Add the penalty λ2‖θ‖2\tfrac{\lambda}{2}\lVert\theta\rVert^2 to the loss. The step becomes

θt+1=(1−ηλ)θt−η∇L(θt).\theta_{t+1} = (1 - \eta\lambda)\,\theta_t - \eta\,\nabla L(\theta_t).

Every step first shrinks all weights by the factor 1−ηλ1 - \eta\lambda, then follows the data gradient. With no data gradient the norm decays geometrically, ‖θt‖=(1−ηλ)t‖θ0‖\lVert\theta_t\rVert = (1 - \eta\lambda)^t\lVert\theta_0\rVert. With one, a fixed point needs ∇L(θ)=−λθ\nabla L(\theta) = -\lambda\theta: the data must push outward exactly as hard as the decay pulls in. Any direction the data does not need drains to zero.

On a quadratic the penalty adds λ\lambda to every eigenvalue of HH. So Theorem 4.1’s threshold becomes η<2/(λ1+λ)\eta < 2/(\lambda_1 + \lambda), and the flattest directions are no longer flat.

On AdamW, which run 037 uses. For plain gradient descent, an L2L_2 penalty and “shrink the weights each step” are the same thing. For adaptive optimizers such as Adam they are not, because Adam rescales each gradient coordinate. Loshchilov and Hutter (arXiv:1711.05101) made this point and proposed applying the decay directly to the weights, separately from the adaptive step. That is AdamW. The norm-shrinking picture above describes AdamW’s decay term. The curvature picture does not transfer directly, because Adam’s rescaling changes the effective step size direction by direction.

The question passed to Chapter 5. Section 3.5 found two ways for the one-layer transformer to lower its cross-entropy: grow the scale AA of its logits, or grow the margin MM by using more frequencies. Weight decay charges for both. Scale costs norm directly, and each extra frequency costs a cosine and a sine direction in the unembedding, plus the neurons that feed them. Which cost wins, and whether that competition is what sets the timing of grokking, is Chapter 5’s question. This chapter does not answer it.

4.6 Labs: P-027 and P-028

Both labs are open probes. Neither has a run, so there are no lab numbers here, only exercises. Neither probe has a prediction or a falsifier filed. Both are the owner’s to write, before any compute.

P-027, staircase as spectral readout. Section 4.3 proves the forward direction in a model: singular values produce plateau times t1/2≈ln⁡(σ/u0)/(2σ)t_{1/2} \approx \ln(\sigma/u_0)/(2\sigma). The probe asks about the reverse direction, and about near-coincident singular values. Before anything nonlinear is tried, an instrument for this probe should reproduce Section 4.3 on a network where the answer is known: a two-layer linear network trained on data with a spectrum you choose. Exercises 5 and 11 build that instrument.

P-028, edge of stability. Section 4.4 gives the one-dimensional result exactly: the threshold at η=1\eta = 1, the cascade accumulating near η≈1.3023\eta \approx 1.3023 with ratios converging to δ\delta, and the merge at ηmerge=33/2−1\eta_{\text{merge}} = 3\sqrt3/2 - 1. An instrument for this probe must reproduce the table in Section 4.4 before it measures anything in higher dimension. Exercises 7, 10 and 12 build that instrument.

Open questions, with no prediction attached. - If a nonlinear network’s loss curve shows plateaus, what, if anything, do the plateau times measure? - When two singular values are close, do their drops merge into one, and can the pair still be resolved from the curve? - In a two- or three-dimensional loss, does gradient descent past 2/λ12/\lambda_1 period-double, and if it does, with what spacing? - As the dimension grows, at what point, if any, does the one-dimensional picture stop describing training?

Exercises

  1. ★ Run gradient descent on L(θ)=12(θ12+10θ22)L(\theta) = \tfrac12(\theta_1^2 + 10\,\theta_2^2) from (1,1)(1, 1) with η=0.15\eta = 0.15 and with η=0.21\eta = 0.21, for four steps each. Which component flips sign? Which run diverges?
  2. ★ For the quadratic in Exercise 1, find the η\eta that makes the slower component shrink fastest while the faster one stays stable. What is the per-step factor of the slow component?
  3. ★ Verify the logistic solution of Section 4.3 by differentiating it. Then check u(0)=u0u(0) = u_0 and u(∞)=σu(\infty) = \sigma.
  4. ★★ Show that a2−b2a^2 - b^2 is conserved by the one-mode flow, and solve the flow for unbalanced starts with a2−b2=c≠0a^2 - b^2 = c \neq 0. What changes about the plateau?
  5. ★★ Take u0=10−3u_0 = 10^{-3} and singular values 33, 1.51.5 and 0.60.6. Compute each t1/2t_{1/2}. What fraction of the total loss has been removed at each one?
  6. ★★ With weight decay λ\lambda added to the one-mode loss, the flow becomes ȧ=b(σ−ab)−λa\dot a = b(\sigma - ab) - \lambda a and likewise for bb. Find the balanced fixed point. Show that a mode with σ<λ\sigma < \lambda is never learned.
  7. ★★ For gη(x)=(1+η)x−ηx3g_\eta(x) = (1 + \eta)x - \eta x^3, find the period-2 orbit around x=1x = 1 just past η=1\eta = 1. (Hint: solve gη(gη(x))=xg_\eta(g_\eta(x)) = x and remove the fixed points.)
  8. ★★ Rederive ηmerge=33/2−1\eta_{\text{merge}} = 3\sqrt3/2 - 1 from gη(xc)=(1+η)/ηg_\eta(x_c) = \sqrt{(1+\eta)/\eta}.
  9. ★★★ The first superstable parameter in Section 4.4’s table is 1.12132034…1.12132034\ldots, which agrees with 3/2−13/\sqrt2 - 1 to every digit computed. Prove it, or find where the agreement breaks.
  10. Computational. Reproduce Section 4.4’s table: find the superstable ηk\eta_k for k=1,…,7k = 1, \dots, 7 by root-finding on gη2k(xc)−xcg_\eta^{2^k}(x_c) - x_c, starting each search just above the previous root. Report the ratios. How many digits of precision do you need by k=7k = 7, and why?
  11. Computational. Train a two-layer linear network by plain gradient descent (finite η\eta, not flow) on whitened data whose correlation matrix has singular values 33, 1.51.5 and 0.60.6, starting balanced at u0=10−3u_0 = 10^{-3}. Plot the loss and mark each predicted t1/2t_{1/2}, converting time to steps by t=η×stepst = \eta \times \text{steps}. Where does finite η\eta make the formula drift?
  12. Computational, open. Run gradient descent on a two-dimensional loss that has the double well in one coordinate and a quadratic in the other, f(x,y)=14(x2−1)2+c2y2f(x, y) = \tfrac14(x^2 - 1)^2 + \tfrac{c}{2}y^2. Sweep η\eta and cc. Record what you see; this chapter makes no prediction about it.

Hints. - (1) The eigenvalues are 1 and 10, so the threshold is η=0.2\eta = 0.2. - (2) Balance the two factors: |1−η|=|1−10η||1 - \eta| = |1 - 10\eta|. - (6) The fixed point is u=σ−λu = \sigma - \lambda when that is positive. - (8) Square both sides before solving. - (10) Near the accumulation point, neighbouring superstable parameters differ in the sixth decimal place, and the orbit is iterated 128 times.

Summary and bridge to Chapter 5

Gradient descent is a map, and a loss curve is its trajectory.

Next. Chapter 5 puts the pieces together on the curve this course is named for. Grokking has a plateau, as in Section 4.3, but the plateau is not a saddle in a linear model. It is a memorizing solution that fits the training set perfectly while the generalizing circuit of Chapter 3 forms underneath, under the weight-decay pressure of Section 4.5. Its lab reads run 037’s training curves and grokking steps.

References for Chapter 4


Chapter 5 — Grokking: Memorization Against Circuit

A network that groks holds two solutions to the same training set, one after the other. The first is a lookup table: fast to build, perfect on the training pairs, useless on anything else. The second is the character circuit of Chapters 1 and 3: slow to build, and correct everywhere. Weight decay is what makes the second one win. This chapter reads that story off run 037’s curves, and it says plainly which parts of the story the curves can and cannot show.

5.1 The shape

Power, Burda, Edwards, Babuschkin and Misra (arXiv:2201.02177) named the effect: on small algorithmic datasets, a network can reach perfect training accuracy, sit there for a long time with test accuracy near chance, and then generalize. In their words, the improvement “can happen well past the point of overfitting.”

Three numbers describe the shape of one run: - strains_{\text{train}}: the first logged step at which training accuracy reaches 0.99. - stests_{\text{test}}: the first logged step at which test accuracy reaches 0.99. - The gap stest/strains_{\text{test}}/s_{\text{train}}.

A network that simply learns has a gap near 1. A grokking network has a gap in the tens or hundreds. Run 037’s six seeds have gaps from 40.5 to 116 (Section 5.6).

5.2 Two solutions to one training set

The training set is 30% of the table: 3,831 pairs on the additive task, 3,763 on the multiplicative one. Many functions fit it exactly. Two matter here.

The lookup table. Store each training pair’s answer somewhere in the weights. This fits the training set perfectly and says nothing about the other 70%. Each stored pair needs its own capacity, so the cost grows with the number of pairs.

The circuit. Embed each token as cosines and sines at a few frequencies (Section 1.1), multiply them (Sections 2.4 and 3.2–3.3), and sum the interference (Sections 1.3 and 3.4). This fits the training set and the rest of the table. Its cost depends on how many frequencies it uses, not on how many pairs it has seen.

Why the lookup comes first. Gradient descent follows the steepest local improvement. Storing one more training pair improves the loss on that pair immediately and on its own. A single frequency of the circuit helps only once the embedding, the products and the readout for that frequency all line up, because a partial circuit mostly produces noise. So early training fills the table. This is a heuristic, not a theorem, and 037’s curves are consistent with it: training accuracy hits 0.99 by step 200 or 300 in every seed.

5.3 What memorization costs on the test set

A memorizer is not ignorant on unseen pairs. It is confidently wrong, and cross-entropy (Section 3.5) punishes that harder than ignorance.

Guessing uniformly over 113 answers gives every test pair the loss

Lguess=ln⁡113=4.727 nats.L_{\text{guess}} = \ln 113 = 4.727 \text{ nats}.

Now suppose the network puts nearly all its probability on one wrong answer and leaves only ε\varepsilon for the remaining 112, spread evenly. The correct answer then gets ε/112\varepsilon/112, and the loss is

L=−ln⁡ε112=ln⁡112+ln⁡1ε.L = -\ln\frac{\varepsilon}{112} = \ln 112 + \ln\frac{1}{\varepsilon}.

A test loss of 20 nats, which is what 037’s seeds show at the moment they finish memorizing (Section 5.6), means ln⁡(1/ε)≈15.3\ln(1/\varepsilon) \approx 15.3, so the network leaves roughly 2×10−72 \times 10^{-7} of its probability for everything but its chosen answer. It is about four times worse than guessing. The test loss is therefore a much more sensitive instrument than the test accuracy. Accuracy sits at chance either way; the loss shows how confident the wrong answers are.

5.4 Weight decay picks the winner

Once the training set is fitted, the data gradient on it is small. What is left pushing on the weights is weight decay (Section 4.5), and the two solutions pay for it differently.

The clock that decay runs on. Run 037 trains with AdamW at a constant learning rate η=10−3\eta = 10^{-3} and weight decay λ=1.0\lambda = 1.0 (the record’s hyperparameters). PyTorch’s AdamW applies the decay as θ←(1−ηλ)θ\theta \leftarrow (1 - \eta\lambda)\,\theta every step, separately from the adaptive step (Section 4.5). So a weight that no gradient defends shrinks by a factor of 0.9990.999 per step:

(1−ηλ)t=0.999t≈e−t/1000.(1 - \eta\lambda)^{t} = 0.999^{t} \approx e^{-t/1000}.

Undefended weight halves in about 1000ln⁡2≈6931000 \ln 2 \approx 693 steps. That sets the natural unit of time for anything decay does in 037: about a thousand steps. (This number is computed for the chapter from the record’s hyperparameters, not measured; Exercise 4 checks it.)

The heuristic, stated as one. The lookup table’s cost grows with the number of stored pairs; the circuit’s cost grows with the number of frequencies. If the circuit fits the same training set at lower weight norm, decay slowly favors it, and once the circuit carries the training loss, decay can dismantle the table, which no longer earns its norm. Section 3.5’s scale-against-margin trade-off is one instance: under decay, every extra frequency and every extra unit of logit scale has to pay for itself. Whether the circuit really is the lower-norm solution for a given architecture is not proved here. Nanda et al. (arXiv:2301.05217, §5.3 and Appendix D.1) report the empirical side: with less weight decay their networks took much longer to grok, and without weight decay or another regularizer they did not grok on this task.

5.5 Three phases, and measures that see them early

Nanda et al. (arXiv:2301.05217, §5.1–5.2) used the circuit of Chapter 3 to define two progress measures, both built from the Fourier analysis of Chapter 1:

With these, they split their mainline run (the same task and hyperparameters as 037’s control arm) into three phases, measured in epochs of full-batch training:

Phase Epochs What the measures show (their §5.2)
Memorization 0 to 1.4k train and excluded loss fall; test and restricted loss stay high
Circuit formation 1.4k to 9.4k excluded loss rises, restricted loss starts to fall, the sum of squared weights falls; train and test loss stay flat
Cleanup 9.4k to 14k test loss drops suddenly, the sum of squared weights drops sharply

Their headline reading: the circuit forms well before test accuracy moves, and the jump happens during cleanup, when decay strips out the memorizing components that were drowning the circuit’s answer on test pairs. On the test set the circuit was already partly right; the lookup table’s confident wrong answers, from Section 5.3, were outvoting it. Grokking, on this reading, is the moment the circuit stops being outvoted.

What 037 can and cannot show here. Both progress measures need the full logits, or all the weights, at many points during training. Run 037 logged train and test loss and accuracy every 100 steps and saved only the final embedding WEW_E (Chapter 3, Section 3.6). So 037 cannot compute restricted or excluded loss, and it did not log the weight norm. The phase boundaries in the table above are Nanda et al.’s, about their model; none of them is measured in the repo.

Watch. After the phases table: Welch Labs, “The most complex model we actually understand” (YouTube), which animates the grokked modular-addition network and its phases. It adds a moving picture of what this section can only tabulate. Any claim this chapter takes from it would be marked as the video’s; none is.

5.6 Lab: run 037’s curves

The record is lab/runs/037-grokking-multiplicative-characters.md, scored confirmed. Every number below comes from R26_training_dynamics/metrics/{add,mul}-transformer-s{0,1,2}.json: the grokking block for the step numbers and the per-100-step log for the rest. The first-crossing steps are resolved to the logging interval, 100 steps. No spectral numbers appear in this lab.

Arm, seed strains_{\text{train}} (0.99) stests_{\text{test}} (0.99) gap test acc 0.1 → 0.9, steps test loss at strains_{\text{train}} peak test loss (step) final test loss (step 25,000)
add, 0 200 21,900 109.5 17,600 → 21,400 20.11 38.59 (1,500) 9.4 × 10⁻⁷
add, 1 300 21,600 72.0 19,100 → 21,300 22.21 36.92 (1,500) 6.3 × 10⁻⁵
add, 2 200 8,100 40.5 5,900 → 7,700 20.23 37.11 (1,400) 4.3 × 10⁻⁵
mul, 0 200 10,900 54.5 9,000 → 10,700 20.48 36.04 (1,400) 1.8 × 10⁻⁶
mul, 1 200 12,300 61.5 9,700 → 12,000 19.22 37.19 (1,400) 8.0 × 10⁻⁵
mul, 2 200 23,200 116.0 17,700 → 22,400 19.09 37.82 (1,400) 8.7 × 10⁻³

All losses are in nats; chance is ln⁡113=4.727\ln 113 = 4.727 on the additive arm and ln⁡112=4.718\ln 112 = 4.718 on the multiplicative one.

Reading it with the chapter. - Memorization is fast and uniform. Every seed on both arms fits the training set by step 300, and at that moment every test accuracy is between 0.4% and 2.1%, near chance. - The confidence of the wrong answers keeps growing after the fit. Test loss is about 20 nats at strains_{\text{train}}, already four times the guessing loss (Section 5.3). It keeps climbing for another thousand steps and peaks at 36–39 nats, at step 1,400 or 1,500 in all six seeds. - The jump is short and late. The climb from 10% to 90% test accuracy takes 1,700 to 4,700 steps, against waits of 5,900 to 19,100 steps before it starts. On the decay clock of Section 5.4 the jump spans a few thousand-step units; the wait before it can be close to twenty. - Seeds disagree about when, not whether. With identical hyperparameters, stests_{\text{test}} ranges from 8,100 to 23,200, a factor of 2.9. Three seeds per arm is too few to say whether the arms differ. - The latest groker is still cleaning up. Multiplicative seed 2 reached 0.99 last (step 23,200), and at step 25,000 its test loss is 8.7×10−38.7 \times 10^{-3} nats, two to four orders of magnitude above the others’. It is consistent with a run caught before cleanup finished. The record cannot confirm that, because 037 has no progress measure.

One coincidence, marked as one. The test-loss peak lands at step 1,400–1,500 in all six seeds, and Nanda et al.’s memorization phase ends at 1.4k epochs under the same learning rate and weight decay. It is tempting to call these the same event. Nothing in 037’s record can test that: the peak is visible in the test loss, while the phase boundary was defined with the excluded loss, which 037 did not log.

Open questions, with no prediction attached. - What sets a seed’s grokking step, when everything but the seed is fixed? - Is the test-loss peak the end of memorization, in the sense of Nanda et al.’s excluded loss? - Does the multiplicative arm, which must build its own discrete-log coordinate (Section 1.6), grok at a different time from the additive arm, once there are enough seeds to tell?

Answering any of them needs a retrain that logs the weight norm and saves checkpoints through training, so the progress measures can be computed. As Section 3.7 notes, that retrain must run on the device of the original and check that it reproduces the saved WEW_E before anything is read (note N-031).

Exercises

  1. ★ Compute ln⁡113\ln 113 and ln⁡112\ln 112. Explain why the two arms have different chance losses.
  2. ★ A network puts probability 0.9 on one wrong answer and spreads 0.1 evenly over the other 112. What is its loss on that pair? Compare with guessing.
  3. ★ From the lab table, compute the ratio of wait to jump for each seed: the step at which test accuracy reaches 0.1, divided by the number of steps from 0.1 to 0.9.
  4. ★★ Show that (1−ηλ)t≈e−ηλt(1 - \eta\lambda)^t \approx e^{-\eta\lambda t} when ηλ\eta\lambda is small. With ηλ=10−3\eta\lambda = 10^{-3}, how far off is the approximation at t=1000t = 1000? At t=20,000t = 20{,}000?
  5. ★★ Invert Section 5.3: what value of ε\varepsilon gives a test loss of 37 nats? What does that say about the network at the peak?
  6. ★★ A toy of the competition, labelled a toy. Let uu be the strength of a “lookup” solution and vv the strength of a “circuit” solution. Both fit the training set, so the training loss is 12(1−u−v)2\tfrac12(1 - u - v)^2. Only the circuit helps on test pairs, so the test loss is 12(1−v)2\tfrac12(1 - v)^2. Add decay λ2(u2/c1+v2/c2)\tfrac{\lambda}{2}(u^2/c_1 + v^2/c_2), where c1<c2c_1 < c_2 makes the lookup more expensive. Find the minimum of the regularized training loss. Which solution carries the fit, and how does the answer depend on c1/c2c_1/c_2?
  7. ★★★ In the toy of Exercise 6, start at u=1u = 1, v=0v = 0 and run gradient flow. Show that the lookup is abandoned only as fast as decay allows, and find the time constant. What in the toy plays the role of the wait?
  8. Computational. From add-transformer-s0.json, plot train and test loss on a log scale against step. Mark strains_{\text{train}}, the peak, and stests_{\text{test}}. Then overlay the undefended decay curve e−t/1000e^{-t/1000}, suitably scaled, and describe what it does and does not match.
  9. Computational, open. For all six seeds, find the step at which test loss first falls back below its value at strains_{\text{train}}. Record it alongside stests_{\text{test}}. The chapter makes no prediction about how the two relate.

Hints. - (2) The correct answer gets 0.1/1120.1/112. - (4) Take logarithms and use ln⁡(1−x)=−x−x2/2−…\ln(1 - x) = -x - x^2/2 - \dots. - (6) At the minimum the gradients in uu and vv match the decay in each; the cheaper direction takes more of the fit. - (7) Linearize about the minimum from Exercise 6; the slower of the two decay rates is the time constant.

Summary and bridge to Chapter 6

Grokking is a competition between a lookup table and a circuit that fit the same training set.

Next. Every group in this course so far has been cyclic, so one discrete log was enough. Chapter 6 takes the units of ℤ/561\mathbb{Z}/561, which form ℤ/2×ℤ/10×ℤ/16\mathbb{Z}/2 \times \mathbb{Z}/10 \times \mathbb{Z}/16, with no single discrete log at all. The circuit then has to live on a product of circles, and the Chinese Remainder Theorem becomes a statement about an embedding. Its lab is P-031.

References for Chapter 5