Fine-tuning and LoRA
When should you adapt a model, and how is it done cheaply?
Lesson complete
If you like:
Part two ended with a base model: it can continue text, but it does not know your case. Not your tone, not your formats, not your categories.
No voice: the lesson advances on its own with subtitles.
The voice for this lesson is being recorded: for now it advances on its own with subtitles.
Review modeComment on this stepI finished the lesson
What you will achieve
- Explain what fine-tuning is and why moving every parameter with examples from a single area can make the model forget what it already knew.
- Calculate how many numbers LoRA trains with the rule rank × (rows + columns) and compare them with those of the full table.
- Decide among prompt, RAG, and fine-tuning for a case, and know what data and what evaluation to demand before tuning.
Key ideas
- Fine-tuning keeps training an already trained model on pairs of input and desired answer: it is the same loop as in lesson 8 (answer, measure the error, backpropagate, adjust), with far less data.
- Moving every parameter with examples from a single area disturbs everything else: that is catastrophic forgetting. The basic defense is replay (mixing in examples of what it already knew) and also measuring what it already knew.
- LoRA freezes the original table and trains a low-rank correction ΔW = B·A: rank × (rows + columns) numbers instead of rows × columns. On GPT-3, about ten thousand times fewer trainable parameters.
- B starts at zero, so the model starts out identical; since the base never changes, the adapter (B and A) can be removed or swapped: one base model and one adapter per task. QLoRA stores the base in 4 bits and so tunes a 65-billion-parameter model on one 48 GB GPU.
- A good prompt first; if information that changes is missing, RAG; fine-tuning for a stable, repeated behavior, with good data and your own evaluation. It is not a good way to add new facts.
What many people believe
Common belief For the model to know my company’s documents, I have to fine-tune it on them.
What is true Fine-tuning changes how the model behaves (tone, format, task), but it is a poor way to add facts: it learns them slowly, cannot cite them, and, once it learns them, may make more things up. For your own knowledge that changes, start with RAG; LoRA makes tuning cheaper, but it does not change this.
Check yourself
Four questions. No grade, no account: they just show whether the idea stuck.
Under the hoodFor those who want the math and the code. You do not need it to follow the course.
What supervised fine-tuning minimizes
Given a model with weights and examples (an input and the desired answer), supervised fine-tuning keeps minimizing the cross-entropy,
with the same gradient descent from lesson 4 and the backpropagation gradients from lesson 8. In a language model, is a sequence of tokens and the sum runs only over the answer tokens. It starts from the pretrained weights (lesson 23), with much smaller learning rates than in pretraining and only a few passes over the data. LIMA (Zhou et al., 2023) used 1,000 examples, about 750,000 tokens, on the 65-billion-parameter LLaMA, which was pretrained on 1.4 trillion tokens (Touvron et al., 2023).
LoRA: the math
For a pretrained weight matrix , LoRA freezes it and writes the update as
The forward pass is . starts as a Gaussian and as zeros, so at the start (Hu et al., 2021); only and receive gradients. Since is proportional to , only moves on the first step.
Each column of and each row of form a rank-one piece, (column times row, like the lesson’s multiplication table): . Hence the name: the correction has rank at most .
Trainable parameters: instead of . It saves only if ; for a square matrix, . With (the tiny model’s middle layer), is a tie: .
Once trained it can be merged, , and inference costs the same as the original model; or the adapter can stay separate to swap it for another.
For GPT-3 175B (, 96 layers), adapting only and with gives trainable parameters: about 9,300 times fewer than 175 billion (the paper says “roughly 10,000×”). In FP16 the adapter takes about 35 MB versus the model’s 350 GB, and 100 adaptations take about 354 GB instead of 35 TB (Hu et al., 2021).
Why the change has low rank
If is the singular value decomposition, the Eckart–Young theorem says the best rank- matrix (in Frobenius norm) is the sum of the first terms, and its error is . In the tiny model, the change that full fine-tuning leaves in the 32×32 layer has singular values that fall quickly: the first four gather about 97% of . That is what LoRA assumes and exploits; Aghajanyan et al. (2020) had already measured that fine-tuning a language model needs very few effective dimensions. It is not a law: Hu et al. do not expect a small rank to work for every task (for example, a language different from the pretraining one), and Biderman et al. (2024) measured that, in programming and math, full fine-tuning learns changes whose rank is 10 to 100 times higher than typical LoRA configurations.
Forgetting, replay, and what the evidence says
With narrow data, moving shared weights shifts whatever that data does not cover. In the tiny model (70 new examples from a single area, 300 full-batch Adam steps, one run with fixed seeds):
| tuning | trainable | accuracy on the new part | accuracy on what it knew |
|---|---|---|---|
| none (base model) | — | 0% | 100% |
| full | 1,251 | 98% | 93% |
| full + 30 for replay | 1,251 | 94% | 97% |
| LoRA r = 2 | 128 | 91% | 87% |
| LoRA r = 2 + 30 for replay | 128 | 93% | 98% |
Here LoRA without replay forgets more than full fine-tuning; in large models, Biderman et al. (2024) found the opposite on average (LoRA learns less and forgets less), but not that it stops forgetting. Moral: forgetting is a risk with both methods, and you measure it with data the tuning did not see. The name “catastrophic” comes from McCloskey and Cohen (1989); in the toy the loss is moderate.
Memory: from sixteen bytes per parameter to less
Training with Adam in mixed precision stores, per parameter: FP16 weights (2 bytes), FP16 gradients (2) and, in FP32, a copy of the weights, momentum, and variance (): bytes (Rajbhandari et al., 2019; lesson 25). With LoRA, frozen weights only need their copy (2 bytes in FP16) and the 16 bytes are paid only for and . QLoRA also stores the base in 4 bits (NF4 format, with “double quantization” of the constants) and trains the adapter in 16 bits. Our own count for a 7-billion-parameter model, without activations: full fine-tuning GB; FP16 base, 14 GB; 4-bit base, about 3.5 GB, plus the adapter and activations.
The papers’ figures do not come exactly out of this count, because they depend on what is stored and how: the LoRA paper gives, for GPT-3 175B, from 1.2 TB to 350 GB, and the QLoRA paper counts more than 780 GB to fine-tune 65 billion parameters in 16 bits (about 12 bytes per parameter). Always compare under the same count.
The “Q” part can be tried in the tiny model: with its three matrices in 4 bits (NF4, blocks of 64), the map changes in 22 of 1,600 cells, and rank-2 LoRA with replay reaches 91% on the new part and 98% on what it knew, versus 93% and 98% with the 16-bit base. It is a toy: it reproduces the idea, it proves nothing about large models.
In code
import numpy as np
# 1) the count: one GPT-3 matrix (12288 x 12288) and rank 8
d = k = 12288
r = 8
full = d * k
lora = r * (d + k)
print(full, lora, full // lora) # 150994944 196608 768
# 2) the correction starts at zero (B = 0): the model does not change
rng = np.random.default_rng(0)
W0 = rng.normal(size=(6, 6)) # frozen matrix (tiny)
A = rng.normal(size=(2, 6)) # r = 2, Gaussian
B = np.zeros((6, 2)) # zeros
x = rng.normal(size=6)
h = W0 @ x + B @ (A @ x) # alpha/r = 1
print(np.allclose(h, W0 @ x)) # True
# 3) after training, B is no longer zero: the correction has rank <= 2
B = rng.normal(size=(6, 2)) * 0.1
print(np.linalg.matrix_rank(B @ A)) # 2
What comes next
Tuning on input-output pairs changes format, style, and task. Turning a model that only completes text into an assistant uses that same mechanism, but the question is which pairs and which signal: instruction tuning and reinforcement learning from human feedback (lesson 28). And it is practical: QLoRA was used to instruction-tune the Guanaco family (Dettmers et al., 2023), and those authors found that data quality matters far more than quantity (9 thousand OASST1 examples beat 450 thousand from FLAN v2 in their chatbot test).
Decision lens
What this idea means if your job is to decide, not to code.
- Demand the baseline before tuning: what does a good prompt achieve? And RAG? If the team cannot show those numbers on your own cases, tuning is a blind bet.
- Fine-tuning changes behavior and style; it is not a good way to “stuff in fresh knowledge.” For prices, policies, or catalogs that change, RAG updates without retraining and lets you cite the source.
- Ask about data and evaluation first: how many examples, who reviewed them, which unseen cases measure the improvement, and how you check what the model may have forgotten.
- LoRA makes training and storage cheap (megabyte adapters, not hundred-gigabyte copies), but each adapter is tied to the base model it was trained on: ask who maintains it when the base changes, and treat tuning data as sensitive.
Terms in this lesson
- Fine-tuning Continuing to train an already pretrained model on a small set of your own examples (input and desired answer) to change its behavior, without starting from scratch.
- LoRA (low-rank adaptation) A fine-tuning technique that freezes the original parameters and trains only a correction ΔW = B·A, the product of two thin tables. The pair B and A is called an adapter: it can be removed or swapped.
- Low rank A property of a table (matrix) that can be written as a sum of a few “column × row” pieces. The rank says how many pieces are needed; a low-rank table is described with far fewer numbers than rows × columns.
- Catastrophic forgetting Loss of earlier skills when a model keeps training on data of a single kind: the same parameters serve everything, and moving them for the new disturbs the old.
- Base model A language model that has only gone through pretraining: it can continue texts, but it is not tuned to follow instructions or converse like an assistant.
- Pretraining The first stage of training a language model: over a huge corpus, the model guesses the next piece of text again and again and adjusts its parameters to lower the error. The result is a base model.
- Parameter Each of the numbers a model adjusts while training and in which it stores what it learned.
- Backpropagation An algorithm that computes the gradient of the loss with respect to every weight of a network in a single backward sweep, applying the chain rule layer by layer. It computes the blames; it does not move the weights (in the 1986 paper, the name covered the whole learning procedure).
- Gradient descent A method that adjusts the weights step by step, always against the slope of the error (the gradient), until it reaches a bottom.
- Adam An optimizer that combines momentum with a step size of its own for each weight, computed from moving averages of the gradient and its square (Kingma and Ba, 2015).
- Quantization Storing a trained model’s parameters with fewer bits (8 or 4 instead of 16), rounding each one to the nearest mark of a scale shared by its group. It reduces memory and read time, with a loss of quality that has to be measured.
- Prompt The text used to ask a generative model for something; in an image generator, the description of the desired image.
- RAG (retrieval-augmented generation) A technique that, before generating, looks up in a collection of documents the chunks most similar to the question and includes them in the prompt, so the model answers from those sources without being retrained.
- Validation set Data the model does not use to fit itself, used to choose between models or hyperparameters.
Full transcript
Sources
- Hu, E. J., Shen, Y., Wallis, P., Allen-Zhu, Z., Li, Y., Wang, S., Wang, L., Chen, W. (2021). LoRA: Low-Rank Adaptation of Large Language Models
- Dettmers, T., Pagnoni, A., Holtzman, A., Zettlemoyer, L. (2023). QLoRA: Efficient Finetuning of Quantized LLMs
- Zhou, C., Liu, P., Xu, P., Iyer, S., Sun, J., Mao, Y., Ma, X., Efrat, A., Yu, P., Yu, L., Zhang, S., Ghosh, G., Lewis, M., Zettlemoyer, L., Levy, O. (2023). LIMA: Less Is More for Alignment
- Touvron, H., Lavril, T., Izacard, G., Martinet, X., Lachaux, M.-A., Lacroix, T., Rozière, B., Goyal, N., Hambro, E., Azhar, F., Rodriguez, A., Joulin, A., Grave, E., Lample, G. (2023). LLaMA: Open and Efficient Foundation Language Models
- McCloskey, M., Cohen, N. J. (1989). Catastrophic Interference in Connectionist Networks: The Sequential Learning Problem (Psychology of Learning and Motivation 24, 109–165)
- Biderman, D., Portes, J., Gonzalez Ortiz, J. J., Paul, M., Greengard, P., Jennings, C., King, D., Havens, S., Chiley, V., Frankle, J., Blakeney, C., Cunningham, J. P. (2024). LoRA Learns Less and Forgets Less
- Ovadia, O., Brief, M., Mishaeli, M., Elisha, O. (2023). Fine-Tuning or Retrieval? Comparing Knowledge Injection in LLMs
- Gekhman, Z., Yona, G., Aharoni, R., Eyal, M., Feder, A., Reichart, R., Herzig, J. (2024). Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?
- Brown, T. B. et al. (2020). Language Models are Few-Shot Learners
- Rajbhandari, S., Rasley, J., Ruwase, O., He, Y. (2019). ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
- Aghajanyan, A., Zettlemoyer, L., Gupta, S. (2020). Intrinsic Dimensionality Explains the Effectiveness of Language Model Fine-Tuning
- Eckart, C., Young, G. (1936). The approximation of one matrix by another of lower rank (Psychometrika 1, 211–218)
CommentsThis lesson’s public conversation: questions, facts to check, ideas.
Comments live in GitHub Discussions, in the course’s public repository; writing one requires a GitHub account. They load from giscus.app when you open this section. The course reviewers read them, and if a change is accepted, it is applied in both languages. Open the thread on GitHub