05 · QLoRA: a bigger model on a small GPU
Store the frozen weights in 4 bits and train the same adapter. On a free T4 the 1.5B model scored 71.8%, exactly what lesson 4's LoRA did, in 39% less memory, and a 7B model that cannot train with plain LoRA fitted in 8.07 GB and scored 73.4%.
- Part 2
- Train
- Model
Qwen/Qwen2.5-7B-Instruct, and the 1.5B for comparison- Data
- The SQL splits from lesson 3
- Hardware
- One T4, in Google Colab
Lesson 2 left a gap. The most accurate model it measured, Qwen2.5-7B-Instruct, could not be trained on a T4 with LoRA: its weights alone take 15.2 GB of a 15.6 GB card, and the run ran out of memory while loading. Lesson 4 therefore trained the 1.5B model. This lesson closes the gap with QLoRA (Dettmers et al., 2023), which changes one thing: the frozen weights are stored in 4 bits instead of 16. The adapter, the data, the loss and the trainer are lesson 4's.
The result comes first and the exact setup, time and cost are in How it was built at the end. Figure 1 shows the memory budget that decides everything else: where each model's GPU memory goes, and the measured peaks.
Four bits per weight is what moves the 7B model under the T4's 15.6 GB, with room for activations
GPU memory before activations, GB: frozen linear weights, embedding and output head, and the adapter's training state (weights, gradients, Adam); ◆ measured peak
1The method has a clear record. The paper fine-tuned a 65-billion-parameter model on a single 48 GB GPU. Three companies published what it did for them:
| Company | Base model | What 4-bit was for | Result |
|---|---|---|---|
| Dialpad | Qwen2-7B | Serve on an NVIDIA T4 for support calls and meetings | Call-outcome F1 0.835 with 4-bit plus QLoRA, against 0.798 for a 16-bit fine-tune |
| Apoidea | Qwen2-VL-7B | Read tables in banking documents; served with 4-bit quantisation in vLLM | Table-structure score 81.1, from 23.4 for the base model |
| BMW | Gemma 4 E4B | Adapters per task on one shared base | Beat a prompted model about four times larger; adapters "tens of megabytes" |
Dialpad's is the most instructive, because it chose 4 bits for the GPU this course runs on, and wrote down why: 4 bits gave "an optimal balance of memory footprint, latency and accuracy" for its use. This lesson measures each part of that trade.
1. Why the 7B model does not fit
Think of GPU memory as a limited workspace. Compressing stored weights can free room for the training computation, but the other memory costs remain. Measure the complete run, not the nominal weight size alone.
Training memory has three parts that do not depend on the batch: the frozen weights, the embedding and output head, and the adapter's training state (its weights, gradients and Adam's two moments, 16 bytes for each trainable number). Activations come on top and grow with the batch.
Figure 1, at the top of the page, adds the three up for each model.
The 7B model's linear layers hold 6.53 billion weights. In fp16 that is 13.1 GB, and the embedding and output head add 2.2 GB, so plain LoRA is over the line before training starts. Store the linear weights in 4 bits and they take 3.4 GB. Note what the 4 bits do not reach: bitsandbytes quantises linear layers only, so the embedding and output head stay in 16 bits and are now the largest single item. That matters in section 4.
2. What 4 bits do to a weight
Sixteen levels cannot represent a weight exactly; the question is where to put them. QLoRA's answer has three parts.
Blocks. The weights are cut into blocks of 64. Each block is divided by its largest absolute value, its absmax , so every value lands in , and each value is stored as the index of the nearest of 16 levels :
A block of small weights gets a small , so one large weight elsewhere does not flatten everything.
NF4 levels. Trained weights are close to normally distributed, most of them near zero. NormalFloat-4 places its 16 levels at quantiles of the normal distribution, so that each level stands for a similar share of the weights. Evenly spaced levels spend codes on the tails, where few weights are.
NF4 puts its sixteen levels where the weights are; evenly spaced levels waste codes on the tails
Top: the distribution of weights in a block after dividing by its largest value, with NF4's levels (blue) and evenly spaced 4-bit levels (grey). Below: share of weights rounded to each level
2Double quantisation. Each block's is a 32-bit number, which costs bits per weight on top of the 4. QLoRA quantises those constants too, to 8 bits in blocks of 256, which brings the overhead to
The notebook quantises one real layer of the 1.5B model, its 13.8-million-weight down-projection in layer 14, every way bitsandbytes allows, and runs 1,035 real inputs through it:
On a real layer NF4 errs 26% less than FP4, and double quantisation saves 0.37 bits per weight for free
Layer 14 down-projection of Qwen2.5-1.5B (13.8M weights), blocks of 64. Left: storage, bits per weight. Right: error of the weights (bar) and of the layer's output on 1,035 real inputs (●), %
3NF4 rebuilds the weights with 9.7% relative error against FP4's 13.1%, and the layer's output with 8.1% against 11.1%. Double quantisation drops storage from 4.5 to 4.127 bits per weight and changes the error not at all. Neither number is small, and that is the point of what follows: the frozen weights are now slightly wrong, and the adapter is trained on top of them, so it can learn to compensate.
In code, the whole change from lesson 4 is how the model is loaded:
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4", # the default is "fp4"
bnb_4bit_use_double_quant=True, # 4.127 instead of 4.5 bits per weight
bnb_4bit_compute_dtype=torch.float16, # rebuilt to fp16 for each product (no bf16 on a T4)
)
model = AutoModelForCausalLM.from_pretrained(
"Qwen/Qwen2.5-1.5B-Instruct", quantization_config=bnb_config,
torch_dtype=torch.float16, device_map={"": 0}, # the GPU number, not "cuda"
)Three of these values differ from the defaults, and the last line is easy to get wrong. The device_map must name the GPU by number: with accelerate 1.6.0 a 4-bit model on "cuda" fails as soon as training starts, because accelerate reads the device's index and "cuda" has none.
3. What 4 bits cost
Lesson 4's run, repeated with the 4-bit base: the same 8,000 examples, settings, seed and 500 test questions.
Three tests, one answer: once the adapter is trained, 4-bit storage of the base costs no measurable accuracy
Each panel holds everything fixed except how the frozen weights are stored
4QLoRA paper: NF4 matches 16-bit
Mean 5-shot MMLU, %
aDialpad: 4-bit plus QLoRA beats 16-bit
Call-outcome F1, deployed on a T4
bThis course: identical score
Qwen2.5-1.5B, same 8,000 examples, exact match %
cWhat 4-bit did cost here
1.5B, QLoRA against LoRA, same run otherwise
dThe accuracy did not move: 71.8% exact match, the same as lesson 4 to the decimal, and the validation loss followed the same path (0.031 and 0.024 at steps 200 and 400, against 0.032 and 0.023). The QLoRA paper found the same across LLaMA models from 7B to 65B, and Dialpad's 4-bit model with an adapter scored above its 16-bit fine-tune. A trained adapter absorbs the rounding.
The cost is elsewhere, and Figure 4, panel d, measures it. Peak memory fell 39%, from 9.87 to 6.01 GB. Training took 33% longer, 19.4 minutes against 14.6, because every matrix product first rebuilds its weights from 4 bits. Answers took 51% longer, 307 ms against 203, for the same reason. For a model that fits in 16 bits, as the 1.5B does, QLoRA trades time for memory you did not need. It pays only when the memory is the constraint.
4. The memory trap
Pass a 4-bit model and a peft_config to TRL's SFTTrainer and, before adding the adapter, it calls PEFT's prepare_model_for_kbit_training. That helper casts every parameter that is not 4-bit to fp32: the norms, and also the embedding and output head, which section 1 showed are now the largest item. The notebook loads the 7B model and measures it before and after:
| GPU memory | fp16 | fp32 | 4-bit | |
|---|---|---|---|---|
| After loading in 4-bit | 5.65 GB | 2.18 GB | — | 3.26 GB |
After prepare_model_for_kbit_training | 7.83 GB | — | 4.36 GB | 3.26 GB |
2.18 GB is added before a single training step, more than a third of what the 4-bit model occupied. Lesson 2 measured a 7B QLoRA step at 15.2 GB this way, at the edge of the card. The cast exists for numerical stability, but with fp16 mixed precision only the trainable weights need fp32, and PEFT already keeps the adapter in fp32. So the notebook builds the adapter itself and hands TRL a ready model, which skips the helper:
def build_peft_model(model, lora):
"""Attach a LoRA adapter to a 4-bit model without prepare_model_for_kbit_training."""
model.config.use_cache = False # incompatible with gradient checkpointing
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
model.enable_input_require_grads() # gradients must reach the adapters through frozen layers
peft_model = get_peft_model(model, lora) # PEFT keeps the adapter weights in fp32
bad = [n for n, p in peft_model.named_parameters() if p.requires_grad and p.dtype != torch.float32]
assert not bad, f"trainable parameters that are not float32: {bad[:3]}"
return peft_model
trainer = SFTTrainer(model=build_peft_model(model7, lora), args=config7,
train_dataset=train_ds7, processing_class=tok) # no peft_config: TRL does not prepare again5. What the 7B model buys
The 7B model, 4-bit, untrained, with lesson 4's zero-shot prompt, already scores 65.2% exact match against the 1.5B's 58.4%. A bigger model knows more SQL, and the gap is wider than either interval.
Then the same adapter settings, with a batch of 4 and 4 accumulation steps for the same effective 16. The 7B model processes about 237 padded tokens per second on a T4, under a third of the 1.5B's QLoRA speed, so to keep the notebook near an hour it trains on 1,600 examples, a fifth of lesson 4's. That took 12.3 minutes at a peak of 8.07 GB, half the card. The adapter has 40.4 million parameters and is 161.5 MB.
The 7B model starts higher and ends highest, but only 1.6 points above the 1.5B and 2.1 times slower than lesson 4’s model
Exact match on 500 held-out questions (bars: 95% interval) against time to generate one answer on a T4, unmerged adapters; labels give training examples
5The 7B model trained on 1,600 examples reached 73.4%, the best score in the course so far, from a fifth of the data. But it is 1.6 points above the 1.5B, well inside the ±3.9-point interval, so this test cannot say it is better, and every answer takes 427 ms against 307 for the 1.5B on the same 4-bit base and 203 for lesson 4's fp16 model. Its training loss was still moving between 0.027 and 0.043 over the last 50 steps, so more data would likely help it; that is a measured next step, not a conclusion.
Where the two QLoRA models differ:
The 7B model picks the right aggregate more often but writes more SQL that does not run
Misses of the two QLoRA models on the same 500 questions, by lesson 4's rules
6The larger model understands the question better, with 13 fewer wrong aggregates (one that remains: MAX where the gold query sums), but writes more queries that fail to run, 10 against 3. One example: asked for "the 1993 value with a 1r in 1991", it swapped the column names and the values. That is the signature of a model that has seen less of this dataset's conventions, which is what 1,600 examples against 8,000 predicts.
Three of the 7B model's misses, one of each kind, as the notebook prints them:
What is the 1993 value with a 1r in 1991 and sf in 1990?
- Gold
- SELECT 1993 FROM table_name_75 WHERE 1991 = "1r" AND 1990 = "sf"
- 7B QLoRA
- SELECT 1993 FROM table_name_75 WHERE 1r = "1991" AND sf = "1990"
Does not run: the column names and the values are swapped.
What's the rank when the obese children and adolescent count is 14.2%?
- Gold
- SELECT SUM(obesity_rank) FROM table_name_74 WHERE obese_children_and_adolescents = "14.2%"
- 7B QLoRA
- SELECT MAX(obesity_rank) FROM table_name_74 WHERE obese_children_and_adolescents = "14.2%"
Wrong aggregate: MAX where the gold query sums.
Who directed episode 11 in the series?
- Gold
- SELECT directed_by FROM table_26136228_3 WHERE series_no = 11
- 7B QLoRA
- SELECT directed_by FROM table_26136228_3 WHERE series_no = "11"
Right in another form: the quoted number returns the same rows whenever the column holds that value.
For this task the 1.5B model is the better buy: the same accuracy within the test's resolution, at less than half the latency. What QLoRA bought here is the ability to run the comparison at all on a free GPU, and to learn that the bigger model starts ahead and is worth training on more data before the decision is final. On a task where the 7B's head start were larger, as on lesson 2's banking intents, the answer could differ, and now it can be measured.
6. What to keep
Two adapters: 73.9 MB for the 1.5B, 161.5 MB for the 7B. Each was trained against the 4-bit version of its base and is scored on a fresh 4-bit copy, so that is how it should be served. Merging it into the weights is not free here: PEFT warns that merging into a 4-bit layer rounds the result back to 4 bits. Lesson 12 measures the options, from serving the adapter beside a 4-bit base, as Dialpad and Apoidea did, to merging into a 16-bit copy.
| 1.5B LoRA (lesson 4) | 1.5B QLoRA | 7B QLoRA | |
|---|---|---|---|
| Exact match on 500 | 71.8% | 71.8% | 73.4% |
| Runs in SQLite | 99.0% | 99.4% | 98.0% |
| Training examples | 8,000 | 8,000 | 1,600 |
| Training time | 14.6 min | 19.4 min | 12.3 min |
| Peak GPU memory | 9.87 GB | 6.01 GB | 8.07 GB |
| Time per answer | 203 ms | 307 ms | 427 ms |
| Adapter | 73.9 MB | 73.9 MB | 161.5 MB |
If you have a task like this one:
- Use QLoRA when the 16-bit weights do not fit, not otherwise. For the 1.5B model it traded 33% more training time and 51% more time per answer for 3.9 GB of memory that was not needed; the score did not move.
- Load the base as NF4 with double quantisation and fp16 compute, and give
device_mapthe GPU number. NF4 rebuilt the layer's output with 8.1% error against FP4's 11.1%, and double quantisation saved 0.37 bits per weight at no cost in error. - Skip
prepare_model_for_kbit_trainingwhen memory is tight. On the 7B model it added 2.18 GB before the first step; attach the adapter yourself and assert it is fp32. - Train the larger model on more data before choosing it. 73.4% against 71.8% is within the test's resolution and costs 2.1 times lesson 4's time per answer, so for this task the 1.5B model is the better buy.
- Serve the adapter beside the 4-bit base it was trained on, rather than merging into 4-bit weights.
- Next to try, not tested here: the 7B model on 8,000 examples, since its training loss was still moving and it wrote more queries that do not run (10 against 3).
- Next to try, not tested here: FP4 in place of NF4 for a full run, to see whether the trained adapter absorbs its 35% larger rounding error as it absorbed NF4's.
How it was built
| Item | Setting |
|---|---|
| Base model | Qwen/Qwen2.5-1.5B-Instruct (1.54 billion weights) and Qwen/Qwen2.5-7B-Instruct (7.62 billion); frozen linear layers stored in 4-bit, embedding and output head in fp16 |
| Data | sql-create-context at lesson 3's pinned commit, cleaned and split by table (train 69,170, validation 3,817, test 3,923); 8,000 training examples for the 1.5B model, the first 1,600 of them for the 7B model; 500 validation examples for the 1.5B loss curve |
| Test | 500 test questions, seed 42, the same as lesson 4 and the same for every system; exact match after normalising case, white space, a trailing semicolon and quote characters, plus whether the query runs in SQLite on the empty schema; ±3.9 to 4.3 points at 95% |
| Quantisation | BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.float16), blocks of 64; device_map={"": 0} |
| Method | LoRA through TRL SFTTrainer: r=16, lora_alpha=32, lora_dropout=0.05, target_modules="all-linear"; 18,464,768 trainable weights for the 1.5B model, 40,370,176 for the 7B; the 7B adapter is built by build_peft_model without prepare_model_for_kbit_training |
| Training | 1.5B: 1 epoch, 500 optimizer steps, batch 8 × 2 accumulation = 16, validation every 200 steps. 7B: 1 epoch, 100 steps, batch 4 × 4 = 16, no validation. Both: learning rate 2e-4 with cosine decay and 3% warm-up, fp16, gradient checkpointing, max_length=256, loss on the answer only, seed 42 |
| Decoding | Greedy, batches of 16, up to 128 new tokens; every model gets the zero-shot prompt, adapters not merged |
| Hardware | One Tesla T4 (15.6 GB) on Google Colab; transformers 4.51.3, peft 0.15.2, trl 0.19.1, accelerate 1.6.0, datasets 3.6.0, bitsandbytes 0.50.2 |
Time and cost. The 1.5B model loads in 4-bit at 1.24 GB (3.09 GB in fp16). Its 8,000 examples hold 738,225 tokens, about 953,928 once batches are padded; training took 19.4 minutes including two validation passes, about 819 padded tokens per second, with 6.01 GB allocated at its peak (14.96 GB reserved). The 7B model loads at 5.65 GB, 5.82 GB once the adapter is attached; its 1,600 examples hold 147,591 tokens, about 175,736 padded, and training took 12.3 minutes at about 237 tokens per second, with 8.07 GB allocated at its peak (9.62 GB reserved). The adapters are 73.9 MB and 161.5 MB. Answers take 114 ms (1.5B zero-shot, fp16), 203 ms (1.5B LoRA, fp16), 307 ms (1.5B QLoRA), 385 ms (7B zero-shot) and 427 ms (7B QLoRA), so scoring 500 questions takes 2 to 4 minutes per system (derived). All five systems are scored on the same 500 test questions; the validation set only draws the 1.5B loss values, and the layer test in section 2 uses 1,035 input vectors from 16 of the test prompts.
Run it yourself
The notebook runs in about an hour on a free Colab T4: 19 minutes training the 1.5B, 12 training the 7B, and the rest generation and loading. Its numbered sections follow this page: 1 is what 4 bits do to a weight, 2 what they cost, 3 why the 7B model does not fit, 4 the memory trap, 5 and 6 what the 7B model buys, and 7 what to keep. Three changes to try:
- Set
N_TRAIN_7B = 8000, lesson 4's size. Does the 7B model pull clear of the 1.5B's interval, and is the gain worth twice the latency? - Pass
peft_configto the 7B trainer instead of a ready model, so TRL callsprepare_model_for_kbit_training. What is the new peak, and does the batch of 4 still fit? - Change
bnb_4bit_quant_typeto"fp4"for the 1.5B run. Section 2 measured 35% more rounding error; does the trained adapter absorb it too?
Lesson 6 keeps the 1.5B model and teaches it a new output: tool calls that a program can check.
How is this page?
Last updated on