Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
adding MOE and speculative decoding
raiyanyahyaae560cc8c9fa
diff --git a/README.md b/README.mdindex af90645..0750cfc 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@<p align="center"><img src="https://img.shields.io/badge/chapters-12-blue" alt="12 chapters"><img src="https://img.shields.io/badge/lines-7%2C500%2B-green" alt="7,500+ lines">- <img src="https://img.shields.io/badge/topics_explained-24-teal" alt="24 topic explainers">+ <img src="https://img.shields.io/badge/topics_explained-26-teal" alt="26 topic explainers"><img src="https://img.shields.io/badge/code%20commented-100%25-brightgreen" alt="100% commented"><img src="https://img.shields.io/badge/prerequisite-python%20basics-orange" alt="Python basics only"><img src="https://img.shields.io/badge/architecture-LLaMA%203%20style-purple" alt="LLaMA 3 style">@@ -23,7 +23,7 @@This is a **12-chapter, 7,500+ line interactive textbook** that teaches you how to build, train and run a modern language model from absolute scratch. The same family of architecture behind ChatGPT, Claude, LLaMA and Mistral.-Alongside the chapters there are **24 standalone topic explainers** covering every technique in depth. RoPE, attention, RMSNorm, SwiGLU, KV cache, AdamW, mixed precision and more. Plus two narrative walkthroughs that trace a single sentence through the entire model step by step. Each file follows the same style: child language, no jargon, a code example you can run.+Alongside the chapters there are **26 standalone topic explainers** covering every technique in depth. RoPE, attention, RMSNorm, SwiGLU, KV cache, AdamW, mixed precision and more. Plus two narrative walkthroughs that trace a single sentence through the entire model step by step. Each file follows the same style: child language, no jargon, a code example you can run.You won't just read about Transformers. You'll **write every line yourself**: tokenizer, embeddings, attention, training loop, inference engine. Every single line annotated to explain **what** it does and **why** it's there.@@ -195,6 +195,8 @@ The last two files are narrative walkthroughs. A Token's Journey follows one sen| Grouped Query Attention | [grouped_query_attention.md](explanations%20and%20examples%20WIP/grouped_query_attention.md) | MHA vs GQA vs MQA explained || Flash Attention | [flash_attention.md](explanations%20and%20examples%20WIP/flash_attention.md) | How Flash Attention makes training 4× faster || Loss Curves | [how_to_read_loss.md](explanations%20and%20examples%20WIP/how_to_read_loss.md) | Diagnose training problems from the loss curve |+| Mixture of Experts | [mixture_of_experts.md](explanations%20and%20examples%20WIP/mixture_of_experts.md) | How MoE scales models with sparse routing |+| Speculative Decoding | [speculative_decoding.md](explanations%20and%20examples%20WIP/speculative_decoding.md) | 2-3× faster generation with a draft model || Cheatsheet | [cheatsheet.md](explanations%20and%20examples%20WIP/cheatsheet.md) | Every formula and hyperparameter in one place || FAQ | [faq.md](explanations%20and%20examples%20WIP/faq.md) | Troubleshooting common problems || Encoder vs Decoder | [encoder_decoder_architectures.md](explanations%20and%20examples%20WIP/encoder_decoder_architectures.md) | GPT vs BERT vs T5 explained |@@ -290,7 +292,7 @@ Each chapter follows the same **4-step structure**:│ ├── 04_data_preparation.md│ ├── 05_full_finetune.md│ └── 📓 notebooks/lora_finetune.ipynb-├── 📚 explanations and examples WIP/ ← Standalone explainers (24 topics)+├── 📚 explanations and examples WIP/ ← Standalone explainers (26 topics)└── 📄 CONTRIBUTING.md```diff --git a/explanations and examples WIP/mixture_of_experts.md b/explanations and examples WIP/mixture_of_experts.mdnew file mode 100644index 0000000..c12af96--- /dev/null+++ b/explanations and examples WIP/mixture_of_experts.md@@ -0,0 +1,309 @@+# Mixture of Experts: How to Scale Without Scaling Everything++## The short answer++A Mixture of Experts model has many feed forward networks instead of+one. Each token is routed to only a few of them. The model has far+more total parameters than a standard model but uses only a fraction+of them for any given token. This is how models like Mixtral 8x7B+and GPT-4 achieve the performance of much larger models while keeping+the compute cost of much smaller ones.++Think of it like a hospital. A standard model has one doctor who+treats every patient. An MoE model has many specialist doctors. Each+patient is sent to the two or three doctors most qualified to handle+their case. The hospital has more total expertise but each patient+only spends time with the relevant specialists.++## Where it sits++MoE replaces the feed forward network in each transformer block.+Attention stays the same. Normalization stays the same. Only the+FFN changes from a single dense network to a collection of experts+with a router that decides which experts to use.++```+Standard transformer block:+ x → RMSNorm → Attention → +x+ → RMSNorm → FFN → +x++MoE transformer block:+ x → RMSNorm → Attention → +x+ → RMSNorm → Router → Expert 1 (used 30% of the time)+ → Expert 2 (used 25%)+ → Expert 3 (used 20%)+ → ...+ → Expert 8 (used 5%)+ → Combine outputs → +x+```++Each expert is an entire feed forward network. Same architecture as+our standard FFN with SwiGLU. Same input and output dimensions. The+difference is that there are eight of them instead of one.++## Why MoE works++Dense models use every parameter for every token. This is wasteful.+Some parameters handle grammar. Some handle facts. Some handle+reasoning. For any given token only a subset of parameters is+actually useful. The rest contribute noise or are effectively dead.++MoE lets different tokens use different paths through the model. A+token representing a verb might use experts that specialize in verb+conjugation and argument structure. A token representing a noun+might use experts that specialize in entity recognition and coreference.+The router learns to send each token to the right experts.++The total parameter count is larger because experts are duplicated.+But the compute cost per token is roughly the same because only a+few experts are activated. The model gets more capacity without more+compute. This is capacity with low active parameters.++## The router++The router is a small linear layer. It takes the hidden state of a+token and outputs a score for each expert. The token is sent to the+experts with the highest scores.++```python+class Router(nn.Module):+ def __init__(self, d_model, num_experts, top_k=2):+ super().__init__()+ self.num_experts = num_experts+ self.top_k = top_k+ self.gate = nn.Linear(d_model, num_experts, bias=False)++ def forward(self, x):+ # x: [batch, seq, d_model]+ logits = self.gate(x) # [batch, seq, num_experts]++ # Select top-k experts per token+ top_k_logits, top_k_indices = torch.topk(logits, self.top_k, dim=-1)+ top_k_weights = F.softmax(top_k_logits, dim=-1)++ return top_k_indices, top_k_weights+```++For each token the router selects the top two experts. It also+outputs weights for each selected expert. The weights determine+how much each expert contributes to the final output. The weights+are computed by applying softmax to the top-k logits so they sum+to one.++## Top-k selection++The model does not use all experts. It uses only the top two per+token. This is the key to MoE efficiency. With eight experts and+top-2 selection only 25 percent of the FFN parameters are active+for each token. The model has 8x the FFN parameters of a dense+model but only 2x the compute.++```+Dense model FFN: 768 → 3072 → 768 (7.1M params per block)+MoE model FFN: 8 × (768 → 3072 → 768) = 56.7M params per block+Active per token: 2 × (768 → 3072 → 768) = 14.2M params used++Total FFN params: 8× larger+Active compute: 2× larger (top-2 of 8)+```++You get 8x the capacity for 2x the compute. This ratio improves as+the number of experts grows. With 64 experts and top-2 selection you+get 64× capacity for 2× compute.++## Load balancing++The router can learn to always send tokens to the same expert. Expert+1 gets 80 percent of the tokens. Experts 2 through 8 are idle. The+model becomes effectively a dense model with seven wasted experts.++Preventing this requires a load balancing loss. The loss encourages+the router to distribute tokens evenly across experts. Each expert+should receive roughly the same number of tokens over the course of+training.++```python+def load_balancing_loss(router_logits, expert_mask, num_experts):+ """+ router_logits: [batch * seq, num_experts] : raw router scores+ expert_mask: [batch * seq, num_experts] : 1 if expert was selected++ Returns a scalar loss that penalizes uneven routing.+ The loss is zero when every expert receives equal tokens.+ """+ # Fraction of tokens routed to each expert+ fraction_per_expert = expert_mask.float().mean(dim=0)++ # Average router probability for each expert+ router_probs = F.softmax(router_logits, dim=-1)+ avg_prob_per_expert = router_probs.mean(dim=0)++ # Loss = num_experts * sum(fraction × probability)+ # Minimized when fractions and probabilities are uniform+ return num_experts * (fraction_per_expert * avg_prob_per_expert).sum()+```++The load balancing loss is added to the main language modeling loss+with a small coefficient typically 0.01. It pushes the router toward+uniform usage without dominating the training objective.++## Expert capacity++Even with load balancing some experts may receive more tokens than+others in a given batch. To prevent memory spikes each expert has a+capacity limit. If more tokens are routed to an expert than its+capacity the overflow tokens are dropped. They pass through the+residual connection unchanged.++```+Expert capacity = (tokens_per_batch / num_experts) × capacity_factor++capacity_factor = 1.25 means each expert can handle 25% more tokens+than its fair share. Overflow tokens above this limit are dropped.+```++The capacity factor is typically 1.0 to 1.5. Higher values waste+compute because experts are allocated for tokens they never receive.+Lower values increase the chance of dropping tokens which degrades+model quality.++Dropped tokens are not a complete loss. The residual connection+still carries the token's information forward. The token skips the+FFN for this layer and gets processed by the next layer's experts.++## The full MoE transformer block++```python+class MoETransformerBlock(nn.Module):+ def __init__(self, d_model, num_heads, num_experts=8, top_k=2):+ super().__init__()+ self.norm1 = RMSNorm(d_model)+ self.attention = MultiHeadAttention(d_model, num_heads)+ self.norm2 = RMSNorm(d_model)++ # MoE replaces the single FFN+ self.router = nn.Linear(d_model, num_experts, bias=False)+ self.experts = nn.ModuleList([+ SwiGLU(d_model) for _ in range(num_experts)+ ])+ self.num_experts = num_experts+ self.top_k = top_k++ def forward(self, x, mask=None):+ batch, seq, d_model = x.shape++ # Attention+ x = x + self.attention(self.norm1(x), mask)++ # MoE FFN+ residual = x+ x = self.norm2(x)++ # Route tokens to experts+ logits = self.router(x) # [batch, seq, num_experts]+ top_k_logits, top_k_indices = torch.topk(logits, self.top_k, dim=-1)+ top_k_weights = F.softmax(top_k_logits, dim=-1) # [batch, seq, top_k]++ # Process tokens through selected experts+ output = torch.zeros_like(x)+ for expert_idx in range(self.num_experts):+ # Find tokens routed to this expert+ expert_mask = (top_k_indices == expert_idx).any(dim=-1)+ if not expert_mask.any():+ continue++ # Get the tokens for this expert+ tokens = x[expert_mask] # [num_routed, d_model]++ # Run through the expert+ expert_output = self.experts[expert_idx](tokens)++ # Weight by the router weight for this expert+ weight_idx = (top_k_indices == expert_idx).float().argmax(dim=-1)+ weights = top_k_weights[expert_mask]+ weights = weights.gather(-1, weight_idx.unsqueeze(-1))++ # Accumulate weighted output+ output[expert_mask] += weights * expert_output++ x = residual + output+ return x+```++The forward pass loops over experts. This is slow in pure Python+but fast in optimized implementations that batch all expert+computations into a single matrix multiplication. Libraries like+Megablocks and DeepSpeed MoE handle this efficiently.++## Which models use MoE++| Model | Total Params | Active Params | Experts per Layer | Top-k |+|---|---|---|---|---|+| Mixtral 8x7B | 46.7B | 12.9B | 8 | 2 |+| Mixtral 8x22B | 141B | 39B | 8 | 2 |+| GPT-4 (rumored) | ~1.7T | ~280B | 8 or 16 | 2 |+| Gemini 1.5 (rumored) | Unknown | Unknown | Unknown | Unknown |+| Switch Transformer | 1.6T | 1.6T | 2048 | 1 |+| GLaM | 1.2T | 96B | 64 | 2 |++The active parameters column is what matters for inference speed.+Mixtral 8x7B has 46.7 billion parameters on disk but only 12.9+billion are active per token. It runs roughly as fast as a 13+billion parameter dense model while matching the quality of a much+larger one.++Switch Transformer used top-1 routing which sends each token to+exactly one expert. This maximizes efficiency but hurts quality+because tokens cannot benefit from multiple specialists. Most+modern MoE models use top-2 as the sweet spot.++## Why not use MoE everywhere++MoE has downsides. The model is physically larger requiring more+memory to store. Inference memory is dominated by the KV cache not+the model weights for long sequences so this matters less than it+seems. But loading a 47 billion parameter model still requires more+VRAM than loading a 13 billion parameter one even if they run at+similar speeds.++Training is harder. The load balancing loss and expert capacity+constraints add complexity. The router can collapse to always using+the same expert which requires monitoring and intervention. MoE+models are more prone to training instability than dense models.++Fine-tuning MoE models is trickier. With LoRA you need to decide+whether to adapt the experts or the router or both. The interactions+between experts and router are not yet as well understood as standard+transformer components.++## Should we add MoE to our model++Our model is too small to benefit from MoE. The expert count should+exceed the number of useful specializations. With only 4 layers and+152 million parameters there are not enough distinct linguistic+patterns for experts to specialize in. A single FFN per layer is+sufficient.++MoE starts to help around the 1 billion parameter mark. Below that+the overhead of routing and load balancing outweighs the benefit of+additional capacity. The sweet spot for MoE is models with 10 billion+or more parameters where the compute savings from sparse activation+are substantial.++## What you need to remember++A Mixture of Experts model replaces each feed forward network with+multiple expert networks. A router sends each token to the top one+or two experts. The model has more total parameters but uses only a+fraction per token. This gives the capacity of a large model at the+compute cost of a smaller one.++Load balancing ensures all experts get used rather than collapsing+to a single favored expert. Expert capacity limits prevent memory+spikes from uneven routing. The router and experts are trained+jointly with the rest of the model.++MoE is the likely architecture behind GPT-4 and Gemini. It is the+most practical way to scale models beyond the point where dense+training becomes prohibitively expensive. Understanding MoE is+understanding how the largest AI systems are built.diff --git a/explanations and examples WIP/speculative_decoding.md b/explanations and examples WIP/speculative_decoding.mdnew file mode 100644index 0000000..d26a0d5--- /dev/null+++ b/explanations and examples WIP/speculative_decoding.md@@ -0,0 +1,305 @@+# Speculative Decoding: Making Generation 3× Faster++## The short answer++Speculative decoding uses two models to generate text faster than+either could alone. A small fast model called the draft model+generates several candidate tokens quickly. A large slow model called+the target model checks all of them in one pass. Accepted tokens are+kept. Rejected tokens are regenerated by the large model. The result+is text identical to what the large model would have produced alone+but generated two to three times faster.++Think of it like a senior engineer and a junior engineer. The junior+writes a first draft quickly. The senior reviews it and accepts the+parts that are correct. For the parts that are wrong the senior+rewrites them. The final document is the senior engineer's quality but+produced much faster because the senior only had to edit not write+from scratch.++## Where it sits++Speculative decoding is an inference only technique. It does not+change training. It does not change the model weights. It changes+only the generation loop. You can apply it to any autoregressive+model without retraining.++```+Without speculative decoding:+ Large model generates one token at a time+ Each token requires one full forward pass+ 100 tokens = 100 forward passes of the large model++With speculative decoding:+ Small model drafts K tokens per step+ Large model verifies K tokens in one forward pass+ Accepts some. Rejects and regenerates others.+ 100 tokens ≈ 100/K forward passes of the large model+ + 100 forward passes of the small model+ If K=4 and small model is 10× faster: ~2-3× total speedup+```++The speedup comes from converting large model forward passes into+small model forward passes. The small model is much faster so+replacing even some large model passes with small model passes+reduces total time.++## How it works step by step++### Step 1: The draft phase++The target model has generated everything up to position t. We want+the next token. Instead of running the large model we run the small+model K times in sequence to produce K candidate tokens.++```+Current tokens: "The cat sat on"++Draft model generates:+ Step 1: "the" (from "The cat sat on")+ Step 2: "mat" (from "The cat sat on the")+ Step 3: "and" (from "The cat sat on the mat")+ Step 4: "then" (from "The cat sat on the mat and")++Draft proposal: ["the", "mat", "and", "then"]+```++The draft model is fast. Generating four tokens with a model that is+10 percent the size takes about 40 percent of the time of one large+model forward pass. So drafting four tokens costs less than half a+large model token.++### Step 2: The verification phase++The large model takes the original sequence plus the draft tokens+and runs one forward pass.++```+Input to large model: "The cat sat on the mat and then"++The model processes all four new tokens in a single forward pass.+For each position it computes the probability of the draft token+that was at that position.++Output: probability(correct for position t+1)+ probability(correct for position t+2)+ probability(correct for position t+3)+ probability(correct for position t+4)+```++One forward pass checking four tokens. If they are all correct we+just saved three large model forward passes.++### Step 3: The acceptance phase++For each position the large model computes a probability for the draft+token that was proposed. It also computes its own top prediction. The+acceptance rule compares the probabilities from both models.++```+For position t+1 (where draft proposed "the"):+ Draft model probability: 0.85+ Target model probability: 0.82++ Since target probability is close to draft probability the token+ is accepted. This means the two models agree. "the" stays.++For position t+2 (where draft proposed "mat"):+ Draft model probability: 0.72+ Target model probability: 0.35++ The target model disagrees strongly. The probability ratio is+ too low. The token is rejected. All tokens after this position+ are also rejected.++Result: "the" is accepted. "mat" "and" "then" are rejected.+The target model generates ONE new token at position t+2.+```++The acceptance rule is based on probability ratios. If the target+model's probability for the draft token is similar to or higher than+the draft model's own probability the token is accepted. If the+target probability is much lower the token is rejected.++This guarantees that the output distribution is identical to what the+large model would have produced alone. The small model's errors are+caught and corrected. The final text is the large model's quality.++### Step 4: Continue++After acceptance and rejection the sequence has been extended by some+number of tokens. Accepted tokens stay. Rejected positions are filled+by the large model. The process repeats from the new end of the+sequence.++```+Sequence after one cycle: "The cat sat on the shelf"++Draft again: "and" "stared" "out" "the"+Verify. Accept "and". Reject "stared" and onward.+Regenerate: "looked"++Sequence: "The cat sat on the shelf and looked"++Continue until enough tokens are generated.+```++## The acceptance math++The magic of speculative decoding is that the output is+mathematically identical to what the target model would have+generated. This is not an approximation. It is exact.++The acceptance test for each draft token x at position p is:++```+1. Compute target model probability: P_target(x | context)+2. Compute draft model probability: P_draft(x | context)+3. Accept if: P_target(x) ≥ P_draft(x)+ If P_target(x) < P_draft(x): accept with probability+ P_target(x) / P_draft(x)+```++When the target model thinks the token is more likely than the draft+model did it is always accepted. When the target thinks it is less+likely it is accepted proportionally to the ratio. This sampling+procedure guarantees the output follows the target model's exact+distribution.++The proof is a few lines of probability theory. But you do not need+to understand the proof to use the technique. The key takeaway is+that speculative decoding gives you the exact quality of the large+model. Not an approximation. Not a distillation. Exact.++## What makes a good draft model++The draft model should be much smaller than the target model but+share the same tokenizer. It should be trained on similar data so+its predictions correlate with the target model's.++Good draft models:+- A smaller version of the same architecture (7B draft for 70B target)+- A distilled version of the target model+- The same model with fewer layers or smaller dimensions+- A completely different fast model with the same tokenizer++The draft model does not need to be good at generating text on its+own. It only needs to get enough tokens right that the acceptance+rate is reasonable. Even with 60 percent acceptance the speedup is+significant because accepting three out of five tokens means three+large model passes saved for the cost of five small model passes.++```+Acceptance rate 50% with K=5 draft tokens:+Old: 100 large model passes+New: 100/2.5 = 40 large model passes + 100 small model passes+Speedup: ~2.0x (if small model is 10% of large model cost)++Acceptance rate 80% with K=5 draft tokens:+Old: 100 large model passes+New: 100/4 = 25 large model passes + 100 small model passes+Speedup: ~3.5x+```++## A simplified implementation++```python+def speculative_generate(target_model, draft_model, tokenizer,+ prompt, max_new_tokens=100, K=5):+ """+ Generate text using speculative decoding.+ The output is identical to target_model.generate() but faster.+ """+ input_ids = tokenizer.encode(prompt)++ while len(input_ids) < max_new_tokens:+ # Phase 1: Draft K tokens with the small model+ draft_ids = input_ids.copy()+ draft_probs = []+ for _ in range(K):+ logits, _ = draft_model(draft_ids[-max_seq_len:])+ probs = F.softmax(logits[:, -1, :], dim=-1)+ next_token = torch.multinomial(probs, num_samples=1).item()+ draft_probs.append(probs[0, next_token].item())+ draft_ids.append(next_token)++ # Phase 2: Verify with large model in one pass+ full_sequence = draft_ids[-max_seq_len:]+ target_logits, _ = target_model(full_sequence)+ target_probs = F.softmax(target_logits, dim=-1)++ # Phase 3: Accept or reject+ accepted = 0+ for i in range(K):+ pos = len(input_ids) - K + i+ draft_token = draft_ids[pos]+ target_prob = target_probs[0, pos, draft_token].item()+ draft_prob = draft_probs[i]++ if target_prob >= draft_prob:+ accepted += 1+ elif random.random() < target_prob / draft_prob:+ accepted += 1+ else:+ break++ # Keep accepted tokens+ input_ids = draft_ids[:len(input_ids) - K + accepted]++ # If no tokens accepted sample one from target+ if accepted == 0:+ target_probs = F.softmax(target_logits[:, -1, :], dim=-1)+ next_token = torch.multinomial(target_probs, num_samples=1).item()+ input_ids.append(next_token)++ return tokenizer.decode(input_ids)+```++The crucial detail: the target model processes all K draft tokens in+a single forward pass (line 26). This is where the speedup comes from.+One target model forward pass checks K draft tokens. If most are+accepted we save K minus one target model passes.++## Why this matters in practice++A 70 billion parameter model generates about 10 tokens per second on+an A100 GPU. A 7 billion parameter draft model generates about 100+tokens per second. With K=4 and an acceptance rate of 70 percent the+speculative decoding system generates about 25 tokens per second. A+2.5x speedup with zero quality loss.++For a chat application where users expect responses in under a second+this is the difference between feasible and frustrating. For a batch+processing pipeline generating millions of tokens per day this is the+difference between one GPU and three.++## The KV cache interaction++Speculative decoding works with KV caches. The target model's cache+is shared across verification steps. The draft model also maintains+its own cache. After acceptance the target model's cache is updated+to include the accepted tokens. After rejection the target model's+cache is rolled back to before the rejected tokens.++Cache management is the trickiest part of implementation. Incorrect+cache handling leads to corrupted generations where the model+attends to tokens it should not see or fails to attend to tokens it+should see. Most production speculative decoding implementations+spend more code on cache management than on the acceptance logic.++## What you need to remember++Speculative decoding uses a small fast draft model to propose tokens+and a large slow target model to verify them. Accepted tokens are+kept. Rejected tokens are regenerated. The output is mathematically+identical to the target model alone. The speedup comes from replacing+expensive target model passes with cheap draft model passes.++The acceptance rate depends on how well the draft model predicts what+the target model would have produced. A draft model that is 10 percent+the size of the target can achieve 70 to 80 percent acceptance. With+four candidate tokens per step this yields a 2x to 3x speedup.++Speculative decoding is a pure inference optimization. No retraining.+No weight changes. No quality tradeoff. It is free speed for any+model serving system.