Fine-tuning, LoRA and quantization: adapting and running big models cheaply

A big language model is a stack of matrices that hold a huge number of values called weights. To adapt it to your job you have to train those values again, and to run it you have to load them all into memory. Both cost a lot. Here you try two ways to pay less: change less (LoRA) and write smaller (quantization).

Short answer. Fine-tuning trains a model that is already trained a little more on your own data. Changing every weight is expensive, so LoRA keeps the original weights W frozen and trains only "the change", written as the product of two small matrices B × A with rank r. Quantization writes each weight with fewer bits so the model gets smaller.

Full d × d
LoRA 2 × d × r

d is the side of one weight matrix, and r is the LoRA rank. The bars show how many numbers you train. With "Log scale" on, bar length follows the number of digits, so even a very short LoRA bar shows up. In the picture, W is the original weight matrix that stays as is, and B and A are the small new matrices you train.

Definitions

The text below explains with pictures and labs. These are the textbook definitions. W is a d × k weight matrix that came from pre-training (if it is square, as in the other sections of this page, k = d).

fine-tuning
Starting from the weights of a pre-trained model and training the model further on data for a specific job. When every weight is changed, it is called full fine-tuning.
rank
The largest number of linearly independent columns of a matrix (counting rows gives the same number). The rank of a product of two matrices is never more than the rank of either one, so if B is d × r and A is r × k:

rank(BA)≤r

LoRA (low-rank adaptation)
A fine-tuning method that freezes W (does not change it during training), writes the change ΔW as the product of B ∈ ℝd×r and A ∈ ℝr×k, and trains only B and A. The rank r is chosen much smaller than d and k. B starts as all 0 and A starts as small random numbers. α is a constant that sets the scaling factor.

W′=W+αrBA

adapter, merge
An adapter is the package of B and A saved after LoRA training, to plug into the original model. Merging is computing (α ÷ r) × B × A once and adding it to W, so you keep a single matrix W' of the original size.
quantization
Writing numbers with fewer bits. Uniform b-bit quantization writes a value x as the number q (an integer from 0 to 2b − 1) of the closest of 2b evenly spaced marks between the smallest value xmin and the largest value xmax, and rebuilds the value when it is used. s is the gap between marks (the scale).

s=xmax−xmin2b−1

q=round(x−xmins)

x^=xmin+qs

1. Pre-training and fine-tuning

A big language model is made in two steps.

StepWhat it doesDataResult
Pre-trainingReads a huge amount of text and practices guessing the next wordA huge amount (web pages, books and so on)A base model that can talk about many things
Fine-tuningTrains the base model a little more on examples of your jobA small amount (question and answer examples you collected, for example)A model fitted to your job

Fine-tuning is training too. It moves the weights little by little in the direction that lowers the error (the loss), as in gradient descent. The difference is the starting point. You start from weights that already learned a lot, not from random numbers, so you need far less data. How a model picks the next word is in the previous topic, softmax and sampling.

Why changing everything is expensive. Full fine-tuning changes every weight, so it has to keep a gradient for every number. An optimizer such as Adam also keeps two extra values for every number. So memory grows several times over as the count of trained numbers grows. And if you keep one changed model per job, storage grows by a whole model each time. LoRA attacks this by training far fewer numbers.

2. Prompting, RAG or fine-tuning: which one when

Fine-tuning is not the only way to fit a model to your job. Below is a common rule of thumb. It is not a fixed rule, and people often mix all three.

MethodWhat changesOften a good fit forWhat it costs
Prompt (instructions)The text you feed in. The weights stay the sameThe first thing to try. Tell it the task, the format and a few examples in wordsAlmost nothing. A long prompt adds work to every call
RAGAt question time, find related documents and add them to the text. The weights stay the sameNew facts, facts that change often, internal documents. When you must show where an answer came fromA collection of documents and a search system
Fine-tuningThe weightsTone, answer format, a task always done the same way. When you do not want to attach long instructions every timeExample data and compute for training

