DEV Community

Cover image for LoRA and QLoRA, explained: how you fine-tune a 7B model on one GPU, and what it costs you
M.T.Ramkrushna
M.T.Ramkrushna

Posted on

LoRA and QLoRA, explained: how you fine-tune a 7B model on one GPU, and what it costs you

Tuesday Weekly AI Post. This week: LoRA and QLoRA, the two ideas behind almost every "I fine-tuned a 7B model on a single GPU" post you see. I want to cover what they actually change in the model, the memory math, the code, and the trade-off the hype posts leave out.

Short version: LoRA doesn't make fine-tuning cheaper by being clever about training. It makes it cheaper by training far fewer numbers. That's also exactly where its limits come from.

Why full fine-tuning hurts

Full fine-tuning updates every weight. For each trainable parameter you hold the weight, its gradient, and the optimizer state (Adam keeps two extra values per parameter). For a 7B model that adds up to far more memory than one consumer or mid-range GPU has.

There's a deployment cost too. The LoRA paper uses GPT-3 175B as the example: if every task gets its own fully fine-tuned copy, you're deploying a separate 175B-parameter model per task.

LoRA: freeze the model, learn a small low-rank update

LoRA (Hu et al., 2021) freezes the pretrained weights and injects small trainable matrices next to selected weight matrices in each Transformer layer.

For a frozen weight matrix W0 of shape d × k, instead of learning a full update ΔW (also d × k), LoRA learns two thin matrices:

  • B: d × r
  • A: r × k

with a rank r much smaller than d or k. The layer's output becomes:

h = W0·x + (B·A)·x
Enter fullscreen mode Exit fullscreen mode

Only A and B get gradients and optimizer state. W0 never changes.

A quick sense of scale (my own arithmetic, not from the paper): one 4096 × 4096 projection has 16,777,216 weights. A rank-8 LoRA on it trains 8 × (4096 + 4096) = 65,536 weights, about 0.39% of that matrix.

What the paper reports: compared with fine-tuning GPT-3 175B with Adam, LoRA can cut trainable parameters by 10,000× and the GPU memory requirement by 3×. It performed on par with or better than full fine-tuning on RoBERTa, DeBERTa, GPT-2 and GPT-3 in their experiments, with higher training throughput.

And one property that matters a lot in production: no extra inference latency. Because B·A has the same shape as W0, you can merge it into the weights after training (W = W0 + B·A) and serve a normal model. Classic adapter layers, by contrast, add extra layers to the forward pass.

That also fixes the deployment problem: one shared base model, plus a small adapter file per task.

QLoRA: put the frozen base in 4-bit

LoRA shrinks what you train, but you still have to hold the frozen base model in memory. QLoRA (Dettmers et al., 2023) attacks that part: it backpropagates through a frozen, 4-bit quantized base model into LoRA adapters.

Three pieces make it work:

  1. 4-bit NormalFloat (NF4), a data type the authors describe as information-theoretically optimal for normally distributed weights.
  2. Double quantization: quantizing the quantization constants themselves to save more memory.
  3. Paged optimizers to absorb memory spikes during training.

The headline results from the paper:

  • Fine-tuning a 65B model on a single 48GB GPU, while preserving full 16-bit fine-tuning task performance.
  • Their Guanaco models reached 99.3% of ChatGPT's performance level on the Vicuna benchmark after 24 hours of fine-tuning on one GPU.
  • They fine-tuned more than 1,000 models for the analysis, and found that a small, high-quality dataset can beat larger models trained on more data.

(The same paper also warns that the chatbot benchmarks of the time weren't trustworthy for judging chatbot quality, so read that 99.3% as "strong on that benchmark", not "as good as ChatGPT".)

What it looks like in code

This is the common Hugging Face stack: transformers + bitsandbytes for 4-bit loading, peft for LoRA. A sketch, not a full training script:

import torch
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training

bnb = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",          # QLoRA's NormalFloat4
    bnb_4bit_use_double_quant=True,     # double quantization
    bnb_4bit_compute_dtype=torch.bfloat16,
)

