Skip to content

Build a modern LLM from scratch. Every line commented. Explained like we are five.

update content on fine tuning and added some more examples and explanations

raiyanyahya572b916d56cc
diff --git a/README.md b/README.md
index f42ed32..279bbca 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-18-teal" alt="18 topic explainers">
+ <img src="https://img.shields.io/badge/topics_explained-21-teal" alt="21 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 **18 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 **21 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.
@@ -192,6 +192,9 @@ The last two files are narrative walkthroughs. A Token's Journey follows one sen
| Gradient Clipping | [gradient_clipping.md](explanations%20and%20examples%20WIP/gradient_clipping.md) | Preventing training explosions |
| 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 |
+| 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 |
| πŸ“– **A Token's Journey** | [a_tokens_journey.md](explanations%20and%20examples%20WIP/a_tokens_journey.md) | Follow one sentence through every layer |
| πŸ“– **The Complete Story** | [the_complete_story.md](explanations%20and%20examples%20WIP/the_complete_story.md) | The full narrative: 22 parts, 7800 words |
@@ -284,7 +287,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 (18 topics)
+β”œβ”€β”€ πŸ“š explanations and examples WIP/ ← Standalone explainers (21 topics)
└── πŸ“„ CONTRIBUTING.md
```
diff --git a/explanations and examples WIP/cheatsheet.md b/explanations and examples WIP/cheatsheet.md
new file mode 100644
index 0000000..0a04e8f
--- /dev/null
+++ b/explanations and examples WIP/cheatsheet.md
@@ -0,0 +1,216 @@
+# Cheatsheet: Everything You Need in One Place
+
+## Model sizes
+
+| Model | Layers | d_model | Heads | Head Dim | Params |
+|---|---|---|---|---|---|
+| Tiny (our default) | 4 | 256 | 4 | 64 | 17.1M |
+| GPT-2 Small | 12 | 768 | 12 | 64 | 124M |
+| GPT-2 Medium | 24 | 1024 | 16 | 64 | 350M |
+| GPT-2 Large | 36 | 1280 | 20 | 64 | 774M |
+| GPT-3 1.3B | 24 | 2048 | 32 | 64 | 1.3B |
+| GPT-3 6.7B | 32 | 4096 | 32 | 128 | 6.7B |
+| GPT-3 175B | 96 | 12288 | 96 | 128 | 175B |
+| LLaMA 7B | 32 | 4096 | 32 | 128 | 7B |
+| LLaMA 13B | 40 | 5120 | 40 | 128 | 13B |
+| LLaMA 70B | 80 | 8192 | 64 | 128 | 70B |
+
+## Parameter count formula
+
+For our model with SwiGLU and weight tying:
+
+```
+Embedding: vocab_size Γ— d_model
+Per block QKV: 3 Γ— d_model Γ— d_model
+Per block Output: d_model Γ— d_model
+Per block SwiGLU: 3 Γ— d_model Γ— (4 Γ— d_model)
+Per block Norms: 2 Γ— d_model
+LM Head: 0 (weight tied with embedding)
+```
+
+For GPT-2 Small equivalent (768 dims, 12 layers, 50257 vocab):
+```
+152M total = 38.6M (embedding) + 113.3M (12 blocks) + 768 (norm)
+```
+
+## Training hyperparameters
+
+| Parameter | Our Default | Range | Notes |
+|---|---|---|---|
+| Learning rate | 3e-4 | 1e-5 to 5e-4 | Lower for fine-tuning (1e-5 to 5e-5) |
+| Weight decay | 0.1 | 0.01 to 0.3 | Only on 2D+ params. Not norms/biases |
+| Betas | (0.9, 0.95) | : | LLaMA defaults. Don't change |
+| Epsilon | 1e-8 | : | Never needs tuning |
+| Warmup steps | 2000 | 500 to 5000 | ~5% of total steps |
+| Max steps | 100K | Depends on data | More data = more steps |
+| Batch size | 8 (Γ— 4 accum) | As large as fits | Effective batch = 32 |
+| Grad clip | 1.0 | 0.5 to 2.0 | 1.0 is standard |
+| Dropout | 0.1 | 0.0 to 0.3 | Higher = more regularization |
+
+## Sampling parameters
+
+| Parameter | Default | Use Case |
+|---|---|---|
+| temperature | 0.8 | General. Lower = focused (0.3-0.5), higher = creative (1.2-1.5) |
+| top_k | 50 | Eliminate nonsense tokens. 0 = disabled |
+| top_p | 0.9 | Adaptive cutoff. 1.0 = disabled |
+| max_new_tokens | 100 | Depends on task. Longer for stories, shorter for answers |
+
+## Key formulas
+
+### Embedding
+```
+output = self.embed(token_ids)
+No scaling with RoPE (LLaMA convention)
+```
+
+### RoPE rotation angles
+```
+ΞΈ_i = p / (10000^(2i / d_head))
+cos_cached = cos(ΞΈ_i) for all p and i
+sin_cached = sin(ΞΈ_i) for all p and i
+x_rotated = x * cos + rotate_half(x) * sin
+```
+
+### Attention
+```
+Q = input @ W_q [batch, heads, seq, head_dim]
+K = input @ W_k [batch, heads, seq, head_dim]
+V = input @ W_v [batch, heads, seq, head_dim]
+
+Q_rot = RoPE(Q, seq_len)
+K_rot = RoPE(K, seq_len)
+
+scores = Q_rot @ K_rot^T / sqrt(head_dim) [batch, heads, seq, seq]
+scores = masks(scores) (causal: upper triangle = -inf)
+weights = softmax(scores, dim=-1) (row sum = 1.0)
+output = weights @ V [batch, heads, seq, head_dim]
+
+concat heads β†’ [batch, seq, d_model]
+output = concat @ W_o
+```
+
+### RMSNorm
+```
+rms = sqrt(mean(x^2) + eps)
+output = x / rms * weight
+```
+
+### SwiGLU FFN
+```
+h = SiLU(input @ W1) [batch, seq, 4Γ—d_model]
+g = input @ W2 [batch, seq, 4Γ—d_model]
+output = (h * g) @ W3 [batch, seq, d_model]
+```
+
+### Cross entropy loss
+```
+loss = -log(P_model(true_token))
+For random model: loss β‰ˆ ln(vocab_size) = ln(50257) β‰ˆ 10.82
+```
+
+### AdamW update
+```
+momentum = Ξ²1 Γ— momentum + (1 - Ξ²1) Γ— gradient
+velocity = Ξ²2 Γ— velocity + (1 - Ξ²2) Γ— gradient^2
+
+m_hat = momentum / (1 - Ξ²1^step)
+v_hat = velocity / (1 - Ξ²2^step)
+
+weight = weight * (1 - lr * weight_decay) (decoupled)
+weight = weight - lr * m_hat / (sqrt(v_hat) + Ξ΅)
+```
+
+### Cosine warmup schedule
+```
+if step < warmup:
+ lr = max_lr * step / warmup
+else:
+ progress = (step - warmup) / (total - warmup)
+ lr = min_lr + (max_lr - min_lr) * 0.5 * (1 + cos(Ο€ * progress))
+```
+
+### Gradient clipping
+```
+total_norm = sqrt(Ξ£ grad_i^2)
+if total_norm > max_norm:
+ scale = max_norm / total_norm
+ grad_i *= scale for all i
+```
+
+## Memory requirements (approximate)
+
+| Model Size | bfloat16 Weights | Optimizer (AdamW) | Total (no batch) |
+|---|---|---|---|
+| 17M (tiny) | 34 MB | 136 MB | 170 MB |
+| 152M (GPT-2 small) | 304 MB | 1.2 GB | 1.5 GB |
+| 7B (LLaMA) | 14 GB | 56 GB | 70 GB |
+| 70B (LLaMA) | 140 GB | 560 GB | 700 GB |
+
+Optimizer states = 2 Γ— params Γ— 4 bytes (float32). Gradients = params Γ— 4 bytes.
+Total training memory β‰ˆ 2Γ—weights + 2Γ—optimizer + gradients + activations.
+With bfloat16 weights: ~8 bytes per parameter for full training.
+
+## Shape conventions
+
+| Component | Input Shape | Output Shape |
+|---|---|---|
+| Tokenizer | text | [batch, seq] |
+| Embedding | [batch, seq] | [batch, seq, d_model] |
+| RoPE | [batch, heads, seq, head_dim] | Same |
+| Attention (internal Q/K/V) | [batch, heads, seq, head_dim] | Same |
+| Attention (external) | [batch, seq, d_model] | [batch, seq, d_model] |
+| RMSNorm | [batch, seq, d_model] | Same |
+| SwiGLU | [batch, seq, d_model] | Same |
+| TransformerBlock | [batch, seq, d_model] | Same |
+| LM Head | [batch, seq, d_model] | [batch, seq, vocab_size] |
+| Loss | logits + targets | scalar |
+
+## What a good loss looks like
+
+```
+10.8: Random. Model knows nothing
+9.0: Starting to learn word frequencies
+7.0: Learning basic grammar
+5.0: Coherent phrases emerging
+3.0: Decent sentences. Still makes mistakes
+2.0: Good model. Plausible text
+1.5: Very good. Near production quality
+<1.0: Overfitting or memorization (on small datasets)
+```
+
+## Dataset sizes
+
+| Dataset | Documents | Tokens | Size |
+|---|---|---|---|
+| WikiText-103 | 28,475 | 103M | 516 MB |
+| BookCorpus | ~11,000 | 985M | 5 GB |
+| C4 | 364M | 156B | 305 GB |
+| The Pile | : | 825B | 825 GB |
+
+## Common error messages
+
+| Error | Meaning |
+|---|---|
+| `CUDA out of memory` | Batch too big or model too big. Reduce batch size or use gradient accumulation |
+| `nan in loss` | Learning rate too high or gradients exploded. Lower LR or add gradient clipping |
+| `loss = 10.82` | Model is random. Normal at step 0. If it stays there check optimizer and loss function |
+| `size mismatch` | Shape error. Check batch/seq/head dimensions. Common bug in reshape/permute |
+| `weights_only load failed` | PyTorch 2.6+ requires `weights_only=False` for checkpoints with custom classes |
+
+## Key files in the repo
+
+```
+πŸ“¦ how-to-train-your-gpt/
+β”œβ”€β”€ main.py ← Single file training. Run this.
+β”œβ”€β”€ requirements.txt ← Dependencies
+β”œβ”€β”€ chapters/ ← 12 chapter textbook
+β”œβ”€β”€ notebooks/ ← 8 chapter notebooks + attention viz + colab
+β”œβ”€β”€ fine-tuning/ ← 7 files on fine-tuning + LoRA notebook
+β”œβ”€β”€ explanations and examples WIP/ ← 18 topic deep dives
+β”‚ β”œβ”€β”€ attention.md ← Most popular. 363 lines, worked example
+β”‚ β”œβ”€β”€ the_complete_story.md ← 1166 lines. Everything connected
+β”‚ β”œβ”€β”€ a_tokens_journey.md ← 301 lines. Follow one sentence
+β”‚ └── ... (15 more topics)
+└── README.md
+```
diff --git a/explanations and examples WIP/encoder_decoder_architectures.md b/explanations and examples WIP/encoder_decoder_architectures.md
new file mode 100644
index 0000000..9da6211
--- /dev/null
+++ b/explanations and examples WIP/encoder_decoder_architectures.md
@@ -0,0 +1,295 @@
+# Encoder, Decoder and Encoder-Decoder: The Three Transformer Families
+
+## The short answer
+
+There are three ways to build a transformer. Decoder-only models like
+GPT generate text one token at a time. They can only see what came
+before. Encoder-only models like BERT look at the entire input at once
+in both directions. They understand text but cannot generate it.
+Encoder-decoder models like T5 read the full input with an encoder and
+generate output with a decoder. They are built for tasks that transform
+one piece of text into another.
+
+This guide builds a decoder-only model. The same architecture as GPT
+and LLaMA and Mistral. This file explains why and what the other
+options do.
+
+## Decoder-Only (GPT family)
+
+### What it looks like
+
+```
+Input: "The cat sat on the"
+ β†’ Token embedding
+ β†’ Causal attention (can only look backward)
+ β†’ Feed forward
+ β†’ Repeat N times
+ β†’ Output projection
+ β†’ Predict next token: "mat"
+```
+
+The key feature is the causal mask. Every token can only attend to
+tokens that came before it. Token 5 can see tokens 0 through 4. Token
+5 cannot see token 6 because token 6 has not been written yet.
+
+### How it's trained
+
+Decoder-only models are trained on next token prediction. Show the
+model a sequence of tokens. Ask it to predict each next token. The
+model learns to guess what comes next. This is called autoregressive
+training.
+
+```
+Training example:
+ Input: [The, cat, sat, on, the]
+ Target: [cat, sat, on, the, mat]
+
+ The model sees "The" and must predict "cat"
+ The model sees "The cat" and must predict "sat"
+ The model sees "The cat sat" and must predict "on"
+ ... and so on
+```
+
+Every prediction is made using only past tokens. The model never sees
+the future. The causal mask enforces this during training. During
+generation no mask is needed because future tokens simply do not exist
+yet.
+
+### What it's good at
+
+Text generation. Writing stories. Answering questions. Having
+conversations. Completing code. Any task where you produce new text
+one token at a time.
+
+Decoder-only models are the universal tool. With enough scale and the
+right training data they can do almost anything. GPT-3 showed this in
+2020. The model could translate and summarize and answer questions
+despite being trained only to predict the next word. It learned these
+skills implicitly because the training data contained examples of
+translation and summarization and question answering.
+
+### Why we chose it
+
+Decoder-only models are the simplest to build and train. One task.
+Predict the next token. One architecture. Causal attention whose output
+goes through a feed forward network. No separate encoder. No cross
+attention between encoder and decoder. One stack of identical blocks.
+
+They also scale the best. Every major breakthrough in capability from
+GPT-2 to GPT-3 to GPT-4 came from decoder-only models. The simplicity
+of the architecture means all resources go into making the model bigger
+and the data better. There is no complexity budget spent on additional
+components.
+
+### The limitation
+
+Decoder-only models cannot look at the full input bidirectionally.
+Token 5 cannot use information from token 10 because token 10 does not
+exist yet. This is fine for generation but suboptimal for understanding
+tasks where the entire input is available from the start.
+
+For tasks like classification or named entity recognition where you
+have the complete input a bidirectional model can capture context from
+both directions. A decoder-only model can only capture context from the
+left. In practice this matters less than you might think. With enough
+scale a decoder-only model learns to compensate for the missing right
+context by building rich representations that anticipate what comes
+next.
+
+## Encoder-Only (BERT family)
+
+### What it looks like
+
+```
+Input: "The cat sat on the [MASK]"
+ β†’ Token embedding
+ β†’ Bidirectional attention (can look everywhere)
+ β†’ Feed forward
+ β†’ Repeat N times
+ β†’ Output projection
+ β†’ Predict masked token: "mat"
+```
+
+The key feature is bidirectional attention. Every token can attend to
+every other token regardless of position. There is no causal mask.
+Token 5 can see token 0 and token 10 equally.
+
+### How it's trained
+
+Encoder-only models are trained on masked language modeling. Hide some
+percentage of input tokens randomly. Ask the model to predict what was
+hidden.
+
+```
+Training example:
+ Original: "The cat sat on the mat"
+ Masked: "The cat [MASK] on the [MASK]"
+ Target: "sat" and "mat"
+
+ The model sees the whole sentence including words after the mask.
+ It uses context from both directions to predict the hidden words.
+```
+
+The model sees the entire input at once. It can use information from
+words before AND after the masked token. This is fundamentally
+different from decoder-only training where the model is blind to the
+future.
+
+### What it's good at
+
+Understanding tasks. Classification. Named entity recognition. Question
+answering where the answer is in the provided text. Sentiment analysis.
+Any task where the input is complete and the output is a label or a
+span of text rather than a generated sequence.
+
+BERT embeddings became the standard for representing text. For years
+the best approach for any NLP task was to take a pretrained BERT model
+and add a small task specific head on top. Fine-tune for a few epochs.
+The approach worked because BERT's bidirectional understanding captured
+rich representations of word meaning in context.
+
+### The limitation
+
+Encoder-only models cannot generate text autoregressively. They have
+no causal mask. They have no mechanism to produce one token at a time
+conditioned on previous outputs. You cannot use BERT to write a story
+or hold a conversation.
+
+Encoder-only models are also limited by their training objective. Masked
+language modeling teaches the model to fill in blanks. It does not teach
+the model to produce coherent sequences. You can generate text by
+iteratively masking and predicting but the output is typically worse
+than what a decoder-only model produces.
+
+## Encoder-Decoder (T5 family)
+
+### What it looks like
+
+```
+Input: "Translate to French: The cat sat on the mat"
+ β†’ Encoder (bidirectional attention)
+ β†’ Hidden representation of the full input
+ β†’ Decoder (causal attention + cross attention)
+ β†’ Output: "Le chat s'est assis sur le tapis"
+```
+
+The encoder reads the entire input bidirectionally. It produces a dense
+representation of the input. The decoder generates the output
+autoregressively one token at a time. The decoder has both causal self
+attention like a GPT and cross attention that looks at the encoder's
+output.
+
+The cross attention is the key difference from decoder-only models. At
+every generation step the decoder can look back at the full encoded
+input. This gives the decoder direct access to the input representation
+without needing to encode it in the autoregressive state.
+
+### How it's trained
+
+Encoder-decoder models are trained on sequence to sequence tasks. Show
+the model an input sequence and a target output sequence. The encoder
+processes the input. The decoder generates the output one token at a
+time.
+
+```
+Training example:
+ Input: "Summarize: The cat sat on the mat for three hours..."
+ Target: "A cat stayed on a mat for a long time."
+
+ The encoder reads the full input bidirectionally.
+ The decoder generates "A" then "cat" then "stayed" and so on.
+ At each step the decoder can cross attend to the encoder's output.
+```
+
+The training uses teacher forcing. The decoder is given the correct
+previous tokens during training. The model learns to produce the next
+token given the input and the correct history.
+
+### What it's good at
+
+Sequence to sequence tasks. Translation. Summarization. Any task where
+the input and output are both text but have different lengths or
+structures.
+
+Encoder-decoder models separate the concerns. The encoder focuses on
+understanding the input. The decoder focuses on generating the output.
+This division of labor can be more efficient than a decoder-only model
+which must do both in a single stack of layers.
+
+### The limitation
+
+Encoder-decoder models are more complex. Two separate stacks of layers.
+Cross attention between them. More parameters for the same quality on
+general language tasks. The architecture is specialized for sequence to
+sequence tasks and less flexible for open ended generation.
+
+The rise of decoder-only models has reduced the popularity of encoder
+decoder architectures. A large enough decoder-only model can implicitly
+perform the separation that an encoder-decoder model makes explicit.
+GPT-3 showed this for translation and summarization. The decoder-only
+model learned to understand the input and generate the output in a
+single stack of layers.
+
+## Why this guide teaches decoder-only
+
+Decoder-only models are the foundation of modern AI. ChatGPT is a
+decoder-only model. Claude is a decoder-only model. LLaMA and Mistral
+are decoder-only models. Understanding how they work means
+understanding the architecture behind the most capable AI systems ever
+built.
+
+The architecture is also the simplest. One stack of blocks. One
+attention pattern with causal masking. One training objective. Next
+token prediction. The simplicity makes it the best starting point for
+learning. Once you understand the decoder-only transformer you can
+understand any transformer variant.
+
+Encoder-only models are still widely used. BERT and its variants power
+search engines and classification systems and information retrieval.
+But they cannot generate text. Understanding them is useful for
+specialized applications but not essential for building generative AI.
+
+Encoder-decoder models are becoming less common. The gap between
+decoder-only and encoder-decoder performance has narrowed. For most
+practical purposes a large decoder-only model matches or exceeds an
+encoder-decoder model on the same task. The added complexity is harder
+to justify.
+
+## When to use each
+
+```
+Do you need to generate new text token by token?
+ β†’ Decoder-only (GPT, LLaMA, Mistral)
+
+Do you need to understand text and produce a label or classification?
+ β†’ Encoder-only (BERT, RoBERTa, DeBERTa)
+
+Do you need to transform text from one form to another and want the
+best possible quality for a specific task?
+ β†’ Encoder-decoder (T5, BART)
+
+Do you want one architecture that can do everything reasonably well
+and is simple to understand and build?
+ β†’ Decoder-only
+```
+
+## What you need to remember
+
+Decoder-only models generate text one token at a time using only past
+context. They are trained on next token prediction. This is the GPT
+family and what this entire guide teaches.
+
+Encoder-only models understand text bidirectionally using the full
+context. They are trained on masked language modeling. This is the
+BERT family. They cannot generate text.
+
+Encoder-decoder models combine both. An encoder reads the input
+bidirectionally. A decoder generates the output autoregressively with
+cross attention to the encoder. This is the T5 family. They are built
+for sequence to sequence tasks.
+
+All three use the same building blocks. Attention. Feed forward
+networks. Residual connections. Normalization. The only differences are
+the attention mask pattern and the training objective. Master the
+decoder-only architecture and you have mastered the foundation of all
+modern language models.
diff --git a/explanations and examples WIP/faq.md b/explanations and examples WIP/faq.md
new file mode 100644
index 0000000..f72b3a8
--- /dev/null
+++ b/explanations and examples WIP/faq.md
@@ -0,0 +1,235 @@
+# FAQ and Troubleshooting
+
+## Training
+
+### Q: My loss is stuck at 10.8 after thousands of steps. What is wrong
+
+10.8 is the loss of a random model predicting uniformly over the
+vocabulary. It equals ln(50257). If your loss stays at 10.8 your model
+is not learning. Possible causes.
+
+The learning rate is too low to move the weights. Try increasing from
+3e-4 to 1e-3 temporarily and see if the loss moves.
+
+The optimizer is not stepping. Check that `optimizer.step()` is being
+called and that `optimizer.zero_grad()` is called after.
+
+The gradients are zero. A bug in the loss computation or the backward
+pass. Check that `loss.backward()` is called and that gradients are
+flowing. Print `model.layers[0].attention.qkv_proj.weight.grad` after
+backward. It should be non zero.
+
+The data is wrong. Maybe input and target are identical or the targets
+are all the same token. Print a few samples.
+
+### Q: My loss is NaN. What happened
+
+NaN means not a number. It means a number overflowed or divided by zero.
+This is almost always caused by the learning rate being too high or
+gradient clipping being missing.
+
+Fix: lower the learning rate by 10x. Add gradient clipping with max
+norm 1.0. Check that your loss function is computing correctly. Print
+the logits before loss. If they contain NaN the problem is in the model
+forward pass. If they are fine the problem is in the loss computation.
+
+### Q: My loss decreases for a while then suddenly spikes
+
+This is gradient explosion. A rare batch of data causes very large
+gradients that shoot the model weights into a region where the loss
+is huge.
+
+Fix: add gradient clipping. `torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)`. This should be called after `loss.backward()` and before `optimizer.step()`.
+
+### Q: Training is extremely slow on CPU. What can I do
+
+CPU training is 10x to 50x slower than GPU. Options:
+
+Use the tiny config (d_model=256, 4 layers). It trains in minutes on
+CPU. The small config (d_model=768, 12 layers) will take days.
+
+Use gradient accumulation to simulate larger batches without more
+memory. But this does not speed up training. It only lets you use a
+bigger effective batch size.
+
+Use a cloud GPU. Google Colab provides a free T4 GPU. Run the colab
+notebook for one click training.
+
+Use Apple MPS if you have a Mac. Main.py now auto detects MPS and
+enables mixed precision.
+
+### Q: Do I need to train the full 50,000 steps
+
+No. You can stop early. 500 steps on the tiny config gives a loss
+around 6 to 7. The model will not be good but it proves the code works.
+For the small config 5,000 steps shows obvious learning. 50,000 steps
+is for production quality. Stop whenever you are satisfied with the
+generated text.
+
+### Q: How do I know if my model is overfitting
+
+If the training loss keeps decreasing but the model generates
+repetitive or nonsensical text it is overfitting. The model memorized
+the training data instead of learning general patterns.
+
+Fix: increase dropout (try 0.2 or 0.3). Increase weight decay (try
+0.2). Reduce the number of training steps. Use a larger and more
+diverse dataset.
+
+## Generation
+
+### Q: The model generates gibberish
+
+This is normal for a randomly initialized model or a model trained for
+very few steps. Even 500 steps on the tiny config produces mostly
+gibberish. The model needs thousands of steps to produce coherent text.
+
+If the model was trained for many steps and still produces gibberish
+check that the tokenizer is the same one used during training. Using
+a different tokenizer for generation than training produces garbage
+because the token IDs mean different things.
+
+### Q: The model repeats the same phrase over and over
+
+This is a common problem called repetitive degeneration. The model
+learns that repeating itself is a safe prediction because repeated
+patterns are common in text.
+
+Fix: increase the temperature to 0.8 or 1.0. Use top_k sampling with
+k=50. Use top_p sampling with p=0.9. These prevent the model from
+always picking the most likely token which is often a repetition.
+
+### Q: How do I make the model more creative
+
+Increase temperature to 1.2 or 1.5. Remove or increase top_k to 100.
+Set top_p to 0.95. The model will pick less likely tokens more often
+producing more varied output.
+
+### Q: How do I make the model more factual
+
+Decrease temperature to 0.3 or 0.5. Set top_k to 20. Use top_p of 0.5
+to 0.7. The model will stick to its most confident predictions. More
+accurate but less interesting.
+
+### Q: What is the `<|endoftext|>` token I see in my output
+
+This is the end of text marker. The model was trained with this token
+between documents. During generation the model sometimes predicts this
+token meaning it thinks the text should end. You can filter it out or
+stop generation when it appears.
+
+## Architecture
+
+### Q: Why RoPE instead of learned positional embeddings
+
+Learned positional embeddings cannot handle sequences longer than the
+training length. If trained on 1024 tokens the model cannot process
+2048 tokens. RoPE captures relative position so it generalizes to any
+length. RoPE also has no learned parameters. Free improvement.
+
+### Q: Why RMSNorm instead of LayerNorm
+
+RMSNorm is mathematically simpler and about 15 percent faster. It
+removes the mean centering and bias which experiments showed are
+unnecessary. Every modern model uses RMSNorm.
+
+### Q: Why SwiGLU instead of ReLU or GELU
+
+SwiGLU has a gating mechanism. It learns which information to pass and
+which to block. ReLU and GELU treat every input the same way. The gate
+gives SwiGLU more expressive power per parameter. At large scale this
+translates to better performance.
+
+### Q: Why weight tying
+
+The embedding layer and output layer do inverse operations. Embeddings
+map token IDs to vectors. The output layer maps vectors to token
+probabilities. Sharing the matrix saves 30 percent of parameters and
+improves training because each token embedding gets gradient signals
+from both directions.
+
+### Q: Does our model use Flash Attention
+
+No. Flash Attention is an optimized CUDA kernel that speeds up
+attention by 2x to 4x. It does not change the math. Our implementation
+uses standard PyTorch operations which are slower but understandable.
+For production use you would swap in Flash Attention.
+
+### Q: Does our model use grouped query attention
+
+No. Grouped query attention reduces the number of key and value heads
+relative to query heads. This saves memory in the KV cache during
+inference. Our model uses standard multi head attention where Q K and
+V all have the same number of heads.
+
+## Hardware
+
+### Q: Can I train on my laptop
+
+Yes. The tiny config (256 dims, 4 layers, 17M params) trains in 2 to 5
+minutes on a modern laptop CPU. The small config (768 dims, 12 layers,
+152M params) takes hours to days on CPU. A GPU makes a huge difference.
+
+### Q: What GPU do I need
+
+Tiny config: any GPU or CPU.
+GPT-2 Small (152M): 4GB VRAM minimum. 8GB comfortable.
+GPT-2 Medium (350M): 8GB VRAM minimum. 12GB comfortable.
+GPT-3 1.3B: 12GB VRAM minimum. 16GB comfortable.
+GPT-3 6.7B: 24GB VRAM minimum.
+GPT-3 175B: 8x A100 80GB.
+
+### Q: How much memory does my model use
+
+Rule of thumb: each parameter uses 2 bytes (bfloat16) for weights plus
+8 bytes (float32) for optimizer states during training. Total is about
+10 bytes per parameter for training.
+
+```
+17M params: 170 MB training memory
+152M params: 1.5 GB training memory
+7B params: 70 GB training memory (needs multiple GPUs)
+```
+
+## Bugs
+
+### Q: PyTorch 2.6+ fails to load my checkpoint
+
+PyTorch 2.6 changed `torch.load` defaults to `weights_only=True`.
+Pass `weights_only=False` to load checkpoints containing custom classes
+like GPTConfig. Our code handles this. If you use an older notebook
+that does not have the fix add `weights_only=False` to your load call.
+
+### Q: I get a shape mismatch error in attention
+
+The most common cause is the sequence length and number of heads being
+swapped. Our attention expects input as [batch, seq_len, d_model]
+which is reshaped internally to [batch, num_heads, seq_len, head_dim].
+If your input has num_heads where seq_len should be the broadcast fails.
+
+### Q: My loss prints as 0.0000
+
+The loss is probably computed as 0 divided by something. Check that
+logits and targets have the correct shapes and that cross_entropy is
+called correctly. Cross entropy expects logits of shape [N, vocab_size]
+and targets of shape [N] with integer class indices.
+
+### Q: I get `RuntimeError: expected scalar type Float but found Half`
+
+This happens when mixed precision is enabled but some operation expects
+float32. Use `torch.amp.autocast(device_type, enabled=True)` for the
+forward pass and keep the loss computation in float32. The autocast
+context manager handles dtype conversion for most operations.
+
+### Q: The attention weights are all NaN after a few training steps
+
+This is usually caused by the attention scores becoming too large
+before softmax. Check that you are dividing by `sqrt(head_dim)` in the
+attention score computation. Without this division the scores can be
+large enough that `exp(score)` overflows to infinity.
+
+### Q: I ran import tiktoken and got an error
+
+Install tiktoken: `pip install tiktoken`. This is the tokenizer used
+by GPT-2 and GPT-3. It is written in Rust and is very fast. If you get
+a compilation error on installation try `pip install tiktoken --no-binary tiktoken` or upgrade your pip.
diff --git a/fine-tuning/03_qlora_explained.md b/fine-tuning/03_qlora_explained.md
index d3fa915..ba76ba5 100644
--- a/fine-tuning/03_qlora_explained.md
+++ b/fine-tuning/03_qlora_explained.md
@@ -73,6 +73,91 @@ Most weights are near zero and get high precision. The few outlier
weights at the extremes get lower precision. This matches the actual
distribution of pretrained model weights.
+## A tiny code example
+
+Here is a simplified version of how QLoRA quantizes and dequantizes
+weights during training.
+
+```python
+import torch
+
+def quantize_4bit(weights, block_size=64):
+ """
+ Quantize a weight matrix to 4 bits.
+ Works on blocks of weights for better accuracy.
+ """
+ out_features, in_features = weights.shape
+ quantized = torch.zeros(out_features, in_features // 2, dtype=torch.uint8)
+
+ for i in range(0, out_features):
+ for j_start in range(0, in_features, block_size):
+ j_end = min(j_start + block_size, in_features)
+ block = weights[i, j_start:j_end]
+
+ # Find min and max of this block
+ w_min = block.min()
+ w_max = block.max()
+
+ # Quantize to 4 bits (16 levels)
+ scale = (w_max - w_min) / 15.0
+ zero_point = -w_min / scale
+
+ quantized_block = torch.clamp(
+ torch.round(block / scale + zero_point), 0, 15
+ ).to(torch.uint8)
+
+ # Pack two 4-bit values into one 8-bit byte
+ for j in range(0, len(quantized_block), 2):
+ byte_idx = j_start // 2 + j // 2
+ high = quantized_block[j] << 4
+ low = quantized_block[j + 1] if j + 1 < len(quantized_block) else 0
+ quantized[i, byte_idx] = high | low
+
+ return quantized
+
+
+def dequantize_4bit(quantized, original_shape, block_size=64):
+ """
+ Reconstruct approximate float values from 4-bit quantized weights.
+ This simplified version does not store scales per block.
+ In real QLoRA the scale and zero point are stored alongside.
+ """
+ out_features, packed_in_features = quantized.shape
+ in_features = packed_in_features * 2
+ reconstructed = torch.zeros(out_features, min(in_features, original_shape[1]))
+
+ for i in range(out_features):
+ for j in range(0, min(in_features, original_shape[1]), 2):
+ byte_idx = j // 2
+ packed = quantized[i, byte_idx].item()
+ high = (packed >> 4) & 0xF
+ low = packed & 0xF
+ if j < original_shape[1]:
+ reconstructed[i, j] = float(high)
+ if j + 1 < original_shape[1]:
+ reconstructed[i, j + 1] = float(low)
+
+ return reconstructed
+
+
+# Example: quantize and dequantize a small weight matrix
+weights = torch.randn(4, 16) * 0.5
+quantized = quantize_4bit(weights, block_size=8)
+reconstructed = dequantize_4bit(quantized, weights.shape, block_size=8)
+
+# In real QLoRA the scale and offset per block are stored
+# so reconstructed values are much closer to originals
+print(f"Original shape: {weights.shape}")
+print(f"Quantized shape: {quantized.shape}")
+print(f"Compression ratio: {weights.numel() * 4 / quantized.numel():.1f}x")
+```
+
+In a real QLoRA implementation the scale and zero point are stored
+alongside the quantized values for each block. During dequantization
+the integer values are converted back using their block specific scale
+and zero point. This gives much higher accuracy than the simplified
+version above which loses the per block metadata.
+
## Double quantization
QLoRA applies a second round of quantization to the quantization
@@ -137,6 +222,47 @@ within a few percent on standard benchmarks.
QLoRA: fine-tune up to ~3B models
```
+## A real QLoRA training snippet
+
+Using the popular bitsandbytes library which implements QLoRA.
+
+```python
+import torch
+from transformers import AutoModelForCausalLM, BitsAndBytesConfig
+
+# Configure 4-bit quantization
+bnb_config = BitsAndBytesConfig(
+ load_in_4bit=True,
+ bnb_4bit_quant_type="nf4", # NormalFloat4
+ bnb_4bit_compute_dtype=torch.bfloat16, # Compute in bfloat16
+ bnb_4bit_use_double_quant=True, # Enable double quantization
+)
+
+# Load a 7B model in 4-bit (~4 GB instead of ~14 GB)
+model = AutoModelForCausalLM.from_pretrained(
+ "meta-llama/Llama-2-7b-hf",
+ quantization_config=bnb_config,
+ device_map="auto",
+)
+
+# Add LoRA on top (using peft library)
+from peft import LoraConfig, get_peft_model
+
+lora_config = LoraConfig(
+ r=16,
+ lora_alpha=32,
+ target_modules=["q_proj", "v_proj"],
+ lora_dropout=0.05,
+)
+
+model = get_peft_model(model, lora_config)
+model.print_trainable_parameters()
+# Output: trainable params: 8,388,608 || all params: 6,746,726,400 || trainable%: 0.12%
+
+# Now train as usual. Only the LoRA params update.
+# The 4-bit base model stays frozen.
+```
+
## What you need to remember
QLoRA compresses the frozen base model to four bits. LoRA adapters
diff --git a/fine-tuning/05_full_finetune.md b/fine-tuning/05_full_finetune.md
index 3dc87fe..f48e93f 100644
--- a/fine-tuning/05_full_finetune.md
+++ b/fine-tuning/05_full_finetune.md
@@ -125,3 +125,69 @@ forgetting where the model loses its general abilities. The quality
improvement over LoRA is marginal for most tasks. Full fine-tuning is
the right tool only when you are building foundation models or need
the absolute maximum performance regardless of cost.
+
+## A full fine-tuning training loop
+
+Here is what a full fine-tuning loop looks like. Compare it with the
+LoRA notebook. The only differences are that every parameter is
+trainable not just a few adapters and the learning rate is smaller.
+
+```python
+import torch
+from torch.utils.data import DataLoader
+
+model = load_pretrained_model()
+model.train()
+
+# All parameters are trainable in full fine-tuning
+for param in model.parameters():
+ param.requires_grad = True
+
+optimizer = torch.optim.AdamW(
+ model.parameters(),
+ lr=2e-5, # Smaller LR than LoRA
+ weight_decay=0.1,
+ betas=(0.9, 0.95),
+)
+
+# Training loop identical to pretraining
+for epoch in range(num_epochs):
+ for batch in dataloader:
+ input_ids, target_ids = batch
+
+ with torch.amp.autocast('cuda', dtype=torch.bfloat16):
+ logits = model(input_ids)
+ loss = F.cross_entropy(
+ logits.view(-1, vocab_size),
+ target_ids.view(-1),
+ )
+
+ loss.backward()
+ torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
+ optimizer.step()
+ optimizer.zero_grad()
+
+ if step % 100 == 0:
+ print(f"Step {step}: loss = {loss.item():.4f}")
+
+# Save the full model checkpoint
+torch.save({
+ "model_state_dict": model.state_dict(),
+ "optimizer_state_dict": optimizer.state_dict(),
+}, "fine_tuned_model.pt")
+```
+
+Notice the learning rate. Two e minus five instead of three e minus
+four used in pretraining. The model is close to a good solution. Large
+steps would destroy its pretrained knowledge. Small steps refine its
+behavior.
+
+Notice also that every parameter is trainable. The optimizer stores two
+states per parameter. For a seven billion parameter model that means
+fifty six gigabytes just for the optimizer. This is why full
+fine-tuning needs multiple GPUs.
+
+Compare this with the LoRA notebook where only 0.19 percent of the
+parameters are trainable. The training loop is the same. The optimizer
+is the same. The only difference is how many parameters are updated.
+LoRA updates a few. Full fine-tuning updates all of them.
diff --git a/fine-tuning/06_dpo_explained.md b/fine-tuning/06_dpo_explained.md
new file mode 100644
index 0000000..1fd5635
--- /dev/null
+++ b/fine-tuning/06_dpo_explained.md
@@ -0,0 +1,207 @@
+# DPO: Direct Preference Optimization
+
+## The short answer
+
+DPO teaches a model to prefer good responses over bad ones. Instead of
+training a separate reward model like RLHF does DPO works directly
+with pairs of responses. Each training example shows the model a chosen
+response and a rejected response for the same prompt. The model learns
+to increase the probability of the chosen one and decrease the
+probability of the rejected one. No reward model needed. No
+reinforcement learning needed. Just a dataset of preferences and a small
+modification to the training loss.
+
+## Where it sits
+
+DPO is a fine-tuning method. It takes a base chat model that already
+knows how to follow instructions and improves the quality of its
+responses. RLHF came first. DPO came later and is simpler. Both achieve
+the same goal: making the model's outputs more aligned with what humans
+want.
+
+```
+Base model (knows language)
+ β†’ Instruction tuning (knows how to follow instructions)
+ β†’ DPO or RLHF (knows which responses are better)
+ β†’ Aligned model (helpful, harmless, honest)
+```
+
+## Why DPO replaced RLHF for most teams
+
+RLHF has three steps. Train a reward model on human preference data.
+Use the reward model to score the language model's outputs. Update the
+language model using reinforcement learning to maximize the reward. Each
+step is complex and error prone. The reward model can be fooled. The RL
+training can be unstable. The whole process requires constant
+monitoring.
+
+DPO has one step. Train the language model directly on the preference
+data using a modified loss function. The loss encourages the model to
+increase the probability of chosen responses relative to rejected
+responses. No separate reward model. No RL algorithm. No instability.
+The training loop is the same as standard fine-tuning. Only the loss
+function changes.
+
+## How DPO works
+
+DPO compares two responses to the same prompt. One was preferred by a
+human. One was rejected. The model sees both and adjusts its weights to
+make the chosen response more likely and the rejected response less
+likely.
+
+The DPO loss is a modified cross entropy loss.
+
+```
+Given:
+ prompt: "Explain gravity to a child"
+ chosen: "Gravity is the force that pulls things toward each other."
+ rejected: "Gravity is a fundamental interaction."
+
+The DPO loss:
+ log_ratio = log(P(chosen | prompt)) - log(P(rejected | prompt))
+ loss = -log(sigmoid(beta * log_ratio))
+```
+
+The beta parameter controls how strongly the model is pushed toward the
+chosen responses. Higher beta means stronger preference signal. Lower
+beta is more conservative. Typical beta values are 0.1 to 0.5.
+
+The reference model is the model before DPO training. DPO compares the
+current model's probabilities to the reference model's probabilities.
+This prevents the model from drifting too far from its original
+behavior. Without the reference model the model could learn to repeat
+the chosen responses verbatim. With the reference model it learns the
+general pattern of what makes a good response.
+
+```
+Full DPO loss with reference model:
+
+log_ratio_current = log(P_current(chosen | prompt)) - log(P_current(rejected | prompt))
+log_ratio_ref = log(P_ref(chosen | prompt)) - log(P_ref(rejected | prompt))
+loss = -log(sigmoid(beta * (log_ratio_current - log_ratio_ref)))
+```
+
+The subtraction of the reference model's log ratio is what makes DPO
+work. It asks: does the current model prefer the chosen response MORE
+than the reference model did. If yes the loss is small. If no the loss
+is large and the model is updated.
+
+## The data format
+
+DPO training data is simple. Each example has a prompt, a chosen
+response and a rejected response.
+
+```json
+{
+ "prompt": "Explain gravity to a child.",
+ "chosen": "Gravity is what keeps your feet on the ground. It pulls everything toward the Earth.",
+ "rejected": "Gravity is a fundamental interaction. Newton described it mathematically."
+}
+```
+
+The chosen response is better. Maybe it uses simpler language. Maybe it
+is more complete. Maybe it avoids factual errors. The rejected response
+is worse. Maybe it uses jargon. Maybe it is too brief. Maybe it contains
+a mistake. The model learns from the difference.
+
+The quality of DPO training depends entirely on the quality of
+preference pairs. If the rejected response is actually better than the
+chosen one the model learns the wrong lesson. Every preference pair must
+be carefully curated. High quality data is expensive to produce but
+essential for good results.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn.functional as F
+
+def dpo_loss(policy_model, reference_model, prompt_ids,
+ chosen_ids, rejected_ids, beta=0.1):
+ """
+ Compute DPO loss for a single preference pair.
+ policy_model is the model being trained.
+ reference_model is frozen and represents pre-DPO behavior.
+ """
+ with torch.no_grad():
+ ref_chosen_logp = reference_model(chosen_ids)[0].log_softmax(-1).sum()
+ ref_rejected_logp = reference_model(rejected_ids)[0].log_softmax(-1).sum()
+ ref_log_ratio = ref_chosen_logp - ref_rejected_logp
+
+ policy_chosen_logp = policy_model(chosen_ids)[0].log_softmax(-1).sum()
+ policy_rejected_logp = policy_model(rejected_ids)[0].log_softmax(-1).sum()
+ policy_log_ratio = policy_chosen_logp - policy_rejected_logp
+
+ logits = policy_log_ratio - ref_log_ratio
+ loss = -F.logsigmoid(beta * logits)
+
+ return loss
+
+
+# Example usage (conceptual)
+preference_pairs = [
+ {
+ "prompt": "Explain gravity to a child.",
+ "chosen": "Gravity is what keeps your feet on the ground.",
+ "rejected": "Gravity is a fundamental physical interaction.",
+ },
+ {
+ "prompt": "What is the capital of France?",
+ "chosen": "The capital of France is Paris. It is known for the Eiffel Tower.",
+ "rejected": "Paris.",
+ },
+]
+
+policy_model = ... # Your chat model
+reference_model = ... # Frozen copy of the same model
+
+for pair in preference_pairs:
+ prompt_ids = tokenize(pair["prompt"])
+ chosen_ids = tokenize(pair["chosen"])
+ rejected_ids = tokenize(pair["rejected"])
+
+ loss = dpo_loss(policy_model, reference_model, prompt_ids,
+ chosen_ids, rejected_ids, beta=0.1)
+ loss.backward()
+ optimizer.step()
+```
+
+## DPO versus RLHF
+
+| Aspect | RLHF | DPO |
+|---|---|---|
+| Steps | 3 (reward model + PPO + KL penalty) | 1 (direct loss) |
+| Stability | Can be unstable. Needs careful tuning | Stable. Standard supervised learning |
+| Compute | Higher. Must run reward model | Lower. Only the policy model |
+| Code complexity | High. PPO implementation is tricky | Low. Modified loss function |
+| Data | Same preference pairs | Same preference pairs |
+| Quality | Established. Used by ChatGPT | Comparable in many benchmarks |
+
+DPO has largely replaced RLHF in the open source community. It is
+simpler to implement and achieves comparable results on most benchmarks.
+The main advantage of RLHF is that it can learn from online feedback
+where the model generates responses and humans rate them in real time.
+DPO requires pre collected preference pairs. For offline datasets the
+two methods perform similarly.
+
+## When to use DPO
+
+Use DPO when you have access to human preference data and want to
+improve the quality of a model's responses beyond what instruction
+tuning alone can achieve. The model must already follow instructions.
+DPO cannot teach a base model to chat. It can only improve the quality
+of a model that already chats.
+
+Use DPO when you want to reduce harmful outputs or improve factual
+accuracy or make responses more concise or align with specific style
+guidelines. Any quality dimension that can be expressed as a preference
+between two responses can be optimized with DPO.
+
+## What you need to remember
+
+DPO trains a model directly on preference pairs without a separate
+reward model. The loss function encourages the model to prefer chosen
+responses over rejected ones. A reference model prevents the model from
+drifting too far from its original behavior. DPO is simpler and more
+stable than RLHF and achieves comparable results. It is the standard
+preference optimization method in the open source community.
diff --git a/fine-tuning/07_prompt_vs_finetune.md b/fine-tuning/07_prompt_vs_finetune.md
new file mode 100644
index 0000000..9eae9fc
--- /dev/null
+++ b/fine-tuning/07_prompt_vs_finetune.md
@@ -0,0 +1,185 @@
+# Prompt Engineering versus Fine-Tuning
+
+## The short answer
+
+Both prompt engineering and fine-tuning change how a model behaves. The
+difference is where the change lives. Prompt engineering changes the
+input. Fine-tuning changes the model itself. Choose prompt engineering
+when you need quick results on a few use cases. Choose fine-tuning when
+you need consistent behavior at scale.
+
+## Where they sit
+
+```
+Raw user input
+ β†’ Prompt engineering adds context and instructions
+ β†’ Base or fine-tuned model
+ β†’ Response
+```
+
+Prompt engineering wraps the user's request in additional text that
+guides the model. The model weights never change. Every query gets the
+same prompt template. The model interprets the template and responds
+accordingly.
+
+Fine-tuning bakes the guidance into the model's weights. The prompt can
+be simple because the model already knows how to behave. The behavior
+is consistent because it is encoded in the weights not in the prompt
+text.
+
+## When to prompt engineer
+
+Prompt engineering is the first thing to try. It is free. It takes
+minutes. It works with any model through any API.
+
+Use prompt engineering when:
+- You have a few well defined use cases
+- The behavior you want can be described in a few sentences
+- You do not need perfect consistency across hundreds of variations
+- You are prototyping and iterating quickly
+- You are using a hosted API and cannot modify the model
+
+Prompt engineering can achieve remarkable results. A well written system
+prompt can make a base chat model behave like a domain expert for
+medical questions or a creative writing coach or a code reviewer. The
+technique improves as base models get better. Each generation of models
+requires less prompting to achieve the same results.
+
+```python
+# Prompt engineering example
+system_prompt = """
+You are a helpful medical assistant. Always:
+- Use simple language a patient can understand
+- Never diagnose. Suggest seeing a doctor instead
+- Cite reliable sources when possible
+- Ask clarifying questions if symptoms are vague
+"""
+
+user_question = "My head hurts and I feel dizzy."
+
+full_prompt = f"{system_prompt}\n\nPatient: {user_question}\nAssistant:"
+response = model.generate(full_prompt)
+```
+
+The prompt does all the work. The model is unchanged. Different prompts
+can be used for different use cases. A medical prompt for health
+questions. A legal prompt for contract review. A creative prompt for
+story generation. All running on the same base model.
+
+## When to fine-tune
+
+Prompt engineering has limits. Long prompts consume context window
+space. Complex behaviors are hard to describe in words. Some patterns
+are easier to demonstrate than to explain. Prompt injection attacks can
+override system prompts. Consistency across thousands of query
+variations is hard to guarantee.
+
+Fine-tuning addresses these limits. The model learns the desired
+behavior from examples. The context window is free for the actual
+user input. The behavior is encoded in the weights and cannot be
+overridden by a cleverly crafted user message. The consistency comes
+from thousands of training examples covering every edge case.
+
+Use fine-tuning when:
+- You have hundreds or thousands of examples of the desired behavior
+- The behavior is too complex to describe in a prompt
+- You need the context window for user input not instructions
+- You need consistent behavior that cannot be prompt injected
+- You are serving the model in production at scale
+
+```python
+# Fine-tuning example with LoRA
+training_data = [
+ {"symptom": "headache and dizziness", "response": "These symptoms can have many causes..."},
+ {"symptom": "chest pain", "response": "Chest pain should be evaluated by a doctor immediately..."},
+ {"symptom": "sore throat", "response": "A sore throat is often caused by a viral infection..."},
+ # ... hundreds more examples
+]
+
+model = load_base_model()
+model = add_lora(model, rank=16)
+
+for example in training_data:
+ prompt = f"Patient: {example['symptom']}\nAssistant:"
+ response = example['response']
+ loss = compute_loss(model, prompt, response)
+ loss.backward()
+
+# Now the model responds medically without any prompt instructions
+response = model.generate("Patient: My head hurts and I feel dizzy.\nAssistant:")
+```
+
+After fine-tuning the model produces medical responses without needing
+a system prompt. The behavior is in the weights. The context window is
+free for the patient's detailed description of symptoms.
+
+## The cost comparison
+
+| Aspect | Prompt Engineering | Fine-Tuning |
+|---|---|---|
+| Time to implement | Minutes | Hours to days |
+| Cost | Free (API costs per query) | GPU time + data collection |
+| Expertise needed | Writing skills | ML engineering skills |
+| Consistency | Varies with prompt phrasing | Consistent across variations |
+| Context window used | 200 to 2000 tokens for prompt | 0 tokens for instructions |
+| Vulnerability to injection | High | Low |
+| Iteration speed | Instant | Hours per experiment |
+| Model dependency | Must redo for each model | Adapter transfers between models |
+
+## The hybrid approach
+
+Most production systems use both. Fine-tuning teaches the model the
+core behavior. Prompt engineering handles the situation specific
+details that change with each query.
+
+```
+Fine-tuning: teaches the model to be a medical assistant
+Prompt: adds patient specific context, recent lab results, medication list
+
+Fine-tuning: teaches the model to review Python code
+Prompt: adds the specific code to review, coding standards, context
+
+Fine-tuning: teaches the model to write in a brand voice
+Prompt: adds the specific topic, target audience, desired length
+```
+
+The fine-tuned model provides the foundation. The prompt provides the
+specifics. Together they are more effective than either alone.
+
+## The decision flowchart
+
+```
+Do you have a few use cases and need results today?
+ β†’ Prompt engineer
+
+Do you need consistent behavior across thousands of user inputs?
+ β†’ Fine-tune
+
+Can you describe the desired behavior clearly in words?
+ β†’ Prompt engineer
+
+Is the behavior hard to describe but easy to demonstrate with examples?
+ β†’ Fine-tune
+
+Are you using a hosted API and cannot modify the model?
+ β†’ Prompt engineer
+
+Do you have a dataset of good responses for your use case?
+ β†’ Fine-tune
+
+Is each query unique with specific context the model needs?
+ β†’ Prompt engineer
+
+Do you need to prevent users from overriding instructions?
+ β†’ Fine-tune
+```
+
+## What you need to remember
+
+Prompt engineering and fine-tuning are complementary. Prompt
+engineering is fast and flexible and changes with every query.
+Fine-tuning is slow and consistent and lives in the model's weights.
+Start with prompt engineering. Move to fine-tuning when you need
+consistency or scale or resistance to injection attacks. Most
+production systems combine both: fine-tuned models with task specific
+prompts.
diff --git a/fine-tuning/README.md b/fine-tuning/README.md
index 15442e6..a454f23 100644
--- a/fine-tuning/README.md
+++ b/fine-tuning/README.md
@@ -13,10 +13,12 @@ teaches it to be helpful.
| [03_qlora_explained.md](03_qlora_explained.md) | QLoRA. Quantization plus LoRA. Run on a laptop. |
| [04_data_preparation.md](04_data_preparation.md) | How to format data for instruction tuning. Chat templates. |
| [05_full_finetune.md](05_full_finetune.md) | Full fine-tuning. When and why not. |
+| [06_dpo_explained.md](06_dpo_explained.md) | DPO. Preference optimization without RL. |
+| [07_prompt_vs_finetune.md](07_prompt_vs_finetune.md) | When to prompt engineer vs when to fine-tune. |
## Notebook
-[`notebooks/lora_finetune.ipynb`](notebooks/lora_finetune.ipynb) . a
+[`notebooks/lora_finetune.ipynb`](notebooks/lora_finetune.ipynb). A
runnable notebook that fine-tunes a small model with LoRA on a toy
instruction dataset. Runs on a single consumer GPU.
@@ -24,5 +26,6 @@ instruction dataset. Runs on a single consumer GPU.
Start with 01 for the big picture. Then 02 to understand LoRA which is
what almost everyone uses. 03 adds quantization for even smaller GPUs.
-04 shows you how to prepare your data. 05 covers the full approach which
-is mostly for reference since it needs expensive hardware.
+04 shows you how to prepare your data. 05 covers the full approach.
+06 explains DPO the simpler alternative to RLHF. 07 helps you decide
+between prompting and fine-tuning for your own use case.