In short, to change "how it talks", fine-tuning is the usual starting point. To grow "what it knows", RAG is. You can put new facts in with fine-tuning, but you have to train again each time the facts change, and there is no promise that the model will recall them exactly. RAG is the next topic, RAG.

3. LoRA: make only the change small

After fine-tuning, a weight matrix W becomes W'. If we call the change ΔW (delta W), then W' = W + ΔW. Full fine-tuning trains all d × d cells of ΔW. LoRA writes ΔW as the product of two small matrices.

W' = W + (α ÷ r) × B × A

How this formula is built, one piece at a time, is shown in section 4.

SymbolSizeRole
Wd × dThe weights from pre-training. Frozen, never changed
Bd × rTrained. Every cell starts at 0
Ar × dTrained. Starts as small random numbers
rone numberThe rank. Much smaller than d (for example 8)
α (alpha)one numberHow strong the change is. Dividing by r keeps the strength about the same when you change r

B × A is (d × r) times (r × d), so the result is a d × d matrix. It has the same size as W, so you can add them. The rules of matrix products are in matrix multiplication. The rank of this product can never be more than r (rank). So LoRA is a bet that "the change we need has a low rank". The paper states this as its working assumption.

Why B starts at 0. At the start B × A = 0, so W' = W. The moment training begins, the model is exactly the original model. It starts from what it already learned instead of shaking it with random noise. There is also a reason not to set A to 0 as well. The gradient of B comes from multiplying by A, and the gradient of A comes from multiplying by B. If both were 0, both gradients would be 0 and nothing would ever move. With A not 0, B starts moving from the first step.

α ÷ r. The paper set α to the first r it tried and did not tune it after that. The goal is to avoid retuning other settings, such as the step size, every time you change r.

Where to attach it. A model has many weight matrices. LoRA attaches one pair B, A to each matrix you pick. The paper attached it only to the attention weights of the Transformer in its experiments.

4. How the formula is built

Here we build the formula from section 3 one piece at a time. The picture uses the same 8 × 8 grid and cell colors as the experiment in section 6 (blue positive, orange negative, white 0), and the change ΔW is that experiment's starting pattern, "Cross". W holds made-up values from a fixed seed. A matrix has d rows and k columns. When it is square, as in the rest of this page, k = d.

Press "Next" to go one step at a time. A piece is added to the formula on top (the orange background marks the new piece), the picture changes by that much, and the reason appears below. The green frame is W, blue is B, and purple is A. An orange square inside a cell marks a cell being trained, and W covered in gray is frozen.

  1. Add the change: W' = W + ΔW. After fine-tuning, W becomes W'. We call the difference ΔW, so this is always true. Full fine-tuning trains all d × k cells of ΔW. In the picture that is 8 × 8 = 64 cells. With d = 1000 as in the first experiment, it is 1,000,000.
  2. A product of two thin matrices: W' = W + B × A. Write ΔW as a tall B (d × r) times a wide A (r × k). (d × r) times (r × k) gives d × k, the same size as ΔW. The numbers to train are d × r + r × k = r × (d + k). In the picture r = 2, so 2 × (8 + 8) = 32 numbers fill 64 cells. "Cross" has rank 2, so it fits exactly. The first column of B is 1 only in rows 4 and 5, the second column is all 1. The first row of A is 0 only in columns 4 and 5, the second row is 1 only in columns 4 and 5. With d = k = 1000 and r = 8, 1,000,000 numbers become 16,000 (1.6%). For a matrix four times wider, 1000 × 4000, 4,000,000 become 40,000 (1%). When it is square (k = d), r × (d + d) = 2 × d × r, the same formula as in the first experiment. An assumption comes in here. The rank of B × A can never be more than r, so the ΔW you need must be fine with a low rank. The paper states this as its assumption. It is not a proven fact. What is left over when it does not hold is shown in section 6.
  3. Freeze W, start B at 0: at the start B = 0 → W' = W. During training the 64 cells of W stay as they are, and only the 32 numbers of B and A change. If every cell of B starts at 0, every cell of B × A is 0, so W' = W. The moment training begins, the model is exactly the original. A starts as small random numbers. If both were 0, both gradients would be 0 and nothing would move (section 3).
  4. The scale, then merging: W' = W + (α ÷ r) × B × A. α ÷ r is a scale that keeps the strength about the same when you change r. The paper set α to the first r it tried and did not tune it again. Here α = r = 2, so the scale is 1. Raise r to 4 and keep α = 2, and it becomes 0.5. That this scale saves you from retuning other settings is the paper's explanation, and we do not prove it here. After training, compute (α ÷ r) × B × A once and add it to W. In the picture the cross moves onto W and W becomes W'. What is left is one matrix the same size as W, so answering takes d × k multiplications, the same as before. Keeping them apart gives the same answer, W' x = W x + (α ÷ r) × B × (A × x) (multiplication distributes over addition), but A × x takes r × k more multiplications and B × (A × x) takes d × r more (the scale can be multiplied into B ahead of time). In the picture that is 32 on top of 64. With d = k = 1000 and r = 8, it is 16,000 on top of 1,000,000 (1.6%).

