cat /en/where-pinocchio-looks/
MDN-121:40
SERIES Inside the Puppet · Chapter 12

Where Pinocchio looks

· Artificial Intelligence · 7 min read

The LSTM of chapter 9 carries the past in a state that is updated one character at a time: to know what was there a hundred characters ago, it must have kept it for a hundred steps. Attention, the idea on which the Transformer rests, does something different. Each position looks directly at all the ones before it and decides how much to take from each.

Chapter 12 of the book builds it from three ingredients. Each position asks a question (query, Q), shows a label (key, K) and offers a content (value, V). The dot product between the question of one position and the labels of the others says how similar they are; the softmax turns it into weights that add up to 1; the result is the weighted average of the contents. Two details complete the recipe. The scores are divided by the square root of d, the length of the vectors, because otherwise they grow with d and the softmax locks onto a single winner. And a mask hides the future: a model that writes cannot look at the characters it has yet to write.

DEMO Where Pinocchio looks · about this demo · full screen ↗

On the left is the chapter’s GPT, with a single attention head and 62,469 parameters, trained on Pinocchio with the book’s seed; its weights run in the browser. Type a sentence: each row of the grid is a character that looks, each column a character that is looked at, brighter where attention is stronger. Above the diagonal everything is dark, because that is the future. Click a row to see where that character looks. On the right, the book’s worked example by hand, with the two knobs of the recipe.

Three experiments

1. Where it looks. Press “1”. The sentence is the one in figure 12.1 of the book, “— Babbo mio! — gridò Pinocchio.” (“Daddy!” cried Pinocchio.), and the selected row is that of the “r” in “gridò”. It looks mostly at itself (42%), then at the “g” (24%) and at the space before (19%). Click the other rows: attention forms a narrow strip along the diagonal, the last two or three characters. Inside “Pinocchio” the strip widens towards the earlier letters of the word. A single head, with 64 numbers, learns the most useful thing of all: looking at the last letters of the word being written.

2. No looking at the future. Press “2” and look at the weights. With the mask, the first position can look only at itself and has weight 1. The second splits between the first two, 0.33 and 0.67. The third sees everything and does not change. The covered positions have a score of −∞, and the softmax of −∞ is exactly zero. Remove the mask: the first position takes 40% of its content from the third, that is, from the future.

3. Why the square root of d. Press “3”. Without the division, the example’s scores are 0, 1 and 2 and the softmax is already sharper. With random vectors of 256 numbers, below, the difference becomes huge. Without dividing, the best of eight candidates takes on average 93.6% of the weight: the softmax is almost a maximum, and a maximum does not let the gradient through. Dividing by 16, the weight drops to 35.9%, and the network can still learn.

The same experiment in Python

The code redoes the worked example and the saturation calculation, then trains the GPT with one head as in the chapter (a couple of minutes without a GPU) and prints where the book’s three characters look.

!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/pinocchio.txt

import torch
import torch.nn as nn
import torch.nn.functional as F

