Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 17/ 160
01. LLM Fundamentals

QLoRA

4-bit quantized base models plus LoRA for fine-tuning on consumer GPUs.

Advanced4-bit Base · NF43 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Squash the big model into a much smaller memory footprint, then train a small add-on on top of it.

Think of it like…

Packing a suitcase with vacuum bags: the clothes (the frozen weights) are compressed hard to fit the small case, and you only unpack and use each item briefly when needed, while the new items you're adding (the adapters) go in at full size.

Where you’ve seen it

A team wants to adapt a 13B model to their support transcripts. In 16-bit the weights alone need about 26 GB, which won't fit alongside training state on their 24 GB GPUs. With QLoRA the base loads in about 7 to 8 GB, adapters and optimiser add a few GB, and a 4,000-example fine-tune runs overnight on one GPU. Held-out evaluation shows quality within a point or two of a 16-bit LoRA run they later did on rented hardware.

Words you’ll hear

NF4
4-bit NormalFloat, a data type matched to the roughly normal distribution of pretrained weights.
Double quantisation
Quantising the per-block scale constants to save additional memory.
Paged optimisers
Optimiser state that spills to CPU memory during GPU memory spikes.
Compute dtype
The higher precision (bf16/fp16) used for the actual matrix maths and adapter weights.

Visual diagram

Loading interactive diagram

Theory & deep dive

What QLoRA adds to LoRA

Plain 4-bit rounding of weights loses too much quality, so QLoRA uses NF4, whose quantisation levels are placed to match the near-normal distribution of pretrained weights, and quantises in small blocks (for example 64 values) each with its own scale, so outliers only distort their own block. Double quantisation compresses those per-block scales again, saving around 0.4 bits per parameter. Paged optimisers use unified memory so optimiser state can move to CPU RAM when the GPU is briefly out of memory, instead of crashing the run.

Training works because the base weights are frozen: they never need to be updated, so storing them in low precision doesn't add noise to gradient updates. Each layer dequantises its weights to the compute dtype, runs the matrix multiply, and gradients flow through to the adapters, which are kept in bf16 or fp32. The reported finding was that this matches 16-bit full fine-tuning quality on the benchmarks tested, though results vary by model and task.

Memory arithmetic for a 13B model

16-bit weights: 13B × 2 bytes ≈ 26 GB. NF4 weights: 13B × ~0.5 bytes ≈ 6.5 GB plus scales, about 7 to 8 GB. Adapters (about 50M parameters) and their optimiser state add a few GB, and activations depend on batch size and sequence length, which is why gradient checkpointing is common.

Key takeaway: NF4 + double quantisation + paged optimisers shrink the frozen base; adapters stay high precision.

Trade-offs and practice

QLoRA trades time for memory: dequantising on the fly makes each step slower than 16-bit LoRA (commonly noticeably so), so if you have enough memory, plain LoRA is faster. Quality is usually close to 16-bit LoRA but not guaranteed identical; evaluate on your task and, for important models, compare a QLoRA run to a 16-bit run once.

Practical workflow: load the base with BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16), attach LoRA adapters (often to all linear layers, which helps QLoRA quality), enable gradient checkpointing, train, and save the adapter. To deploy, either serve the 4-bit base plus adapter (small, a bit slower, some quality loss at inference), or reload the base in 16-bit, merge the adapter and quantise again with an inference-oriented method such as AWQ or GPTQ. Don't merge an adapter into 4-bit weights directly, since rounding errors accumulate.

Loading a 4-bit base for training

bnb = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, bnb_4bit_compute_dtype=torch.bfloat16); model = AutoModelForCausalLM.from_pretrained(name, quantization_config=bnb) then wrap it with get_peft_model and a LoraConfig.

Key takeaway: Slower than LoRA but fits in far less memory; merge into a 16-bit copy for deployment.

How it works, step by step

Step 1 of 4
Planning

1. Estimate memory

Compare model size in 16-bit versus 4-bit, then add adapters, optimiser, activations and your sequence length.

13B: 26 GB (16-bit) → ≈ 7–8 GB (NF4)
Key numbers at this step
Rule
≈ 0.5 bytes/param in 4-bit

When to use it & trade-offs

What it is

QLoRA combines two ideas: load the frozen base model in 4-bit precision (the NF4 data type) to shrink its memory footprint roughly fourfold versus 16-bit, then train LoRA adapters in higher precision on top of it. During the forward and backward pass, 4-bit weights are dequantised block by block on the fly; gradients flow only into the adapters. It also adds double quantisation (quantising the quantisation constants) and paged optimisers to survive memory spikes. The result: fine-tuning a 7B to 13B model on a single consumer or mid-range GPU, and much larger models on one data-centre GPU.

Why it matters: Memory, not compute, is usually what stops people fine-tuning: a 7B model in 16-bit needs about 14 GB just for weights, before activations and optimiser state. QLoRA brings the base down to roughly 4 to 5 GB so a 16 to 24 GB GPU is enough, with quality close to 16-bit LoRA in published results. It democratised fine-tuning, and it's a favourite topic for "how would you fine-tune on a budget" questions.

When to reach for it

  • Fine-tuning 7B–13B models on a single 16–24 GB GPU
  • Prototyping specialisation before investing in larger hardware
  • Training on budget cloud instances

When to avoid or be careful

  • QLoRA when the 16-bit model fits easily and speed matters
  • Merging adapters directly into 4-bit weights
  • Assuming QLoRA equals 16-bit quality without an evaluation

QLoRA vs LoRA vs full fine-tuning

QLoRA
Best for: Limited GPU memory; 7B–70B models on one or few GPUs

Strengths: Smallest memory footprint; quality close to 16-bit LoRA.

Watch out: Slower steps; small possible quality gap.

LoRA (16-bit base)
Best for: When the model fits comfortably in memory

Strengths: Faster training; no quantisation noise.

Watch out: Needs about 4× the base-model memory of QLoRA.

Full fine-tuning
Best for: Large datasets and big behaviour changes

Strengths: Maximum capacity.

Watch out: Multi-GPU memory and a full copy per variant.

Interview signals & numbers to know

When this topic comes up

  • “Fine-tune a 13B model on one GPU”
  • “What is NF4?”
  • “We run out of GPU memory when fine-tuning”
  • bitsandbytes
  • QLoRA vs LoRA

Benchmarks & rules of thumb

≈ 0.5 bytes -
per parameter in 4-bit
≈ 4× -
base-model memory reduction vs 16-bit
64 -
a common quantisation block size

Common mistakes & follow-ups

Common interview mistakes

  • Merging the trained adapter into the quantised weights and getting degraded output.
  • Forgetting gradient checkpointing and running out of memory on activations even with a 4-bit base.
  • Choosing QLoRA on a GPU with ample memory and accepting slower training for no benefit.

Likely interviewer follow-ups

  • How does QLoRA reduce memory without hurting quality much?
  • What is NF4, and why not plain 4-bit integers?
  • How would you deploy a QLoRA-tuned model?
Interview tip: Walk through the 13B memory arithmetic. Showing 26 GB becoming about 7 GB turns an abstract technique into an obvious engineering choice.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply QLoRA with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Fine-tuning with LoRA
Next topic
Quantization