5. Count it by hand

Small: d = 3, r = 1. B is the column (1, 2, 3) and A is the row (1, 0, −1). The product is a 3 × 3 matrix where each cell of B multiplies the whole row A.

  1. Row 1: 1 × (1, 0, −1) = (1, 0, −1)
  2. Row 2: 2 × (1, 0, −1) = (2, 0, −2)
  3. Row 3: 3 × (1, 0, −1) = (3, 0, −3)
  4. 6 numbers (3 in B, 3 in A) filled 9 cells. Every row is a multiple of (1, 0, −1), so the rank is 1.

Big: d = 1000, r = 8. These are the starting values of the experiment.

  1. Full: 1000 × 1000 = 1,000,000 (one million)
  2. LoRA: B has 1000 × 8 = 8,000, A has 8 × 1000 = 8,000. Together 16,000
  3. Ratio: 16,000 ÷ 1,000,000 = 0.016, that is 1.6%
  4. B × A is still a 1000 × 1000 matrix. 16,000 numbers fill a million cells. The price is that its rank cannot go above 8.

In general, ratio = 2 × d × r ÷ (d × d) = 2r ÷ d. If r is half of d, the two are equal. If r is bigger than that, LoRA has more. For a 4096 × 4096 matrix with r = 8, it is 16,777,216 against 65,536 (0.39%).

Try this. ① The page starts at d = 1000, r = 8. As in the hand example, that is 1,000,000 against 16,000, or 1.6%. ② Raise d to 4096 and you get 0.39%. Then lower r to 1 and you get 0.05%. If the LoRA bar almost disappears, turn on "Log scale". ③ Lower d to 64 and raise r to 32, and both become 4,096. Raise r to 64 and LoRA is 8,192, twice as many. The bigger the matrix, the more LoRA saves.

6. Catching up with a low rank

LoRA works well when the change you really need, ΔW, can be described well with a low rank. The experiment below shows this on an 8 × 8 grid. On the left is the wanted change ΔW, in the middle the closest B × A you can build with rank r, and on the right the difference between them.

Wanted change ΔW
B × A (rank r)
Difference ΔW − B × A

This is a scaled-down toy. A real model's matrices have thousands of cells on a side, and real LoRA does not know ΔW in advance. It learns B and A from data.

Cell colors: blue is positive, orange is negative, white is 0. Numbers in the cells are rounded to one decimal place. On a narrow screen, tap a cell to see its values under the grids.

