Level 3 In-Depth AI · Transformers and Language Models
Build a GPT from Scratch
A complete, working GPT in about 150 lines of PyTorch, small enough to train on a laptop CPU in under a minute. Every part of the previous chapters (tokens, embeddings, causal self-attention, Transformer blocks, next-token loss and sampling) appears here as real code you can run and change.
- Level
- ●●●●● Intermediate
- Reading
- 15 min
- To learn it well
- 2 hours to read and run, a weekend to explore
- Builds on
- 35 concepts →
- Quiz
- 5 questions ↓
This leads to
—The full path from zero — 35 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- Python for AI
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Tokenization
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- NumPy and Array Thinking
- Language Modeling and Next-Token Prediction
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- PyTorch
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- GPT and Decoder-Only Models
- Build a GPT from Scratch
Read them roughly in this order. See it on the concept map →
Why it matters
You can read about attention and Transformer blocks for weeks and still feel unsure how the pieces fit together. Writing one yourself removes the mystery. In this chapter you build and train a real GPT, the same architecture as GPT-2 and, in all essentials, as the models behind today's chatbots, in about 150 lines of PyTorch. It trains on a laptop CPU in under a minute and generates text you can watch improving.
Nothing is hidden. There is no transformers library and no pretrained weights: just tensors, an embedding table, the Self-Attention and Multi-Head Attention formula, layer norms, a feed-forward network, the next-token loss and a sampling loop. Once it works, every bigger model is "the same, with more": more layers, wider vectors, a subword tokenizer, more data, more GPUs (Pretraining Large Language Models, Scaling Laws).
This chapter follows the spirit of Andrej Karpathy's Let's build GPT video and his nanoGPT repository, which go further and are highly recommended.
The intuition
Here's the whole plan, in five steps that match the five sections of the code:
- Settings. Decide the size: how many characters the model sees at once (64), how wide each vector is (128), how many heads (4) and blocks (4).
- Data. Take some text. Make the simplest possible tokenizer: each distinct character is a token. Cut random 64-character windows out of the text; the target for each position is simply the next character.
- Model. Embed each character and its position as a vector; pass the vectors through 4 Transformer blocks (attention, then MLP, with residuals and layer norm); turn each final vector into 94 scores, one per possible next character.
- Training. Show the model random batches, measure how surprised it is by the true next characters (cross-entropy), and nudge all 825,600 parameters to be less surprised. 700 times.
- Sampling. Start from a prompt, predict a distribution for the next character, draw one, append it, repeat.
Key idea A GPT is: embeddings → N × (causal self-attention + MLP, each with residual and layer norm) → linear layer to vocabulary scores. Train with cross-entropy on next-token targets; generate by sampling one token at a time.
How it works: the code, section by section
The code is split into five blocks. Put them one after another in a single file, tiny_gpt.py, or run them in order in one notebook (Notebooks: Jupyter and Colab), and run with any recent PyTorch on CPU. The output shown at the end is real, from a laptop CPU with PyTorch 2.
1. Settings
"""A tiny character-level GPT, trained from scratch on the CPU in about a minute."""
import collections, inspect, json, math, re, string, textwrap, time
import random as _random
import torch
import torch.nn as nn
import torch.nn.functional as F
# ---------------------------------------------------------------- 1. settings
torch.manual_seed(1337)
block_size = 64 # context length: how many characters the model can see
batch_size = 32 # sequences per training step
n_embd = 128 # width of every token vector (d_model)
n_head = 4 # attention heads per block (each 32 wide)
n_layer = 4 # Transformer blocks
dropout = 0.1
lr = 3e-3
max_steps = 700
eval_every = 100
These hyperparameters set the model's size. The block size is the context window: the model can never look further back than 64 characters. n_embd is the residual-stream width, in the The Transformer chapter; with 4 heads, each head works on 32 of the 128 numbers. GPT-2 small used block size 1,024, width 768, 12 heads and 12 layers. The seed makes the run repeatable.
2. Data: a character-level tokenizer and batches
# ---------------------------------------------------------------- 2. data
# Built-in training text: the documentation of a few Python standard-library modules.
mods = (collections, json, re, string, _random, textwrap, math, inspect)
text = "\n\n".join(inspect.getdoc(o) for m in mods
for o in [m, *vars(m).values()] if inspect.getdoc(o))
# To train on Shakespeare instead, download tinyshakespeare/input.txt and use:
# text = open("input.txt").read()
chars = sorted(set(text)) # the vocabulary: every distinct character
vocab_size = len(chars)
stoi = {c: i for i, c in enumerate(chars)} # character -> id
itos = {i: c for c, i in stoi.items()} # id -> character
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)
n = int(0.9 * len(data))
train_data, val_data = data[:n], data[n:]
print(f"{len(text):,} characters, vocabulary of {vocab_size}")
def get_batch(split):
d = train_data if split == "train" else val_data
ix = torch.randint(len(d) - block_size - 1, (batch_size,)) # random starting points
x = torch.stack([d[i:i + block_size] for i in ix]) # inputs
y = torch.stack([d[i + 1:i + block_size + 1] for i in ix]) # targets: shifted by one
return x, y
The text. To keep the example self-contained, it trains on something every Python installation already has: the documentation strings of eight standard-library modules, about 160,000 characters of English technical prose. The classic choice is Tiny Shakespeare, a 1.1 MB file of Shakespeare's plays from Karpathy's char-rnn repository; download it as input.txt and swap the commented line in.
The tokenizer is the simplest possible: a character-level model uses one token per distinct character, 94 of them here (letters, digits, punctuation, space and newline). encode turns a string into a list of ids and decode reverses it. Compared with the subword tokenizers of real LLMs, this needs a tiny vocabulary but makes sequences about four times longer.
The split. The first 90% of the text is for training and the last 10% for validation, text the model never trains on, so we can detect memorisation (Overfitting and the Bias–Variance Tradeoff).
Batches. get_batch picks 32 random starting points and cuts out 64-character windows. The targets y are the same windows shifted one character to the right. Each window therefore holds 64 training examples at once: predict character 2 from character 1, character 3 from characters 1 and 2, and so on up to 64.
3. The model
# ---------------------------------------------------------------- 3. the model
class CausalSelfAttention(nn.Module):
def __init__(self):
super().__init__()
self.qkv = nn.Linear(n_embd, 3 * n_embd) # queries, keys, values in one go
self.proj = nn.Linear(n_embd, n_embd) # W_O: mixes the heads
self.drop = nn.Dropout(dropout)
def forward(self, x):
B, T, C = x.shape
q, k, v = self.qkv(x).split(C, dim=2)
# (B, T, C) -> (B, n_head, T, head_size)
q, k, v = (z.view(B, T, n_head, C // n_head).transpose(1, 2) for z in (q, k, v))
att = (q @ k.transpose(-2, -1)) / math.sqrt(k.size(-1)) # (B, nh, T, T) scores
mask = torch.tril(torch.ones(T, T, dtype=torch.bool))
att = att.masked_fill(~mask, float("-inf")) # no peeking at the future
att = self.drop(F.softmax(att, dim=-1))
y = att @ v # weighted sum of values
y = y.transpose(1, 2).contiguous().view(B, T, C) # concatenate heads
return self.drop(self.proj(y))
class Block(nn.Module):
def __init__(self):
super().__init__()
self.ln1 = nn.LayerNorm(n_embd)
self.attn = CausalSelfAttention()
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))
def forward(self, x):
x = x + self.attn(self.ln1(x)) # communicate
x = x + self.mlp(self.ln2(x)) # compute
return x
class GPT(nn.Module):
def __init__(self):
super().__init__()
self.tok_emb = nn.Embedding(vocab_size, n_embd)
self.pos_emb = nn.Embedding(block_size, n_embd)
self.drop = nn.Dropout(dropout)
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, bias=False)
self.apply(self._init_weights)
def _init_weights(self, m):
if isinstance(m, (nn.Linear, nn.Embedding)):
nn.init.normal_(m.weight, mean=0.0, std=0.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.zeros_(m.bias)
def forward(self, idx, targets=None):
B, T = idx.shape
x = self.tok_emb(idx) + self.pos_emb(torch.arange(T)) # (B, T, C)
x = self.blocks(self.drop(x))
logits = self.head(self.ln_f(x)) # (B, T, vocab_size)
loss = None
if targets is not None:
loss = F.cross_entropy(logits.view(-1, vocab_size), targets.view(-1))
return logits, loss
@torch.no_grad()
def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):
for _ in range(max_new_tokens):
idx_cond = idx[:, -block_size:] # crop to the context window
logits, _ = self(idx_cond)
logits = logits[:, -1, :] / temperature # last position only
if top_k is not None:
v, _ = torch.topk(logits, top_k)
logits[logits < v[:, [-1]]] = float("-inf")
probs = F.softmax(logits, dim=-1)
idx = torch.cat([idx, torch.multinomial(probs, 1)], dim=1)
return idx
model = GPT()
print(f"{sum(p.numel() for p in model.parameters()):,} parameters")
Three classes, each one a chapter you've already read.
CausalSelfAttention is multi-head causal self-attention. One linear layer produces queries, keys and values for all heads at once (it is , and stacked side by side), and split separates them. view and transpose reshape (B, T, 128) into (B, 4, T, 32) so that each head becomes a separate batch dimension. The next line is the formula , giving a (B, 4, T, T) table of scores. torch.tril builds a lower-triangular matrix of Trues, and masked_fill writes everywhere above the diagonal: the causal mask. Softmax turns each row into weights, att @ v takes the weighted sum of values, and the heads are concatenated back to (B, T, 128) and mixed by proj (). This is the same as calling F.scaled_dot_product_attention(q, k, v, is_causal=True), written out so you can see it.
Block is the pre-norm Transformer block: x = x + attn(ln1(x)), then x = x + mlp(ln2(x)). The residual additions let the 4 blocks each refine the vectors rather than replace them. The MLP widens each vector to 512, applies GELU, and narrows it back. Attention is where tokens "communicate"; the MLP is where each token "computes" on its own.
GPT assembles the whole thing. Two embedding tables give each token a learned vector for its identity and one for its position (learned positional embeddings, as in GPT-2), and they are added. After the blocks and a final layer norm, head maps each 128-vector to 94 logits, one per character. The weights start as small random numbers (standard deviation 0.02, as in GPT-2), so at step 0 the model predicts every character with roughly equal probability.
In forward, the targets are flattened so that cross_entropy sees separate predictions and averages their losses. generate is the autoregressive loop from the GPT and Decoder-Only Models chapter: crop to the last 64 characters, run the model, keep only the last position's logits, apply temperature and top-k (Decoding: Temperature, Top-k and Top-p), sample one character with torch.multinomial, append, repeat.
Real models often also tie the output head to the token embedding table (use the same matrix for both), which saves parameters. Adding self.head.weight = self.tok_emb.weight would do it here.
4. Training
# ---------------------------------------------------------------- 4. training
@torch.no_grad()
def estimate_loss():
model.eval()
out = {}
for split in ("train", "val"):
out[split] = torch.stack([model(*get_batch(split))[1] for _ in range(20)]).mean().item()
model.train()
return out
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.1)
sched = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=lr, total_steps=max_steps,
pct_start=0.1) # warm-up, then cosine decay
t0 = time.time()
for step in range(max_steps + 1):
if step % eval_every == 0:
l = estimate_loss()
print(f"step {step:4d} train {l['train']:.3f} val {l['val']:.3f} ({time.time() - t0:.0f}s)")
if step == max_steps:
break
x, y = get_batch("train")
_, loss = model(x, y)
optimizer.zero_grad(set_to_none=True)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # guard against spikes
optimizer.step()
sched.step()
The four lines in the middle are the heart of every training loop (Gradient Descent): forward pass and loss, clear old gradients, Backpropagation, update. Around them are the standard tricks used in real LLM training, in miniature:
- AdamW (Optimizers: SGD, Momentum and Adam) with weight decay, the optimizer used for nearly all LLMs.
- A learning-rate schedule (Learning Rate Schedules):
OneCycleLRwarms up over the first 10% of steps and then decays along a cosine curve. - Gradient clipping: if the overall size of the gradient exceeds 1.0, scale it down. This prevents one bad batch from causing a destructive jump.
- Validation loss: every 100 steps,
estimate_lossaverages the loss over 20 batches from each split, with dropout switched off bymodel.eval(). If validation loss rises while training loss falls, the model is memorising.
5. Sampling
# ---------------------------------------------------------------- 5. sampling
model.eval()
prompt = torch.tensor([encode("Return ")])
print(decode(model.generate(prompt, 300, temperature=0.8, top_k=20)[0].tolist()))
We start from the prompt "Return " (many docstrings begin that way) and generate 300 characters at temperature 0.8 with top-k 20, which trims the unreliable tail of the distribution.
The output
Here is the complete output of the five blocks, run on a laptop CPU in 47 seconds:
160,256 characters, vocabulary of 94
825,600 parameters
step 0 train 4.583 val 4.577 (1s)
step 100 train 2.517 val 2.539 (8s)
step 200 train 2.176 val 2.162 (15s)
step 300 train 1.815 val 1.803 (21s)
step 400 train 1.599 val 1.618 (28s)
step 500 train 1.460 val 1.456 (34s)
step 600 train 1.329 val 1.371 (40s)
step 700 train 1.310 val 1.361 (47s)
Return if for value of calls to an the string andler returns the string
or is string object new nots crestring object.
Return the code to the given of the given object. If encoding object.
str(object='''') -> str(byted bytes_or_buffer
ors defaults to 'strict'.
str(bytes_or_buffer[, encoding[, errors]]
(Exact numbers and text depend on your Python and PyTorch versions, because the docstrings and random number streams differ slightly.)
Read the numbers. At step 0 the loss is 4.58, almost exactly : a model guessing uniformly among 94 characters. By step 700 it is 1.36 nats per character on validation text, a perplexity of : on average the model is as uncertain as a choice between about four characters. Training and validation losses stay close, so it is learning general patterns rather than memorising.
Now read the text. It has learned spelling of common words ("string", "object", "returns", "defaults"), docstring conventions (sentences starting "Return", two spaces after a full stop, blank lines between entries) and even the shape of a Python signature, str(bytes_or_buffer[, encoding[, errors]], which echoes the real docstring of str. It has no idea what any of it means. A 64-character window and 825,600 parameters can only take you so far.
Trained on Tiny Shakespeare with exactly the same settings, the same script produces lines such as "By my givefor that ansoe them and your all my lighat my" after "ROMEO:", the rhythm and layout of a play with few real words: Shakespeare's vocabulary is larger and the text more varied, so 700 steps get it less far.
Common pitfalls
- Off-by-one targets. If
yisn't shifted by exactly one character relative tox, the model learns to copy its input and the loss collapses to near zero. Suspiciously low loss is a bug, not a breakthrough. - A missing or wrong mask. Delete the
masked_fillline and training loss drops dramatically, because each position can see the answer, but generation produces garbage. Test: change the last input character and confirm the logits at earlier positions don't change. - Shape mix-ups in the head split.
view(B, T, n_head, C // n_head).transpose(1, 2)is correct;view(B, n_head, T, C // n_head)runs without error and silently scrambles tokens across heads. - Prompts longer than the block size, or with unseen characters.
generatecrops to the last 64 characters, andencoderaises aKeyErrorfor any character not in the training text. - Forgetting
model.eval(). Dropout left on during evaluation or sampling makes the losses noisier and the samples worse.
Watch out Don't judge a language model by its training loss alone. With a small dataset, keep training long enough and training loss keeps falling while validation loss turns upward: the model is memorising. In this run, try
max_steps = 3000and watch the gap open.
Where it leads
Ways to grow this model, in roughly increasing effort:
- Scale it up:
n_layer = 6,n_embd = 384,n_head = 6,block_size = 256. On a GPU (setdevice = "cuda"and move the model and batches to it), that's the configuration of Karpathy's Shakespeare example in nanoGPT, which writes far more convincing pseudo-Shakespeare. - Use a subword tokenizer (Tokenization): swap
encodeanddecodefortiktoken's GPT-2 encoding. Sequences get four times shorter for the same text, but the vocabulary grows to 50,257 and you need much more data. - Modernise the block (The Transformer): RMSNorm, SwiGLU, RoPE (Positional Encodings) and
F.scaled_dot_product_attentionfor speed. - Add a KV cache to make generation faster (The KV Cache and Fast Inference).
- Reproduce GPT-2 (124M): nanoGPT and Karpathy's follow-up video do this on a single multi-GPU machine in hours.
- Fine-tune a pretrained model instead (Fine-Tuning, LoRA and Parameter-Efficient Fine-Tuning), or teach it to chat (Instruction Tuning and Chat Models).
A bit of history
Character-level language models were popularised by Andrej Karpathy's 2015 blog post The Unreasonable Effectiveness of Recurrent Neural Networks and its char-rnn code, which introduced Tiny Shakespeare. In January 2023 Karpathy released nanoGPT, a minimal, readable GPT training repository, and the two-hour video Let's build GPT: from scratch, in code, spelled out; this chapter's model follows that design closely. Sebastian Raschka's book Build a Large Language Model (From Scratch) (2024) and Stanford's CS336 course take the same build-it-yourself approach much further, through pretraining, fine-tuning and alignment. The architecture you just wrote is, apart from size and a few refinements, the one used by GPT-2, GPT-3 and the open models that followed.
Try it
- Sample with
temperature=0.3andtemperature=1.5. Describe the difference. Which looks more like real documentation, and which makes more new words?- Set
n_layer = 1and retrain. How much worse is the final validation loss? Then tryn_layer = 8(it will take longer).- Delete the
masked_fillline, retrain, and compare the training loss and the samples with the original. Explain what went wrong.Hint for 3: without the mask, every position can attend to the next character, which is exactly its target. The loss can fall very low, but at generation time the "future" doesn't exist yet, so the model has learned nothing useful.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Let's build GPT: from scratch, in code, spelled out
Two hours of live-coding a Transformer language model, explaining every line.
nanoGPT
The simplest, fastest repository for training and fine-tuning medium-sized GPTs.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
Build a Large Language Model (From Scratch)
Step by step from tokenizer to pretraining to fine-tuning a GPT-like model in PyTorch. The code repository is free.
LLM Visualization
A 3D walk-through of every computation inside a GPT model, step by step.
Stanford CS336: Language Modeling from Scratch
Build every part of an LLM yourself, from tokenizer to training, scaling and alignment.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/llm/build-gpt-from-scratch.md