# 2. Questions, labels, contents: the worked example, with the mask
Q = K = torch.tensor([[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
V = torch.tensor([[1.0, 0.0], [0.0, 2.0], [3.0, 3.0]])
punteggi = Q @ K.T / 2 ** 0.5                         # divided by the square root of d = 2
maschera = torch.tril(torch.ones(3, 3))
pesi = F.softmax(punteggi.masked_fill(maschera == 0, float("-inf")), dim=1)
print(pesi.round(decimals=3))
# [[1, 0, 0], [0.33, 0.67, 0], [0.248, 0.248, 0.503]]

# 3. Why the square root of d: the softmax that saturates
torch.manual_seed(2026)
d = 256
q, k = torch.randn(1000, d), torch.randn(1000, 8, d)
p = (k @ q.unsqueeze(-1)).squeeze(-1)                 # 1000 rows of 8 scores
print(round(F.softmax(p, 1).max(1).values.mean().item(), 3), round(F.softmax(p / d ** 0.5, 1).max(1).values.mean().item(), 3))
# 0.936 0.359

# 1. Where it looks: the GPT with one attention head, trained as in the chapter
testo = open("pinocchio.txt", encoding="utf-8").read()
caratteri = sorted(set(testo))
Vc = len(caratteri)
stoi = {c: i for i, c in enumerate(caratteri)}
itos = {i: c for i, c in enumerate(caratteri)}
dati = torch.tensor([stoi[c] for c in testo])
n = int(0.9 * len(dati))
train, val = dati[:n], dati[n:]
T = 128

def finestre(B=32):
    ix = torch.randint(0, len(train) - T - 1, (B,))
    X = torch.stack([train[i : i + T] for i in ix])
    Y = torch.stack([train[i + 1 : i + T + 1] for i in ix])
    return X, Y

nv = (len(val) - 1) // T
Xva = val[: nv * T].view(nv, T)
Yva = val[1 : nv * T + 1].view(nv, T)
class Testa(nn.Module):
    def __init__(self, D, Dt):
        super().__init__()
        self.query = nn.Linear(D, Dt, bias=False)     # what I am looking for
        self.key = nn.Linear(D, Dt, bias=False)       # what I offer
        self.value = nn.Linear(D, Dt, bias=False)     # what I give, if I am chosen
        self.register_buffer("maschera", torch.tril(torch.ones(T, T)))

    def forward(self, x):
        B, t, _ = x.shape
        Q, K, V = self.query(x), self.key(x), self.value(x)
        A = Q @ K.transpose(1, 2) / K.shape[-1] ** 0.5         # (B, t, t)
        A = A.masked_fill(self.maschera[:t, :t] == 0, float("-inf"))
        A = F.softmax(A, dim=-1)
        self.pesi = A                                          # keep them so we can look at them
        return A @ V                                           # (B, t, Dt)

class GPT(nn.Module):
    def __init__(self, D=64, pensiero=False):
        super().__init__()
        self.embedding = nn.Embedding(Vc, D)
        self.posizione = nn.Embedding(T, D)                    # one vector for each position
        self.testa = Testa(D, D)
        self.pensiero = nn.Sequential(nn.Linear(D, 4 * D), nn.ReLU(),
                                      nn.Linear(4 * D, D)) if pensiero else None
        self.uscita = nn.Linear(D, Vc)

    def forward(self, X):
        t = X.shape[1]
        x = self.embedding(X) + self.posizione(torch.arange(t))
        x = self.testa(x)
        if self.pensiero is not None:
            x = self.pensiero(x)
        return self.uscita(x)
torch.manual_seed(2026)
gpt = GPT(pensiero=True)
ott = torch.optim.AdamW(gpt.parameters(), lr=1e-3, weight_decay=0.01)
for passo in range(10001):                             # a couple of minutes without a GPU
    X, Y = finestre()
    L = F.cross_entropy(gpt(X).reshape(-1, Vc), Y.reshape(-1))
    ott.zero_grad(); L.backward(); ott.step()
gpt.eval()
with torch.no_grad():
    print(round(F.cross_entropy(gpt(Xva).reshape(-1, Vc), Yva.reshape(-1)).item(), 3))
# 1.716
frase = "— Babbo mio! — gridò Pinocchio."
with torch.no_grad():
    gpt(torch.tensor([[stoi[c] for c in frase]]))
A = gpt.testa.pesi[0]                                  # who looks at whom
for i in [7, 16, 29]:
    top = A[i].topk(3)
    print(repr(frase[: i + 1]), [(frase[j], round(v, 2)) for v, j in zip(top.values.tolist(), top.indices.tolist())])
# '— Babbo ' [(' ', 0.55), ('b', 0.17), ('o', 0.14)]
# '— Babbo mio! — gr' [('r', 0.42), ('g', 0.24), (' ', 0.19)]
# '— Babbo mio! — gridò Pinocchio' [('o', 0.33), ('i', 0.29), ('h', 0.26)]

In the book

This lab accompanies chapter 12, “Attention”. The chapter starts from the average of the past and the trick of the triangular matrix, introduces questions, labels and contents with a worked example by hand, explains the square root of d and the causal mask, and builds a GPT with one attention head, first on its own and then followed by a “thinking” layer. With 10,000 steps its validation loss falls to 1.716.

COVER COMING SOON
dltp · 2026

Deep Learning. Teoria, matematica e pratica delle reti neurali

Michele di Nuzzo · in Italian

Over the course of the book we build a small language model, a GPT, from scratch and grow it one piece at a time. At the start it is a model that counts which letter follows which. At the end it is a complete Transformer that writes dialogue, answers questions, reads images and draws the digits we ask for in words.

[the book’s page] [shop links coming soon]

The “Inside the Puppet” series