How the closest B × A is found. Real LoRA learns B and A with gradient descent. In this experiment we pretend to know the answer ΔW and compute it directly with the singular value decomposition. Split ΔW into σ1 u1 v1ᵀ + σ2 u2 v2ᵀ + … + σ8 u8 v8ᵀ and keep only the r largest pieces. The columns of B are σk uk and the rows of A are vkᵀ. No matrix of rank r is closer to ΔW than this (low-rank approximation). So the error here is a floor: "even perfect training with rank r leaves at least this much".

Error size. Square every cell of the difference grid, add them all up, and take the square root. You can also get it from the dropped singular values: error size = √(σ(r+1)² + … + σ8²).

Try this. ① The page starts with "Cross" and r = 1. There are only two singular values, 4.61 and 2.61, so this pattern has rank 2. With r = 1, the dropped 2.61 becomes the error size, 49.2% of the size of ΔW (5.29). The four middle cells should be 1 but overshoot to 1.47. Raise r to 2 and the error becomes 0. ② In "Square", every row is either the same shape or all 0, so the rank is 1. The error is already 0 at r = 1. ③ "Ring" has rank 4, but its fourth singular value is tiny, 0.01. The error drops to 17.2% at r = 2 and 0.29% at r = 3. Even when the rank is not tiny, a few large pieces explain almost everything. ④ "Random" has singular values spread out evenly, so its rank is the full 8. 66.4% is left at r = 2, still 39.7% at r = 4, and it only reaches 0 at r = 8. A low rank cannot catch this kind of change.

7. Swapping and merging

When training ends, you only need to save B and A. This small package that plugs into the original model is called an adapter.

8. Limits of LoRA

9. Quantization: fewer bits per number

If each weight is a 32-bit (4-byte) decimal number, a model with 1 billion numbers takes 4 billion bytes, about 4 GB. Quantization writes those numbers with fewer bits, such as 8 or 4, to make the model smaller.

With b bits you can write only 2b different values. So you draw 2b evenly spaced levels from the smallest value to the largest, and move each value to the nearest level. What you store is the level number (an integer) for each value, plus two numbers per group: "the smallest value" and "the gap between levels".

gap      = (largest value − smallest value) ÷ (2^b − 1)
level    = round((value − smallest value) ÷ gap)
restored = smallest value + level × gap

The level is an integer from 0 to 2b − 1, and the level is what you store. When you use the weight, the third line brings the value back.

By hand: five values with 2 bits

The values are −1.5, −0.4, 0.2, 0.9, 1.5.

  1. Number of levels. 2² = 4.
  2. Gap. (1.5 − (−1.5)) ÷ (4 − 1) = 3 ÷ 3 = 1. The levels are −1.5, −0.5, 0.5, 1.5.
  3. Level numbers and restored values.
    Value(value + 1.5) ÷ 1LevelRestoredError
    −1.500−1.50
    −0.41.11−0.50.1
    0.21.720.50.3
    0.92.420.50.4
    1.5331.50
  4. Average error. (0 + 0.1 + 0.3 + 0.4 + 0) ÷ 5 = 0.16. The largest error, 0.4, is not more than half the gap, 0.5. Since each value goes to the nearest level, this is always true.
  5. Size. 2 bits instead of 32 bits per number is 1/16. Each group also stores two numbers (−1.5 and 1), but for a large group they add almost nothing.

This is a scaled-down toy. The 40 weights are made-up values drawn from a normal distribution with a fixed seed. Real models have far more numbers, and real methods often split them into small groups with their own levels, or space the levels unevenly.

The slider picks the number of bits (1, 2, 3, 4, 6, 8). The green dots at the top are the original values, the blue lines on the number line are the levels you can use, and the black dots are the rounded values. Each arrow shows which level a value moved to.

Try this. ① The page starts at 4 bits, 16 levels. The average error is 0.059, and the size is 1/8 of 32 bits. ② Go up to 8 bits and the levels get dense (256 of them), the arrows point almost straight down, and the average error is 0.003. The size is 1/4. ③ Go down to 2 bits: 4 levels and an average error of 0.313. ④ At 1 bit there are only two levels, the smallest value −1.72 and the largest value 2.24, so every value goes to one of them. The average error is 1.211. ⑤ The 2.24 at the right end sits far from the others. That one value stretches the range and widens the gap between levels. At 4 bits, only 14 of the 16 levels are actually used.

