← govind p lal
AI and ML Bootcamp · Lecture 13 · lecture notes

Fine-Tuning, LoRA and Continued Pre-Training

In short — Pre-training, prompting, RAG and agents all leave the model's weights untouched. Fine-tuning is the one approach that changes the model itself. This lecture covers when to fine-tune and the four types of fine-tuning. It explains why full fine-tuning is painful, how LoRA and QLoRA fix that, and a continued pre-training run on financial text with Unsloth.

What is fine-tuning

builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026, Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026

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).

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.

TechniqueWhat it changes
Pre-trainingModel learns from data
PromptingWe talk to the model
RAGWe give it external knowledge
AgentsWe give it tools and a harness
Fine-tuningThe model itself (weights)

Why fine-tune, and what to try first

builds on Lecture 10: Week 9 - AI&ML | RAG from the Ground Up - Part 1 | 13/03/2026

Order to try

Four types of fine-tuning

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026
TypeUse it whenHow
Continued pre-training (CPT)Model lacks domain knowledgeKeep training on raw domain text
Supervised fine-tuning (SFT)Model answers in the wrong mannerQuestion-answer pairs (user / assistant chat format)
Preference tuning (RLHF, DPO)You want answers humans prefer, less bias, friendlier personalityHumans pick A or B
RLVRYou want better reasoning on math, code, logicRL with verifiable rewards; more reasoning tokens

Typical order: pre-training -> SFT / instruction tuning -> preference and reasoning RL.

CPT vs SFT

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026, Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026
!

CPT teaches a domain (the whole learning phase). SFT teaches how to answer, format and stop (interview prep).

Problems with full fine-tuning

builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026, Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026

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

What we want: fewer GPUs, no overfit, keep general knowledge, store only the changes, no inference slowdown. -> LoRA

LoRA: low-rank adaptation

builds on Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026, Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026

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.

ItemShapeParameters
Full W4096 x 409616.7 million
A (rank 32)4096 x 32about 131k
B (rank 32)32 x 4096about 131k
A + B-about 262k
Input xFrozen W4096 x 4096A (down)4096 x 32B (up)32 x 4096Sum = output
LoRA: a frozen path plus a trainable low-rank path, added at the end.

LoRA hyperparameters

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026
HyperparameterMeaning
Rank (r)Independent features to update (bottleneck). Higher = more capacity, more memory and time. Try 8, 16, 32, 64 and compare.
AlphaScaling 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 modulesWhich matrices get adapters: attention q, k, v, o; FFN up, down, gate. Usually all.
DropoutGenerally 0 in fine-tuning.

Why CPT also trains embed_tokens and lm_head

builds on Lecture 4: Week 3 - AI and ML | Transformers- Part 1 | 31/01/2026
!

Common mistake: skipping embed_tokens and lm_head during CPT.

QLoRA and quantization

builds on Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026

Unsloth

builds on Lecture 6: Week 5 - AI&ML | Introduction to Tensors and PyTorch | 14/02/2026, Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026
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

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026
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

CPT experiment on SEC filings

builds on Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026, Lecture 8: Week 7 - AI&ML | Training Your First Model | 28/02/2026

Perplexity - how surprised the model is by the text. Lower is better. Measure on held-out financial text before and after CPT.

Pipeline

Load 4-bit basemodelBaseline testperplexity 19.1Load SEC data, cleanOverlapping chunksAttach LoRA r=32Train 2 epochsPerplexity 13.2Save model +tokenizer
CPT workflow from baseline to saved model.
!

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.