Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
rope interleaving, double shift targets and remove unnecessary embed scaling. Thank you Grace for pointing this out.
raiyanyahya4058e56a7049
diff --git a/chapters/03_embeddings.md b/chapters/03_embeddings.mdindex a71a505..c738deb 100644--- a/chapters/03_embeddings.md+++ b/chapters/03_embeddings.md@@ -93,27 +93,22 @@ Direction 4 (192-255): Formality — formal vs casualThese "directions" aren't assigned by humans. They emerge from the geometry of language. The model discovers that it's useful to cluster related concepts together because they appear in similar contexts.-## Why sqrt(d_model) Scaling?+## A note on scaling-Our embedding code multiplies by `sqrt(d_model)`. Why?+GPT-2 and GPT-3 multiply embeddings by `sqrt(d_model)`. This is needed+when you ADD positional encodings to embeddings because the two signals+must have comparable magnitude. Position values from sin/cos are between+-1 and 1 while freshly initialized embeddings are much smaller.-```python-embeddings = self.embed(x) # Values are ~N(0, 0.02) from init-embeddings = embeddings * sqrt(768) # Now values are ~N(0, 0.55)-```--**The problem:** After embedding, we combine with positional encoding. Positional encoding values (cos/sin) are between -1 and 1. GPT embeddings are initialized very small (~N(0, 0.02), giving values mostly between -0.04 and 0.04). Without scaling, the embedding values are ~25× smaller than the positional values. The positional signal would **drown out** the word meaning.--**The fix:** Scale embeddings up by sqrt(d_model) so they reach a comparable magnitude to the positional encoding. Both signals can then contribute to the representation.+We use RoPE instead. RoPE does not add position information. It rotates+the query and key vectors. Rotation preserves vector magnitude so there+is no problem of one signal drowning out the other. Following LLaMA's+convention we do not apply any scaling to the embeddings in our code.+The embedding layer just looks up the vector and returns it.```python-# Without scaling:-embedding = [0.01, -0.02, 0.01] # Tiny-position = [0.84, 0.54, -1.00] # Much larger — position dominates!--# With scaling:-embedding = [0.28, -0.55, 0.28] # Scaled up-position = [0.84, 0.54, -1.00] # Same magnitude — both matter+embeddings = self.embed(x) # Values are ~N(0, 0.02) from init+# No scaling needed with RoPE — LLaMA and Mistral do not scale embeddings```## What Determines Embedding Quality?@@ -181,9 +176,6 @@ class Embedding(nn.Module):# return self.weight[x] # index into the weight matrixself.embed = nn.Embedding(vocab_size, d_model)- # WHAT: Cache d_model for the scaling step- self.d_model = d_model-def forward(self, x: torch.Tensor) -> torch.Tensor:"""WHAT: Look up embeddings for each token ID in the input.@@ -208,12 +200,11 @@ class Embedding(nn.Module):# lookup operation — very fast, even for 50K+ vocabulary.embeddings = self.embed(x) # [batch, seq_len, d_model]- # WHAT: Scale by sqrt(d_model)- # WHY: See explanation above. Without this, embedding values- # would be dwarfed by the positional encoding values.- # sqrt(d_model) scales embeddings from ~N(0, 0.02) to ~N(0, sqrt(d_model)*0.02),- # making them comparable to positional values in [-1, 1].- return embeddings * math.sqrt(self.d_model)+ # WHAT: Return embeddings unchanged+ # WHY: We use RoPE for position encoding. RoPE rotates rather+ # than adds, so no scaling is needed. LLaMA and Mistral+ # follow this same convention.+ return embeddings```## Quick Mind-Testdiff --git a/chapters/04_positional_encoding.md b/chapters/04_positional_encoding.mdindex fa4a94d..1e30334 100644--- a/chapters/04_positional_encoding.md+++ b/chapters/04_positional_encoding.md@@ -197,7 +197,7 @@ class RotaryPositionalEmbedding(nn.Module):# WHAT: Duplicate to full dimension# WHY: Each dim pair (2i, 2i+1) gets the same angle,# so we copy each angle: [θ0, θ1, θ2, ...] -> [θ0, θ0, θ1, θ1, ...]- emb = torch.cat([freqs, freqs], dim=-1) # [max_seq_len, d_model]+ emb = freqs.repeat_interleave(2, dim=-1) # [max_seq_len, d_model]# WHAT: Cache cos and sin for all positions# WHY: register_buffer means these move with model.to(device)diff --git a/chapters/07_gpt_model.md b/chapters/07_gpt_model.mdindex b8f9ecc..3f7cffb 100644--- a/chapters/07_gpt_model.md+++ b/chapters/07_gpt_model.md@@ -198,8 +198,7 @@ class GPT(nn.Module):Target: [cat, sat, on, the, mat, ?]Predict: P(cat|The) P(sat|The,cat) ... P(mat|The,cat,sat,on,the)- We slice logits[:, :-1] (drop last) and targets[:, 1:] (drop first)- to align predictions with what comes next.+The dataset already provides shifted targets so we compute loss on all positions."""batch_size, seq_len = input_ids.shape@@ -249,95 +248,12 @@ class GPT(nn.Module):# ^# We drop this# (no target for it)- logits_flat = logits[:, :-1, :].contiguous().view(+ logits_flat = logits.contiguous().view(-1, self.config.vocab_size- ) # [batch*(seq-1), vocab_size]- targets_flat = targets[:, 1:].contiguous().view(+ )+ targets_flat = targets.contiguous().view(-1- ) # [batch*(seq-1)]-- # WHAT: Cross-entropy loss- # WHY: For each prediction, -log(P(correct_token)).- # Averaged over all predictions in the batch.- # Lower loss = more confident correct predictions.- loss = F.cross_entropy(logits_flat, targets_flat)-- return logits, loss-- @torch.no_grad()- def generate(- self,- input_ids: torch.Tensor,- max_new_tokens: int,- temperature: float = 1.0,- top_k: int = None,- top_p: float = None,- ) -> torch.Tensor:- """- WHAT: Generate new text token by token (autoregressive).- WHY: During inference, we generate one token, append it,- then generate the next. Each token depends on all- previously generated tokens.-- @torch.no_grad(): WHY this decorator is critical:- During training, PyTorch builds a computation graph- tracking every operation — this enables backpropagation- but consumes memory.- During inference, we DON'T need gradients. @torch.no_grad()- disables the computation graph, saving ~50% GPU memory- and making generation ~2x faster.-- Sampling parameters:- temperature: Controls randomness.- < 1.0 = focused/deterministic- = 1.0 = natural distribution- > 1.0 = creative/wild-- top_k: Only sample from the K most likely tokens.- e.g., top_k=50 means "consider only top 50 tokens"-- top_p: Nucleus sampling. Keep the smallest set of tokens- whose cumulative probability ≥ top_p.- e.g., top_p=0.9 means "keep tokens until we have- 90% of the probability mass"- """- # WHAT: Switch model to evaluation mode- # WHY: Disables dropout. During training, dropout randomly- # silences neurons for regularization. During generation,- # we want ALL neurons active for consistent output.- self.eval()-- for _ in range(max_new_tokens):- # ===== CROP IF TOO LONG =====- # WHAT: If the sequence exceeds max_seq_len, keep only- # the most recent tokens- # WHY: The model has a fixed max context window.- if input_ids.shape[1] > self.config.max_seq_len:- input_ids = input_ids[:, -self.config.max_seq_len:]-- # ===== FORWARD PASS =====- # WHAT: Get predictions for the next token- # WHY: logits[:, -1, :] takes ONLY the last position.- # We only care about what comes NEXT, not about- # past positions we've already generated.- logits, _ = self.forward(input_ids)- logits = logits[:, -1, :] # [batch, vocab_size]-- # ===== APPLY TEMPERATURE =====- logits = logits / temperature-- # ===== TOP-K FILTERING =====- # WHAT: Keep only K most likely tokens, mask the rest- if top_k is not None:- v, _ = torch.topk(logits, min(top_k, logits.size(-1)))- logits[logits < v[:, -1:]] = float('-inf')-- # ===== TOP-P (NUCLEUS) FILTERING =====- # WHAT: Keep smallest set of tokens with cumulative prob > top_p- if top_p is not None:- sorted_logits, sorted_indices = torch.sort(- logits, descending=True- )+ )cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)diff --git a/main.py b/main.pyindex 54a3210..0648d56 100644--- a/main.py+++ b/main.py@@ -20,7 +20,7 @@ class RotaryPositionalEmbedding(nn.Module):inv_freq = 1.0 / (theta ** (dim_indices / d_model))positions = torch.arange(max_seq_len).float()freqs = torch.outer(positions, inv_freq)- emb = torch.cat([freqs, freqs], dim=-1)+ emb = freqs.repeat_interleave(2, dim=-1)self.register_buffer("cos_cached", emb.cos())self.register_buffer("sin_cached", emb.sin())@@ -170,8 +170,8 @@ class GPT(nn.Module):logits = self.lm_head(x)loss = Noneif targets is not None:- logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)- targets_flat = targets[:, 1:].contiguous().view(-1)+ logits_flat = logits.contiguous().view(-1, self.config.vocab_size)+ targets_flat = targets.contiguous().view(-1)loss = F.cross_entropy(logits_flat, targets_flat)return logits, lossdiff --git a/notebooks/03_embeddings.ipynb b/notebooks/03_embeddings.ipynbindex 5e5b343..cf09013 100644--- a/notebooks/03_embeddings.ipynb+++ b/notebooks/03_embeddings.ipynb@@ -64,10 +64,9 @@" def __init__(self, vocab_size, d_model):\n"," super().__init__()\n"," self.embed = nn.Embedding(vocab_size, d_model)\n",- " self.d_model = d_model\n","\n"," def forward(self, x):\n",- " return self.embed(x) * math.sqrt(self.d_model)"+ " return self.embed(x)"]},{@@ -127,7 +126,7 @@"source": ["## The scaling trick\n","\n",- "We multiply embeddings by sqrt(d_model). This keeps the values\n",+ "We use RoPE for position encoding. RoPE rotates vectors\nrather than adding position information. Rotation preserves\nvector magnitude so no scaling is needed. LLaMA uses the\nsame approach.\n","at a good scale before we add positional encoding later.\n","Without this scaling the position information would get lost."]@@ -148,11 +147,12 @@}],"source": [+ "# Embeddings work with or without scaling when using RoPE.\n",+ "# LLaMA does not apply scaling so we follow that convention.\n","embed_raw = nn.Embedding(vocab_size, d_model)\n","x = embed_raw(token_ids)\n",- "\n",- "print(f\"Without scaling: mean={x.mean():.4f}, std={x.std():.4f}\")\n",- "print(f\"With scaling: mean={(x * math.sqrt(d_model)).mean():.4f}, std={(x * math.sqrt(d_model)).std():.4f}\")"+ "print(f\"Embedding values: mean={x.mean():.4f}, std={x.std():.4f}\")\n",+ "print(f\"Shape: {x.shape}\")\n"]},{@@ -249,4 +249,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of filediff --git a/notebooks/04_positional_encoding.ipynb b/notebooks/04_positional_encoding.ipynbindex 7e5aede..ae7c3fc 100644--- a/notebooks/04_positional_encoding.ipynb+++ b/notebooks/04_positional_encoding.ipynb@@ -70,7 +70,7 @@"\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n","\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n",@@ -202,4 +202,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of filediff --git a/notebooks/05_attention.ipynb b/notebooks/05_attention.ipynbindex d076821..c8b5fd4 100644--- a/notebooks/05_attention.ipynb+++ b/notebooks/05_attention.ipynb@@ -120,7 +120,7 @@" inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n","\n",diff --git a/notebooks/06_transformer_block.ipynb b/notebooks/06_transformer_block.ipynbindex be7e9ab..761f626 100644--- a/notebooks/06_transformer_block.ipynb+++ b/notebooks/06_transformer_block.ipynb@@ -76,7 +76,7 @@" inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n","\n",@@ -343,4 +343,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of filediff --git a/notebooks/07_gpt_model.ipynb b/notebooks/07_gpt_model.ipynbindex 55768b4..0cf4845 100644--- a/notebooks/07_gpt_model.ipynb+++ b/notebooks/07_gpt_model.ipynb@@ -70,7 +70,7 @@" inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n","\n",@@ -255,8 +255,8 @@"\n"," loss = None\n"," if targets is not None:\n",- " logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)\n",- " targets_flat = targets[:, 1:].contiguous().view(-1)\n",+ " logits_flat = logits.contiguous().view(-1, self.config.vocab_size)\n",+ " targets_flat = targets.contiguous().view(-1)\n"," loss = F.cross_entropy(logits_flat, targets_flat)\n","\n"," return logits, loss\n",@@ -370,4 +370,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of filediff --git a/notebooks/08_training.ipynb b/notebooks/08_training.ipynbindex 52dbb9c..6802ea0 100644--- a/notebooks/08_training.ipynb+++ b/notebooks/08_training.ipynb@@ -83,7 +83,7 @@" inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n","\n",@@ -226,8 +226,8 @@" logits = self.lm_head(x)\n"," loss = None\n"," if targets is not None:\n",- " logits_flat = logits[:, :-1, :].contiguous().view(-1, self.config.vocab_size)\n",- " targets_flat = targets[:, 1:].contiguous().view(-1)\n",+ " logits_flat = logits.contiguous().view(-1, self.config.vocab_size)\n",+ " targets_flat = targets.contiguous().view(-1)\n"," loss = F.cross_entropy(logits_flat, targets_flat)\n"," return logits, loss\n","\n",@@ -526,4 +526,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of filediff --git a/notebooks/09_inference.ipynb b/notebooks/09_inference.ipynbindex 65068a8..d20e09f 100644--- a/notebooks/09_inference.ipynb+++ b/notebooks/09_inference.ipynb@@ -54,7 +54,7 @@" inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n"," positions = torch.arange(max_seq_len).float()\n"," freqs = torch.outer(positions, inv_freq)\n",- " emb = torch.cat([freqs, freqs], dim=-1)\n",+ " emb = freqs.repeat_interleave(2, dim=-1)\n"," self.register_buffer(\"cos_cached\", emb.cos())\n"," self.register_buffer(\"sin_cached\", emb.sin())\n","\n",@@ -326,4 +326,4 @@},"nbformat": 4,"nbformat_minor": 5-}+}\ No newline at end of file