10. Trading accuracy for size

BitsLevelsSize vs 32 bitsModel with 1 billion numbersAverage error in the experiment
32(decimal format)14 GB0
82561/41 GB0.003
4161/80.5 GB0.059
241/160.25 GB0.313
121/320.125 GB1.211

Fewer bits make the model smaller, so it fits on devices with less memory, and it can also run faster because less has to be read from memory. The price is an error in every value, and when errors pile up the answers can get worse. How far you can go depends on the model and the method, so you measure it yourself.

Outliers. The levels evenly split the range from the smallest value to the largest. So one value that sticks far out spreads the levels thin for everyone else. If you split the numbers into small groups with their own levels, an outlier only affects its own group.

Using both: QLoRA. QLoRA (Dettmers and others, 2023) quantizes the base model to 4 bits, keeps it frozen, and trains LoRA adapters on top. It cuts the memory needed to fine-tune a big model even further.

Another way: knowledge distillation. Train a small model (the student) to copy the answers of a big model (the teacher), and you get a smaller, faster model.

11. Key properties

PropertyIn plain words
Numbers LoRA trains: 2 × d × r. Full: d × d. Ratio: 2r ÷ dIt only saves when r is less than half of d. The bigger the matrix, the more it saves
rank of B × A ≤ rIt can only make low-rank changes. It works well when the needed change fits in that
B = 0 at the start, so W' = WTraining starts from exactly the original model
After training it can be merged as W + (α ÷ r) × B × AAnswering takes no extra work. If you keep it separate, you can swap adapters
Quantization: 2^b levels, error ≤ gap ÷ 2, size b ÷ 32One bit less halves the number of levels and makes the error bigger

Where it is used

Common questions

What is LoRA?

It is a way to fine-tune a big model where you keep the original weights W frozen and train only the change, written as the product of two small matrices B × A. The name is short for Low-Rank Adaptation. For one matrix, the numbers to train go from d × d down to 2 × d × r.

When should I use fine-tuning, and when RAG?

A common rule of thumb: to change how the model talks, such as its tone or answer format, use fine-tuning. To give it new facts or data that changes often, use RAG. Try a prompt first, and if that is not enough, people often use both together.

How big should the rank r be?

There is no fixed value. Start small, such as 4, 8 or 16, and raise it while you check the results. A larger r can follow more kinds of change, but it also adds more numbers to train.

Does quantization make the model worse?

It can, because every value picks up a rounding error. The fewer bits, the bigger the error. How far you can go depends on the model and the method, so you measure it yourself.

Can LoRA and quantization be used together?

Yes. QLoRA quantizes the base model to 4 bits, keeps it frozen, and trains LoRA adapters on top. This cuts the memory needed to fine-tune a big model even further.

Words

Word used hereWord used in textbooks
the first big trainingpre-training
training a little morefine-tuning. Changing every weight is full fine-tuning
the numbers inside a modelweights, parameters
keeping fixedfreezing
the change ΔWweight update
training the change as a product of two small matricesLoRA (Low-Rank Adaptation)
fine-tuning that trains only a few numbersparameter-efficient fine-tuning (PEFT)
the small package you swap inadapter
mergingmerge
rankrank
strength αscaling factor, alpha
square the cell differences, add, take the square rootFrobenius norm
writing numbers with fewer bitsquantization
gap between levelsscale, step size
putting the smallest value at level 0zero point, asymmetric quantization
instructionsprompt
finding documents and adding them before answeringretrieval-augmented generation (RAG)
making a small model that copies a big oneknowledge distillation

Sources

← Structured outputHallucination and evaluating LLMs →