Eight books and one
The mini-GPT of chapter 14 has read a single book, 217 thousand characters. The scaling laws say that to improve you need a larger model and more data, together. The book’s Workshop C goes and gets the data where they are: seven other works by Collodi, from the fairy tales of I racconti delle fate to Giannettino; three of these exist only as scans, and their text carries the reading errors along with it. In all, 2.4 million characters, eleven times Pinocchio.
With more text the model can grow: 192 numbers per vector, 6 attention heads, 6 blocks, 2.7 million parameters. And training becomes long: 10,000 steps on a GPU, with a learning rate that rises slowly at the start and then falls along a cosine, and with intermediate checkpoints to resume if the session is interrupted. In the end the loss on the Pinocchio validation set is 1.209, against 1.353 for the mini-GPT. Then the model is specialised: another 1,500 steps on Pinocchio alone, the fine-tuning, and the loss drops to 1.174.
On the left the two models write from the same beginning, with the same seed and the Workshop’s settings: temperature 0.8 and top-p 0.9. At the top is the general model, below it the one specialised on Pinocchio. On the right are the losses of the two models on each of the eight works, measured on the final part that neither of them has seen. To fit in a page, the weights of the two models are at 4 bits, as in chapter 16: it costs about one hundredth of loss.
Three experiments
1. The Fairy. Press “1”: it is the beginning used in the Workshop, “— Pinocchio, — disse la Fata,” (“Pinocchio,” said the Fairy). Read the two texts. The syntax is more solid than the mini-GPT’s, the dialogues are well built and the mangled words are few, but the meaning remains vague: the model knows how Collodi sounds, not what he tells.
2. Giannettino. Press “2”. “Giannettino” is the protagonist of another book by Collodi. With seed 2026, the general model carries on in some ordinary nineteenth-century Italian; the specialised one opens a dialogue, names a puppet and after a few lines writes “XXIV.”, the number of a chapter of Pinocchio. Change the seed: the tendency remains. In the Python code below, with PyTorch’s die, the general model brings in Minuzzolo, a character from Giannettino, while the specialised one goes straight to Pinocchio. Fine-tuning has pushed everything towards a single book: the specialised model sees Pinocchio everywhere.
3. What is forgotten. Press “3”. The upper bars of each pair are the general model, the lower ones the specialised model. On Pinocchio fine-tuning improves things, from 1.209 to 1.174. On all the other works it makes them worse: I racconti delle fate from 1.205 to 1.302, Un romanzo in vapore from 1.988 to 2.419. In 1,500 steps the model has forgotten part of what it knew about the rest of Collodi. This is catastrophic forgetting, and it comes with every specialisation: you gain where you insist, you lose elsewhere.
The same experiment in Python
The code downloads from the book’s repository the mini-GPT, the eight works and the two models of the Workshop, prepares the validation sets as in the Workshop, makes the two models write and measures the losses work by work. The measurement takes a few minutes without a GPU.
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/minigpt.py
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/pinocchio.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/racconti_delle_fate.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/giannettino.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/misteri_di_firenze.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/occhi_e_nasi.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/romanzo_in_vapore.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/storie_allegre.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/dati/collodi/ragazzi_grandi.txt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/modelli/minigpt_collodi.pt
!wget -q https://raw.githubusercontent.com/mid079/deep-learning-teoria-pratica/main/modelli/minigpt_collodi_pinocchio.pt
import torch
import torch.nn.functional as F
from collections import Counter
from minigpt import MiniGPT, finestre, T
OPERE = ["pinocchio", "racconti_delle_fate", "giannettino", "misteri_di_firenze",
"occhi_e_nasi", "romanzo_in_vapore", "storie_allegre", "ragazzi_grandi"]
testi = {o: open(f"{o}.txt", encoding="utf-8").read() for o in OPERE}
conta = Counter()
for t in testi.values():
conta.update(t) # how many times each character appears
rari = {c for c, n in conta.items() if n < 50} # fewer than 50 times in 2.4 million
testi = {o: "".join(c for c in t if c not in rari) for o, t in testi.items()}
caratteri = sorted(set("".join(testi.values())))
stoi = {c: i for i, c in enumerate(caratteri)}
itos = {i: c for i, c in enumerate(caratteri)}
Vc = len(caratteri)
codifica = lambda t: torch.tensor([stoi[c] for c in t])
def blocchi(dati): # consecutive windows, as in chapter 9
n = (len(dati) - 1) // T
return dati[: n * T].view(n, T), dati[1 : n * T + 1].view(n, T)
pin = codifica(testi["pinocchio"])
n = int(0.9 * len(pin))
pezzi_train, val_altri = [pin[:n]], {}
for o in OPERE[1:]:
d = codifica(testi[o])
k = int(0.95 * len(d)) # the last 5% of each work is left out
pezzi_train.append(d[:k])
val_altri[o] = blocchi(d[k:])
train = torch.cat(pezzi_train)
Xva, Yva = blocchi(pin[n:]) # the same validation set as in chapters 9-14
def valuta(modello, X, Y, lotto=64):
modello.eval()
with torch.no_grad():
somma = sum(F.cross_entropy(modello(X[i : i + lotto]).reshape(-1, Vc), Y[i : i + lotto].reshape(-1),
reduction="sum").item() for i in range(0, len(X), lotto))
modello.train()
return somma / X.numel()
Xal = torch.cat([v[0] for v in val_altri.values()])
Yal = torch.cat([v[1] for v in val_altri.values()])
def genera(modello, inizio, n=300, temperatura=0.8, top_p=0.9, seme=2026): # as in the Workshop
g = torch.Generator().manual_seed(seme)
contesto = [stoi[c] for c in inizio]
modello.eval()
with torch.no_grad():
for _ in range(n):
z = modello(torch.tensor([contesto[-T:]]))[0, -1] / temperatura
p_ord, idx = torch.sort(F.softmax(z, dim=0), descending=True)
z[idx[p_ord.cumsum(0) - p_ord > top_p]] = float("-inf") # the nucleus
contesto.append(torch.multinomial(F.softmax(z, dim=0), 1, generator=g).item())
return "".join(itos[i] for i in contesto)
# 1 and 2. The same beginning, the general model and the specialised one
for file in ["minigpt_collodi.pt", "minigpt_collodi_pinocchio.pt"]:
modello = MiniGPT(Vc, 192, 6, 6)
modello.load_state_dict(torch.load(file, map_location="cpu"))
print("---", file)
print(genera(modello, "Giannettino", 200))
# --- minigpt_collodi.pt
# Giannettino. — E qui a questo tempo di due grandi fiori conoscono la
# sorella. — E io non voglio carità di me! — gridò Minuzzolo di qualche ...
# --- minigpt_collodi_pinocchio.pt
# Giannettino. —
#
# Pinocchio, che lo vedeva un pezzo a un po' di pane di città sententiva ...
# 3. What is forgotten: the loss work by work, before and after fine-tuning (a few minutes)
for file in ["minigpt_collodi.pt", "minigpt_collodi_pinocchio.pt"]:
modello = MiniGPT(Vc, 192, 6, 6)
modello.load_state_dict(torch.load(file, map_location="cpu"))
perdite = {"pinocchio": valuta(modello, Xva, Yva)}
perdite.update({o: valuta(modello, X, Y) for o, (X, Y) in val_altri.items()})
print(file, {o: round(p, 3) for o, p in perdite.items()})
# minigpt_collodi.pt {'pinocchio': 1.209, 'racconti_delle_fate': 1.205, 'giannettino': 1.467, 'misteri_di_firenze': 1.375,
# 'occhi_e_nasi': 1.368, 'romanzo_in_vapore': 1.988, 'storie_allegre': 1.204, 'ragazzi_grandi': 1.25}
# minigpt_collodi_pinocchio.pt {'pinocchio': 1.174, 'racconti_delle_fate': 1.302, 'giannettino': 1.656, 'misteri_di_firenze': 1.517,
# 'occhi_e_nasi': 1.481, 'romanzo_in_vapore': 2.419, 'storie_allegre': 1.216, 'ragazzi_grandi': 1.376}
In the book
This lab accompanies Workshop C, “The GPT of all of Collodi”, between chapters 14 and 15. The Workshop collects and cleans the eight works, redoes the scaling laws with more data, introduces warmup with the cosine, saving and resuming training, training on a GPU, the work-by-work analysis and fine-tuning on Pinocchio. The specialised model is the starting point for the assistant of chapter 15.
The “Inside the Puppet” series
- Chapter 1 The teacher inside the text
- Chapter 2 Pinocchio turns into numbers
- Chapter 3 The loaded die
- Chapter 4 The neuron that learns to count
- Chapter 5 The engine in reverse
- Chapter 6 Bending the line
- Chapter 7 Bengio’s network
- Chapter 8 Training well
- Workshop A The diagnosis threshold
- Chapter 9 The puppet’s memory
- Workshop B The bag and the network
- Chapter 10 The token maker
- Chapter 11 The map of words
- Chapter 12 Where Pinocchio looks
- Chapter 13 Sixteen glances
- Chapter 14 The puppet’s thermometer
- Workshop C Eight books and one
- Chapter 15 The Cricket answers
- Chapter 16 How many bits are needed
- Chapter 17 Learning to say “I don’t know”
- Chapter 18 The Cricket with the open book
- Chapter 19 The puppet’s eyes
- Workshop D Thirty-two by thirty-two
- Chapter 20 The plane of digits
- Chapter 21 The pencil