← Personal Learnings data tokens model one step learning loss run it

Hands-on · machine learning from zero

Training a GPT from nothing

A language model starts as millions of random numbers that produce gibberish. This page follows one real model from that state to fake Shakespeare: what the training data is, what the model is made of, what a single training step does to it, and what it writes along the way. Every number and every sample below comes from the actual run on a home GPU.

1.1 MB
of plain text: all the training data
65
distinct characters = the vocabulary
10.8 M
weights, all random at the start
4.8 min
5,000 steps on an RTX 5060 Ti
01

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.

02

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.

03

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

Character IDse.g. 256 integers between 0 and 64.0
↓
Character lookup tableA 65 × 384 table. Each ID picks out its row: 384 numbers that will come to stand for that character.24,960
↓ plus
Position lookup tableA 256 × 384 table, so the model can tell the 1st character from the 200th.98,304
↓
Transformer layer × 6Attention: each position mixes in information from the positions before it (never after: it may not peek at the answer). Feed-forward: each position's 384 numbers go through a small two-layer network on their own.6 × 1,774,464
↓
Output layerTurns each position's 384 numbers into 65 scores, one per character. The softmax function turns the scores into probabilities that add to 1.25,793
↓
At every position: a probability for each of the 65 possible next characters= 10,795,841

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.

04

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

after step

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.

05

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.

after step

What it writes


    

What it expected, on text it never trained on

0%100% probability on the true character · hover a character

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.

06

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

training textheld-out text
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.

07

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.

08

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.