Quantisation and QLoRA
9 min read
What quantisation does
A 16-bit weight takes two bytes. A 4-bit weight takes half a byte, so the same model needs a quarter of the space. To do this, the weights are scaled into a small range of integers and rounded. To use them, the integers are scaled back. The restored value is close to the original and not equal to it.
Weights alone for a 7 billion parameter model take about 14 GB at 16 bits, 7 GB at 8 bits and 3.5 GB at 4 bits, plus a small overhead for the scales. Setting up your environment has the full table. Training also needs gradients, optimiser state and activations, which is why LoRA matters here.
See the rounding error
The program below quantises 256 random weights of typical size, plus one outlier that is much larger than the rest. It uses a simple scheme: scale by the largest absolute value in the block, round to the nearest integer level and scale back. It compares 8 bits and 4 bits, and compares one block with small blocks of 64.
import random
random.seed(3)
weights = [random.gauss(0, 0.02) for _ in range(256)]
weights[100] = 0.4
def quantise(block, bits):
levels = 2 ** (bits - 1) - 1
scale = max(abs(w) for w in block) / levels
return [round(w / scale) * scale for w in block]
def error(original, restored):
return sum(abs(a - b) for a, b in zip(original, restored)) / len(original)
def in_blocks(values, size, bits):
restored = []
for start in range(0, len(values), size):
restored += quantise(values[start:start + size], bits)
return restored
typical = sum(abs(w) for w in weights) / len(weights)
print(f"typical weight size: {typical:.4f}")
print(f"8-bit, one block: {error(weights, quantise(weights, 8)):.4f}")
print(f"4-bit, one block: {error(weights, quantise(weights, 4)):.4f}")
print(f"4-bit, blocks of 64: {error(weights, in_blocks(weights, 64, 4)):.4f}")It prints:
typical weight size: 0.0174
8-bit, one block: 0.0008
4-bit, one block: 0.0127
4-bit, blocks of 64: 0.0041With 8 bits, the average error is 0.0008, tiny next to a typical weight of 0.0174. With 4 bits and one block, the outlier sets the scale, so the step between levels is about 0.057 and most ordinary weights, which are around 0.017, are rounded to zero or to one coarse step. The error is 0.0127, about three quarters of a typical weight. With blocks of 64, only the block that holds the outlier suffers, and the error drops to 0.0041, about a third of that.
This is why practical 4-bit formats work on small blocks of weights, each with its own scale. QLoRA uses a 4-bit format called NF4. Its levels are spaced to suit weights that are roughly bell-shaped, not evenly like this program, and it can also quantise the scales themselves to save a little more. Treat the program as a way to see why block size matters. It is not NF4.
QLoRA: adapter on a frozen 4-bit base
QLoRA combines the two ideas from this module.
- Load the base model in 4 bits and freeze it.
- Attach LoRA adapters, kept in a higher precision such as 16-bit.
- During the forward pass, dequantise each block of base weights on the fly and compute with them.
- Send gradients only to the adapter. The quantised weights never change.
The memory saving comes from storing the big part of the model in 4 bits, while the small trainable part keeps its full precision. The code below shows the setup with the Transformers and bitsandbytes libraries. It needs a CUDA GPU on most setups, and library support changes, so follow the current documentation. Replace the placeholder model name and the target names for your model.
import torch
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
quantisation = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
base = AutoModelForCausalLM.from_pretrained(
"your-base-model",
quantization_config=quantisation,
device_map="auto",
)
base = prepare_model_for_kbit_training(base)
model = get_peft_model(base, LoraConfig(task_type="CAUSAL_LM", r=16, lora_alpha=32, target_modules=["q_proj", "v_proj"]))
model.print_trainable_parameters()The compute type sets the precision used for the arithmetic, and the stored weights stay at 4 bits. The PEFT quantization guide lists current examples and limits.
What it costs
- Quality. Rounding changes outputs. Many tasks lose little, but you should not assume that. Compare the quantised model and adapter with a 16-bit baseline on held-out cases, and look at the cases where small changes matter, such as numbers and rare words.
- Speed. Dequantising on the fly adds work, so a step can be slower than 16-bit LoRA on a card where the model would fit anyway.
- Merging. Merging an adapter into a 4-bit model is not always supported or exact. Check before you plan to serve a merged file, and see Serving a fine-tuned model.
- Support. Format, hardware and library versions all matter. A setup that works on one GPU may not on another.
If the model fits in 16-bit with LoRA, that is simpler, and you can skip quantisation. Use QLoRA when memory is the limit, as the estimate in Fitting training into memory shows.
| Weights for 7B | Use when | |
|---|---|---|
| 16-bit LoRA | About 14 GB | The model fits, and you want the simplest setup |
| 8-bit | About 7 GB | You need to halve memory with a small quality risk |
| 4-bit QLoRA | About 3.5 GB | Memory is the limit, and you can test quality |
What does quantisation do?
A 7B model in 16-bit takes about 14 GB.
Fewer bits per weight cut memory, at the cost of some precision.
What is QLoRA?
You want to tune a large model on one GPU.
The base is stored in 4-bit and adapters are trained in higher precision.
What should you check after quantising?
The smaller model runs.
Lower precision can change answers, so measure the effect.
Your reading position is saved
0 of 36 complete
Lesson complete
Quantisation and QLoRA
Up next