Fine-Tuning, LoRA and Continued Pre-Training
What is fine-tuning
Base model - a pre-trained model, trained on trillions of tokens at huge cost and time. Fine-tuning - take the base model and update its weights on a specific domain (finance, legal, coding, medical).
- Not training from scratch.
- Same loop as pre-training: forward pass -> loss -> backprop -> weight update.
- Result: same model, but better in one domain.
Analogy: school and university make you a pre-trained model. A job builds domain knowledge. You get much better at one domain, even if other skills get a bit dull.
| Technique | What it changes |
|---|---|
| Pre-training | Model learns from data |
| Prompting | We talk to the model |
| RAG | We give it external knowledge |
| Agents | We give it tools and a harness |
| Fine-tuning | The model itself (weights) |
Why fine-tune, and what to try first
Order to try
- 1) Prompt the model well. If it works, stop.
- 2) Add information sources (RAG, tools). If it works, stop.
- 3) If it still fails, fine-tune.
- Fine-tuning costs money and engineering effort.
- If the model knows something, prompting or RAG can get it out.
- If the domain is not in the base model at all, fine-tune.
- Weight updates change style, behaviour and what it has learned. Tools only stack on top.
- Small fine-tuned model: lower cost, lower latency, can be hosted on a small machine for one narrow task.
- Enterprises do this: swap a big API model for a fine-tuned 8B to 200B model, claimed 10x cheaper and 20x faster.
Four types of fine-tuning
| Type | Use it when | How |
|---|---|---|
| Continued pre-training (CPT) | Model lacks domain knowledge | Keep training on raw domain text |
| Supervised fine-tuning (SFT) | Model answers in the wrong manner | Question-answer pairs (user / assistant chat format) |
| Preference tuning (RLHF, DPO) | You want answers humans prefer, less bias, friendlier personality | Humans pick A or B |
| RLVR | You want better reasoning on math, code, logic | RL with verifiable rewards; more reasoning tokens |
- RLHF - reinforcement learning from human feedback. DPO - direct preference optimization.
- RLVR - reinforcement learning with verifiable rewards. GRPO and PPO are RL algorithms used inside it.
- Chat A/B choices are how preference data is collected.
- The model personality (e.g. liking Claude over ChatGPT) comes from preference optimization.
Typical order: pre-training -> SFT / instruction tuning -> preference and reasoning RL.
CPT vs SFT
- Base / CPT model is a next-token predictor. Given 'My name is' it just keeps completing. It does not know when to stop.
- SFT keeps it a next-token predictor, but trains it on chat patterns: human asks, assistant answers.
- Special tokens: BOS - beginning of sequence. EOS - end of sequence.
- After an answer is done the model predicts EOS and stops generating. This is how it learns to stop.
CPT teaches a domain (the whole learning phase). SFT teaches how to answer, format and stop (interview prep).
Problems with full fine-tuning
Where the weights live: attention block (Wq, Wk, Wv, Wo), FFN block (up, down, gate), embed tokens (input) and LM head (output). Full fine-tuning updates all of them.
Reasons full fine-tuning hurts
- Memory - GPU must hold the model, its gradients and optimizer states (about 4x model size). An 8B model at FP16 needs at least 64-128 GB VRAM.
- Overfitting - e.g. 5 million tokens of data on an 8B model. Every weight tries to memorise the data to lower the loss.
- Catastrophic forgetting - learns the domain, forgets English, math and other skills.
- Storage - 5 variants means 5 full model copies, one per client.
What we want: fewer GPUs, no overfit, keep general knowledge, store only the changes, no inference slowdown. -> LoRA
LoRA: low-rank adaptation
Finding After full fine-tuning, the weight change Delta W has very low intrinsic dimensionality. Most weights barely change. The change is low rank.
Rank - number of independent patterns (directions) in a matrix. Rank 1 is one pattern repeated in scale. Rank 32 is 32 independent patterns.
Example
Photo filter. A photo has 10 million pixels, but you do not set pixels one by one. You move 4-5 sliders (warmth, coolness, vignette). The whole image changes along 5 directions. Choir: 100 singers, but only 4-5 unique parts (guitar, piano, violin), so you need only 4-5 mics.
Idea: do not update every weight. Choose a rank (16, 32, 64) and update only that many independent directions.
W stays frozen. A and B are trained. After training, A x B has the same shape as W, so it is simply added. No extra inference cost.
| Item | Shape | Parameters |
|---|---|---|
| Full W | 4096 x 4096 | 16.7 million |
| A (rank 32) | 4096 x 32 | about 131k |
| B (rank 32) | 32 x 4096 | about 131k |
| A + B | - | about 262k |
- Faster, smaller GPU, comparable quality to full fine-tuning.
- Less forgetting, because most weights are frozen and keep the old knowledge.
- Memory: 8B model goes from 60+ GB (full) to about 4.2 GB VRAM, which fits a Colab notebook.
- Example run: 149M total parameters, only about 40M trainable and about 110M frozen.
LoRA hyperparameters
| Hyperparameter | Meaning |
|---|---|
| Rank (r) | Independent features to update (bottleneck). Higher = more capacity, more memory and time. Try 8, 16, 32, 64 and compare. |
| Alpha | Scaling factor alpha/r on the LoRA output. Set equal to r gives 1x scaling. Larger values weight the LoRA output more than frozen weights. |
| Target modules | Which matrices get adapters: attention q, k, v, o; FFN up, down, gate. Usually all. |
| Dropout | Generally 0 in fine-tuning. |
- Choose a small rank when data is small or similar to what the model already learned.
- Rank 32 trains about 260k per matrix; rank 16 trains about half that.
- Full fine-tuning and LoRA were compared and performed about the same.
Why CPT also trains embed_tokens and lm_head
- embed_tokens - at the input, turns a token id into a vector.
- lm_head - at the output, turns a vector into a probability distribution over tokens.
- CPT on finance or tech: terms like EBITDA, subordinated debentures, 10-K, K8s, AWS, LLM were barely seen in pre-training. The model needs better representations for them and the ability to output them.
- So add embed_tokens and lm_head to target modules in CPT.
- SFT only teaches instruction format (user / assistant template). No new knowledge, so these are not needed.
Common mistake: skipping embed_tokens and lm_head during CPT.
QLoRA and quantization
- Quantization - lowering the bits used per number.
- FP32 - 32 bits, 4 bytes per parameter (standard).
- FP16 - 16 bits, half the memory, but smaller range, so numbers can overflow.
- QLoRA - quantized LoRA: load the base model in 4-bit or 8-bit, train LoRA adapters at 16-bit, then merge.
- The 4-bit format used is designed for neural network weight distributions, so there is almost no quality loss.
Unsloth
- Unsloth - a library/company that makes fine-tuning faster. Same maths, same architecture.
- Writes custom CUDA kernels for attention, FFN, embeddings, LM head. Also fused operations, smarter checkpointing, automated mixed precision.
- Analogy: NumPy vs PyTorch.
- Gradient checkpointing - do not store activations at every layer. Store at checkpoints and recompute the rest when needed. Saves VRAM at some compute cost. Like saving a game only at certain points.
- In code: use_gradient_checkpointing='unsloth'.
from unsloth import FastLanguageModel
model, tokenizer = FastLanguageModel.from_pretrained(
model_name=MODEL, max_seq_length=MAX_LEN, load_in_4bit=True)
model = FastLanguageModel.get_peft_model(
model, r=32, lora_alpha=32, lora_dropout=0,
target_modules=['q_proj','k_proj','v_proj','o_proj',
'up_proj','down_proj','gate_proj',
'embed_tokens','lm_head'],
use_gradient_checkpointing='unsloth')Catastrophic forgetting and fixes
Example
Before CPT: 'The cat sat on the' -> 'mat'. After training only on finance data: 'The cat sat on the' -> 'balance sheet'. Domain learned, general knowledge lost.
Why: gradients only care about lowering the training loss, so the model overfits the domain.
Fixes
- Mix data - e.g. 80% domain and 20% general (or 90/10, 60/40).
- Low learning rate - weights do not move far.
- LoRA - most weights are frozen, so pre-trained knowledge stays.
- Short training - stop when validation loss plateaus.
CPT experiment on SEC filings
Perplexity - how surprised the model is by the text. Lower is better. Measure on held-out financial text before and after CPT.
Pipeline
- Data - SEC 10-K filings from Hugging Face (373k rows). Keep only the text column and strip special characters.
- Split into overlapping chunks so sentences are not cut and meaning is kept: 6,830 train and 1,200 validation rows.
- Before: model continues a financial sentence but does not stop, and rambles.
- Rank 32 (new knowledge), alpha equal to rank, all attention and FFN modules plus embed_tokens and lm_head. About 40M of 150M parameters trainable.
- Two epochs on a T4 GPU, eval and checkpoint every 25 steps. Loss fell from 2.76 to about 2.3 in about 15 minutes.
- Perplexity fell from 19.1 to 13.2, a 31% improvement.
- Forgetting check with 80/20 data mix matters for longer runs (40-60 minutes).
Experiment: vary rank (8, 16, 32), data size, and remove embed_tokens and lm_head, then compare. Many runs fail before one works.
Glossary
- Base model
- A pre-trained model before any fine-tuning.
- CPT
- Continued pre-training: keep training a base model on raw domain text.
- SFT
- Supervised fine-tuning on question-answer pairs so the model follows instructions.
- RLVR
- Reinforcement learning with verifiable rewards, for reasoning on math, code and logic.
- LoRA
- Low-rank adaptation: freeze W and train small matrices A and B instead.
- Rank
- Number of independent patterns or directions in a matrix; LoRA's main hyperparameter.
- QLoRA
- LoRA on a quantized (4-bit or 8-bit) base model.
- Catastrophic forgetting
- Losing general knowledge while learning a narrow domain.
- Perplexity
- How surprised a model is by text; lower is better.
- Gradient checkpointing
- Store activations only at some layers and recompute others to save memory.