Build a modern LLM from scratch. Every line commented. Explained like we are five.
Python attention-mechanismdeep-learningeducationalfrom-scratchgptlanguage-modelllamallmmachine-learningnatural-language-processingpythonpytorchtokenisationtransformerstutorial
adding flash attention and ho to read loss
raiyanyahya00c355b15f93
diff --git a/README.md b/README.mdindex 4fc4138..af90645 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-22-teal" alt="22 topic explainers">+ <img src="https://img.shields.io/badge/topics_explained-24-teal" alt="24 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 **22 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 **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.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.@@ -193,6 +193,8 @@ The last two files are narrative walkthroughs. A Token's Journey follows one sen| Cosine Warmup | [cosine_warmup.md](explanations%20and%20examples%20WIP/cosine_warmup.md) | The learning rate schedule || Pre-Norm | [pre_norm.md](explanations%20and%20examples%20WIP/pre_norm.md) | Where to normalize || 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 || 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 |@@ -288,7 +290,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 (22 topics)+├── 📚 explanations and examples WIP/ ← Standalone explainers (24 topics)└── 📄 CONTRIBUTING.md```diff --git a/explanations and examples WIP/flash_attention.md b/explanations and examples WIP/flash_attention.mdnew file mode 100644index 0000000..c24750b--- /dev/null+++ b/explanations and examples WIP/flash_attention.md@@ -0,0 +1,271 @@+# Flash Attention: Making Attention Fast++## The short answer++Flash Attention is not a new type of attention. It is the same math+running faster. Standard attention computes the full Q times K+transpose matrix then applies softmax then multiplies by V. This+requires reading and writing a massive intermediate matrix from GPU+memory. Flash Attention avoids storing that matrix entirely. It+computes attention in small blocks and keeps everything inside the+GPU's fast on-chip memory. The result is two to four times faster+training and generation for long sequences.++Every major LLM training run since 2022 has used Flash Attention.+It is not an optional optimization. It is the difference between+training on 2048 tokens and training on 32768 tokens on the same GPU.++## Where the bottleneck is++GPUs have two kinds of memory. The big memory called HBM or VRAM+stores everything. Model weights. KV caches. Training data. It is+large but slow. Reading from it takes hundreds of cycles. The small+memory called SRAM lives on the GPU chip itself. It is tiny but+extremely fast. A few megabytes. Reading from it takes a few cycles.++The standard attention implementation writes the full attention matrix+to HBM. Then reads it back for softmax. Then writes the weights back+to HBM. Then reads them back for the V multiplication. Each of these+reads and writes is a bottleneck.++```+Standard attention memory flow:++ Q, K, V in HBM+ → Load Q, K to compute scores+ → Write scores matrix to HBM (seq_len × seq_len)+ → Read scores from HBM for softmax+ → Write weights matrix to HBM (seq_len × seq_len)+ → Read weights and V from HBM for output computation+ → Write output to HBM++ Problem: The seq_len × seq_len matrix is huge.+ For 8192 tokens: 8192 × 8192 × 2 bytes = 134 MB just for scores.+ Every transformer layer reads and writes this.+ 96 layers × 134 MB = ~13 GB of HBM traffic just for attention.+```++Flash Attention never writes the full matrix. It processes attention+in small tiles that fit entirely in SRAM. The compute happens on-chip.+The output is the only thing written back to HBM.++```+Flash Attention memory flow:++ Q, K, V in HBM+ → Load a tile of Q into SRAM+ → Load a tile of K into SRAM+ → Compute scores for this tile pair+ → Apply softmax online (incrementally)+ → Load corresponding V tile+ → Accumulate weighted values in SRAM+ → Write only the final output tile to HBM++ Result: The seq_len × seq_len matrix never exists in HBM.+ Memory traffic is proportional to seq_len, not seq_len squared.+```++## The two key ideas++### Tiling++Instead of processing the entire Q and K matrices at once split them+into small tiles. A tile of Q is 128 tokens by 64 dimensions. A tile+of K is 128 tokens by 64 dimensions. The attention scores between+these tiles is 128 by 128. That fits in SRAM. Process one pair of+tiles at a time. Accumulate results.++This is like reading a book one page at a time instead of spreading+all the pages on the floor. You can only hold one page in your hands+at a time but you can read the whole book without needing a bigger+table.++### Online softmax++Softmax is usually computed in two passes. First find the maximum+value for numerical stability. Then compute exponentials and divide+by the sum. This requires having all scores available at once.++Online softmax computes softmax incrementally as each tile of scores+arrives. It maintains a running maximum and running sum. When a new+tile arrives with a larger maximum it rescales the previous results.+When the last tile is processed the final output is ready. No second+pass needed.++```+Online softmax for tile i:++ m_new = max(m_old, max(scores_i))+ sum_new = sum_old × exp(m_old - m_new) + sum(exp(scores_i - m_new))+ output = (output_old × sum_old × exp(m_old - m_new)+ + V_i × sum(exp(scores_i - m_new))) / sum_new+ m_old = m_new+ sum_old = sum_new+```++The rescaling by `exp(m_old - m_new)` corrects the old output when the+maximum increases. This is mathematically identical to computing+softmax on all scores at once. Just done in pieces.++## Why it matters for the causal mask++Flash Attention with a causal mask is even faster. Tiles in the upper+triangle of the attention matrix are zero. There is no need to compute+them at all. Skip them entirely. For a sequence of length N only about+half the tiles need computation. The other half are known to be zero+from the mask alone.++```+Causal attention tile pattern (N=6 tiles of 128 tokens each):++ K0 K1 K2 K3 K4 K5+ Q0 ██ ░░ ░░ ░░ ░░ ░░+ Q1 ██ ██ ░░ ░░ ░░ ░░+ Q2 ██ ██ ██ ░░ ░░ ░░+ Q3 ██ ██ ██ ██ ░░ ░░+ Q4 ██ ██ ██ ██ ██ ░░+ Q5 ██ ██ ██ ██ ██ ██++ ██ = compute this tile+ ░░ = skip (all zeros from causal mask)++ Computed tiles: 21 of 36 = 58 percent of the full matrix+```++Standard attention still writes zeros for the upper triangle tiles.+Flash Attention never touches them. It computes only the lower+triangle tiles. For long sequences this roughly halves the already+reduced workload.++## The speed difference++For training with sequence length 2048 on an A100 GPU.++```+Standard attention: 85 ms per forward pass+Flash Attention V1: 24 ms per forward pass (3.5x faster)+Flash Attention V2: 19 ms per forward pass (4.5x faster)++Memory used for attention scores:+Standard attention: 64 MB per layer+Flash Attention: 0 MB per layer (never materialized)++Maximum sequence length on 40 GB A100:+Standard attention: ~4096 tokens+Flash Attention: ~16384 tokens (4× longer)+```++The speed difference grows with sequence length. At 8192 tokens+Flash Attention can be 8x faster than standard attention. The memory+savings mean you can train on sequences four times longer or use four+times the batch size on the same GPU.++## A simplified code sketch++This is not production code. It shows the structure. Real Flash+Attention is written in CUDA C++ and highly optimized for specific+GPU architectures.++```python+def flash_attention_forward(Q, K, V, causal=True, block_size=128):+ """+ Simplified flash attention. Processes attention in blocks+ to avoid materializing the full N×N attention matrix.+ """+ batch, heads, seq_len, head_dim = Q.shape+ scale = 1.0 / math.sqrt(head_dim)++ output = torch.zeros_like(Q)++ for i in range(0, seq_len, block_size):+ q_block = Q[:, :, i:i + block_size]+ q_max = torch.full((batch, heads, block_size, 1),+ float('-inf'), device=Q.device)+ q_sum = torch.zeros(batch, heads, block_size, 1, device=Q.device)+ out_block = torch.zeros_like(q_block)++ j_end = (i + block_size) if causal else seq_len+ for j in range(0, j_end, block_size):+ k_block = K[:, :, j:j + block_size]+ v_block = V[:, :, j:j + block_size]++ scores = (q_block @ k_block.transpose(-2, -1)) * scale++ new_max = torch.maximum(q_max, scores.max(dim=-1, keepdim=True).values)+ correction = torch.exp(q_max - new_max)++ exp_scores = torch.exp(scores - new_max)+ new_sum = correction * q_sum + exp_scores.sum(dim=-1, keepdim=True)++ out_block = (correction * q_sum / new_sum) * out_block+ out_block = out_block + (exp_scores / new_sum) @ v_block++ q_max = new_max+ q_sum = new_sum++ output[:, :, i:i + block_size] = out_block++ return output+```++The crucial detail: `out_block` is accumulated in place across the+inner loop without ever storing the full scores matrix. The running+max and sum track the softmax state. When the maximum increases the+correction term rescales the previous output. When all K tiles are+processed the block of Q tiles has its complete attention output.++## Can I use Flash Attention in this project++Yes. The pip package is called `flash-attn`. Install it and replace+the attention forward pass with `flash_attn_func`. But there are two+catches.++First it only works on NVIDIA GPUs with compute capability 8.0 or+higher. That means A100 H100 RTX 3090 RTX 4090. It does not work on+CPU or Apple MPS or older GPUs.++Second the API expects a slightly different tensor layout. The input+must be in shape batch seq_len num_heads head_dim with the sequence+dimension before the head dimension. Our code uses batch num_heads+seq_len head_dim. You need to transpose.++```python+# Using Flash Attention with our model+from flash_attn import flash_attn_func++# Our attention (simplified):+qkv = self.qkv_proj(x)+qkv = qkv.reshape(batch, seq, 3, num_heads, head_dim)+qkv = qkv.permute(2, 0, 3, 1, 4) # [3, batch, heads, seq, head_dim]+q, k, v = qkv[0], qkv[1], qkv[2]++# Flash Attention expects [batch, seq, heads, head_dim]:+q = q.permute(0, 2, 1, 3) # [batch, seq, heads, head_dim]+k = k.permute(0, 2, 1, 3)+v = v.permute(0, 2, 1, 3)++output = flash_attn_func(q, k, v, causal=True)++output = output.permute(0, 2, 1, 3) # Back to [batch, heads, seq, head_dim]++# Continue as normal+output = output.transpose(1, 2).contiguous()+output = output.reshape(batch, seq, d_model)+output = self.out_proj(output)+```++## What you need to remember++Flash Attention is the same attention math running faster. It never+writes the full N by N attention matrix to GPU memory. Instead it+processes attention in small tiles using fast on-chip memory. Online+softmax computes the softmax incrementally without a second pass.++For sequences under 512 tokens the difference is small. For sequences+over 2048 tokens Flash Attention is 3x to 8x faster. It also reduces+memory usage by not storing the attention matrix enabling longer+sequences or larger batch sizes on the same GPU.++Every production LLM training run since 2022 uses Flash Attention.+It is not an optional optimization for serious work. It is a+requirement.diff --git a/explanations and examples WIP/how_to_read_loss.md b/explanations and examples WIP/how_to_read_loss.mdnew file mode 100644index 0000000..cc4499f--- /dev/null+++ b/explanations and examples WIP/how_to_read_loss.md@@ -0,0 +1,317 @@+# How to Read a Loss Curve++## The short answer++A loss curve is the single most important diagnostic for training a+language model. It tells you if the model is learning and if it is+learning well and if something is broken. A good curve goes down+smoothly. That is the happy path. Everything else is a problem.+This guide shows you every common pattern and what to do about it.++## The setup++You are training a model. Every 100 steps you record the loss. You+plot the steps on the x axis and the loss on the y axis. You want+the line to go down. But the shape of the line matters more than the+direction. Two training runs can both have decreasing loss but one+is doomed and the other is thriving.++All the examples below use starting loss around 10.8 which is the+loss of a random model predicting uniformly over GPT-2's 50257+token vocabulary. Loss equals negative log of one divided by 50257+which is approximately ln(50257) which is approximately 10.82.++## Pattern 1: The good curve++```+Loss+ 10.8 |*+ | *+ 9.0 | *+ | *+ 7.0 | *+ | **+ 5.0 | ***+ | ******+ 3.0 | ************+ +-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k+ Steps+```++The loss starts around 10.8. It drops quickly in the first few+thousand steps. The drop slows as training continues. The curve is+smooth. No spikes. No plateaus. This is what successful training+looks like.++The early rapid drop is the model learning basic patterns. Capital+letters start sentences. Periods end them. Common words appear in+predictable positions. These patterns are easy to learn because+they are consistent. The loss drops fast.++The later slow descent is the model learning subtle patterns.+Subject verb agreement. Pronoun resolution. The difference between+affect and effect. These patterns are harder because they depend+on long range context and nuanced meaning.++The curve never plateaus completely because the model always has+something more to learn. There is always a slightly better set of+weights that predicts the next word a tiny bit more accurately.++## Pattern 2: The flat line++```+Loss+ 10.8 |********************************************+ |+ 8.0 |+ |+ 5.0 |+ |+ 2.0 |+ +-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k+```++The loss never moves. It stays at 10.8 forever. The model is not+learning at all. This is almost always a bug.++Possible causes in order of likelihood.++The learning rate is zero or the optimizer is not stepping. Check+that `optimizer.step()` is called. Check that `optimizer.zero_grad()`+is called AFTER step not before.++The gradients are zero. A bug in the loss computation. Check that+the logits and targets are correctly aligned. The logits should be+for predicting the next token. The targets should be the actual+next tokens.++The model weights are not updating. Check `weight.grad` after+`loss.backward()`. It should be non-zero for at least some weights.++The data is broken. Maybe input and target are identical. Maybe all+targets are the same token. Print a few batches and inspect them.++## Pattern 3: Loss spikes++```+Loss+ 10.8 |*+ | *+ 9.0 | *+ | * /+ 7.0 | * /+ | ** /+ 5.0 | / **+ | / ***+ 3.0 | / ******+ +-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k+ ↑+ spike+```++The loss was decreasing nicely. Then it jumped up by a factor of+two or three. The model is still learning but something bad happened.++Cause: gradient explosion. A rare batch of training data contained+an unusual pattern. The gradients became very large. The weights took+a large step in a bad direction.++Fix: add gradient clipping. `torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)`. Call this after `loss.backward()` and before `optimizer.step()`. Our training code already does this.++If clipping is already in place the max norm might be too high. Try+reducing from 1.0 to 0.5. If the spikes persist lower the learning+rate.++A single spike is not fatal. The model usually recovers. But repeated+spikes are a sign that something is systematically wrong. The data+might contain corrupted examples. The learning rate might be too+high. The architecture might have a bug in how it handles certain+sequence lengths.++## Pattern 4: The plateau++```+Loss+ 10.8 |*+ | *+ 9.0 | *+ | *+ 7.0 | *+ | *+ 6.5 | ******************************+ |+ 3.0 |+ +-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k+ ↑+ plateau starts+```++The loss drops to around 6.5 and then stops. No matter how many more+steps you train the loss refuses to go lower. The model has hit a+wall.++This is called a learning rate plateau. The learning rate is too low+for the model to escape its current region of weight space. The+gradients are too small to move the model to a better configuration.++Fix: increase the learning rate. If you are using the cosine schedule+try increasing the peak learning rate from 3e-4 to 1e-3. If you are+already at the minimum of the schedule restart with a higher peak.++Alternative cause: the model capacity is exhausted. A model with 17+million parameters trained on 100 megabytes of text can only capture+so much. The loss cannot go below a certain floor determined by the+model size and data complexity. To push lower you need a bigger model+or more data or both.++## Pattern 5: Training loss goes down but validation loss goes up++```+Loss+ 10.8 |*+ 9.0 | * Training (solid)+ 7.0 | * *+ | * * *+ 5.0 | * * *+ | * * *+ 3.0 | *** ************* Validation (dashed)+ | * **************+ 1.0 | ***** ******+ +-----+-----+-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k 35k 40k+ ↑+ overfitting starts+```++The training loss keeps decreasing. The validation loss was decreasing+too but then it started going up. The model is overfitting. It is+memorizing the training data instead of learning general patterns.++Fix: stop training at the point where validation loss starts rising.+This is called early stopping. You do not need to fix the model. You+just need to stop before it overfits.++Prevention: increase dropout from 0.1 to 0.2 or 0.3. Increase weight+decay from 0.1 to 0.2. Use a larger and more diverse training dataset.+The model cannot memorize data it has not seen enough times.++## Pattern 6: Loss goes negative or NaN++```+Loss+ 10.8 |*+ | *+ 9.0 | *+ | *+ 7.0 | * |+ | * |+ 5.0 | * |+ | * |+ 3.0 | *|+ | *+ 0.0 +----------*--------*-------*------+ --------------------------------+ NaN NaN NaN NaN NaN NaN NaN+```++The loss was decreasing. Then it went to zero. Then it became NaN.+Training is dead. The model is producing infinities or NaN values.++Cause: numerical overflow. The logits or the loss computation produced+numbers too large for bfloat16 or float32 to represent. This happens+when the learning rate is too high and the weights blow up.++Fix: lower the learning rate dramatically. Add gradient clipping.+Check that you are dividing by `sqrt(head_dim)` in the attention+scores. Without this division the scores can become large enough that+`exp(score)` overflows bfloat16. Check that your loss computation is+correct. Cross entropy with logits of 1000 and targets produces NaN.++If using mixed precision check that the autocast context is set up+correctly. Some operations like softmax and layer norm should stay+in float32 for numerical stability. Autocast handles this but only+if the backend supports it.++## Pattern 7: The step function++```+Loss+ 10.8 |*+ | *+ 9.0 |******+ | ******+ 7.0 | ******+ | ******+ 5.0 | ******+ | ******+ 3.0 | ******+ +-----+-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k 30k+```++The loss drops suddenly at regular intervals. The drops coincide with+learning rate changes. The learning rate was reduced by a factor of+10 and the loss jumped down.++Cause: step decay learning rate schedule. Some training setups use+this intentionally. But the sudden drops can disturb the model's+momentum. The model took a while to adapt to the old learning rate+and now the rate changed abruptly.++Preference: use cosine decay instead of step decay. Cosine decay is+smooth. The model adapts continuously. No sudden jumps. Our training+code uses cosine warmup with cosine decay. No step changes.++## Pattern 8: The sawtooth++```+Loss+ 10.8 |* * * *+ | * * * *+ 9.0 |* * * *+ | * * * *+ 7.0 |* * * * * *+ | * * * * * *+ 5.0 |* * * * * * * *+ | * * * * * * * *+ 3.0 |* * * * * * * * * *+ +-----+-----+-----+-----+-----++ 0 5k 10k 15k 20k 25k+```++The loss bounces up and down every few steps. The overall trend is+downward but the noise is high.++Cause: batch size is too small. Each batch is too small to be+representative of the overall data distribution. Some batches are+easy and produce low loss. Others are hard and produce high loss.+The model overreacts to each batch.++Fix: increase the batch size or use gradient accumulation to simulate+a larger batch. Our training code uses gradient accumulation with+`grad_accum_steps=2`. Try increasing to 4 or 8. The effective batch+size increases without using more GPU memory.++The sawtooth is not necessarily a problem. Even with a good batch+size some noise is normal. The model learns the average gradient+direction over many batches. Individual batches can be noisy as long+as the average is correct.++## What you need to remember++A good loss curve is smooth and decreasing with a steep early drop+and a gradual later descent. No spikes. No plateaus. No NaN.++If your curve does not look like Pattern 1 something is wrong. The+most common fixes are gradient clipping and learning rate adjustment+and batch size increases and dropout increases. Try them in that+order.++Always save your loss values during training. A loss curve is a+debugging tool. Without it you are training blind. With it you can+diagnose most training problems in seconds by matching the pattern+to one of the eight patterns above.