Every Letter Looks Back

The same four sentences as example 7, read by a different kind of network. A transformer has no memory that is handed along step by step. Instead every character looks directly at every character before it, decides how much to borrow from each, and predicts what comes next. All sixteen positions of a window are computed at once. This is the architecture inside GPT-style language models, shrunk to 855 parameters so every number can be checked.

What is a transformer?

A network that reads by looking, not by remembering. Example 7's recurrent network read text one character at a time and squeezed everything it had seen into a 12-number memory. Whatever was not in the memory was gone. A transformer keeps every position in view. When it works on the 16th character, it can look straight at the 1st, the 9th and the 15th, and choose how much to take from each. That choosing is called attention, and it is the only new idea. The rest is pieces you have already met: weighted sums, ReLU, softmax, and the same three moves of predict, measure the miss, nudge every weight.

Every character becomes a vector. Instead of a one-hot vector picking a column, each of the 15 characters owns a learned row of 8 numbers, its embedding. Because attention on its own cannot tell first from last, a second table gives each of the 16 positions its own 8 numbers, and the two are added: "t at position 1" is the t-row plus the position-1 row.

Attention is a lookup where every entry answers a little. Each position makes three vectors from its embedding: a query (what am I looking for?), a key (what do I contain?) and a value (what do I hand over if chosen?). A position scores every earlier position by the dot product of its query with that position's key, turns the scores into weights with a softmax, and takes the weighted average of the values. High score, big share. Because the task is to predict the next character, a position may only look at itself and what came before: peeking ahead would be cheating. That rule is the causal mask, and it is what makes this a language model that can write text.

Then a small ordinary network, applied to each position on its own. The attention output is added back onto the embedding (a residual connection: the original can pass through untouched), and a two-layer ReLU network of the kind in example 4 refines the result, again added on. Finally 15 weighted sums and a softmax give the next-character probabilities, exactly as in example 7. Attention is where positions talk to each other; the feed-forward network is where each position thinks alone.

Why it took over. Nothing here runs step by step: all 16 positions are computed together as a few matrix products, so training spreads across thousands of processors. And the path from any position back to any earlier one is a single hop, so the blame from a late mistake reaches an early cause undiminished. Stage 9 shows it: where example 7's blame shrank as it travelled back through time, here it arrives at position 1 as strong as at position 16.

What the real thing adds. This page has one attention head, one layer, and no normalization. A production model stacks the block dozens of times, runs several heads side by side so different heads can look for different things, normalizes the vectors between blocks, uses word pieces rather than characters, sees thousands of positions rather than 16, and is trained with a smarter optimizer than plain gradient descent. GPT-2 was 12 of these blocks, 768 numbers per position and 124 million parameters; the largest models today are the same design with far more of everything. The name comes from the 2017 paper that introduced it, "Attention Is All You Need".

embedding
the learned 8-number vector that stands for a character, or for a position
query, key, value
three vectors each position makes from its embedding: what it seeks, what it offers, what it hands over
attention weights
a position's softmax over its scores; how much of each earlier value it takes
causal mask
the rule that a position may look only at itself and earlier positions
residual connection
adding a block's input to its output so the input can pass straight through
head, layer
one attention pattern; one attention-plus-feed-forward block. Real models have many of both

The network over one window

Each column is one position. Top to bottom: the character, its 8-number embedding, the attention matrix (row t shows where position t looks: only at columns up to t, darker = larger share), the 8 numbers after attention and feed-forward, and the predicted next character with the probability given to the true one. Yellow = being computed, green = computed, red dashed = receiving blame.

Keyboard: → or space for Next, ← for Back. An epoch is the 74 windows of the training text, each 16 characters, sliding one character at a time. About 500 epochs gives good text.

What is new in this example

Two embeddings, added. x_t = E[c_t] + P[t]: row c_t of the character table plus row t of the position table. Both tables are learned. Stage 2 is eight additions, checkable by hand.

