A transformer can look back exactly 25 steps in a chaotic signal and use what it finds. A flat network cannot. Turn a waveform into tokens and see why.
Learn how a GPT-style model predicts the next sample of a signal: tokens, positions, attention, and the five test signals that show what attention buys.
Pick which step back the attention head reads, then shrink the context window below 26. Watch the head lose its target and the hit rate collapse. Then we build every piece from zero, slide by slide.
You need a little linear algebra (a vector is a list of numbers, a matrix turns one list into another) and the idea of a sampled signal. We build the rest from zero.
Based on the Transformers lecture of Stanford EE269: Signal Processing and Quantization for Machine Learning (Winter 2026), taught by Mert Pilanci. The lecture slides (PDF) and the course site are public. Every picture and device here is our own.
Illustrative: the signal is the lecture’s Mackey-Glass series with delay 25 (slide 32), quantized to 32 tokens on the range 0 to 2. The head is hand built from the lecture’s sinusoid construction (slides 14 to 16), not trained. After it reads a sample, one step of the Mackey-Glass update predicts the next one. The lecture’s trained MiniGPT reached 54.0% on this task (slide 62).
Chapter 0
See why a language-model trick, next-token prediction, also predicts sensor signals, and what a flat baseline cannot do
A vibration sensor is bolted to a pump. Every millisecond it reports one number. After an hour you hold three million numbers in a row, and your job is simple to say: given what the pump did so far, guess what it does next.
The row of numbers is a signal: a quantity measured over time. Each reading is a sample. Engineers have predicted the next sample for decades, with tools such as the least-squares line fit of Lecture 20 and the adaptive filters of Lecture 22. This lecture asks a bolder question. Can the model that predicts the next word in a chat, a transformer, predict the next sample too?
The lecture states the whole task in one line. You get a sequence of tokens t0, t1, …, tn−1. You must predict the next token tn. A token is a whole number from a fixed list, the way a word is one entry in a dictionary.
Why tokens and not raw numbers? A language model picks from a fixed menu, and it scores every item on the menu at once. A raw measurement has no menu: between 0.31 and 0.32 lie infinitely many values. The fix is quantization, the rounding of each sample to the nearest of a few levels. Number the levels 0, 1, 2, … and you have tokens. Chapter 1 builds this step. The lecture also notes that quantizing is only one way to tokenize, and lists five.
Look at what the data becomes. Below is a plain sine wave that repeats every 16 samples, quantized to 32 levels. Drag the position and see the two things a model gets: a context (the last 24 tokens it may look at) and a target (the token it must guess).
Pink dots are tokens. The shaded block is the context the model sees. The ring is the target. Drag the position, then switch on the copy arrow.
The signal is the lecture’s Signal 1, x[n] = sin(2πn/16), quantized to Q = 32 levels (slide 29). The token values match the lecture’s example windows on slide 30.
Notice what solves this signal: copy the token from 16 steps ago. The sine repeats exactly, so the answer is always sitting in the context, 16 places back. A good predictor must find that place. That one skill, finding the right place in the past, is the whole lecture.
The lecture sets two families side by side. The baselines are the classic tools: a linear predictor (a weighted sum of the last few samples, fitted by least squares) and a deep neural network predictor (several layers of weighted sums with bends between them). Both take the context as one fixed block of numbers and apply the same wiring every time.
The transformer, here the GPT kind, works differently. In the lecture’s words, each position attends to previous positions and dynamically selects which past tokens matter. Attention is a lookup that the data itself steers: each position asks a question, scores every earlier position against it, and reads mostly from the best match. The lecture calls this “programmable” retrieval plus computation. We will make that precise, and then measure it.
Here is the idea in one picture. If the sample you need is always 16 steps back, a fixed wiring can learn that. If the needed step changes with a hidden switch, a fixed wiring cannot. A steerable lookup can. The hero at the top of this page shows the first half of that story on a chaotic signal: one head, one chosen delay, and a window that must be long enough to hold it.
A word on logistics, and then we move on. The lecture pairs with a homework in which you run five signals through three models and sweep the depth of the transformer. The script, signal_gpt_v4.py, takes about 2 minutes on a GPU or about 48 minutes on a CPU. Everything below explains what that script does and why.
Chapter 1
Cut a continuous signal into integers with a quantizer, and meet the five other ways to tokenize
Think of a thermometer with a dial instead of a screen. The needle moves smoothly, but you read it by saying “about 21”. You have rounded a smooth quantity to a whole number on a printed scale. That act is the first step of this lecture.
A language model works with a vocabulary, a numbered list of allowed tokens. To feed a signal to it, you must turn each real-valued sample into one entry of such a list. The lecture’s goal is exact: convert a real-valued signal into discrete tokens t0, t1, … where each t is an integer in {0, 1, …, B−1}. The number B is the vocabulary size, the count of bins (the intervals the amplitude range is cut into).
Uniform quantization is the simplest tokenizer. It cuts the amplitude axis into equal steps. You make three choices and then run one formula. First, pick a clipping range [xmin, xmax], the stretch of values you will keep. Second, pick the number of bins B. Third, compute the step size Δ, the gap between neighbouring levels.
Work one sample. Take the range [−1, 1] and B = 32 bins. Then Δ = 2/31 = 0.0645. A sample x = 0.3827 is inside the range, so xc = 0.3827. Its distance above −1 is 1.3827. In steps that is 1.3827 / 0.0645 = 21.43, and rounding gives token 21. This is exactly the token the sine example of Chapter 0 shows after 16.
To get a number back, run the formula in reverse: x̂ = xmin + t·Δ. Token 21 gives −1 + 21 × 0.0645 = 0.355. The true sample was 0.3827, so the error is 0.028. Rounding can never miss by more than half a step, and half a step here is 0.032. That bound, Δ/2, is the price of using a finite menu.
Now play with the three choices. The pink staircase is what the model sees. The blue curve is what the sensor measured.
Pick the number of bins, then narrow the clipping range until the peaks flatten. Dashed lines mark the range edges.
Illustrative signal: 0.8 sin(2πt) + 0.4 sin(6πt + 0.6), 160 samples over two periods. The range is symmetric, xmin = −a and xmax = a. Errors are measured over all 160 samples in your browser.
Two failure modes show up at once. With few bins, the staircase is coarse: the error grows with Δ. With a narrow range, the peaks are cut flat and the error at those samples is large, no matter how many bins you add. The cure is a wide enough range plus enough bins. Both cost something: a wider range at a fixed B makes Δ larger, and more bins make the vocabulary bigger. At B = 32 each token carries 5 bits (25 = 32).
Slide 5 lists five families. Uniform quantization is the simplest member of the first.
| Family | What becomes a token | Where it fits |
|---|---|---|
| A. Scalar quantization | One sample, rounded to a level. Levels may be uneven: Lloyd–Max, a compander, or a high-rate optimal quantizer. | Slow signals, simple pipelines. See Lloyd–Max and quantization noise. |
| B. Vector quantization | A short block of samples, matched to the nearest entry of a codebook (for example one built by k-means). | Blocks of audio and patches of images. |
| C. Transform, then quantize | The coefficients of a DFT, DCT or wavelet transform, each rounded. | Signals whose energy sits in a few frequencies. See the DFT and wavelets. |
| D. Learned tokenizers | A model maps the signal to codes from a learned codebook. | Tokens that match what people hear or see. The slide names KyutAI Mimi for audio and Nvidia Cosmos for images and video. |
| E. Event-based | An event: a threshold crossing, a peak, an onset. | Signals that change at only a few moments. |
Why so many? Each one decides what the model must predict. Scalar tokens make the model predict amplitude, one sample at a time. Vector and learned tokens pack many samples into one token, so a sequence is shorter and each guess carries more. Event tokens throw away the quiet parts altogether. The rest of this lecture uses the scalar kind, because it keeps the mechanism bare: one token per sample, 32 levels.
Chapter 2
Trace the road from attention to GPT, then turn integers into vectors and add the one thing a bag of vectors lacks: order
You are reading a long recipe, and you need to know how much salt goes in. The amount is on line 3. You are on line 40. Your eyes jump back to line 3 and pick it out from everything else. That jump, from the present to a useful place in the past, is what the field spent a decade learning to do in software.
Before 2017, the standard sequence models struggled with long-range dependencies: cases where the sample you need sits far back in the sequence. They carried a running summary forward, and a summary forgets. Slides 6 and 7 tell the story in five steps.
| When | What arrived | The key idea |
|---|---|---|
| 2014 to 2016 | Attention | Learn to focus on the relevant parts of the input: compute weights over past states and take a weighted sum. A soft lookup. |
| 2017 | Transformer | Combine self-attention with fully connected MLP blocks. Every position can attend to earlier positions, and a GPU can process them all at once. |
| 2018 | GPT | A transformer trained to predict the next token, pretrained on large text, then fine-tuned. Many tasks become “predict the next token”. |
| 2019 | GPT-2 | More scale and broader data gave strong zero-shot and few-shot behaviour, without task-specific training. |
| 2020 on | The LLM era | Scaling laws (bigger models, more data and compute keep helping), instruction tuning, reinforcement learning from feedback, tools, retrieval, multimodal models. |
The lecture’s point for us is the GPT line. A transformer trained on one job, predict the next token, picked up general skills when it grew. We will test the same recipe, at toy scale, on signals. Our model is small: its job is to show the mechanism, not to match GPT-2.
A neural network cannot compute with the integer 7. The number 7 is not “a bit more than 6” in any useful sense; it is a label. The network needs a vector, a list of numbers it can add and scale. The fix is a lookup table, the token embedding matrix WE with V rows (one per token) and d columns. Token 7 becomes row 7: a vector e7 of d numbers, learned during training.
The lecture’s setup has V = 32 tokens and d = 64. The slide uses the six tokens 7, 12, 15, 14, 9, 3. Their shapes are:
t: (6,) → look up rows of WE (32, 64) → E: (6, 64)
Similar tokens can end up with similar vectors, because training pushes them to behave alike. For quantized samples that is natural: levels 20 and 21 stand for nearby amplitudes, so a good table will put them near each other.
Here is a problem. The six vectors et0, …, et5 are, as the slide puts it, just a set of vectors. Attention (Chapter 4) compares vectors with vectors and never asks where they came from. If you shuffle the input, the outputs shuffle the same way. The model has no idea which token came first.
For signals that is fatal. Whether a sample came 1 step ago or 25 steps ago changes everything. So we give each place its own vector. A position embedding pi is a d-vector for place i, and we add it to the token vector:
Adding is a deliberate choice. The sum keeps the shape (6, 64), so nothing downstream changes. The model must then learn, from the sum, both what and where. The slide says it learns relative-position structure through these vectors. Chapter 3 shows a construction where the structure is built in. Try the effect first.
Each column is one place in the sequence: its token, its token vector, its position vector, and their sum. Press Reverse the order with positions off, then on.
Toy numbers: d = 4 instead of 64, and the vectors come from fixed sine formulas, not training. Cell colour shows sign: warm positive, blue negative. The six tokens are the lecture’s slide 9 example.
With positions off, reversing the order gives the very same six vectors, only in different slots. Attention sees a bag, and a bag has no order. With positions on, every slot gets its own tag, so the reversed sequence builds a different set. The model can now tell “25 steps ago” from “1 step ago”.
The slide leaves pi open: it may be fixed or learnable, one vector per place i from 0 to K−1. The next chapter studies a fixed choice with surprising structure.
Chapter 3
Prove that sines and cosines turn a shift into a rotation and a dot product into a distance meter
Look at a clock. The second hand tells you the moment within a minute. The minute hand tells you the minute within an hour. The hour hand tells you the hour within a day. No single hand names the time uniquely, yet together they do, and the gap between two moments is easy to read from how far each hand has turned. Sinusoidal position embeddings are a clock with many hands.
Vaswani and colleagues (2017) gave each position i a vector built from sines and cosines. For each pair of dimensions, indexed by k, they pick a frequency and write down a sine and a cosine of i times that frequency. A frequency ω here is the angle, in radians, that the hand turns per step.
The slide plots four of these for k = 0 to 3, with ω = 1, 0.1, 0.01 and 0.001. A sinusoid finishes one cycle when its angle grows by 2π, so its wavelength (the number of steps per cycle) is λk = 2π/ωk = 2π · 100002k/d. The fastest hand has λ = 2π ≈ 6 tokens. The slowest has λ ≈ 2π · 10000. Fast hands tell near positions apart. Slow hands tell far positions apart. Together they give every position a unique multi-resolution signature, the slide says, a set of Fourier features.
Here is the reason the design is clever. Take one frequency ω. Place position i on a circle: pω(i) = (sin ωi, cos ωi). Now move k steps ahead. The sum-of-angles identities say:
sin(ω(i+k)) = sin(ωi) cos(ωk) + cos(ωi) sin(ωk)
cos(ω(i+k)) = cos(ωi) cos(ωk) − sin(ωi) sin(ωk)
Read the right sides as a matrix times the old point. The numbers cos(ωk) and sin(ωk) do not depend on i at all. So pω(i+k) = R(ωk) pω(i), where R is the 2×2 matrix [[cos ωk, sin ωk], [−sin ωk, cos ωk]]. In words: a relative offset of k steps is one fixed rotation, whatever place you start from. Try it. Two start points, one shift: the arcs match.
Violet dots are positions on the circle for ω = 0.5. Move the start position and the shift. The second pair, five places later, turns by the same angle.
One frequency only, ω = 0.5, so the angle after i steps is 0.5i radians. The identities are exact; only the drawing is illustrative.
Attention scores come from dot products (Chapter 4), so ask what the dot product of two position vectors is. For one frequency:
pω(i)T pω(j) = sin(ωi) sin(ωj) + cos(ωi) cos(ωj) = cos(ω(i − j))
The last step is the cosine-difference identity. The result depends only on the offset i − j, never on i or j alone. Now stack all d/2 frequencies. The dot product of the full vectors is a sum:
At offset 0 every cosine is 1, so the sum is d/2: the peak. With d = 8 that is 4, exactly the peak on slide 14. Away from 0 the terms fall out of step and the sum drops. So the dot product acts as a distance meter. Now the key trick. Suppose the key weights WK rotate each (sin, cos) pair by the angle τωk. Then the query-key score becomes ∑ cos((i − j − τ)ωk), and the peak slides to i − j = τ. The score is now a position-selective filter: it is largest at exactly the offset the head wants. Build the kernel yourself.
The curve is the score between a query and a key at each offset i − j. Raise d to sharpen it. Move τ to slide the peak.
The kernel is computed live: score(o) = sum over k of cos((o − τ)ωk) with ωk = 10000−2k/d. At d = 8 and τ = 0 the peak is 4, as on slide 14.
At small d, the curve repeats: with d = 2 there is one frequency and the score repeats about every 6 steps, so the head cannot tell offset 3 from offset 9. More frequencies break the tie. That is the multi-resolution idea at work, and it is why a model with a larger width d can aim more sharply.
Chapter 4
Build queries, keys and values, aim one head at a fixed delay, and hide the future with a mask
Picture a card catalogue in a small library. You write what you need on a slip: “the book about tides.” Every shelf label is compared with your slip. The best match wins, and you take the book from that shelf. A blurry slip matches several shelves a little, and you take a blend. This is self-attention, with one twist: the slips, the labels and the books are all made from the same sequence.
Each position i holds a hidden-state vector hi, the sum of token and position vectors from Chapter 2. Attention makes three new vectors from it with three learned weight matrices. In the slide’s words:
query qi = WQ hi “what am I looking for?”
key ki = WK hi “what do I contain?”
value vi = WV hi “what should I output?”
The query is your slip. The key is the shelf label. The value is the book. Position i compares its query with the key of each position j. A high dot product means a good match. The match scores turn into weights, and the output is a weighted sum of values.
The softmax turns any list of scores sj into weights: esj divided by the sum of all the es. It makes every weight positive and the total 1, and it exaggerates leaders. Take scores 2, 1, 0. Then e2 = 7.389, e1 = 2.718 and e0 = 1, with sum 11.107. The weights are 0.665, 0.245 and 0.090. A gap of one point in score gave the leader about 2.7 times the weight.
Why divide by √dk? A dot product adds dk terms. If each term is a random number of size about 1, the sum has size about √dk. Dividing brings it back to size 1. Without it, a wide model would produce huge scores, the softmax would saturate to a hard 0 or 1, and learning would stall.
Now the payoff of Chapter 3. Slide 16 sets the goal: position i should attend strongly to position j = i − τ, say τ = 3. The construction uses d = 2. Let the position vectors be pi = (cos iω, sin iω), the query matrix WQ = I (do nothing), and the key matrix WK = a rotation by 3ω. Then qi = pi and kj = R(3ω) pj, and the dot product is
qiT kj = cos((i − j − 3)ω)
This equals 1 exactly when j = i − 3 and is below 1 otherwise. The softmax then favours position i − 3. The slide shows the result as a weight row such as [0, 0, 0.95, 0.02, 0.02, 0.01]: about 95% on one place. One honest detail: a score that tops out at 1 gives a soft peak. Real peaks come from larger weights, which scale all scores up. The device below has a gain slider that stands in for that growth. The slide’s own conclusion: one head can implement a fixed-offset lookup.
Each row is a query, each column a key. Hatched cells are masked: the future. Choose the query row and the delay, then raise the gain and watch one cell take over.
Illustrative: one frequency, ω = 0.5, scores = gain × cos((i − j − τ)ω), with the lecture’s d = 2 construction (slide 16). The row of weights on the slide is a sketch; these numbers are computed live.
We train the model to predict the next token, so position i must not see tokens after i. If it could, it would just copy the answer. The fix is a mask. Before the softmax, set every score where j > i to −∞. Since e−∞ = 0, those entries get weight 0 and the rest renormalize. The score matrix S = QKT/√dk becomes lower triangular: row 0 sees only itself, row 3 sees four entries.
This makes the model autoregressive: each prediction depends only on the past. The same mask is used in every GPT. It also lets training run in parallel. One pass over a 64-token window yields 64 predictions at once, because each row is masked to its own past.
Data flow: H: (K, d) → Q, K, V: (K, dk) → S: (K, K) masked → softmax by row → out: (K, dk)
Chapter 5
Stack parallel heads, a normalizer, a per-token MLP and two residual paths into one transformer block
A newsroom has a research desk and a writing desk. The researchers fetch facts from earlier files. The writers take the fetched facts and compose a sentence. Neither desk can do the other’s job well. A transformer block is the same two desks, run one after the other: attention fetches, an MLP composes. Four small parts keep them stable and let many blocks stack.
One head makes one kind of lookup. A signal may need several at once. So the block runs H heads side by side, each with its own WQ, WK, WV, and then joins the results:
headh = Attn(WQ(h) h, WK(h) h, WV(h) h), h = 1, …, H
MultiHead(h) = concat(head1, …, headH) · WO
The slide gives four example jobs: attend to position n − 25 (a fixed delay), attend to the nearest key token (content match), copy from position n − 1 (local prediction), attend to a specific token (symbol matching). The homework model has d = 64 and H = 4, so each head works in dk = 64/4 = 16 dimensions. Four outputs of width 16 are concatenated back to width 64, then WO (64×64) mixes them. Each head is, in the slide’s phrase, a different retrieval program running in parallel.
After many additions, the numbers in a vector can drift large or small, and learning gets fragile. Layer normalization (LN) fixes the scale of each token vector separately. For a vector x with d entries, compute the mean μ and the variance σ2 (the average squared distance from the mean), subtract, divide, then apply a learned scale γ and shift β:
μ = (1/d) ∑ xk, σ2 = (1/d) ∑ (xk − μ)2, LN(x) = γ ⊙ (x − μ)/√(σ2 + ε) + β
The symbol ε is a tiny constant that prevents division by zero. The symbol ⊙ means multiply entry by entry. Slide 19 works d = 4: x = [2, 0, 0, 2]. The mean is 1. The squared distances are 1, 1, 1, 1, so σ2 = 1. With γ = 1 and β = 0, LN(x) ≈ [1, −1, −1, 1]. Try your own numbers. Notice that scaling the input by 5 changes nothing.
Blue bars are the input vector. Pink bars are LN(x) with γ = 1 and β = 0. Edit the four numbers, or use a preset.
The first preset is slide 19’s tiny example. ε = 10−5. Real models learn γ and β; they are fixed here so the effect of the normalizing step is clear.
Why this helps, in the lecture’s words: it keeps activations in a stable range so attention and the MLPs can train reliably across many layers.
Attention mixes information across tokens. The MLP (multi-layer perceptron, a small two-layer network) works within each token. It takes one vector hi in Rd and computes
MLP(hi) = W2 φ(W1 hi + b1) + b2, W1 in Rdff×d, W2 in Rd×dff
The vector is widened to dff numbers, bent by a nonlinearity φ (ReLU or GELU, a function that is not a straight line), and squeezed back to d. The same weights act on every position independently. The slide’s motto: attention is communication (where to look), the MLP is local compute (what to do). Four things the MLP can do once attention has fetched the right tokens: build new features (AND, OR), gate channels by context, do arithmetic and comparisons on retrieved values, and denoise by soft-thresholding.
Slide 22 gives a language example worth keeping. The prompt is “The capital of France is”, and the model must say Paris. Attention at the last place concentrates its weight on the position j* of “France”: αij* ≈ 1, so the output zi ≈ vj*, a transformed embedding of France. Then the MLP maps that retrieved subject to the right object. The association France to Paris sits in the MLP weights as parametric memory, weights that hold a fact. Attention retrieves; the MLP stores and computes.
Now assemble. The block (slide 21) runs, with h(ℓ) the input from block ℓ:
h′ = h(ℓ) + MHA(LN(h(ℓ))), h(ℓ+1) = h′ + MLP(LN(h′))
The plus signs are residual connections (skip paths). The input is copied past each sub-layer and added back. Think of a river with tributaries: the river keeps flowing, and each sub-layer pours in a small change. That preserves information and lets every layer make an incremental update. It also gives gradients a short road back during training. Step through one block below. The shape never changes: (K, 64) in, (K, 64) out.
The bars are the eight numbers of a toy token vector. Press Next step to move through LayerNorm, attention, the residual add, LayerNorm, the MLP and the second residual add.
Toy numbers: an 8-number vector instead of 64, with fixed made-up changes standing in for what attention and the MLP would compute. LayerNorm is computed for real (γ = 1, β = 0).
Chapter 6
Count every one of MiniGPT’s 158,272 weights, then see what the linear and MLP baselines can and cannot read
Before you trust a machine, you open it and count the parts. A model with a hundred thousand weights is small enough to count by hand, and the count teaches where the capacity lives. The lecture’s homework model, which we call MiniGPT, has exactly 158,272 weights. We will find every one.
Slide 23 draws the whole model as a short stack. The input is 64 tokens, t0 to t63. A token embedding (d = 64) plus a position embedding (K = 64) gives the first hidden state. Three transformer blocks follow. A final LayerNorm and a linear head turn the last hidden state into 32 logits, one score per token. A logit is a raw score before it becomes a probability. Only the last position, h63, feeds the head, because we want one next token. The settings are L = 3 layers, d = 64, H = 4 heads.
Now count. A weight matrix with r rows and c columns has r·c numbers, and a bias adds r more.
Token embedding: 32 × 64 = 2,048. Position embedding: 64 × 64 = 4,096. Together 6,144, the slide’s “6K”.
Attention in one block: four 64×64 matrices (WQ, WK, WV, WO) with biases = 4 × (4,096 + 64) = 16,640.
MLP in one block (dff = 4d = 256): 64×256 + 256 + 256×64 + 64 = 33,088.
Two LayerNorms in one block: 2 × (64 + 64) = 256. One block: 16,640 + 33,088 + 256 = 49,984, the slide’s “∼50K each”.
Three blocks: 149,952. Final LayerNorm: 128. Head: 64 × 32 = 2,048, no bias.
Total: 6,144 + 149,952 + 128 + 2,048 = 158,272.
The MLP is the largest single piece. It holds about two thirds of the block’s weights. Slide 20’s role split fits: attention is communication, the MLP is the bulk of the compute. Play with the counter. The same formula gives GPT-2 in Chapter 10.
Pick a preset, then change the number of layers or the width. The bar splits the total by part.
Formula: V·d + K·d + L·[4(d²+d) + (8d² + 5d) + 4d] + 2d, plus V·d for the head unless its weights are tied to the embedding (Chapter 10). The vocabulary V and context K come from the preset. MiniGPT reproduces the slide’s 158,272 exactly; GPT-2 Small gives about 124 million, the slide’s ∼124M.
Slide 24 lists five architectural settings and what each lets the model do. Memorize the logic, not the table: each knob limits one kind of task.
| Knob | Symbol | What it buys you |
|---|---|---|
| Context length | K | How far back you can possibly look. A dependency at offset τ needs K > τ. |
| Depth (layers) | L | How many sequential reasoning steps you can compose: retrieve, transform, retrieve again. |
| Heads | H | How many different retrieval patterns run in parallel. |
| Width | d | Feature capacity per token: sharper attention, richer representations. |
| MLP expansion | dff | Compute for arithmetic and piecewise functions after retrieval. |
Try one thought experiment with the table. Suppose the task needs a delay of 60 steps. With K = 64 the window barely holds it, so context is the binding knob. Suppose instead the task needs three lookups chained, one after another. Now depth is the binding knob, and a wider window will not help. Suppose it needs four different delays at once. Now the head count is binding. Each failure points to one knob, which is why the lecture’s tasks are built to isolate them. Note also why only the last position, h63, feeds the head: the other 63 positions have already done their job by lending their values to it through attention.
To see what attention adds, the lecture builds two models with no attention at all. The linear predictor embeds each of the 64 tokens into R8, flattens them into one vector z of 512 numbers ((64, 8) to (512,)), and computes ŷ = Wz + b with W of size 32×512. Count it: the embedding table is 32 × 8 = 256, and the layer is 32 × 512 + 32 = 16,416, for 16,672 in all. The slide notes two limits. Position information survives only as which slice of the 512 numbers a token landed in. And it cannot dynamically choose where to read. It is good for periodic signals and fixed patterns, and bad for variable lookups.
The MLP predictor adds bends: Linear(512, 128) + ReLU, Linear(128, 128) + ReLU, Linear(128, 32). With the same 256 embedding weights it has 256 + 65,664 + 16,512 + 4,128 = 86,560 weights. It can learn nonlinear functions, but the slide lists what it still cannot do. It has no per-position processing, it cannot route information by content, and the same weights apply whichever key token appeared. Both baselines read a fixed wiring. The transformer builds its wiring from the data, every time.
Chapter 7
Check the model on a signal that anything can learn, then on one whose next sample hides 25 steps back
A good test starts with a case you can solve in your head. If the machine fails there, the bug is in the machine. The lecture opens its experiments with the easiest signal possible, and then moves to one that is genuinely hard.
The first signal is x[n] = sin(2πn/16), quantized to Q = 32 levels. Its period is P = 16, so it repeats every 16 samples. After quantizing it uses only 9 unique tokens. It follows token[n] = token[n + 16] without exception. So next-token prediction reduces to copying the token from 16 steps back.
Slide 30 lists what is enough to solve it. The context must hold a full period: K ≥ P, so K = 16 works. One layer is enough, since there is no multi-step reasoning (L = 1). One head is enough, since there is one copy pattern (H = 1). The baselines can do it too, because a fixed position-to-output map suffices. The expected result on slide 29: all models reach 100% accuracy; if any fails, you have a bug.
The training curves (slide 31) show all three converging fast. The MLP gets the lowest loss by epoch 5 thanks to its nonlinear capacity. The GPT converges slowest, because 158K weights are overkill for this task. All reach 100% token accuracy despite different loss values. Loss and accuracy measure different things: loss rewards confidence, accuracy only counts the top guess.
Explore the signals below, including the chaotic ones, to see how different they are.
Choose a signal. The blue curve is the signal, the pink dots are its 32-level tokens. Read how many different tokens it uses and how often the next token equals the current one.
Mackey-Glass is generated with the lecture’s discrete update (slide 33), starting from a seeded near-constant history, so the same curves appear on every visit; the exact wiggles differ from the slide’s plots. Tokens: 32 levels, range −1 to 1 for the sine, 0 to 2 for Mackey-Glass.
The Mackey-Glass equation was written to model how the body controls white blood cell production, a process called hematopoiesis. The body senses how many cells exist and adjusts production, but the sensing is delayed: today’s production responds to the level τ time units ago. In math (slide 32), with xτ = x(t − τ):
dx/dt = β xτ / (1 + xτ10) − γ x(t)
The first term is production: it grows with the old level xτ and then saturates, because 1 + x10 grows so fast that the fraction shrinks again for large x. That saturation stops unbounded growth. The second term is loss: cells die at rate γ times the current level. For small τ the curve settles into a smooth wave. For large τ it turns chaotic, meaning tiny differences in the start grow into very different futures, and the curve never repeats exactly.
The lecture uses τ = 25 and the discrete update (with β = 0.3, γ = 0.1):
x[n+1] = x[n] + 0.3 · x[n−25] / (1 + x[n−25]10) − 0.1 · x[n]
Work one step. Say x[n] = 1.0 and x[n−25] = 1.2. Then 1.210 = 6.19, so the fraction is 0.3 × 1.2 / 7.19 = 0.050, and x[n+1] = 1.0 + 0.050 − 0.1 = 0.950. Change the old value to 0.8 and the same x[n] gives 1.0 + 0.217 − 0.1 = 1.117. The next sample depends on x[n−25] strongly. Now the challenge reads clearly: predicting x[n+1] requires the value exactly 25 steps back. A model that cannot look back 25 steps will fail.
This is the construction from Chapter 4, used on purpose. One head gets WQ = I and WK = a rotation by 25ω. Its score is cos((i − j − 25)ω) summed over frequencies, which peaks at j = i − 25. After the softmax, the weight is near 1 on x[n−25] and near 0 elsewhere. The head reads the delayed sample. Then the MLP computes the nonlinear term 0.3x/(1 + x10) from what was read. The slide’s summary: attention is the read operation, the MLP is the nonlinear compute operation.
The MLP baseline sees a flat 512-number vector and must discover that position n−25 matters, with no help from structure. The linear baseline cannot even compute the bend. Slide 37 turns this into a diagnostic test for context length:
| Choice | What it means for Mackey-Glass (τ = 25) |
|---|---|
| K ≤ 25 | Impossible: the window does not contain x[n−25]. |
| K ≈ 32 | Barely enough: it sees the needed point, with little extra context. |
| K = 64 | Comfortable: it contains x[n−25], x[n−1] and more. |
| H ≥ 1 | At least one head can specialize in offset 25. |
| L = 1 | Often enough: retrieve and compute in one block. |
| Large dff | Helps approximate the nonlinearity after retrieval. |
Test the first row yourself. The device below uses the same hand-built head as the hero, with the correct delay of 25, and sweeps the window length. Each bar is the share of 100 next tokens it gets exactly right.
Each bar is one window length. Red bars cannot see offset 25. Drag the marker to read a bar.
Illustrative: a hand-built head with delay 25 plus one exact Mackey-Glass update, scored on 100 samples of our seeded series. It is not a trained model. The lecture’s trained results on this task (slide 62): linear 37.5%, MLP 44.1%, GPT 54.0%.
Below K = 26 the head cannot see its target and the score drops to the level of a guess. From K = 26 up, the score jumps and then holds. The extra context past 26 adds nothing to this task, which is why K = 32 is called barely enough but enough. The slide-36 curves tell the training story: the MLP reaches the lowest train loss but its validation loss plateaus (it overfits, memorizing the training windows). The GPT has the lowest validation loss, since attention generalizes. The linear model underfits: it cannot learn the nonlinear recurrence.
Chapter 8
Follow a delay that changes with a key, a stack that needs depth, and an operation that must be read before it is applied
Imagine a clerk with a stack of forms. A sticky note on top says “check the figure 29 pages back.” Later another note says “now check 41 pages back.” To do the job the clerk first reads the note, then flips to the right page, then does the arithmetic. Three signals in the lecture are built to demand exactly these skills, in rising order of difficulty. They are made of tokens directly, with no quantizing step.
Slide 38 sets the stage. Four key tokens, 28 to 31, each select a delay D from {17, 29, 41, 53}. Between keys, the sequence is made of value tokens, 0 to 27, which follow the rule
x[n] = (3 · x[n − D] + 7) mod 28
The word mod means “the remainder after dividing”: 34 mod 28 = 6, because 28 goes into 34 once with 6 left over. To predict a value token, the model must find the active key and learn D, then look back D steps, then compute 3x + 7 mod 28. Slide 39 works a case. The sequence starts [29, 11, 1, 21, 27, 1, …], so D = 29. Later at time n, if x[n − 29] = 9, then x[n] = (3 · 9 + 7) mod 28 = 34 mod 28 = 6. Try your own key and value.
Pick a key token. It sets the delay. Then set the value that sits that far back and read the answer. Violet marks the key, warm marks the token the model must read.
The delay set {17, 29, 41, 53}, the key range 28 to 31 and the rule are the lecture’s (slide 38). The slide’s example confirms key 29 gives D = 29; the other pairings are assumed in key order. Strip contents other than the key and the read token are illustrative.
The multi-head solution on slide 40 splits the work. Head 1 finds the most recent key token. Key tokens get distinctive embeddings, so the head’s query matches them, and its value vector says which delay is active. After this head, position n knows D. Heads 2 to 4 each look back one delay: peaked at offset −17, −29 and −41, using the rotation construction of Chapter 4. The MLP computes (3x + 7) mod 28 from what was read. A flat model fails here, as the slide says, because it cannot choose which of 64 positions to read based on the value of a key token.
The slide-42 analogy ties the chapter together. Self-attention is a differentiable, content-addressable memory. Content-addressable means you find an item by what it contains, not by an index. Differentiable means the whole lookup is smooth, so gradient descent can train it.
| Memory operation | Attention | Signal 3 example |
|---|---|---|
| Address | query qi = WQ hi | “I need the value at delay D” |
| Memory slots | key kj = WK hj | Key tokens produce matching keys |
| Stored values | value vj = WV hj | Token content at each position |
| Read operation | ∑ αij vj | Weighted retrieval |
Contrast this with a plain lookup table: a table returns one exact entry, while attention returns a soft blend. That softness is what lets gradients flow. The training curves on slide 41 show the effect. The GPT’s validation loss falls to 0.79, far below the baselines. The MLP’s validation loss rises after epoch 15, since it overfits the easy background tokens. The GPT’s train loss looks high because retrieval steps carry 10 times the weight (Chapter 9).
Now a task with memory that changes. Token 30 is an OPEN bracket, and the token after it is a tag, a label such as 7. Token 31 is a CLOSE. After each CLOSE the model must output the tag of the matching unmatched OPEN. That needs a stack, a pile where you add on top and remove from the top. Slide 44 works the sequence 30 7 30 2 31 31. See OPEN 7: stack = [7]. See OPEN 2: stack = [7, 2]. See CLOSE: output 2, pop, stack = [7]. See the next CLOSE: output 7. Step through that and two more.
Choose a sequence, then press Next token. OPEN pushes its tag on the stack. CLOSE pops the top and that tag is the answer.
The first sequence is slide 44. The other two are our own, answered by the same stack rule.
Why can’t one attention hop do this? “Nearest unmatched OPEN” is a stateful property: which OPEN is unmatched changes after every CLOSE. A model has to compute it in stages. Slide 45 sketches five: layer 1 finds all OPEN and CLOSE tokens; layer 2 matches inner pairs; layer 3 marks matched pairs as used; layer 4 finds the nearest unmatched OPEN; layer 5 routes its tag to the output. A model with fewer layers cannot finish the chain.
The depth sweep confirms it, on retrieval steps only: L = 1: 10.6%, L = 3: 9.4%, L = 5: 24.7%. At L ≤ 3 the model is near random. At L = 5 it has enough layers to compose the multi-step simulation. Slide 64 gives the rule of thumb: k-step reasoning often needs about k transformer layers. Try different depths below.
The five boxes are the five steps of the stack simulation. Choose how many layers the model has. Each layer can do one step.
Accuracies are the lecture’s conditional accuracy on retrieval steps for Bracket Matching (slides 45 and 64). The one-step-per-layer filling is our simplification of the rule of thumb on slide 64.
The training curves (slide 46): the GPT starts slow, with high train loss, but ends with the lowest validation loss, and it keeps improving through all epochs. Linear and MLP plateau early because they cannot solve stack matching.
Signal 5 is a tiny program. Token 30 is SET_OP: the next token sets an operation code from 0 to 3. Token 31 is APPLY: the next token is an argument x, and the model must output the result of the active operation. The four operations (slide 47) are identity, increment (x + 1) mod 30, double (2x) mod 30, and complement (29 − x) mod 30. Slide 48’s example: SET_OP 2 selects double, then APPLY 18 must output (2 · 18) mod 30 = 36 mod 30 = 6. With complement it would be 29 − 18 = 11.
Pick the active operation and the argument. The same argument gives different answers, so the model cannot learn one fixed map.
The four operations and the example argument 18 are slides 47 to 49. Token values other than those on the slides are illustrative.
The transformer pipeline (slide 49) has three steps. Attention finds the most recent SET_OP: the query asks “where is SET_OP?”, and SET_OP tokens have distinctive embeddings, so the weight peaks there. Reading the value gives the op code. Then the MLP implements a piecewise function: if op = 0 output the argument, if op = 1 output (x + 1) mod 30, if op = 2 output (2x) mod 30, if op = 3 output (29 − x) mod 30. An MLP alone cannot learn a fixed mapping from the argument, since the right answer depends on context it cannot reach. The result: GPT 27.9% against MLP 6.1% on retrieval steps, a gap of 21.8 percentage points. Its validation loss keeps decreasing; the MLP’s rises after about epoch 15.
Chapter 9
See why one fixed wiring cannot follow a moving delay, then walk the training pipeline and the loss weight that steers it
A mail room has one worker with a fixed routine: take the letter in slot 17, stamp it, send it on. That worker is fast and never confused, until the boss says “today the letter you need is in slot 41.” The routine cannot change, so every answer is wrong. The transformer is a worker who reads the boss’s note first. That is the whole reason flat models fail on Signals 3 to 5.
Slide 52 compares the two wirings. In the MLP and the linear model (flat input), all positions are mixed into one vector, the same weights apply to every input, and the model cannot adapt where to look. In the transformer, each position is processed on its own, attention selects the relevant positions, and routing depends on the input. Flat weights are a fixed map. Attention builds a map per input.
The slide ends with a capability table. Read it as a ladder of tasks, each needing more than the last:
| Capability | MLP | Transformer |
|---|---|---|
| Fixed patterns (the sine) | Yes | Yes |
| Fixed-offset lookup | Partially | Yes |
| Variable-offset lookup | No | Yes |
| Content-based retrieval | No | Yes |
| Multi-step reasoning | No | Yes, with several layers |
Why “partially” for a fixed offset? A flat model can learn a fixed wiring such as “read slot n − 25”, but it must discover this by gradient descent from a 512-number vector, and with chaotic data it tends to memorize instead. The next device makes the variable case plain. Pretend a flat model learned the wiring for D = 17, and ask what the key token does to each model.
The rows are the 64 earlier slots. A green ring means the model reads the slot the task needs. A red ring means it misses. Change the active delay and compare.
Illustrative: the flat model is a stand-in for any fixed wiring that learned the D = 17 slot. Real flat models learn blurry mixtures; the point is that their wiring does not change with the key.
Slide 54 shows how a raw signal becomes training data. First a signal generator makes the series. Signals 1 and 2 are then quantized to Q = 32 tokens. Signals 3 to 5 skip that step, since their tokens are made directly. Next, sliding windows of K = 64 tokens are cut: each window is 64 tokens of context with the next token as the target, then the window slides one step. A series of N tokens yields about N − 64 windows. The windows are split 75% train and 25% test. Training uses AdamW, a gradient method that scales each weight’s step by its own recent gradients and shrinks weights slightly each step (weight decay), with a cosine learning-rate schedule, where the step size falls along a half cosine curve from its starting value toward zero.
The loss is cross-entropy: for each target token, take −log of the probability the model gave it. A model that guessed uniformly over 32 tokens would score −log(1/32) = 3.47 on every token; a perfect model scores 0.
In Signals 3 to 5 most tokens are background. They are easy, because shallow heuristics predict them. A minority are events, the retrieval steps where the model must match an OPEN, find the last SET_OP, or use the right delay. About 85% of tokens are background. If every token counts equally, the loss is dominated by the easy majority, and the optimizer has little reason to learn attention. Slide 55 fixes it with a weight wi on each token:
Count the effect. Say 15% of tokens are events. Unweighted, events carry 15% of the loss weight. With w = 10, events carry 0.15 × 10 = 1.5 against 0.85 for the background: 1.5 / 2.35 = 63.8%. The optimizer now cares mostly about the hard steps, which is what forces it to learn the attention patterns that solve the task. Move the sliders to see the balance.
The top bar is the share of tokens. The bottom bar is the share of the loss weight. Warm is events, pale is background.
The weight of 10 and the roughly 85% background share are the lecture’s (slides 55 and 63). The share formula is f·w / (f·w + 1 − f); it counts weights, not the loss values themselves.
One consequence appears in the results: a weighted loss changes which model looks best by which number. Chapter 11 shows the GPT with lower global accuracy than the MLP on Signals 4 and 5, yet far higher accuracy on the retrieval steps.
Chapter 10
Scale MiniGPT up to GPT-2, then rotate queries and keys so that position enters the score as a pure offset
A model car and a real car share the same engine layout. The real one is bigger, uses stronger parts, and has a few upgrades. MiniGPT and GPT-2 are in the same relation. Slide 56 puts it plainly: GPT-2 keeps the same core block but scales up and uses a different tokenizer.
The same core ideas carry over: causal self-attention with a triangular mask, learned token plus position embeddings, residual connections and LayerNorm, and autoregressive training that predicts the next token. What changes is size and a few details:
| Part | MiniGPT | GPT-2 |
|---|---|---|
| Tokenizer | Toy vocabulary, V = 32 | BPE (byte pair encoding, subword pieces), V ≈ 50,257 |
| Context length | K = 64 | K = 1024 |
| MLP | dff = 4d = 256 | dff = 4d with GELU |
| Output layer | Its own 64×32 head | Weight tying: shares the embedding matrix |
GPT-2 comes in four standard sizes (slide 57), all the same architecture with different L, H and d. Per-head width is dk = d/H, for example 64 for Small. The learned position embedding is WP in R1024×d, and dff = 4d, for example 3072 when d = 768.
| Model | Parameters | Layers L | Heads H | Width d |
|---|---|---|---|---|
| GPT-2 Small | ∼124M | 12 | 12 | 768 |
| GPT-2 Medium | ∼355M | 24 | 16 | 1024 |
| GPT-2 Large | ∼774M | 36 | 20 | 1280 |
| GPT-2 XL | ∼1.5B | 48 | 25 | 1600 |
Check the Small count with the counter from Chapter 6: choose the GPT-2 Small preset and it reports about 124 million. The same formula that gave MiniGPT its 158,272 gives GPT-2 its size. Only the numbers changed.
One GPT-2 block takes h(ℓ) of shape (K, d) and returns h(ℓ+1) of the same shape. It uses pre-LN, meaning LayerNorm comes before each sub-layer, and the residual path stays clean:
h̃ = LN(h(ℓ)), h′ = h(ℓ) + MHA(h̃), h̃′ = LN(h′), h(ℓ+1) = h′ + MLP(h̃′)
MLP(x) = W2 GELU(W1 x + b1) + b2, W1 in Rd×4d, W2 in R4d×d
GELU is a smooth bend: GELU(x) = x Φ(x), where Φ is the standard normal cumulative distribution (the chance a standard bell-curve number falls below x). It acts like ReLU but without a sharp corner.
The input is hi(0) = WE[ti] + WP[i], exactly Chapter 2. After L blocks and a final LayerNorm, the logits are logitsi = hi(L) WET, a vector of V scores. This is weight tying: the output layer reuses the embedding matrix, transposed. The logic is that a token’s input vector and its output direction should agree, and it saves V × d weights, about 38.6 million for GPT-2 Small. The tokenizer note matters too: GPT-2 tokens are subword pieces. In the homework the toy vocabulary already holds the task’s symbols.
Modern language models mostly swap additive positions for RoPE (Su et al., 2021). Instead of adding pi before attention, RoPE rotates the query and key after they are projected. For token embedding xi: qi = xi WQ and ki = xi WK. Then each pair of entries is turned by an angle that grows with the position: θi,k = iωk, with the same ωk = 10000−2k/d as Chapter 3. The rotated vectors are q̃i = R(i) qi and k̃i = R(i) ki.
Rotations undo each other: R(i)T R(j) = R(j − i). So the score becomes q̃iT k̃j = qiT R(j − i) kj. Position enters the score only through the offset j − i. This is the Chapter 3 trick, built directly into the score instead of left for the weights to learn. Slide 60 gives the numbers for one pair with ω0 = 1: take q = (1, 0), k = (1, 0), i = 5, j = 2. Then q̃ = (cos 5, sin 5) = (0.284, −0.959) and k̃ = (cos 2, sin 2) = (−0.416, 0.909), and q̃T k̃ = cos(5 − 2) = cos 3 = −0.990. The slide notes RoPE is widely used in modern decoder-only models such as Qwen, LLaMA, Gemma and Mistral. See the full lesson on the original paper: RoFormer.
The warm arrow is the rotated query at position i, the violet arrow the rotated key at position j. Their dot product is cosine of the gap. Press Shift both by +4 and watch it hold still.
One frequency pair, ω = 1, with q = k = (1, 0), as in the lecture’s numerical example on slide 60. Real models rotate many pairs at many frequencies.
Compare with additive positions. There, position is mixed into the input and the model must learn to read offsets out of the sum. With RoPE the score already depends on the offset, so a head aimed at “3 steps back” stays aimed there at any absolute place in the sequence.
Chapter 11
Read the lecture’s result tables honestly, then keep the numbers, the checklist and the core code
A scoreboard tells you who won. It does not tell you why, or how close the game was. The last slides of the lecture give the scoreboard for all five signals and three models. Read it with care, because one column hides a trap.
Slide 62 lists accuracy for Linear, MLP and GPT. Signal 1 and 2 rows are global accuracy, over all positions. Signals 3 to 5 are conditional accuracy, only at event positions, where retrieval is needed. The gap column is GPT minus MLP: Mackey-Glass +9.9, Switching Delay +6.8, Bracket Matching +2.3, Conditional Routing +21.8 points. The largest gap, the slide says, is Conditional Routing, since read-then-compute is native to transformers. The smallest, at L = 3, is Bracket Matching, which needs deeper models.
Choose a table. Each group is one signal. Yellow bars are the flat baselines, the warm bar is the transformer.
Every number is read from slides 62 to 64. Slide 62 lists Bracket Matching GPT at 9.4%, the L = 3 value; slides 63 and 64 list 24.7%, the L = 5 value from the depth sweep. Both are shown where the slides give them.
Slide 63 warns that in these toy signals GPT’s global accuracy can be lower than the MLP’s. On Bracket Matching, global accuracy is 68.4% (linear), 68.0% (MLP) and 60.5% (GPT). On the retrieval steps only it is 5.9%, 7.1% and 24.7%. For Conditional Routing: global 51.1%, 53.0%, 44.6%, and conditional 4.8%, 6.1%, 27.9%.
The reason: about 85% of the tokens are easy background. MLP and linear models optimize the easy majority and score high globally. The GPT, pushed by the 10× loss weight, spends capacity on the hard retrieval task, so it scores lower on the background and higher on the part that matters. The lecture’s advice: conditional accuracy is the right metric for tasks that need attention. This is a general lesson: pick the metric that measures the skill you care about, not the one that averages it away.
Slide 64 sweeps the transformer’s layers on retrieval steps. Switching Delay climbs steadily: 76.4%, 78.7%, 82.1% for L = 1, 3, 5. Bracket Matching has a sharp threshold: 10.6%, 9.4%, 24.7%. Conditional Routing saturates early: 23.8%, 27.9%, 26.5%, since a single hop is enough. The rule of thumb: k-step reasoning often needs about k transformer layers.
The final slide sorts the world into when attention helps: not for fixed periodic patterns (a flat model already ties it); yes for fixed-offset delay lookups, variable-offset retrieval, content-addressable memory and read-then-compute pipelines; and doubly yes for hierarchical, multi-step reasoning, which needs depth.
In one paragraph. Quantize a signal into tokens. Embed each token and add a position vector. Let a causal, multi-head attention read the right earlier tokens, steered by a position kernel that peaks at the wanted offset, and let a per-token MLP compute on what it read. Stack blocks with LayerNorm and residual paths. Train on windows with a loss that weights the hard steps. Attention wins whenever the answer sits at an offset that changes with the data or must be found by content; a flat model ties it when the wiring is fixed.
| What | Number | Why it matters |
|---|---|---|
| Quantizer | Δ = (xmax − xmin)/(B − 1); token = round((xc − xmin)/Δ) | Turns samples into a vocabulary of B tokens |
| Sinusoid wavelengths | λk = 2π · 100002k/d, from about 6 to about 2π · 10000 | Multi-resolution position signature |
| Position dot product | ∑ cos((i − j)ωk); peak d/2 (4 at d = 8) | A distance meter built from positions |
| MiniGPT | V = 32, d = 64, K = 64, L = 3, H = 4, dk = 16: 158,272 weights | Small enough to count by hand |
| Baselines | Linear 16,672; MLP 86,560 weights | Same task, fixed wiring |
| Sine | P = 16, 9 tokens, all models 100% | A failure here means a bug |
| Mackey-Glass | τ = 25 needs K > 25; linear 37.5, MLP 44.1, GPT 54.0 (%) | A test of context length and delay lookup |
| Switching delay | D in {17, 29, 41, 53}; GPT 78.7% vs MLP 71.9% | Content picks the offset |
| Brackets | L = 1, 3, 5: 10.6, 9.4, 24.7 (%) | Depth threshold at 5 layers |
| Routing | GPT 27.9% vs MLP 6.1%, +21.8 points | Read, then compute |
| Loss weight | 10 on events, 1 on background (about 85%) | Points the optimizer at retrieval |
| GPT-2 Small | 124M, L = 12, H = 12, d = 768, K = 1024, V ≈ 50,257 | Same recipe, scaled |
| RoPE example | i = 5, j = 2: q̃Tk̃ = cos 3 = −0.990 | Score depends on the offset only |
Checklist before you trust a signal-prediction result.
The core, as code. Shapes in the comments; biases left out of attention for brevity.
pythonimport numpy as np def quantize(x, B, lo, hi): # real samples -> tokens in 0..B-1 delta = (hi - lo) / (B - 1) return np.round((np.clip(x, lo, hi) - lo) / delta).astype(int) def sinusoid(K, d): # position table, shape (K, d) i = np.arange(K)[:, None]; k = np.arange(d // 2)[None, :] w = 10000.0 ** (-2 * k / d) p = np.zeros((K, d)); p[:, 0::2] = np.sin(i * w); p[:, 1::2] = np.cos(i * w) return p def layer_norm(x, g, b, eps=1e-5): # per token, over the d channels mu = x.mean(-1, keepdims=True); var = x.var(-1, keepdims=True) return g * (x - mu) / np.sqrt(var + eps) + b def softmax(s): e = np.exp(s - s.max(-1, keepdims=True)); return e / e.sum(-1, keepdims=True) def attention(h, Wq, Wk, Wv, Wo, H): # h: (K, d) K, d = h.shape; dk = d // H q, k, v = (h @ W for W in (Wq, Wk, Wv)) q, k, v = (a.reshape(K, H, dk).transpose(1, 0, 2) for a in (q, k, v)) # (H, K, dk) s = q @ k.transpose(0, 2, 1) / np.sqrt(dk) # (H, K, K) s = np.where(np.tril(np.ones((K, K), bool)), s, -np.inf) # causal mask out = softmax(s) @ v # (H, K, dk) return out.transpose(1, 0, 2).reshape(K, d) @ Wo # (K, d) def block(h, p): # pre-LN block, shape (K, d) in and out h = h + attention(layer_norm(h, p.g1, p.b1), p.Wq, p.Wk, p.Wv, p.Wo, p.H) x = layer_norm(h, p.g2, p.b2) return h + np.maximum(0, x @ p.W1 + p.c1) @ p.W2 + p.c2 def weighted_loss(logits, target, event): # logits (N, V), target (N,), event (N,) bool p = softmax(logits)[np.arange(len(target)), target] w = np.where(event, 10.0, 1.0) return np.mean(w * -np.log(p))
Keep going.
Now press Present or Teach and explain, from memory, how one head finds x[n−25]: the tokens, the position vectors, the rotated key, the softmax, and the MLP step that follows. Then go back to the instrument at the top, set the window to 20 and then to 40, and say why the hit rate jumps.
Credit: this lesson follows the Transformers lecture of Stanford EE269, Signal Processing and Quantization for Machine Learning (Winter 2026), by Mert Pilanci. Course site: web.stanford.edu/class/ee269. Slides: Lecture_Transformers.pdf. All figures, devices and wording are our own; every number marked as the lecture’s comes from its slides, and toy numbers are labelled.