The data is just text
Nobody writes question-and-answer pairs for this stage. The whole dataset is one file: about forty Shakespeare plays run together, 1,115,394 characters. The first 90% (1,003,854 characters) is used for training; the last 10% is held back so we can test the model on text it has never seen.
The examples come from the text itself. Take any stretch of it and ask, at every position, "given everything up to here, what is the next character?" The answer is already sitting in the file, one place to the right. So the target is the input shifted by one:
One training window, cut from the real file
The model reads the top row. At every column it must guess the bottom row, which is just the next character of the text. A real window is 256 characters long; this one is cut short to fit.
Each training step takes 64 random windows of 256 characters, so the model is graded on 16,384 next-character guesses at once. Over 5,000 steps that is 82 million graded guesses drawn from a million characters of text, so every character in the file gets used as a target roughly eighty times. That repetition matters later.
Characters become numbers
A neural network only does arithmetic, so text has to become integers first. This is the tokenizer's whole job. The simplest one possible is used here: list every distinct character in the file, sort them, and number them from 0. There are only 65, so the IDs run 0 to 64.
The entire vocabulary
Character, then its ID. ␣ is a space and ↵ is a line break.
Type anything. A character the file never contains has no ID, so the model can never read or write it.
Production models cut text into larger pieces, usually whole words or common word fragments, from a vocabulary of about 100,000. That makes their sequences shorter and their vocabulary bigger, but the job is identical: text in, a list of integers out.
The model is a pile of weights
The model is a fixed recipe of multiplications and additions. The numbers it multiplies by are the weights, and they are all that training changes. Here is everything a sequence of character IDs passes through, with how many weights each part holds:
One forward pass, top to bottom
At the start, every one of those 10.8 million weights is a small random number. The recipe still runs, it just computes nonsense: the probabilities come out close to even, about 1 in 65 for every character.
What one training step does
Take one position from the held-out text, which the model never trains on. The context ends …this ci and the true next character is t. Here is what the model actually predicted there at six points in the run:
The model's top 8 guesses for the next character
Training turns that into a correction in four moves, and it does all four for 16,384 positions at once:
One step, exactly
1. Forward. Run the 64 windows through the model and get a probability for every possible next character at every position.
2. Score. At each position, look up the probability given to the true character and take −log of it. That is the loss: 0 if the model was certain and right, large if it gave the right answer almost no chance. A uniform guess over 65 characters scores ln(65) = 4.17. Average over all 16,384 positions.
3. Backward. Backpropagation works out, for each of the 10.8 million weights, whether nudging it up or down would lower that average, and by how much.
4. Update. The optimizer (AdamW, learning rate 0.001) moves every weight a tiny amount in its helpful direction. Then a new batch of windows is drawn and it starts again.
No step ever touches the t of "city" in particular. It is held-out text. The probability on it rises from 2.1% to 98% because millions of small corrections on other text taught the model how English spelling and words work.
Watching it learn
Two views of the same checkpoints. On top, text the model writes by itself: it picks a character from its own probabilities, appends it, and repeats. Below, a held-out passage shaded by how much probability the model gave each true character before seeing it. Brighter means the model expected it.
What it writes
What it expected, on text it never trained on
The order it learns things in is the order they pay off. Character frequencies come first, because guessing e and space more often than Q is the cheapest loss reduction available. Then the play format of names in capitals, a colon and a line break. Then common words, then spelling, then grammar across a line. Meaning is never reached at this size.
The loss curve, and overfitting
Every 100 steps the run recorded two numbers: the average loss on its recent training batches, and the loss on held-out text it never trains on.
Loss per character, lower is better
table view
Both fall fast from 4.37, about what random guessing scores. Then they separate. Held-out loss bottoms out at 1.47 around step 1,800 and climbs back to 1.71 by step 5,000, while training loss keeps falling to 0.88. After that point the model is no longer getting better at Shakespeare in general; it is memorizing the particular lines it is shown again and again, about eighty passes over each character. That is overfitting, and the held-out text is the only way to see it. The fix here would be to stop near step 1,800, or to give the model more text.
From here to a chatbot
Everything above is pretraining. A model like ChatGPT starts with the same loop at enormous scale, and every stage after it reuses that loop with different data:
Pretraining · this page
Raw text, next-token loss. Here: 1 MB, 10.8 M weights, one GPU, minutes. At the frontier: trillions of tokens, hundreds of billions of weights, thousands of GPUs for months.
Supervised fine-tuning (SFT)
The same next-token loss on conversations: a user turn, then a good assistant reply. Only the reply is scored. The model learns to answer rather than continue a document.
Reward model
A copy of the network that outputs one score. Shown two replies where people preferred one, it is trained to score the preferred one higher.
RL from feedback (RLHF)
The model writes its own replies, the reward model scores them, and the update raises the probability of tokens in high-scoring replies and lowers it in low-scoring ones.
Underneath all four, the move is the one from step 04: push the probability of particular tokens up or down by nudging every weight a little.
Run it yourself
The whole thing is one Python file of about 200 lines, using only PyTorch. Save it next to the text file and run it on any machine with an NVIDIA GPU:
curl -O https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt python train.py
show train.py
"""A tiny GPT built and trained from random weights on Shakespeare.
Run in WSL: python3 train.py
"""
import json
import math
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
device = "cuda"
# ---------------------------------------------------------------- data
# The whole dataset is one text file. Every character position is a training
# example: "given the characters before, predict this one".
text = open("input.txt", encoding="utf-8").read()
# Tokenizer: each distinct character gets an integer ID. That is all it is.
chars = sorted(set(text))
vocab_size = len(chars) # 65 for Shakespeare
stoi = {c: i for i, c in enumerate(chars)}
itos = {i: c for c, i in stoi.items()}
encode = lambda s: [stoi[c] for c in s]
decode = lambda ids: "".join(itos[i] for i in ids)
data = torch.tensor(encode(text), dtype=torch.long)
split = int(0.9 * len(data))
train_data, val_data = data[:split], data[split:]
block_size = 256 # how many characters the model sees at once
batch_size = 64 # how many windows per training step
def get_batch(source):
# Pick 64 random 256-char windows. The target is the same window shifted
# one character right: at every position, the answer is the next character.
starts = torch.randint(len(source) - block_size - 1, (batch_size,))
x = torch.stack([source[s:s + block_size] for s in starts])
y = torch.stack([source[s + 1:s + block_size + 1] for s in starts])
return x.to(device), y.to(device)
# ---------------------------------------------------------------- model
n_embd, n_head, n_layer, dropout = 384, 6, 6, 0.2
class Block(nn.Module):
"""One transformer layer: tokens look at earlier tokens (attention), then
each token's numbers go through a small feed-forward network."""
def __init__(self):
super().__init__()
self.ln1 = nn.LayerNorm(n_embd)
self.qkv = nn.Linear(n_embd, 3 * n_embd)
self.proj = nn.Linear(n_embd, n_embd)
self.ln2 = nn.LayerNorm(n_embd)
self.mlp = nn.Sequential(
nn.Linear(n_embd, 4 * n_embd), nn.GELU(),
nn.Linear(4 * n_embd, n_embd), nn.Dropout(dropout))
self.drop = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(self.ln1(x)).split(n_embd, dim=2)
q, k, v = (t.view(B, T, n_head, C // n_head).transpose(1, 2) for t in (q, k, v))
# is_causal: position t may only look at positions <= t (no peeking ahead)
a = F.scaled_dot_product_attention(q, k, v, is_causal=True,
dropout_p=dropout if self.training else 0)
x = x + self.drop(self.proj(a.transpose(1, 2).reshape(B, T, C)))
x = x + self.mlp(self.ln2(x))
return x
class TinyGPT(nn.Module):
def __init__(self):
super().__init__()
self.tok_emb = nn.Embedding(vocab_size, n_embd) # char ID -> 384 numbers
self.pos_emb = nn.Embedding(block_size, n_embd) # position -> 384 numbers
self.blocks = nn.Sequential(*[Block() for _ in range(n_layer)])
self.ln_f = nn.LayerNorm(n_embd)
self.head = nn.Linear(n_embd, vocab_size) # 384 numbers -> 65 scores
def forward(self, idx):
T = idx.shape[1]
x = self.tok_emb(idx) + self.pos_emb(torch.arange(T, device=idx.device))
return self.head(self.ln_f(self.blocks(x))) # (batch, T, 65) scores
@torch.no_grad()
def generate(self, idx, n):
for _ in range(n):
logits = self(idx[:, -block_size:])[:, -1] # scores for the next char
probs = F.softmax(logits, dim=-1)
nxt = torch.multinomial(probs, 1) # sample one char
idx = torch.cat([idx, nxt], dim=1)
return idx
model = TinyGPT().to(device)
print(f"vocab {vocab_size} chars, {sum(p.numel() for p in model.parameters())/1e6:.1f}M weights, "
f"{len(train_data):,} training characters")
print(f"loss for a uniform random guess: ln({vocab_size}) = {math.log(vocab_size):.2f}\n")
def sample(n=300):
model.eval()
start = torch.tensor([encode("\n")], device=device)
out = decode(model.generate(start, n)[0].tolist())
model.train()
return out
@torch.no_grad()
def val_loss():
model.eval()
losses = []
for _ in range(20):
x, y = get_batch(val_data)
with torch.autocast("cuda", dtype=torch.bfloat16):
logits = model(x)
losses.append(F.cross_entropy(logits.float().view(-1, vocab_size), y.view(-1)).item())
model.train()
return sum(losses) / len(losses)
# A fixed held-out passage the model never trains on. At each checkpoint we
# record the probability it gives every true next character in it, and its
# full top-8 guess at one position.
probe = text[split:][text[split:].find("TRANIO:\nPardon me"):][:240]
probe_at = probe.find("ci") + 2 # predicting the "t" of "city"
@torch.no_grad()
def probe_record():
model.eval()
ids = torch.tensor([encode(probe)], device=device)
probs = F.softmax(model(ids[:, :-1]).float(), dim=-1)[0]
p_true = probs[torch.arange(len(probe) - 1), ids[0, 1:]].tolist()
top = probs[probe_at - 1].topk(8)
model.train()
return {"p_true": [round(p, 4) for p in p_true],
"top": [[itos[i], round(p, 4)] for p, i in zip(top.values.tolist(), top.indices.tolist())]}
# ---------------------------------------------------------------- training
max_steps = 5000
show_at = {0, 100, 300, 1000, 2500, max_steps}
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
t0 = time.time()
train_loss_avg = 0.0
run = {"vocab": chars, "probe": probe, "probe_at": probe_at, "curve": [], "checkpoints": []}
for step in range(max_steps + 1):
if step % 100 == 0:
run["curve"].append({"step": step, "train": round(train_loss_avg, 3) if step else None,
"val": round(val_loss(), 3), "secs": round(time.time() - t0, 1)})
train_loss_sum, train_loss_n = 0.0, 0
if step in show_at:
print(f"===== step {step} val loss {run['curve'][-1]['val']:.2f} ({time.time()-t0:.0f}s) =====")
text_sample = sample()
print(text_sample)
print()
run["checkpoints"].append({"step": step, "val": run["curve"][-1]["val"],
"sample": text_sample, **probe_record()})
if step == max_steps:
break
x, y = get_batch(train_data)
with torch.autocast("cuda", dtype=torch.bfloat16):
logits = model(x) # forward
# cross_entropy = average of -log(probability given to the correct next char)
loss = F.cross_entropy(logits.float().view(-1, vocab_size), y.view(-1))
optimizer.zero_grad(set_to_none=True)
loss.backward() # backward
optimizer.step() # nudge every weight
train_loss_sum += loss.item(); train_loss_n += 1
train_loss_avg = train_loss_sum / train_loss_n
if step % 500 == 0:
print(f"step {step:5d} train loss {loss.item():.2f}")
json.dump(run, open("run_data.json", "w", encoding="utf-8"))
torch.save({"model": model.state_dict(), "chars": chars}, "tiny_gpt.pt")
print("saved tiny_gpt.pt")
It prints a sample at each checkpoint as it goes and saves the trained weights at the end. Things worth changing to see what happens: n_layer and n_embd for model size, block_size for how far back it can read, max_steps to stop before it overfits, or a different text file entirely. The model architecture follows Andrej Karpathy's nanoGPT.