model = AutoModelForCausalLM.from_pretrained(
    "your-7b-base-model", quantization_config=bnb, device_map="auto"
)
model = prepare_model_for_kbit_training(model)

lora = LoraConfig(
    r=16,
    lora_alpha=32,
    lora_dropout=0.05,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],  # names depend on the architecture
    task_type="CAUSAL_LM",
)
model = get_peft_model(model, lora)
model.print_trainable_parameters()   # check how small the trainable slice really is

# ... train with your usual Trainer / SFT loop ...
# model.save_pretrained("adapter/")  -> saves only the adapter weights
Enter fullscreen mode Exit fullscreen mode

For serving, you can load the base model and attach the adapter, or merge the adapter into a full-precision copy of the base with merge_and_unload() and serve that as a plain model.

The knobs that matter most:

  • r (rank): how much the update can express. Higher rank = more capacity, more memory.
  • target_modules: which matrices get adapters. Attention projections only is the light option; adding the MLP projections gives the adapter more room.
  • lora_alpha: scales the update (the effective scale is alpha / r).

The part the hype skips: LoRA learns less, and forgets less

"LoRA Learns Less and Forgets Less" (Biderman et al., 2024) compared LoRA with full fine-tuning on two hard target domains, programming and mathematics, in both instruction fine-tuning (about 100K prompt-response pairs) and continued pretraining (about 20B tokens).

Their findings:

  • In standard low-rank settings, LoRA substantially underperformed full fine-tuning on those target domains.
  • But LoRA better preserved the base model's performance outside the target domain, mitigating forgetting more than weight decay or dropout, and it kept generations more diverse.
  • Full fine-tuning learned weight perturbations with a rank 10–100× greater than typical LoRA configurations, which may explain the gap.

So the honest picture:

You want to... LoRA / QLoRA fit
Teach a format, style, tone, or narrow task behaviour Good fit: small update, cheap, base skills mostly intact
Serve many task variants on one base model Good fit: one base + many small adapters
Push hard on a new domain (lots of new knowledge, e.g. a big code or math corpus) Expect a gap vs full fine-tuning; try higher rank / more target modules, and measure
Fit training onto a single GPU QLoRA is the usual answer

How I'd approach it

  1. Earn the fine-tune first. Evals, prompts and retrieval usually come before weights. Fine-tune when you have a stable task and a measurable gap.
  2. Build the eval set before training, including a few out-of-domain checks so you see forgetting, not just target-task gains.
  3. Start with QLoRA, a modest rank, attention projections. Check print_trainable_parameters().
  4. If the target metric plateaus, raise the rank and add MLP modules before jumping to full fine-tuning.
  5. Data quality beats data volume. QLoRA's own results point that way.
  6. Ship adapters, not copies. Version the adapter with the exact base model it was trained on; an adapter is useless on a different base.

References

What's your experience: has LoRA been enough for your fine-tunes, or did you hit the gap and need full fine-tuning?

Top comments (3)

Collapse
 
waddah00 profile image
Waddah Ali •

Including out-of-domain checks in the eval set before training is underrated. It's way too easy to celebrate target-task gains and miss that the base model lost general instruction following. For style, tone, or strict format on 7B-8B models, QLoRA has been plenty for me without needing to touch full fine-tuning.

Collapse
 
m_t_ramkrushna profile image
M.T.Ramkrushna •

Agreed, out-of-domain checks are the cheapest way to catch a regression you'd otherwise only notice in production. I'd keep a small frozen set of general instruction-following prompts and score it before and after every run.

Collapse
 
waddah00 profile image
Waddah Ali •

A small frozen set before and after every run is a clean habit. Even 20 to 30 general prompts is usually enough to catch format drift or broken refusals before you ship the adapter.