Building GPT from Scratch
local graph
Chapter 10 — Building GPT from Scratch
Section titled “Chapter 10 — Building GPT from Scratch”Everything in Part III now assembles into a single object. A GPT is an embedding table, a stack of the transformer blocks from Chapter 8 with the rotary positions from Chapter 9, a final normalization, and an output head — wired to the next-token objective from Chapter 4. This chapter puts the pieces together into a complete, trainable model, counts its parameters, trains it, and generates text from it. When you finish, you will have built a real language model end to end; Part IV will then upgrade it, component by component, into a frontier-class architecture.
10.1 Wiring the Model
Section titled “10.1 Wiring the Model”The whole model is a few dozen lines, because the hard parts already exist as modules. A configuration object collects the dimensions; the model embeds tokens, threads them through the blocks (passing the precomputed rotary frequencies so attention can apply RoPE), normalizes, and projects to vocabulary logits. We tie the input embedding and output projection to the same weights — a standard trick that saves parameters and usually improves quality.
from dataclasses import dataclassimport torch, torch.nn as nn, torch.nn.functional as F
@dataclassclass GPTConfig: vocab_size: int = 50304 # padded to a multiple of 64 for efficiency n_layer: int = 12 n_head: int = 12 d_model: int = 768 hidden: int = 2048 # SwiGLU hidden (~8/3 * d_model) max_seq_len: int = 1024
class GPT(nn.Module): def __init__(self, cfg): super().__init__() self.cfg = cfg self.tok_emb = nn.Embedding(cfg.vocab_size, cfg.d_model) self.blocks = nn.ModuleList( Block(cfg.d_model, cfg.n_head, cfg.hidden) for _ in range(cfg.n_layer)) self.norm = RMSNorm(cfg.d_model) self.lm_head = nn.Linear(cfg.d_model, cfg.vocab_size, bias=False) self.tok_emb.weight = self.lm_head.weight # weight tying freqs = precompute_freqs_cis(cfg.d_model // cfg.n_head, cfg.max_seq_len) self.register_buffer("freqs_cis", freqs, persistent=False) def forward(self, idx, targets=None): B, T = idx.shape x = self.tok_emb(idx) # (B, T, d_model) freqs = self.freqs_cis[:T] for block in self.blocks: x = block(x, freqs) # RoPE applied inside attention x = self.norm(x) logits = self.lm_head(x) # (B, T, vocab_size) loss = None if targets is not None: loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1)) return logits, lossPython — gpt.py: the complete model (uses Block, RMSNorm, RoPE from Part III)
The only change from Chapter 8 is that Block.forward now takes the rotary frequencies and its attention applies apply_rotary_emb to the query and key after projection — the two-line addition noted in Chapter 9. That is the entire model. Compare it to nanoGPT’s GPT class and you will find the same skeleton; the differences (RMSNorm instead of LayerNorm, SwiGLU instead of GELU, RoPE instead of learned positions) are precisely the modernizations Part III motivated.
That structure deserves to be seen in its canonical form, so here is nanoGPT’s actual GPT class, reproduced in full — the configuration, the module definition with weight tying, and the forward pass:
from dataclasses import dataclass
@dataclassclass GPTConfig: block_size: int = 1024 vocab_size: int = 50304 n_layer: int = 12 n_head: int = 12 n_embd: int = 768 bias: bool = True
class GPT(nn.Module): def __init__(self, config): super().__init__() self.config = config self.transformer = nn.ModuleDict(dict( wte = nn.Embedding(config.vocab_size, config.n_embd), wpe = nn.Embedding(config.block_size, config.n_embd), h = nn.ModuleList(Block(config) for _ in range(config.n_layer)), ln_f = LayerNorm(config.n_embd, bias=config.bias), )) self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) self.transformer.wte.weight = self.lm_head.weight # tie
def forward(self, idx, targets=None): b, t = idx.size() pos = torch.arange(0, t, dtype=torch.long, device=idx.device) x = self.transformer.wte(idx) + self.transformer.wpe(pos) for block in self.transformer.h: x = block(x) x = self.transformer.ln_f(x) logits = self.lm_head(x) loss = None if targets is not None: loss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1) return logits, lossPython — karpathy/nanoGPT · model.py: GPT (reproduced, MIT licence)
And the generation loop — the function that actually produces text, with temperature and optional top-k exactly as Chapter 4 described:
@torch.no_grad() def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None): for _ in range(max_new_tokens): # crop the context to the last block_size tokens idx_cond = (idx if idx.size(1) <= self.config.block_size else idx[:, -self.config.block_size:]) logits, _ = self(idx_cond) logits = logits[:, -1, :] / temperature # last step if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = -float("Inf") probs = F.softmax(logits, dim=-1) idx_next = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, idx_next), dim=1) # append return idxPython — karpathy/nanoGPT · model.py: GPT.generate (reproduced, MIT licence)
This is the entire model — a few dozen lines that, scaled up and trained, become GPT-2. One honest note on components: nanoGPT is faithful to the original GPT-2, so it uses a learned position embedding (wpe) and LayerNorm, where this book has taught the modern replacements — RoPE (Chapter 9) and RMSNorm (Chapter 8). That difference is the chapter’s whole thesis made visible: swap those two components and the GPT class above is unchanged in every other respect. The scaffolding — embed, add position, run a stack of blocks, normalize, project, tie the weights — is invariant across the GPT-2 of 2019 and the DeepSeek-V3 of today. nanoGPT additionally includes careful weight initialization and a loader for the public GPT-2 checkpoints, both worth reading but the substance of a GPT is exactly what you see here.
10.2 Counting Parameters and Scaling the Same Code
Section titled “10.2 Counting Parameters and Scaling the Same Code”It is worth knowing where the parameters live, because it explains both memory cost and how the model scales. For model dimension d, each block holds roughly 4d² in attention (the q, k, v, and output projections) and 3·d·hidden in the SwiGLU feed-forward network; normalization is negligible. The embedding/output matrix adds vocab·d (counted once, thanks to tying). Figure 10.1 shows the assembled stack, and Table 10.1 shows how holding this architecture fixed and only changing the configuration reproduces the entire GPT-2 size family.
[!visual-conversion] Diagram, PDF 107 (printed 109). A vertical stack of boxes joined by upward arrows. The large block box contains three lines of text.
flowchart BT
ids["token ids (B, T)"] --> emb["token embedding"]
emb --> blk["N × transformer block<br/>RMSNorm → MHA (+RoPE) → +<br/>RMSNorm → SwiGLU FFN → +<br/>(repeated n_layer times)"]
blk --> norm["final RMSNorm"] --> head["LM head (tied)"] --> logits["logits (B, T, V)"]
Figure 10.1. The complete GPT: token ids are embedded, passed through n_layer identical transformer blocks (with RoPE inside attention), normalized once more, and projected back to vocabulary logits by the tied output head.
| Configuration | n_layer | d_model | n_head | Parameters |
|---|---|---|---|---|
| GPT-2 small | 12 | 768 | 12 | ~124M |
| GPT-2 medium | 24 | 1024 | 16 | ~350M |
| GPT-2 large | 36 | 1280 | 20 | ~774M |
| GPT-2 XL | 48 | 1600 | 25 | ~1.56B |
Table 10.1 — The same code at GPT-2 scales (change the config, nothing else)
Parameter counts are for the classic GPT-2 shapes; our modernized model (SwiGLU, RoPE) differs by a few percent. The point stands: depth and width are just configuration, and the same code spans an order of magnitude in size.
10.3 Training the Model
Section titled “10.3 Training the Model”Training reuses the loop from Chapter 3 without modification — that was the whole point of building it carefully. Instantiate the model, hand its parameters to AdamW, and run:
cfg = GPTConfig()model = GPT(cfg).to(device)opt = torch.optim.AdamW(model.parameters(), lr=6e-4, betas=(0.9, 0.95), weight_decay=0.1) # GPT-style settings
model.train()for step in range(max_steps): x, y = get_batch("train") # (B, T) ids and shifted targets (Ch 4, 6) with torch.autocast("cuda", dtype=torch.bfloat16): _, loss = model(x, y) opt.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) opt.step()Python — train_gpt.py: instantiate and train
What to watch as it runs: the training loss should fall quickly from roughly ln(vocab_size) — random-guess perplexity — and then decline slowly. Track a held-out validation loss alongside it; when validation stops improving while training keeps falling, you are overfitting and need more data or regularization. On a real corpus a small GPT reaches coherent English in a few thousand steps. The mechanics of doing this efficiently at large scale — learning-rate schedules, distributed training, FP8 — are Part V; here the loop is enough.
10.4 Generating Text
Section titled “10.4 Generating Text”Generation is the autoregressive loop of Chapter 4 made concrete, with the decoding controls from Table 4.2. At each step we crop the context to the model’s window, take the last position’s logits, optionally reshape the distribution with temperature and top-k, sample, and append.
@torch.no_grad()def generate(model, idx, max_new_tokens, temperature=1.0, top_k=None): model.eval() for _ in range(max_new_tokens): idx_cond = idx[:, -model.cfg.max_seq_len:] # crop to context window logits, _ = model(idx_cond) logits = logits[:, -1, :] / temperature # last step; temperature scaling if top_k is not None: v, _ = torch.topk(logits, min(top_k, logits.size(-1))) logits[logits < v[:, [-1]]] = float("-inf") # keep only the top-k probs = F.softmax(logits, dim=-1) next_id = torch.multinomial(probs, num_samples=1) idx = torch.cat((idx, next_id), dim=1) # append and continue return idxPython — gpt.py: sampling with temperature and top-k
Call it with a primed context of token ids and it produces continuations; lower temperature and a modest top_k give safe, coherent text, while higher values give more variety. Note one inefficiency: this recomputes attention over the whole context at every step. Caching the keys and values to avoid that — the KV cache — is the foundation of efficient inference and the subject of Chapter 27.
Capstone reached You have now built a complete, modern GPT: a tokenizer (Chapter 5), a data pipeline (Chapter 6), scaled dot-product attention (Chapter 7), a multi-head pre-norm block with RMSNorm and SwiGLU (Chapter 8), rotary positions (Chapter 9), and the assembled, trainable, generating model (this chapter). This is already a real language model. Everything that follows makes it bigger, faster, cheaper, and smarter.
10.5 What We Built, and What Comes Next
Section titled “10.5 What We Built, and What Comes Next”The model in this chapter is, architecturally, a 2019-era GPT brought up to a modern baseline — and it would train into a perfectly respectable small model. But it is dense (every parameter fires for every token), its attention stores a full key/value cache (expensive at long context), and it predicts one token at a time. The frontier models of Chapter 1 differ in exactly these respects. Part IV addresses them one at a time: Mixture-of-Experts replaces the dense feed-forward network so capacity can grow without proportional cost (Chapter 11); Multi-head Latent Attention compresses the key/value cache by an order of magnitude (Chapter 12); multi-token prediction densifies the training signal (Chapter 13); and sparse attention makes very long context affordable (Chapter 14). Each slots directly into the block you just built. We begin with the one that most defines the current generation of open models: the Mixture-of-Experts layer.
10.6 Worked Example: Autoregressive Generation
Section titled “10.6 Worked Example: Autoregressive Generation”A trained decoder predicts the next token; turning that into text is a loop that feeds each prediction back as input. The whole of generation, stripped of optimizations, is a handful of lines that tie together the attention of Chapter 7 and the sampling of Section 27.6:
def generate(model, ids, max_new=100): for _ in range(max_new): logits = model(ids)[:, -1, :] # next-token distribution next_id = sample(logits) # temperature/top-p (27.6) ids = torch.cat([ids, next_id], dim=-1) if next_id.item() == EOS: break return idsPython — gen/generate.py: the autoregressive loop
Two facts about this loop shape everything downstream. First, generation is inherently sequential: token t+1 cannot be computed until token t exists, which is why inference latency is dominated by the number of tokens produced, not the prompt length. Second, the naive loop recomputes attention over the entire growing sequence at every step — quadratic waste that the KV cache (Section 27.2) eliminates by storing each layer’s keys and values so only the new token is processed. The five lines above are correct and complete; the entire serving stack of Part VII exists to make them fast.
Training is parallel, generation is serial A decoder trains on all positions at once but must generate one token at a time, each conditioned on the last. That asymmetry — cheap parallel training, costly sequential inference — is the root of nearly every serving optimization in the book.
10.7 The Decoder-Only Choice
Section titled “10.7 The Decoder-Only Choice”The original transformer was an encoder-decoder built for translation: an encoder digested the source sentence, and a decoder generated the target while attending to the encoder’s output. Modern large language models discarded half of that design — they are decoder-only, a single stack of the decoder blocks this chapter assembles, with no separate encoder. Understanding why is understanding a foundational choice of the field.
The decoder-only design won for reasons of simplicity and scale. Its pretraining task — predict the next token over all text (Section 4.2) — is maximally general: every token in the corpus is a training signal, and the same objective covers understanding and generation in one unified model, rather than splitting them across an encoder and a decoder with separate roles. This makes it both simpler to implement and more efficient with data, since nothing is wasted on a separate encoding pass over inputs that the decoder could process directly. The encoder-decoder structure retains advantages for tasks with a clear, fixed input to be transformed into an output — translation being the canonical case — but for a general-purpose model trained on everything and asked to do anything, the decoder-only architecture’s combination of a simple, universal training objective and clean scaling proved decisive. That is why this book builds a decoder-only model, and why the overwhelming majority of the frontier models it studies, from GPT through DeepSeek-V3 and GLM-5.2, share that same single-stack design.
One stack, one universal objective Decoder-only models predict the next token over all text — a maximally general task that unifies understanding and generation and uses every token as signal. Simpler and more scalable than encoder-decoder, it became the standard for general-purpose LLMs.