Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
fixes and updates
raiyanyahyab54621fe931a
diff --git a/README.md b/README.mdindex 306c8da..f5c2a03 100644--- a/README.md+++ b/README.md@@ -61,7 +61,7 @@ Most ML tutorials fall into one of two traps:| **[4: Positional Encoding](chapters/04_positional_encoding.md)** | RoPE: why LLaMA rotates vectors, not adds numbers || **[5: Attention](chapters/05_attention.md)** | β THE CORE. Q,K,V, scaling, causal mask, 8-step walkthrough || **[6: Transformer Block](chapters/06_transformer_block.md)** | RMSNorm, SwiGLU, residuals, pre-norm vs post-norm |-| **[7: Complete GPT Model](chapters/07_gpt_model.md)** | 124M parameter model, weight tying, logits explained |+| **[7: Complete GPT Model](chapters/07_gpt_model.md)** | 151M parameter model (with SwiGLU), weight tying, logits explained || **[8: Training Pipeline](chapters/08_training.md)** | Cross-entropy, backprop, AdamW, cosine warmup, mixed precision || **[9: Inference](chapters/09_inference.md)** | KV cache, temperature, top-k/p, beam search, repetition penalty || **[10: Full Script](chapters/10_full_script.md)** | Runnable `main.py`: everything in one file |@@ -80,7 +80,7 @@ Most ML tutorials fall into one of two traps:| **RoPE** | ~70 | Why LLaMA rotates vectors instead of adding position numbers || **Multi-Head Attention** | ~120 | The exact 8-step computation behind every modern LLM || **Transformer Block** | ~50 | Why residual connections are the "gradient highway" |-| **Full GPT Model** | ~200 | 124M parameter model with weight tying and pre-norm |+| **Full GPT Model** | ~200 | 151M parameter model with SwiGLU, weight tying and pre-norm || **Training Pipeline** | ~250 | AdamW, cosine warmup, mixed precision, gradient accumulation || **Inference Engine** | ~80 | KV cache, temperature, top-k/p, beam search |@@ -129,24 +129,15 @@ python -c "import torch; print(f'CUDA: {torch.cuda.is_available()}')"open chapters/00_overview.md```-To run the full training script, copy `chapters/10_full_script.md` to `main.py` and run:+Run the training script:```bashpython main.py```-**π Expected output (RTX 3090, ~2 hours):**-```-GPT initialized with 124,439,808 parameters-Training starting!-Step 100/50,000 | Loss: 6.2345 | LR: 1.50e-05 | Toks/sec: 45,000-Step 200/50,000 | Loss: 5.1234 | LR: 3.00e-05 | Toks/sec: 45,200-...-Step 50,000/50,000 | Loss: 2.8901 | LR: 1.00e-05 | Toks/sec: 44,800-β Training complete! 112.3 min | Best loss: 2.8901-```+This uses the tiny config (d_model=256, 4 layers) by default. Training takes a few minutes on CPU. For the GPT-2 scale config (151M params, 768 dims, 12 layers), edit the config in main.py and uncomment the larger configuration.-> π» **On CPU only** (~10-50Γ slower): Use the "tiny" config in [Chapter 10](chapters/10_full_script.md).+> π» The default config uses a tiny model (d_model=256, 4 layers, 17M params) that runs in minutes on CPU. For the full GPT-2 scale (151M params, 768 dims, 12 layers), edit the config in `main.py` and uncomment the larger configuration. You'll need a GPU for that one.---@@ -237,7 +228,7 @@ Each chapter follows the same **4-step structure**:βββ π 04_positional_encoding.md β RoPE math, numerical example, thetaβββ π§ 05_attention.md β β THE CORE (713 lines). Q,K,V, scaling, causal maskβββ π§± 06_transformer_block.md β RMSNorm, SwiGLU, residuals, pre-norm vs post- βββ ποΈ 07_gpt_model.md β Complete 124M model, weight tying, logits explained+ βββ ποΈ 07_gpt_model.md β Complete 151M model, weight tying, logits explainedβββ ποΈ 08_training.md β Cross-entropy, backprop, AdamW, cosine warmupβββ π€ 09_inference.md β KV cache, temperature, top-k/p, beam searchβββ π 10_full_script.md β Runnable main.pydiff --git a/chapters/00_overview.md b/chapters/00_overview.mdindex 5023358..ab89237 100644--- a/chapters/00_overview.md+++ b/chapters/00_overview.md@@ -63,7 +63,7 @@ By the end of this guide, you will have built from scratch:| **RoPE** | Teaches the model about word order using rotation | [4](04_positional_encoding.md) || **Attention** | Lets words "look at" and "talk to" each other | [5](05_attention.md) || **Transformer Block** | Complete thinking unit: attention + feed-forward + residuals | [6](06_transformer_block.md) |-| **GPT Model** | Full 124M parameter language model | [7](07_gpt_model.md) |+| **GPT Model** | Full 151M parameter language model (with SwiGLU) | [7](07_gpt_model.md) || **Training Pipeline** | Data loading, AdamW, cosine schedule, mixed precision | [8](08_training.md) || **Inference Engine** | Text generation with temperature, top-k, top-p, KV cache | [9](09_inference.md) || **Complete Script** | One file that trains and generates β runnable start to finish | [10](10_full_script.md) |diff --git a/chapters/03_embeddings.md b/chapters/03_embeddings.mdindex 39433bd..a71a505 100644--- a/chapters/03_embeddings.md+++ b/chapters/03_embeddings.md@@ -28,8 +28,8 @@ This is the most famous example of what embeddings can capture:```python# In a well-trained embedding space:-embedding("king") - embedding("man") + embedding("woman")-β embedding("queen")+# embedding("king") - embedding("man") + embedding("woman")+# β embedding("queen")```**Why does this work?** "King" has two components in meaning-space:diff --git a/chapters/09_inference.md b/chapters/09_inference.mdindex 09a3c2c..b8e0d83 100644--- a/chapters/09_inference.md+++ b/chapters/09_inference.md@@ -76,9 +76,9 @@ This is why long-context inference needs enormous GPU memory or memory-efficient### KV Cache Implementation Concept```python-# Simplified KV cache (conceptual - not full implementation)+# Simplified KV cache (conceptual β not full implementation)class GPTWithKVCache(GPT):- def generate_with_cache(self, input_ids, max_new_tokens, ...):+ def generate_with_cache(self, input_ids, max_new_tokens):# Prefill: process prompt, store K,Vkv_cache = [] # List of (K, V) tuples per layer@@ -121,17 +121,17 @@ Scale logits before softmax. Lower temperature = sharper distribution (more conflogits = [2.0, 1.0, 0.5, 0.1] # 4 possible tokens# T = 0.5 (cold β confident):-scaled = [2.0/0.5, 1.0/0.5, 0.5/0.5, 0.1/0.5] = [4.0, 2.0, 1.0, 0.2]-probs = softmax([4.0, 2.0, 1.0, 0.2]) = [0.86, 0.12, 0.02, 0.00]+scaled = [2.0/0.5, 1.0/0.5, 0.5/0.5, 0.1/0.5] # β [4.0, 2.0, 1.0, 0.2]+probs = softmax([4.0, 2.0, 1.0, 0.2]) # β [0.86, 0.12, 0.02, 0.00]# Token 0 has 86% chance β very confident!# T = 1.0 (standard):-probs = softmax([2.0, 1.0, 0.5, 0.1]) = [0.56, 0.21, 0.13, 0.10]+probs = softmax([2.0, 1.0, 0.5, 0.1]) # β [0.56, 0.21, 0.13, 0.10]# Token 0 = 56% β balanced distribution# T = 2.0 (hot β creative):-scaled = [2.0/2.0, 1.0/2.0, 0.5/2.0, 0.1/2.0] = [1.0, 0.5, 0.25, 0.05]-probs = softmax([1.0, 0.5, 0.25, 0.05]) = [0.36, 0.22, 0.22, 0.20]+scaled = [2.0/2.0, 1.0/2.0, 0.5/2.0, 0.1/2.0] # β [1.0, 0.5, 0.25, 0.05]+probs = softmax([1.0, 0.5, 0.25, 0.05]) # β [0.36, 0.22, 0.22, 0.20]# Flatter β token 0 only 36%, tokens 2 and 3 are competitive```diff --git a/chapters/11_glossary.md b/chapters/11_glossary.mdindex 1a60838..b319c96 100644--- a/chapters/11_glossary.md+++ b/chapters/11_glossary.md@@ -14,7 +14,7 @@ graph TDR1 --> N2["RMSNorm"]N2 --> F["SwiGLU FFN<br/>d_model -> 4x -> d_model"]F --> R2(("+"))- R2 --> R2+ R1 --> R2endL --> FN["Final RMSNorm"]@@ -39,7 +39,7 @@ graph TD## Parameter Count Breakdown-For our 124M model (GPT-2 Small equivalent):+For our 151M model (LLaMA-style with SwiGLU):```Token Embedding: vocab_size x d_model = 50,257 x 768 = 38,597,376@@ -58,9 +58,11 @@ Per Transformer Block (12 total):Final RMSNorm: = 768LM Head: shared with embedding = 0 (weight tying!)-Grand Total: 38,597,376 + 113,264,640 + 768 = ~152M... (with expansion=4)+Grand Total: 38,597,376 + 113,264,640 + 768 = 151,862,784 parameters-With weight tying and standard attention: ~124M parameters+For comparison: a standard GPT-2 (without SwiGLU, using GELU FFN)+would have ~124M parameters. SwiGLU adds about 28M extra parameters+by replacing 2 FFN weight matrices with 3 gated ones.```## What You've Builtdiff --git a/main.py b/main.pyindex 9e22351..54a3210 100644--- a/main.py+++ b/main.py@@ -179,7 +179,7 @@ class GPT(nn.Module):return sum(p.numel() for p in self.parameters())@torch.no_grad()- def generate(self, input_ids, max_new_tokens, temperature=1.0, top_k=None):+ def generate(self, input_ids, max_new_tokens, temperature=1.0, top_k=None, top_p=None):self.eval()for _ in range(max_new_tokens):if input_ids.shape[1] > self.config.max_seq_len:@@ -189,6 +189,14 @@ class GPT(nn.Module):if top_k is not None:v, _ = torch.topk(logits, min(top_k, logits.size(-1)))logits[logits < v[:, -1:]] = float('-inf')+ 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)+ sorted_mask = cumulative_probs > top_p+ sorted_mask[:, 1:] = sorted_mask[:, :-1].clone()+ sorted_mask[:, 0] = False+ mask = sorted_mask.scatter(1, sorted_indices, sorted_mask)+ logits[mask] = float('-inf')probs = F.softmax(logits, dim=-1)next_token = torch.multinomial(probs, num_samples=1)input_ids = torch.cat([input_ids, next_token], dim=1)