Skip to content

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

adding fint tuning

raiyanyahyacd57c88d7b3d
diff --git a/README.md b/README.md
index fee3a14..f42ed32 100644
--- a/README.md
+++ b/README.md
@@ -276,6 +276,14 @@ Each chapter follows the same **4-step structure**:
├── 📓 notebooks/ ← Jupyter notebooks (one per chapter)
│ ├── 🎨 attention_visualized.ipynb ← Watch attention weights in action
│ └── ☁️ colab_train.ipynb ← One-click cloud training on Colab
+├── 🎯 fine-tuning/ ← Fine-tuning guide: LoRA, QLoRA, data prep
+│ ├── 📄 README.md
+│ ├── 01_what_is_finetuning.md
+│ ├── 02_lora_explained.md
+│ ├── 03_qlora_explained.md
+│ ├── 04_data_preparation.md
+│ ├── 05_full_finetune.md
+│ └── 📓 notebooks/lora_finetune.ipynb
├── 📚 explanations and examples WIP/ ← Standalone explainers (18 topics)
└── 📄 CONTRIBUTING.md
```
diff --git a/fine-tuning/01_what_is_finetuning.md b/fine-tuning/01_what_is_finetuning.md
new file mode 100644
index 0000000..826bfcd
--- /dev/null
+++ b/fine-tuning/01_what_is_finetuning.md
@@ -0,0 +1,130 @@
+# What Is Fine-Tuning
+
+## The short answer
+
+Fine-tuning takes a model that already knows language and teaches it
+a specific skill. The model arrives knowing grammar and facts and
+conversation patterns from pretraining. Fine-tuning adds a new layer
+of training on a focused dataset. The result is a model that follows
+instructions or classifies sentiment or translates languages or any
+other task you can describe with examples.
+
+## Where it sits in the pipeline
+
+```
+Raw text from the internet
+ → Pretraining (expensive, general)
+ → Base model (knows language, not chat)
+ → Fine-tuning (cheaper, focused)
+ → Chat model (helpful, follows instructions)
+```
+
+Pretraining takes weeks on thousands of GPUs. Fine-tuning takes hours
+on a single GPU. The base model does the heavy lifting. Fine-tuning just
+points it in the right direction.
+
+## Why we need it
+
+A base model can complete text. Feed it *The capital of France is* and
+it finishes with *Paris.* Feed it *Summarize this article* and it
+finishes with *in a few sentences* instead of actually summarizing. The
+base model does not know it is supposed to follow instructions. It was
+trained to predict the next word in internet text. Internet text
+contains examples of people asking for summaries but also contains
+examples of people writing completions for *Summarize this article.* The
+model learned to complete. Not to follow.
+
+Fine-tuning teaches the model to distinguish between the two. By
+training on examples of instructions paired with the desired responses
+the model learns to recognize when it is being asked to do something
+and how to produce the correct output.
+
+## The three approaches
+
+| Approach | What happens | Hardware needed | How long |
+|---|---|---|---|
+| Full fine-tuning | Update every weight in the model | 4-8 A100 GPUs | Hours to days |
+| LoRA | Train small adapter matrices. Original weights frozen | Single 3090/4090 | Minutes to hours |
+| QLoRA | Quantize the base model to 4-bit. Train LoRA adapters | Single laptop GPU | Hours |
+
+Full fine-tuning updates all 152 million weights. This is the most
+powerful approach but requires hardware that most people do not own.
+The model is fully adapted to the new task but the original model is
+lost. You must store a separate full copy of the model for each task
+you fine-tune for.
+
+LoRA does not change the original weights. It adds small trainable
+matrices alongside them. At the end you have the original model plus
+tiny adapter files that are a few megabytes each. You can swap adapters
+in and out like changing a lens on a camera. One base model. Many
+adapters. Each adapter makes the model good at a different thing.
+
+QLoRA is LoRA with one extra trick. It compresses the base model to
+four bits per weight before applying LoRA. The compression reduces the
+memory needed to load the model by four to eight times. A seven billion
+parameter model that normally needs fourteen gigabytes can run in under
+four gigabytes with QLoRA. This makes fine-tuning accessible on
+consumer hardware.
+
+## When to use which
+
+If you have access to a cluster of GPUs and need maximum performance
+for a mission critical task use full fine-tuning.
+
+If you have a single good GPU and want to teach the model a new skill
+use LoRA. This covers almost everyone building applications. Chatbots
+customer support agents code assistants and content generators are all
+routinely built with LoRA.
+
+If you have a laptop or an older GPU and still want to fine-tune use
+QLoRA. The quality is slightly lower than LoRA but the model still
+learns the task successfully. The difference shrinks as base models
+get better.
+
+## The data format
+
+Fine-tuning data is simple. You provide prompt and response pairs.
+
+```
+{
+ "instruction": "Translate to French: Hello, how are you?",
+ "response": "Bonjour, comment allez-vous?"
+}
+```
+
+Every example teaches the model one thing. Given this input produce this
+output. After seeing thousands of examples the model generalizes and can
+produce correct outputs for inputs it has never seen before.
+
+The format varies by task but the principle is the same. Show the model
+what to do. Let it figure out the pattern. Do not tell it the rules
+explicitly. Let it learn from examples like it learned language from
+sentences.
+
+## What fine-tuning cannot do
+
+Fine-tuning cannot teach the model new knowledge that was not in its
+pretraining data. If the model was never trained on medical records it
+cannot suddenly become a doctor. Fine-tuning can only rearrange and
+apply knowledge the model already has.
+
+Fine-tuning cannot fix fundamental architectural limitations. A model
+with a small context window stays small. A model that hallucinates will
+still hallucinate. Fine-tuning can reduce certain failure modes but
+cannot eliminate them.
+
+Fine-tuning cannot make a bad model good. The base model must already
+be competent. Fine-tuning on a tiny incompetent model produces a tiny
+competent model. The gap between base models of different sizes
+persists after fine-tuning. A fine-tuned 7B model never catches a
+fine-tuned 70B model.
+
+## What you need to remember
+
+Fine-tuning adapts a pretrained model to a specific task. It is cheaper
+and faster than pretraining because it starts from a model that already
+knows language. LoRA is the standard approach because it is fast and
+efficient and produces tiny adapter files. QLoRA extends LoRA to run
+on consumer hardware. The data format is simple instruction response
+pairs. Fine-tuning does not add new knowledge. It rearranges existing
+knowledge to follow patterns.
diff --git a/fine-tuning/02_lora_explained.md b/fine-tuning/02_lora_explained.md
new file mode 100644
index 0000000..8d1f5c7
--- /dev/null
+++ b/fine-tuning/02_lora_explained.md
@@ -0,0 +1,193 @@
+# LoRA: Low-Rank Adaptation
+
+## The short answer
+
+LoRA fine-tunes a model without changing its original weights. It adds
+small trainable matrices to specific layers. At the end you have the
+original model plus a tiny adapter file. The adapter is usually a few
+megabytes. You can train adapters for different tasks and swap them
+instantly. One model. Many skills.
+
+## Where it sits
+
+LoRA is inserted into the linear layers of the transformer. Typically
+the query and value projections in attention and sometimes the feed
+forward layers. The original weight matrix stays frozen. LoRA adds two
+small matrices that are trained from scratch.
+
+```
+Without LoRA:
+ output = input @ W (W is large, 768 × 768, 589,824 params)
+
+With LoRA:
+ output = input @ W + input @ A @ B
+ ^^^^^^^^^^^^^^^^
+ W is frozen. A and B are trained.
+ A is 768 × 16 (12,288 params)
+ B is 16 × 768 (12,288 params)
+ LoRA adds only 24,576 params per layer
+```
+
+The rank r is small. Typically 8 16 or 32. Our example uses 16. The
+original weight matrix has rank up to 768. LoRA constrains the update
+to be low rank. The hypothesis is that fine-tuning updates are low rank
+anyway. You do not need the full rank to adapt a pretrained model to a
+new task. A small subspace is enough.
+
+## Why it works
+
+Pretrained models have rich representations. The weights already encode
+the structure of language. Fine-tuning does not need to teach the model
+language again. It only needs to teach a new behavior on top of the
+existing understanding. Teaching a new behavior on top of a rich
+representation requires only small adjustments. LoRA captures those
+small adjustments in a compact form.
+
+The rank r controls the tradeoff. Higher rank means more capacity to
+learn complex patterns. But also more parameters and slower training.
+For most instruction tuning tasks a rank of 8 or 16 is sufficient.
+For tasks that require learning new formats or patterns a rank of 32
+or 64 might help.
+
+## The math
+
+A full fine-tuning update to a weight matrix W is ΔW. The new weight
+is W + ΔW. ΔW has the same shape as W. For a 768 by 768 matrix ΔW
+has 589824 independent parameters.
+
+LoRA approximates ΔW as the product of two smaller matrices A and B.
+A has shape 768 by r. B has shape r by 768. Their product A times B has
+shape 768 by 768 but only 2 times 768 times r independent parameters.
+For r equals 16 that is 24576 parameters. A compression ratio of 24.
+
+```
+ΔW ≈ A × B
+
+ΔW[i][j] = sum over k from 0 to r-1: A[i][k] × B[k][j]
+```
+
+During training W is frozen. Gradients flow only through A and B. A
+is initialized with random normal values. B is initialized to zero so
+that at the start of training the adapter does nothing. The model
+behaves exactly like the base model until A and B start learning.
+
+## The alpha parameter
+
+LoRA has a scaling factor called alpha. The LoRA output is scaled by
+alpha divided by rank before being added to the original output.
+
+```
+output = input @ W + (alpha / r) × (input @ A @ B)
+```
+
+Alpha controls how much influence the adapter has. A larger alpha means
+the adapter has more impact on the output. The standard value is twice
+the rank. So for rank 16 alpha is usually 32.
+
+When you change the rank the alpha to rank ratio determines the
+effective learning rate of the adapter. Keeping alpha equal to twice
+the rank means the ratio stays 2 regardless of rank. This makes
+hyperparameter tuning transferable across rank values.
+
+## The dropout
+
+LoRA adapters usually include a small dropout on the A matrix output.
+Dropout is 0.05 or 0.1. It prevents the adapter from overfitting to
+the limited fine-tuning data. The base model provides regularization
+because its weights are frozen. The adapter needs its own small
+regularization.
+
+## Which layers to adapt
+
+The standard choice is query and value projections in every attention
+layer. Some configurations also adapt the output projection and the
+feed forward layers. More adapted layers means more capacity but also
+more parameters.
+
+```
+Minimal (recommended for most tasks):
+ Query projection (W_q)
+ Value projection (W_v)
+
+Standard (good for instruction tuning):
+ Query projection (W_q)
+ Value projection (W_v)
+ Key projection (W_k)
+ Output projection (W_o)
+
+Full (maximum capacity):
+ All linear layers including feed forward
+```
+
+For our model with 12 layers the minimal configuration adds about 0.3
+million parameters on top of 152 million frozen parameters. The adapter
+is about 2 megabytes. A full fine-tuning checkpoint would be 600
+megabytes for the same model.
+
+## Merging adapters
+
+At inference time you have two choices. Keep the adapter separate and
+compute the LoRA update on the fly. Or merge the adapter into the base
+weights for faster inference.
+
+```
+Separate (training and experimentation):
+ output = input @ W + input @ A @ B
+ Flexible. Easy to swap adapters. Slightly slower inference.
+
+Merged (deployment):
+ W_merged = W + A @ B
+ output = input @ W_merged
+ No extra computation. No slowdown. Permanent.
+```
+
+Merging is a one way operation. After merging you cannot separate the
+adapter from the base weights. But inference is as fast as the original
+model. Most deployments merge before serving.
+
+## A tiny code example
+
+```python
+import torch
+import torch.nn as nn
+
+class LoRALinear(nn.Module):
+ def __init__(self, in_features, out_features, rank=16, alpha=32):
+ super().__init__()
+ self.linear = nn.Linear(in_features, out_features, bias=False)
+ self.rank = rank
+ self.alpha = alpha
+
+ self.lora_a = nn.Linear(in_features, rank, bias=False)
+ self.lora_b = nn.Linear(rank, out_features, bias=False)
+
+ nn.init.normal_(self.lora_a.weight, std=0.02)
+ nn.init.zeros_(self.lora_b.weight)
+
+ for param in self.linear.parameters():
+ param.requires_grad = False
+
+ def forward(self, x):
+ base = self.linear(x)
+ lora = self.lora_b(self.lora_a(x)) * (self.alpha / self.rank)
+ return base + lora
+
+# Replace a 768x768 linear layer with LoRA
+layer = LoRALinear(768, 768, rank=16)
+
+frozen_params = sum(p.numel() for p in layer.parameters() if not p.requires_grad)
+trainable_params = sum(p.numel() for p in layer.parameters() if p.requires_grad)
+
+print(f"Frozen parameters: {frozen_params:,}")
+print(f"Trainable parameters: {trainable_params:,}")
+print(f"Compression ratio: {frozen_params / trainable_params:.0f}x")
+```
+
+## What you need to remember
+
+LoRA adds small trainable matrices to frozen pretrained layers. The
+update is constrained to be low rank. The rank controls capacity versus
+parameter count. The alpha parameter scales the adapter influence.
+Adapters are tiny files that can be swapped at will. Merging eliminates
+inference overhead. LoRA makes fine-tuning accessible on consumer GPUs
+while maintaining most of the quality of full fine-tuning.
diff --git a/fine-tuning/03_qlora_explained.md b/fine-tuning/03_qlora_explained.md
new file mode 100644
index 0000000..d3fa915
--- /dev/null
+++ b/fine-tuning/03_qlora_explained.md
@@ -0,0 +1,148 @@
+# QLoRA: Quantized LoRA
+
+## The short answer
+
+QLoRA is LoRA plus quantization. The base model is compressed to four
+bits per weight before applying LoRA adapters. This reduces memory by
+four to eight times compared to the full precision model. A seven
+billion parameter model that normally needs fourteen gigabytes can run
+in under four gigabytes. Fine-tuning becomes possible on a laptop.
+
+## Where the quantization happens
+
+Quantization applies to the frozen base model only. The LoRA adapter
+matrices stay in full precision. During training the four bit weights
+are temporarily dequantized back to sixteen bit for the forward and
+backward passes. The dequantization happens inside the computation.
+You do not see it. The model lives in four bits but computes in sixteen
+bits.
+
+```
+Base model weights (frozen):
+ Stored as 4-bit integers
+ Dequantized to bfloat16 for computation
+ Re-quantized after computation (gradients don't flow through them)
+
+LoRA adapters (trained):
+ Stored and computed in bfloat16
+ Gradients flow through them normally
+```
+
+## Why four bits
+
+The standard float32 representation uses 32 bits per weight. Bfloat16
+uses 16 bits. Four bit quantization uses 4 bits. Each reduction halves
+both memory usage and the time to read weights from memory.
+
+```
+Float32 model (7B params): 28 GB (7B × 4 bytes)
+Bfloat16 model (7B params): 14 GB (7B × 2 bytes)
+4-bit quantized (7B params): 3.5 GB (7B × 0.5 bytes)
+Plus LoRA adapters: ~0.1 GB (negligible)
+```
+
+The memory savings are dramatic. A model that would not fit on a 24
+gigabyte RTX 3090 in bfloat16 fits easily in 4-bit with room to spare
+for training batches.
+
+## How the quantization works
+
+Quantization maps floating point values to a small set of integer
+values. The simplest quantization is rounding to the nearest integer.
+But weights in a neural network are not uniformly distributed. Some
+layers have weights clustered near zero. Others have weights spread
+across a wide range.
+
+QLoRA uses a technique called NormalFloat4. It assumes weights follow
+a normal distribution and assigns more quantization levels near zero
+where most weights live and fewer levels at the extremes where few
+weights live.
+
+```
+Standard uniform quantization (2-bit example):
+ 0.00 ... 0.25 ... 0.50 ... 0.75 ... 1.00
+ Each bin gets equal width.
+
+NormalFloat quantization (2-bit example):
+ 0.00 ......... 0.10 . 0.40 ......... 1.00
+ More bins near zero. Fewer bins at extremes.
+```
+
+The result is less quantization error for the same number of bits.
+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.
+
+## Double quantization
+
+QLoRA applies a second round of quantization to the quantization
+constants themselves. Each block of weights has a scaling factor that
+converts between the integer representation and the floating point
+representation. These scaling factors are stored as float32 by default.
+Double quantization compresses them to eight bits.
+
+The savings from double quantization are small. About 0.13 bits per
+parameter on average. But for a seven billion parameter model that is
+about 120 megabytes. Enough to matter when fitting a model into a GPU
+with tight memory.
+
+## Paged optimizers
+
+Training with QLoRA uses an optimizer that manages GPU memory like an
+operating system manages RAM. When the GPU runs out of memory the
+optimizer pages some optimizer states to CPU RAM. When those states
+are needed again they are paged back to GPU memory.
+
+This prevents out-of-memory errors during training. Without paging a
+memory spike from a large gradient calculation could crash training.
+With paging the optimizer shuffles data between GPU and CPU to handle
+the spike.
+
+The technique is borrowed from operating systems where virtual memory
+allows processes to use more memory than physically available by
+swapping pages to disk. The same idea applied to GPU memory management
+during training.
+
+## The tradeoff
+
+QLoRA is slightly slower than LoRA because of the dequantization
+overhead. Every forward and backward pass must convert the base weights
+from four bits to sixteen bits and back. This adds computation time.
+But the memory savings usually outweigh the speed penalty. A model that
+cannot be trained at all in bfloat16 can be trained successfully with
+QLoRA.
+
+The quality is slightly lower than LoRA. The quantization introduces
+noise. Some information is lost in the conversion to four bits. But the
+loss is small. For most tasks the difference between QLoRA and LoRA is
+within a few percent on standard benchmarks.
+
+## What you can run where
+
+```
+16 GB GPU (RTX 4080 laptop):
+ LoRA: fine-tune up to ~7B models
+ QLoRA: fine-tune up to ~13B models
+
+24 GB GPU (RTX 3090/4090):
+ LoRA: fine-tune up to ~13B models
+ QLoRA: fine-tune up to ~34B models
+
+12 GB GPU (RTX 3060/4060):
+ LoRA: fine-tune up to ~3B models
+ QLoRA: fine-tune up to ~7B models
+
+8 GB GPU (RTX 2070):
+ LoRA: fine-tune up to ~1B models
+ QLoRA: fine-tune up to ~3B models
+```
+
+## What you need to remember
+
+QLoRA compresses the frozen base model to four bits. LoRA adapters
+stay in full precision. The combination lets you fine-tune models that
+would otherwise not fit in GPU memory. NormalFloat4 quantization gives
+better accuracy than uniform quantization for the same bit budget.
+Double quantization squeezes a little more memory from the quantization
+constants. Paged optimizers prevent out-of-memory crashes. QLoRA is the
+standard approach for fine-tuning on consumer hardware.
diff --git a/fine-tuning/04_data_preparation.md b/fine-tuning/04_data_preparation.md
new file mode 100644
index 0000000..ea41589
--- /dev/null
+++ b/fine-tuning/04_data_preparation.md
@@ -0,0 +1,172 @@
+# Data Preparation for Fine-Tuning
+
+## The short answer
+
+Fine-tuning data is a collection of examples. Each example shows the
+model what to do. Give it an input and the desired output. After seeing
+thousands of examples the model learns the pattern and can produce
+correct outputs for new inputs. The quality of the data matters more
+than the quantity. Cleaning the data and formatting it consistently is
+most of the work.
+
+## The basic format
+
+Every example has at least an instruction and a response. Some examples
+also have a system prompt or context.
+
+```json
+{
+ "instruction": "Summarize this paragraph in one sentence.",
+ "input": "The cat sat on the mat for three hours...",
+ "response": "A cat stayed on a mat for an extended period."
+}
+```
+
+The input field is optional. Many tasks only need an instruction. The
+model learns from the pattern of instruction followed by response.
+
+## Chat templates
+
+Most fine-tuned models use a chat format. The instruction and response
+are wrapped in special tokens that tell the model where the user
+message ends and the assistant response begins.
+
+```
+<|user|>
+What is the capital of France?
+<|assistant|>
+The capital of France is Paris.
+<|endoftext|>
+```
+
+The exact tokens depend on the base model. LLaMA uses `[INST]` and
+`[/INST]`. Mistral uses `<s>[INST]` and `[/INST]`. Open source chat
+models often use `<|user|>` and `<|assistant|>` markers. Using the
+wrong tokens means the model does not recognize the format and
+produces garbage.
+
+## How much data you need
+
+The minimum is around one hundred examples. Below that the model cannot
+generalize. It memorizes the examples and fails on new inputs. A
+thousand examples is solid for most tasks. Ten thousand is good for
+complex tasks like multi-turn conversation or code generation. Beyond
+ten thousand the returns diminish quickly.
+
+```
+100 examples: Bare minimum. Model might not generalize.
+1,000 examples: Good for most classification and simple QA tasks.
+5,000 examples: Good for instruction following and summarization.
+10,000+ examples: Complex tasks. Diminishing returns after this.
+```
+
+The quality of each example matters more than the total count. A
+thousand carefully written examples beat ten thousand sloppy ones.
+Every mistake in the training data teaches the model to make that
+mistake. The model learns to replicate patterns. Not to judge them.
+
+## Cleaning the data
+
+Before training go through your data and remove anything that would
+teach the model bad habits.
+
+Examples of what to remove. Responses that are cut off or incomplete.
+Responses that contradict the instruction. Instructions that are
+ambiguous or impossible to follow. Repeated examples. Examples where
+the response is in the wrong language or format. Examples with
+offensive or harmful content.
+
+```
+Good example:
+ Instruction: "What is 2 + 2?"
+ Response: "2 + 2 equals 4."
+
+Bad example (vague):
+ Instruction: "Tell me about math."
+ Response: "It's cool."
+
+Bad example (contradicts):
+ Instruction: "Give a short answer."
+ Response: "Let me explain this in great detail over several paragraphs..."
+```
+
+## Balancing the data
+
+Fine-tuning can unbalance the model. If you train only on one task the
+model gets worse at everything else. This is called catastrophic
+forgetting. The model forgets how to have a normal conversation because
+every training example is a specific task.
+
+Mix in some general conversation examples. About ten percent of your
+data should be normal chat. This keeps the model from losing its
+general abilities while learning the new task.
+
+## The prompt matters
+
+The instruction text affects the results. Different phrasings produce
+different behaviors. If you train with instructions like *Summarize
+this* the model learns to summarize when it sees those words. If
+someone asks *Give me a short version* instead the model might not
+recognize it as a summarization request.
+
+Write instructions in multiple ways. For each task provide three or
+four different phrasings of the same instruction. This teaches the
+model the intent behind the words rather than the exact wording.
+
+```
+"Summarize this paragraph."
+"Can you summarize this?"
+"Give me a summary of the following text."
+"Briefly summarize what this says."
+```
+
+All four mean the same thing. Training on all four variants makes the
+model robust to different phrasings.
+
+## Splitting the data
+
+Divide your data into training and validation sets. Train on ninety
+percent. Evaluate on ten percent. The validation set tells you if the
+model is learning the task or just memorizing the examples.
+
+If the training loss goes down but the validation loss goes up the
+model is memorizing. Stop training. Reduce the number of steps or
+increase dropout. If both go down you are on the right track.
+
+## A real example
+
+Here is a small instruction tuning dataset in the format used by Alpaca.
+
+```json
+[
+ {
+ "instruction": "Give three tips for staying healthy.",
+ "input": "",
+ "output": "1. Eat a balanced diet with plenty of vegetables..."
+ },
+ {
+ "instruction": "What are the three primary colors?",
+ "input": "",
+ "output": "The three primary colors are red blue and yellow."
+ },
+ {
+ "instruction": "Describe the following city in three sentences.",
+ "input": "Tokyo",
+ "output": "Tokyo is the capital of Japan and one of the most..."
+ }
+]
+```
+
+Each example is a self-contained lesson. The model sees the instruction
+and learns to produce the output. After thousands of examples it can
+handle variations of instructions it has never seen before.
+
+## What you need to remember
+
+Fine-tuning data is instruction response pairs. The format uses special
+tokens specific to each base model. A thousand good examples beats ten
+thousand bad ones. Clean the data carefully. The model learns to
+replicate patterns not to judge their quality. Mix in general
+conversation to prevent catastrophic forgetting. Vary the phrasing of
+instructions to build robustness. Split into training and validation
+sets to monitor for memorization.
diff --git a/fine-tuning/05_full_finetune.md b/fine-tuning/05_full_finetune.md
new file mode 100644
index 0000000..3dc87fe
--- /dev/null
+++ b/fine-tuning/05_full_finetune.md
@@ -0,0 +1,127 @@
+# Full Fine-Tuning
+
+## The short answer
+
+Full fine-tuning updates every weight in the model. Nothing is frozen.
+Every parameter is trained on the new task. This is the most powerful
+approach but requires the most hardware. It is also the most expensive
+and the least flexible because you must store a complete copy of the
+model for every task you fine-tune for.
+
+## Where it sits
+
+Full fine-tuning takes the pretrained checkpoint and continues
+training. The only difference from pretraining is the data. Instead of
+raw internet text the model sees instruction response pairs. The
+training loop is identical. Forward pass. Compute loss. Backward pass.
+Update weights. The same code that trained the base model trains the
+fine-tuned model.
+
+## Why you might need it
+
+LoRA works for most tasks. But some tasks require changing the model's
+fundamental behavior in ways that low rank updates cannot capture.
+Teaching a model a new language that was not in its pretraining data.
+Radically changing the output format or style. Correcting systematic
+biases or errors in the base model. These cases might justify full
+fine-tuning.
+
+Full fine-tuning also produces the highest quality results when
+measured on standard benchmarks. The gap between full fine-tuning and
+LoRA has been shrinking as base models improve but for the most
+demanding applications full fine-tuning still wins by a small margin.
+
+## Why you probably do not need it
+
+Most real world use cases do not need full fine-tuning. Instruction
+following. Chat behavior. Summarization. Classification. Translation.
+All of these work well with LoRA. The additional cost of full
+fine-tuning rarely justifies the marginal quality improvement.
+
+Full fine-tuning also introduces operational complexity. Each fine-tuned
+variant is a separate multi-gigabyte checkpoint. Storing serving and
+versioning these checkpoints is expensive. With LoRA you store one base
+model and many small adapter files.
+
+## The hardware requirement
+
+Full fine-tuning needs enough GPU memory to store the model weights the
+optimizer states and the activations for a training batch. The optimizer
+states are the largest cost because AdamW stores two values per
+parameter.
+
+```
+Memory for a 7B parameter model during full fine-tuning:
+
+Model weights (bfloat16): 14 GB (7B × 2 bytes)
+Optimizer states (float32): 56 GB (7B × 2 × 4 bytes)
+Gradients (float32): 28 GB (7B × 4 bytes)
+Activations (bfloat16, batch=1): ~2 GB (varies by seq length)
+-------------------------------------------------
+Total: ~100 GB
+```
+
+This requires multiple GPUs. An RTX 4090 has 24 gigabytes. You would
+need four or five of them just to load the model and optimizer. This is
+why full fine-tuning is done in data centers not on desktops.
+
+## The process
+
+Full fine-tuning follows the same steps as pretraining but with
+different hyperparameters.
+
+```
+Learning rate: 1e-5 to 5e-5 (much smaller than pretraining)
+Warmup steps: 100 to 500 (less warmup needed)
+Total steps: 1 to 5 epochs (fewer epochs because less data)
+Batch size: As large as fits in memory
+Weight decay: 0.1 (same as pretraining)
+```
+
+The learning rate is ten to thirty times smaller than pretraining. The
+model is already close to a good solution. Large steps would destroy
+the pretrained knowledge. Small steps refine the behavior without
+disrupting the foundation.
+
+## Catastrophic forgetting
+
+Full fine-tuning has a risk that LoRA avoids. When every weight can
+change the model can forget its pretrained abilities. A model
+fine-tuned on only medical questions might lose the ability to discuss
+sports or politics or history. The weights drift away from the
+pretrained configuration.
+
+Mitigations exist. Mix general data into the fine-tuning set. Use a
+very small learning rate. Stop training as soon as the validation loss
+stops improving. But even with mitigations some forgetting is
+inevitable. The model trades some of its broad knowledge for deep
+knowledge of the fine-tuning task.
+
+LoRA avoids this by freezing the base weights. The original knowledge
+is preserved exactly because the original weights never change. Only
+the adapters learn the new task. This is a fundamental architectural
+advantage of LoRA over full fine-tuning for most applications.
+
+## When it is worth it
+
+Full fine-tuning makes sense in a few specific scenarios. When you are
+building a foundation model that others will fine-tune. When the task
+requires changing the model's knowledge not just its behavior. When
+the marginal quality improvement from full fine-tuning translates to
+real business value. When you have the hardware budget and the
+operational infrastructure to manage large model files.
+
+For everyone else LoRA or QLoRA is the right choice. Less hardware.
+Less storage. Less time. Nearly the same quality. The gap continues to
+shrink as base models improve and adapters get better at capturing
+task specific behavior.
+
+## What you need to remember
+
+Full fine-tuning updates every weight in the model on task specific
+data. It requires expensive hardware because optimizer states consume
+four times the memory of the model itself. It risks catastrophic
+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.
diff --git a/fine-tuning/README.md b/fine-tuning/README.md
new file mode 100644
index 0000000..15442e6
--- /dev/null
+++ b/fine-tuning/README.md
@@ -0,0 +1,28 @@
+# Fine-Tuning: Making the Model Useful
+
+This folder covers everything about adapting a pretrained language model
+for a specific task. Pretraining teaches the model language. Fine-tuning
+teaches it to be helpful.
+
+## What's inside
+
+| File | Topic |
+|---|---|
+| [01_what_is_finetuning.md](01_what_is_finetuning.md) | The concept. Why we fine-tune. Types: full, LoRA, QLoRA. |
+| [02_lora_explained.md](02_lora_explained.md) | LoRA deep dive. Low-rank decomposition. The math in simple terms. |
+| [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. |
+
+## Notebook
+
+[`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.
+
+## Reading order
+
+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.
diff --git a/fine-tuning/notebooks/.gitkeep b/fine-tuning/notebooks/.gitkeep
new file mode 100644
index 0000000..e69de29
diff --git a/fine-tuning/notebooks/lora_finetune.ipynb b/fine-tuning/notebooks/lora_finetune.ipynb
new file mode 100644
index 0000000..191f45f
--- /dev/null
+++ b/fine-tuning/notebooks/lora_finetune.ipynb
@@ -0,0 +1,508 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# LoRA Fine-Tuning\n",
+ "\n",
+ "This notebook fine-tunes a small language model using LoRA.\n",
+ "We start with a tiny pretrained model add LoRA adapters and\n",
+ "train on a small instruction dataset. At the end you will see\n",
+ "how the model learns to follow instructions without changing\n",
+ "its original weights.\n",
+ "\n",
+ "The base model has 17 million parameters. The LoRA adapters\n",
+ "add only 0.3 million trainable parameters. The original\n",
+ "weights stay frozen. This is the power of LoRA."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Imports"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "import torch\n",
+ "import torch.nn as nn\n",
+ "import torch.nn.functional as F\n",
+ "import math\n",
+ "import time\n",
+ "from dataclasses import dataclass\n",
+ "from torch.utils.data import Dataset, DataLoader\n",
+ "import tiktoken"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## The base model\n",
+ "\n",
+ "A tiny GPT with the same architecture we built in the guide.\n",
+ "We keep it small so LoRA training finishes in seconds."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class RotaryPositionalEmbedding(nn.Module):\n",
+ " def __init__(self, d_model, max_seq_len=128, theta=10000.0):\n",
+ " super().__init__()\n",
+ " assert d_model % 2 == 0\n",
+ " dim_indices = torch.arange(0, d_model, 2).float()\n",
+ " inv_freq = 1.0 / (theta ** (dim_indices / d_model))\n",
+ " positions = torch.arange(max_seq_len).float()\n",
+ " freqs = torch.outer(positions, inv_freq)\n",
+ " emb = freqs.repeat_interleave(2, dim=-1)\n",
+ " self.register_buffer(\"cos_cached\", emb.cos())\n",
+ " self.register_buffer(\"sin_cached\", emb.sin())\n",
+ "\n",
+ " @staticmethod\n",
+ " def rotate_half(x):\n",
+ " x1 = x[..., : x.shape[-1] // 2]\n",
+ " x2 = x[..., x.shape[-1] // 2 :]\n",
+ " return torch.cat([-x2, x1], dim=-1)\n",
+ "\n",
+ " def forward(self, x, seq_len):\n",
+ " cos = self.cos_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",
+ " sin = self.sin_cached[:seq_len].unsqueeze(0).unsqueeze(0)\n",
+ " return (x * cos) + (self.rotate_half(x) * sin)\n",
+ "\n",
+ "\n",
+ "def create_causal_mask(seq_len, device):\n",
+ " mask = torch.tril(torch.ones(seq_len, seq_len, device=device))\n",
+ " return mask.view(1, 1, seq_len, seq_len)\n",
+ "\n",
+ "\n",
+ "class RMSNorm(nn.Module):\n",
+ " def __init__(self, d_model, eps=1e-6):\n",
+ " super().__init__()\n",
+ " self.weight = nn.Parameter(torch.ones(d_model))\n",
+ " self.eps = eps\n",
+ "\n",
+ " def forward(self, x):\n",
+ " rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)\n",
+ " return x * rms * self.weight\n",
+ "\n",
+ "\n",
+ "class SwiGLU(nn.Module):\n",
+ " def __init__(self, d_model, expansion_factor=4):\n",
+ " super().__init__()\n",
+ " hidden_dim = expansion_factor * d_model\n",
+ " self.w1 = nn.Linear(d_model, hidden_dim, bias=False)\n",
+ " self.w2 = nn.Linear(d_model, hidden_dim, bias=False)\n",
+ " self.w3 = nn.Linear(hidden_dim, d_model, bias=False)\n",
+ "\n",
+ " def forward(self, x):\n",
+ " return self.w3(F.silu(self.w1(x)) * self.w2(x))\n",
+ "\n",
+ "\n",
+ "class MultiHeadAttention(nn.Module):\n",
+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",
+ " super().__init__()\n",
+ " assert d_model % num_heads == 0\n",
+ " self.d_model = d_model\n",
+ " self.num_heads = num_heads\n",
+ " self.head_dim = d_model // num_heads\n",
+ " self.qkv_proj = nn.Linear(d_model, 3 * d_model, bias=False)\n",
+ " self.out_proj = nn.Linear(d_model, d_model, bias=False)\n",
+ " self.rotary = RotaryPositionalEmbedding(self.head_dim)\n",
+ " self.attn_dropout = nn.Dropout(dropout)\n",
+ " self.resid_dropout = nn.Dropout(dropout)\n",
+ "\n",
+ " def forward(self, x, mask=None):\n",
+ " batch_size, seq_len, _ = x.shape\n",
+ " qkv = self.qkv_proj(x)\n",
+ " qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim)\n",
+ " qkv = qkv.permute(2, 0, 3, 1, 4)\n",
+ " q, k, v = qkv[0], qkv[1], qkv[2]\n",
+ " q = self.rotary(q, seq_len)\n",
+ " k = self.rotary(k, seq_len)\n",
+ " attn_scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",
+ " if mask is not None:\n",
+ " attn_scores = attn_scores.masked_fill(mask == 0, float('-inf'))\n",
+ " attn_weights = F.softmax(attn_scores, dim=-1)\n",
+ " attn_weights = self.attn_dropout(attn_weights)\n",
+ " attn_output = attn_weights @ v\n",
+ " attn_output = attn_output.transpose(1, 2).contiguous()\n",
+ " attn_output = attn_output.reshape(batch_size, seq_len, self.d_model)\n",
+ " output = self.out_proj(attn_output)\n",
+ " output = self.resid_dropout(output)\n",
+ " return output\n",
+ "\n",
+ "\n",
+ "class TransformerBlock(nn.Module):\n",
+ " def __init__(self, d_model, num_heads, dropout=0.1):\n",
+ " super().__init__()\n",
+ " self.norm1 = RMSNorm(d_model)\n",
+ " self.attention = MultiHeadAttention(d_model, num_heads, dropout)\n",
+ " self.norm2 = RMSNorm(d_model)\n",
+ " self.ffn = SwiGLU(d_model)\n",
+ "\n",
+ " def forward(self, x, mask=None):\n",
+ " x = x + self.attention(self.norm1(x), mask)\n",
+ " x = x + self.ffn(self.norm2(x))\n",
+ " return x\n",
+ "\n",
+ "\n",
+ "@dataclass\n",
+ "class GPTConfig:\n",
+ " vocab_size: int = 50257\n",
+ " d_model: int = 256\n",
+ " num_heads: int = 4\n",
+ " num_layers: int = 4\n",
+ " max_seq_len: int = 128\n",
+ " dropout: float = 0.1\n",
+ " embd_dropout: float = 0.1\n",
+ "\n",
+ "\n",
+ "class GPT(nn.Module):\n",
+ " def __init__(self, config):\n",
+ " super().__init__()\n",
+ " self.config = config\n",
+ " self.token_embedding = nn.Embedding(config.vocab_size, config.d_model)\n",
+ " self.embd_dropout = nn.Dropout(config.embd_dropout)\n",
+ " self.layers = nn.ModuleList([\n",
+ " TransformerBlock(config.d_model, config.num_heads, config.dropout)\n",
+ " for _ in range(config.num_layers)\n",
+ " ])\n",
+ " self.final_norm = RMSNorm(config.d_model)\n",
+ " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n",
+ " self.token_embedding.weight = self.lm_head.weight\n",
+ " self.apply(self._init_weights)\n",
+ "\n",
+ " def _init_weights(self, module):\n",
+ " if isinstance(module, (nn.Linear, nn.Embedding)):\n",
+ " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n",
+ " if hasattr(module, 'bias') and module.bias is not None:\n",
+ " torch.nn.init.zeros_(module.bias)\n",
+ "\n",
+ " def forward(self, input_ids, targets=None):\n",
+ " batch_size, seq_len = input_ids.shape\n",
+ " x = self.token_embedding(input_ids)\n",
+ " x = self.embd_dropout(x)\n",
+ " mask = create_causal_mask(seq_len, input_ids.device)\n",
+ " for layer in self.layers:\n",
+ " x = layer(x, mask)\n",
+ " x = self.final_norm(x)\n",
+ " logits = self.lm_head(x)\n",
+ " loss = None\n",
+ " if targets is not None:\n",
+ " logits_flat = logits.contiguous().view(-1, self.config.vocab_size)\n",
+ " targets_flat = targets.contiguous().view(-1)\n",
+ " loss = F.cross_entropy(logits_flat, targets_flat)\n",
+ " return logits, loss\n",
+ "\n",
+ " @torch.no_grad()\n",
+ " def generate(self, input_ids, max_new_tokens, temperature=0.8, top_k=50):\n",
+ " self.eval()\n",
+ " for _ in range(max_new_tokens):\n",
+ " if input_ids.shape[1] > self.config.max_seq_len:\n",
+ " input_ids = input_ids[:, -self.config.max_seq_len:]\n",
+ " logits, _ = self.forward(input_ids)\n",
+ " logits = logits[:, -1, :] / temperature\n",
+ " if top_k is not None:\n",
+ " v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n",
+ " logits[logits < v[:, -1:]] = float('-inf')\n",
+ " probs = F.softmax(logits, dim=-1)\n",
+ " next_token = torch.multinomial(probs, num_samples=1)\n",
+ " input_ids = torch.cat([input_ids, next_token], dim=1)\n",
+ " return input_ids\n",
+ "\n",
+ "\n",
+ "config = GPTConfig()\n",
+ "model = GPT(config)\n",
+ "model.eval()\n",
+ "\n",
+ "print(f\"Base model parameters: {sum(p.numel() for p in model.parameters()):,}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generate before fine-tuning\n",
+ "\n",
+ "The base model knows language but has never been fine-tuned to\n",
+ "follow instructions. Let us see what it produces."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "tokenizer = tiktoken.get_encoding(\"gpt2\")\n",
+ "\n",
+ "def chat(model, prompt, max_tokens=30):\n",
+ " full_prompt = f\"User: {prompt}\\nAssistant:\"\n",
+ " ids = torch.tensor([tokenizer.encode(full_prompt)], dtype=torch.long)\n",
+ " output = model.generate(ids, max_new_tokens=max_tokens)\n",
+ " return tokenizer.decode(output[0].tolist())\n",
+ "\n",
+ "prompts = [\n",
+ " \"What is the capital of France?\",\n",
+ " \"Write a short poem about a cat.\",\n",
+ " \"Explain gravity in simple terms.\",\n",
+ "]\n",
+ "\n",
+ "print(\"=== BEFORE FINE-TUNING ===\")\n",
+ "for p in prompts:\n",
+ " print(f\"\\nPrompt: {p}\")\n",
+ " print(f\"Output: {chat(model, p)[:200]}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Add LoRA adapters\n",
+ "\n",
+ "We freeze the base model and add LoRA to the query and value\n",
+ "projections in every attention layer. Only the LoRA weights\n",
+ "will be trained."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class LoRALinear(nn.Module):\n",
+ " def __init__(self, original_linear, rank=8, alpha=16):\n",
+ " super().__init__()\n",
+ " self.original = original_linear\n",
+ " self.rank = rank\n",
+ " self.alpha = alpha\n",
+ "\n",
+ " in_features = original_linear.in_features\n",
+ " out_features = original_linear.out_features\n",
+ "\n",
+ " self.lora_a = nn.Linear(in_features, rank, bias=False)\n",
+ " self.lora_b = nn.Linear(rank, out_features, bias=False)\n",
+ "\n",
+ " nn.init.normal_(self.lora_a.weight, std=0.02)\n",
+ " nn.init.zeros_(self.lora_b.weight)\n",
+ "\n",
+ " for param in original_linear.parameters():\n",
+ " param.requires_grad = False\n",
+ "\n",
+ " def forward(self, x):\n",
+ " return self.original(x) + self.lora_b(self.lora_a(x)) * (self.alpha / self.rank)\n",
+ "\n",
+ "\n",
+ "def add_lora_to_model(model, rank=8, alpha=16):\n",
+ " for param in model.parameters():\n",
+ " param.requires_grad = False\n",
+ "\n",
+ " lora_params = []\n",
+ " for layer in model.layers:\n",
+ " attn = layer.attention\n",
+ " original_qkv = attn.qkv_proj\n",
+ "\n",
+ " in_dim = original_qkv.in_features\n",
+ " out_dim = original_qkv.out_features\n",
+ "\n",
+ " lora_qkv = LoRALinear(original_qkv, rank=rank, alpha=alpha)\n",
+ " attn.qkv_proj = lora_qkv\n",
+ "\n",
+ " for param in lora_qkv.lora_a.parameters():\n",
+ " lora_params.append(param)\n",
+ " for param in lora_qkv.lora_b.parameters():\n",
+ " lora_params.append(param)\n",
+ "\n",
+ " return lora_params\n",
+ "\n",
+ "\n",
+ "lora_params = add_lora_to_model(model, rank=8, alpha=16)\n",
+ "\n",
+ "base_params = sum(p.numel() for p in model.parameters() if not p.requires_grad)\n",
+ "lora_count = sum(p.numel() for p in lora_params)\n",
+ "\n",
+ "print(f\"Base model (frozen): {base_params:,} parameters\")\n",
+ "print(f\"LoRA adapters (trainable): {lora_count:,} parameters\")\n",
+ "print(f\"LoRA adds only {100 * lora_count / base_params:.2f}% more parameters\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Create a small instruction dataset\n",
+ "\n",
+ "A few examples to teach the model to respond like an assistant.\n",
+ "The model will learn the pattern: User asks something. Assistant\n",
+ "gives a helpful response."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "training_data = [\n",
+ " (\"What is the capital of France?\", \"The capital of France is Paris.\"),\n",
+ " (\"What is 2 + 2?\", \"2 + 2 equals 4.\"),\n",
+ " (\"Who wrote Romeo and Juliet?\", \"William Shakespeare wrote Romeo and Juliet.\"),\n",
+ " (\"What color is the sky?\", \"The sky is blue on a clear day.\"),\n",
+ " (\"How many legs does a cat have?\", \"A cat has four legs.\"),\n",
+ " (\"What is the largest planet?\", \"Jupiter is the largest planet in our solar system.\"),\n",
+ " (\"Name a primary color.\", \"Red is a primary color.\"),\n",
+ " (\"What sound does a dog make?\", \"A dog barks.\"),\n",
+ " (\"What is water made of?\", \"Water is made of hydrogen and oxygen.\"),\n",
+ " (\"How many days in a week?\", \"There are seven days in a week.\"),\n",
+ "] * 5\n",
+ "\n",
+ "print(f\"Training examples: {len(training_data)}\")\n",
+ "\n",
+ "# Show a few\n",
+ "for q, a in training_data[:3]:\n",
+ " print(f\" Q: {q}\")\n",
+ " print(f\" A: {a}\")\n",
+ " print()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Train the LoRA adapters\n",
+ "\n",
+ "Only the LoRA weights are updated. The base model stays frozen.\n",
+ "This trains in seconds even on CPU."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "optimizer = torch.optim.AdamW(lora_params, lr=3e-4)\n",
+ "\n",
+ "tokenizer = tiktoken.get_encoding(\"gpt2\")\n",
+ "\n",
+ "print(f\"Training for 200 steps...\")\n",
+ "start = time.time()\n",
+ "\n",
+ "for step in range(200):\n",
+ " total_loss = 0\n",
+ " for question, answer in training_data:\n",
+ " text = f\"User: {question}\\nAssistant: {answer}\"\n",
+ " ids = tokenizer.encode(text)\n",
+ " ids = torch.tensor([ids], dtype=torch.long)\n",
+ "\n",
+ " input_ids = ids[:, :-1]\n",
+ " target_ids = ids[:, 1:]\n",
+ "\n",
+ " if input_ids.shape[1] > config.max_seq_len:\n",
+ " continue\n",
+ "\n",
+ " _, loss = model(input_ids, target_ids)\n",
+ " total_loss += loss.item()\n",
+ " loss.backward()\n",
+ "\n",
+ " optimizer.step()\n",
+ " optimizer.zero_grad()\n",
+ "\n",
+ " if step % 50 == 0 or step == 199:\n",
+ " elapsed = time.time() - start\n",
+ " print(f\" Step {step:>3d}: loss={total_loss / len(training_data):.4f} ({elapsed:.0f}s)\")\n",
+ "\n",
+ "print(f\"\\nDone in {time.time() - start:.1f}s\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Generate after fine-tuning\n",
+ "\n",
+ "The same prompts. The same model. Now with LoRA adapters\n",
+ "trained to respond like an assistant."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "model.eval()\n",
+ "\n",
+ "print(\"=== AFTER FINE-TUNING ===\")\n",
+ "for p in prompts:\n",
+ " print(f\"\\nPrompt: {p}\")\n",
+ " print(f\"Output: {chat(model, p)[:200]}\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## What changed\n",
+ "\n",
+ "The base model weights are exactly the same as before training.\n",
+ "Only the LoRA adapters were updated. You can prove this by\n",
+ "removing the adapters and generating again. The model will\n",
+ "revert to its original behavior.\n",
+ "\n",
+ "The adapter file is tiny. You could train adapters for\n",
+ "summarization and translation and code generation and swap\n",
+ "them in and out without reloading the base model. One model.\n",
+ "Many skills. This is LoRA."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## Try your own prompts"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "your_prompts = [\n",
+ " \"What is the tallest mountain?\",\n",
+ " \"Explain what a computer does.\",\n",
+ "]\n",
+ "\n",
+ "for p in your_prompts:\n",
+ " print(f\"Prompt: {p}\")\n",
+ " print(f\"Output: {chat(model, p)[:200]}\")\n",
+ " print()"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python",
+ "version": "3.10.0"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
\ No newline at end of file