LoRA & QLoRA

In one sentence

Freeze the model and train a low-rank update per weight matrix: usually under 1% of parameters, saved as a megabyte-sized adapter. QLoRA stores the frozen base in 4-bit, so big models fine-tune on one GPU.

Analogy: Instead of reprinting a 1,000-page manual for each client, you print a thin page of corrections that clips onto the same book. Swap the clip, change the client.

Only A and B get gradients. B starts at zero, so training begins exactly at the base model.

How it works

  • For each frozen matrix W it learns ΔW = B·A: two thin matrices of rank r ≈ 8–64.
  • It works because the change fine-tuning needs is low-rank: a few directions, not a rewrite.
  • Frozen weights need no gradients or optimizer state, so GPU memory drops (~3× on GPT-3 175B).
  • Merge BA into W for zero inference cost, or keep adapters separate to swap them per request.
  • Multi-LoRA serving (vLLM, S-LoRA, LoRAX) batches many tenants' adapters over one shared base model.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your SaaS has 40 enterprise customers, and each needs its own fine-tuned version of an 8B model (own terminology, own report format). New customers arrive monthly. Which design do you propose?

Go deeper

Full explanation

LoRA (Low-Rank Adaptation) fine-tunes a model without touching its original weights. For a frozen matrix W (say 4096×4096) it learns an update ΔW = B·A, where A is r×4096, B is 4096×r and the rank is r ≈ 8–64. The layer computes Wx + (α/r)·BAx. At r=16 that's ~131k trainable numbers instead of ~16.8M; across a model, typically under 1% of parameters.

It works because the change fine-tuning needs is low-rank: a few directions, not a rewrite. What you get:

  • Memory. No gradients or optimizer state for frozen weights; on GPT-3 175B the paper cut GPU memory ~3×.
  • Small, swappable adapters. GPT-3's checkpoint went from 350 GB to ~35 MB. Keep one base and many adapters.
  • No inference cost if merged. Fold BA into W for a single task, or keep it separate to swap per request.

QLoRA stores the frozen base in 4-bit NF4 (plus double quantization and paged optimizers) and trains bf16 LoRA adapters on top. It fine-tuned a 65B model on a single 48 GB GPU while matching 16-bit fine-tuning on the paper's benchmarks.

Multi-LoRA serving: vLLM, S-LoRA and LoRAX keep one base in GPU memory and batch requests for different adapters together, so hundreds of tenants or tasks share the same GPUs.

Code QLoRA setup with transformers + peft
pythonQLoRA setup with transformers + peft
import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

MODEL = "meta-llama/Llama-3.1-8B-Instruct"  # any HF causal LM

# QLoRA: frozen base in 4-bit NF4, math in bf16
bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_use_double_quant=True,       # quantize the scales too
    bnb_4bit_compute_dtype=torch.bfloat16,
)
model = AutoModelForCausalLM.from_pretrained(MODEL, quantization_config=bnb, device_map="auto")
model = prepare_model_for_kbit_training(model)

lora = LoraConfig(
    r=16,                          # rank: 8-64 typical
    lora_alpha=32,                 # update scaled by alpha/r
    lora_dropout=0.05,
    target_modules="all-linear",   # attention + MLP; q/v only is cheaper but weaker
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora)
model.print_trainable_parameters()  # ~42M of 8B, about 0.5%

# ... train with TRL SFTTrainer or transformers Trainer ...
model.save_pretrained("adapter-tenant-acme-v1")  # ~170 MB (fp32 adapter), not the 16 GB base
Real example

A SaaS vendor has 40 enterprise customers, each wanting the assistant to use its own terminology and report format. Forty full fine-tunes of an 8B model would mean 40 checkpoints of 16 GB and 40 deployments. With LoRA (r=16) each customer gets a ~170 MB adapter (fp32; half that in bf16) trained in an hour or two on one GPU, and vLLM serves all 40 from a single base model, routing each request to its tenant's adapter. Customer #41 is a training job, not a new deployment.

Trade-offs +4 · −4

+ You gain

  • Fits big fine-tunes on small hardware: QLoRA did 65B on a single 48 GB GPU.
  • Adapters are megabytes: easy to version, store and swap; one base serves many tasks or tenants.
  • Quality close to full fine-tuning on typical SFT and preference tasks.
  • Merge into the weights for zero added inference latency.

− You pay

  • Learns less than full fine-tuning on big domain shifts like code or math (and, in exchange, forgets less).
  • QLoRA steps run slower than 16-bit LoRA because weights are dequantized on the fly.
  • Unmerged adapters add some per-token overhead and need a server that supports them.
  • An adapter is tied to its exact base model; a new base means retraining every adapter.

Use it when

The default for fine-tuning open models: limited GPUs, many tasks or tenants on one base, or fast iteration on SFT and DPO.

Avoid it when

Large knowledge shifts (a new language, a big domain corpus) where full fine-tuning or continued pretraining learns more, or closed models where managed fine-tuning is the only option.

Numbers to know 5
  • LoRA on GPT-3 175B: ~10,000× fewer trainable parameters, ~3× less GPU memory, checkpoint 350 GB → ~35 MB.
  • QLoRA: 65B model fine-tuned on one 48 GB GPU, matching 16-bit fine-tuning (Dettmers et al., 2023).
  • 8B model, r=16 on all linear layers: ~42M trainable parameters, about 0.5%.
  • Rule of thumb: r = 8–64, alpha ≈ r to 2r, LR ~1e-4–2e-4.
  • S-LoRA: thousands of concurrent adapters served over one shared base model.
Common pitfalls 4
  • Adapting only the attention q/v projections: QLoRA found LoRA on all linear layers was needed to match full fine-tuning.
  • Merging the adapter into the 4-bit training base: merge into 16-bit weights, then quantize separately for serving.
  • Raising the rank to fix bad data: r=256 won't rescue noisy examples.
  • Serving an adapter on a different base revision than the one it was trained on.
Interview questions 3

Answer out loud first, then reveal.

Explain LoRA in one minute.Show answer

Fine-tuning changes a weight matrix W by some ΔW. LoRA bets that ΔW is low-rank, so it learns it as the product of two thin matrices B·A with rank around 8 to 64, while W stays frozen. For a 4096×4096 layer at rank 16 that's ~131k trainable numbers instead of ~16.8M. There's no optimizer state for the frozen weights, so memory drops, and the result is a small adapter I can merge into W for zero latency or keep separate to swap per task.

You need a custom model for each of 200 tenants. How do you serve them?Show answer

One base model, one LoRA adapter per tenant, multi-LoRA serving. vLLM or S-LoRA keep the base weights once in GPU memory, load adapters on demand with a cache, and batch requests for different adapters in the same forward pass, so 200 tenants share a GPU pool instead of 200 deployments. The trade-offs: some per-token overhead versus a merged model, a cap on adapters resident at once, and a retrain of every adapter when I upgrade the base. So the per-tenant training pipeline must be automated from day one.

What does QLoRA trade, and when would you use it?Show answer

QLoRA stores the frozen base in 4-bit NF4, a data type built for normally distributed weights, adds double quantization and paged optimizers to absorb memory spikes, and keeps the adapters and the math in bf16. That's how the paper fit a 65B fine-tune on one 48 GB GPU while matching 16-bit fine-tuning on its benchmarks. The price is slower steps from on-the-fly dequantization. I use it when GPU memory is the constraint; with enough memory, plain 16-bit LoRA trains faster.