Suryanand/ Bootcamp
suryanand.com ↗Let's talk
← Fine-tuningAI guideIntermediate#fine-tuning#lora#qlora#peft
Frame · ai-engineering / fine-tuning / 04-lora-and-qlora.mdGuide 075 / 103

LoRA and QLoRA

LoRA is the reason fine-tuning stopped being a cluster-sized project. Instead of updating every weight in a model, you freeze the base and train a pair of small matrices next to each layer. QLoRA goes one step further and keeps the frozen base in 4-bit precision. Together they let you fine-tune models with billions of parameters on a single consumer or cloud GPU, and serve dozens of task-specific adapters from one base model.

Why it matters

Full fine-tuning a 7B to 8B model needs memory for weights, gradients and optimizer state for every parameter, which pushes you onto multiple large GPUs. LoRA trains a tiny fraction of the parameters (Together's docs describe it as roughly 0.1% to 1% of what full fine-tuning updates), so memory drops dramatically and checkpoints become megabytes instead of gigabytes.

For a long time the worry was that LoRA was a compromise. Thinking Machines' "LoRA Without Regret" (September 2025) ran careful sweeps on SFT and RL and reported that LoRA can match full fine-tuning in sample efficiency and final performance for typical post-training dataset sizes, provided a few details are right: apply it to all layers (including the MLP layers, not just attention) and use a substantially higher learning rate than for full fine-tuning. The TRL docs now include a guide that reproduces those results.

How it works

For a frozen weight matrix W, LoRA learns a low-rank update: two matrices A and B with a small inner dimension r (the rank). The layer's output becomes the original output plus a scaled B times A times the input. Only A and B get gradients.

Rendering diagram…

QLoRA (Dettmers et al., 2023) adds three ideas: store the frozen base in 4-bit NormalFloat (NF4), quantise the quantisation constants themselves (double quantisation), and page optimizer state to CPU memory to survive spikes. Gradients flow through the dequantised weights into the 16-bit LoRA adapters.

The knobs that matter:

  • Rank r. 8 to 64 covers most use cases. Higher rank adds capacity for larger datasets; for small datasets, rank barely matters.
  • Alpha. Scales the update. Many recipes set alpha equal to r or 2r; keep it fixed while you sweep the learning rate.
  • Target modules. Apply to all linear layers. In PEFT, target_modules="all-linear" does this.
  • Learning rate. Around 10 times the full fine-tuning rate is a reasonable starting point, per the Thinking Machines findings; TRL's docs suggest about 1e-4 for SFT adapters.

Reference architecture

The operational win of LoRA is multi-adapter serving: one base model in GPU memory, many adapters swapped per request. vLLM supports this directly with LoRA requests.

Rendering diagram…

You can also merge an adapter into the base weights for deployment if you only serve one task. Merging removes the small runtime overhead but loses the ability to swap adapters.

A precision note from the Unsloth docs worth repeating: train and serve in the same precision. If you plan to serve a 4-bit model, training the adapter against the 4-bit base (QLoRA) avoids a mismatch; if you will serve in 16-bit, train LoRA on the 16-bit base or merge carefully.

Code

QLoRA with Unsloth, which wraps the Hugging Face stack and adds memory and speed optimisations. These are the documented FastLanguageModel entry points.

from unsloth import FastLanguageModel
from trl import SFTConfig, SFTTrainer
from datasets import load_from_disk

model, tokenizer = FastLanguageModel.from_pretrained(
    model_name="unsloth/Qwen3-8B",
    max_seq_length=4096,
    load_in_4bit=True,          # QLoRA: frozen base in 4-bit
)

model = FastLanguageModel.get_peft_model(
    model,
    r=16,
    lora_alpha=16,
    lora_dropout=0,
    target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
                    "gate_proj", "up_proj", "down_proj"],
    use_gradient_checkpointing="unsloth",
)

ds = load_from_disk("triage_sft")
trainer = SFTTrainer(
    model=model,
    processing_class=tokenizer,
    train_dataset=ds["train"],
    args=SFTConfig(output_dir="qwen3-8b-qlora", learning_rate=2e-4,
                   num_train_epochs=2, per_device_train_batch_size=2,
                   gradient_accumulation_steps=8),
)
trainer.train()
model.save_pretrained("adapter")  # small adapter weights only

The plain Hugging Face equivalent uses BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4") plus a PEFT LoraConfig; TRL trainers accept both as quantization_config and peft_config.

Trade-offs and pitfalls

  • Attention-only LoRA underperforms. Older tutorials target only q_proj and v_proj. Include the MLP projections.
  • Learning rate copied from full fine-tuning. Too low a rate is the most common reason LoRA "does not work".
  • Large datasets can exceed adapter capacity. If you are doing continued pretraining on billions of tokens, low-rank adapters may fall short; that is a case for full fine-tuning.
  • Quantisation error. QLoRA trades a little accuracy for memory. For the final run, compare against 16-bit LoRA if you can afford it.
  • Merging into a quantised base. Merging adapters into 4-bit weights can degrade quality; merge into 16-bit weights, then quantise for serving.
  • Adapter sprawl. Hundreds of tenant adapters need a registry with versioning, owners and eval results, or you lose track fast.

Checklist

  • Target all linear layers, not just attention.
  • Start with r between 8 and 32 and a learning rate around 1e-4 to 2e-4.
  • Use QLoRA when memory is the constraint; compare to 16-bit LoRA for the final model.
  • Train and serve in matching precision.
  • Store adapters with base model id, tokenizer version and eval scores.
  • Use multi-LoRA serving when you have several tasks on the same base.

Further reading

Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.