Scaled dot-product attention. Score s_tj = q_t·k_j / √8 for every j ≤ t, then a_t = softmax over those scores, then att_t = Σ_j a_tj v_j. Position 1 has a single score, so its weight is 1 and its attention output is just v₁. Position 2 has two scores, and a softmax over two numbers is a sigmoid of their difference, so stage 4 can be checked with the σ table from example 3.

Sliding windows. Example 7 cut the text into six fixed snippets. This model also has a position table, and with only six snippets it would learn "position 3 is usually e" instead of letter patterns, and then write nonsense when its window slides over new text. So it trains on every 16-character window of the text, 74 of them, and when it writes it always looks at the last 16 characters it produced.

Residual connections change the backward pass. Where a value was added straight through, δ passes straight through too, plus whatever comes back through the branch: δr_t = δu_t + W₁ᵀδpre_t. A residual is a wire that never attenuates blame, which is why blocks can be stacked a hundred deep.

Backward through attention. A value v_j was used by every later position that looked at it, so it collects blame from all of them, weighted by how much they looked: δv_j = Σ_t a_tj δatt_t. The weights themselves get blame through the softmax, which sends it on to the queries and keys. That is the whole reason attention learns where to look.

Mean over positions. The loss is averaged over the 16 positions rather than summed, so δz_t is (p_t − truth)/16. With the sum, plain gradient descent on this model overshoots and the loss bounces; averaging is what every modern training recipe does.

Continue the text

Only the 15 characters of the corpus are allowed: letters a c d e g h l m n o r s t, space and full stop. The bars show what the network expects next.

Where the last character of the seed is looking (its attention weights over the last 16 characters, darker = more):

The weight tables

E: 15 characters × 8, the character embeddings. P: 16 positions × 8. W_q, W_k, W_v: 8 × 8 each. W₁: 16 × 8 and W₂: 8 × 16, the feed-forward network. W_out: 15 × 8, the vote for the next character. With the 39 biases, 855 parameters.

Loss per epoch

training windowsheld-out windows

Nothing trained yet. Cross-entropy per character; ln 15 ≈ 2.71 is pure guessing.

The corpus

training text, 90 characters, 74 windows of 16
held-out text, 45 characters, 29 windows: the same words in sentences never seen

σ lookup table, for a softmax over two scores

dσ(d)1 − σ(d)

softmax(s₁, s₂) = (σ(s₁ − s₂), σ(s₂ − s₁)). For d = s₁ − s₂ read the first weight off the table; the second is 1 minus it. The same σ as example 3.

Cheat sheet

Forward, all positions at once

x_t = E[c_t] + P[t]
q_t = W_q x_t   k_t = W_k x_t   v_t = W_v x_t
s_tj = q_t·k_j / √8 for j ≤ t   a_t = softmax(s_t)   att_t = Σ_j a_tj v_j
r_t = x_t + att_t
u_t = r_t + W₂ relu(W₁ r_t + b₁) + b₂
p_t = softmax(W_out u_t + b_out)   L = mean over t of −ln p_t[next]

Backward

δz_t = (p_t − onehot(next_t)) / 16
δu_t = W_outᵀ δz_t   δpre_t = (W₂ᵀ δu_t) ⊙ [pre_t > 0]   δr_t = δu_t + W₁ᵀ δpre_t
δatt_t = δr_t   δv_j = Σ_t a_tj δatt_t   δa_tj = δatt_t·v_j
δs_tj = a_tj (δa_tj − Σ_k a_tk δa_tk)   δq_t = Σ_j δs_tj k_j / √8   δk_j = Σ_t δs_tj q_t / √8
δx_t = δr_t + W_qᵀ δq_t + W_kᵀ δk_t + W_vᵀ δv_t   ∂E[c_t] += δx_t   ∂P[t] += δx_t
∂W_q = Σ_t δq_t x_tᵀ   (likewise W_k, W_v, W₁, W₂, W_out with their own inputs)

Update

clip every gradient entry to ±1, then p ← p − 0.04 · ∂L/∂p