Updated November 2026: corrected the GPU memory numbers, switched the examples to target_modules="all-linear" and bf16, added DoRA and rsLoRA, and replaced the multi-adapter pseudo-code with real vLLM flags. Sources are linked at the end.
LoRA (Low-Rank Adaptation) is still the default way to adapt an open-weight large language model to your task in 2026. You freeze the base model, train a small adapter, and ship a file measured in megabytes instead of a full copy of the weights. This guide covers the method, the config I’d start with, QLoRA for tight GPUs, and how to serve adapters.
Why LoRA Still Matters
Full fine-tuning updates every parameter. You need memory for the weights, the gradients, and the optimizer state for all of them, which is why full fine-tuning of anything past a few billion parameters means a multi-GPU node.
LoRA freezes the base weights and only trains small low-rank matrices next to selected layers. The original LoRA paper reports that, compared with fine-tuning GPT-3 175B with Adam, LoRA “can reduce the number of trainable parameters by 10,000 times and the GPU memory requirement by 3 times”, with no extra inference latency once the adapter is merged.
Quick memory math for the frozen weights alone:
- 8B model in bf16: 2 bytes per parameter, about 16 GB
- 70B model in bf16: about 140 GB, so more than one 80 GB GPU
- 70B model in 4-bit (QLoRA): about 0.5 bytes per parameter, roughly 35 GB plus overhead
Activations, the adapter, and its optimizer state come on top. That’s why the 2025 version of this post was wrong to say a 70B LoRA run fits on one 40 GB card: in bf16 it doesn’t. The QLoRA paper puts the realistic floor at “a 65B parameter model on a single 48GB GPU” with 4-bit weights.
How LoRA Works
Instead of updating a weight matrix W, LoRA learns a low-rank update:
W_new = W + (alpha / r) * B @ A
W: frozen pretrained weights (d x k)
B: trainable matrix (d x r), initialized to zero
A: trainable matrix (r x k)
r: rank, usually 8 to 64, far smaller than d or k
alpha: scaling factor (lora_alpha in PEFT)
Because B starts at zero, training starts from exactly the base model. After training you can merge B @ A into W and the served model is the same size and speed as the original.
Practical Implementation
I use Hugging Face PEFT (v0.22 at the time of writing). The example uses Qwen3-8B because it trains on one 24 to 48 GB GPU in bf16 with LoRA; swap in any causal LM.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model, TaskType
MODEL_ID = "Qwen/Qwen3-8B"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.bfloat16,
device_map="auto",
)
lora_config = LoraConfig(
r=16, # rank
lora_alpha=32, # scaling factor, 2x rank is a common start
target_modules="all-linear", # every linear layer except the output head
lora_dropout=0.05,
bias="none",
task_type=TaskType.CAUSAL_LM,
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# r=16 on all linear layers of an 8B model trains roughly half a percent of the weights
Choosing Hyperparameters
| Parameter | Value | When |
|---|---|---|
| r (rank) | 4-8 | Simple formatting or style tasks, small datasets |
| r (rank) | 16-32 | Most tasks, a good first try |
| r (rank) | 64+ | Harder tasks with lots of clean data |
| lora_alpha | 2 x r | Standard scaling |
| lora_dropout | 0.05-0.1 | Small datasets, to limit overfitting |
| learning_rate | 1e-4 to 2e-4 | Higher than full fine-tuning |
Two newer PEFT switches are worth a test run. use_rslora=True scales by lora_alpha / sqrt(r) instead of lora_alpha / r, which keeps high ranks from training too timidly. use_dora=True enables DoRA, which “decomposes the pre-trained weight into two components, magnitude and direction” and trains both. DoRA costs a bit more memory and time, so I only keep it when the eval says it helped.
Target Modules Selection
- Attention only (
q_proj,v_proj): smallest adapter, fine for light style changes - All attention projections: a middle ground
"all-linear": attention plus MLP layers, and the safest default
If you’re unsure, start with "all-linear" and a lower rank rather than attention-only with a high rank.
Dataset Preparation
Quality beats volume. A few hundred clean, consistent examples beat 50,000 scraped ones. Use the chat template of the base model, not a home-made format:
messages = [
{"role": "system", "content": "You answer in valid JSON only."},
{"role": "user", "content": "Extract the invoice total from: ..."},
{"role": "assistant", "content": "{\"total\": 1249.00, \"currency\": \"SEK\"}"},
]
text = tokenizer.apply_chat_template(messages, tokenize=False)
Hold out 10% before you look at anything, and read 50 random rows by hand. Every bad label you find there is a few hundred you didn’t.
Training Configuration
from transformers import TrainingArguments, Trainer
training_args = TrainingArguments(
output_dir="./qwen3-8b-lora",
per_device_train_batch_size=4,
gradient_accumulation_steps=4, # effective batch size 16
learning_rate=2e-4,
num_train_epochs=3,
bf16=True,
logging_steps=10,
eval_strategy="epoch",
save_strategy="epoch",
warmup_ratio=0.05,
)
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
)
trainer.train()
Watch eval loss per epoch. If it climbs after epoch one, cut epochs or data repetition before you touch anything else.
QLoRA: When the GPU Is Too Small
QLoRA loads the frozen base model in 4-bit NF4 and trains a normal LoRA adapter on top. The paper adds double quantization and paged optimizers to keep memory spikes down. The Transformers docs recommend NF4 for training and bf16 as the compute dtype:
from transformers import BitsAndBytesConfig
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True, # about 0.4 extra bits per parameter saved
)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
quantization_config=bnb_config,
device_map="auto",
)
The trade-off is speed. 4-bit dequantization makes each step slower, so use QLoRA when the model doesn’t fit otherwise, not by default.
Evaluation
Always evaluate on the held-out set with more than one signal:
- Task metric: exact match, F1, or a schema check for structured output
- Regression check: a fixed set of general prompts to catch damage to the base model
- Human or judge review: sample 100 outputs; an LLM-as-judge pipeline scales this once you trust the rubric
Compare against the base model with a good prompt. If a better prompt closes most of the gap, you don’t need the adapter.
Merging the Adapter
from peft import PeftModel
base = AutoModelForCausalLM.from_pretrained(MODEL_ID, torch_dtype=torch.bfloat16)
model = PeftModel.from_pretrained(base, "./qwen3-8b-lora/checkpoint-best")
merged = model.merge_and_unload() # not in place, keep the return value
merged.save_pretrained("./qwen3-8b-merged")
tokenizer.save_pretrained("./qwen3-8b-merged")
Merge when you serve one adapter. Keep adapters separate when you serve many.
Serving LoRA Adapters with vLLM
vLLM serves adapters on top of one base model. Each --lora-modules entry becomes a model name in the OpenAI-compatible API:
vllm serve Qwen/Qwen3-8B \
--enable-lora \
--max-lora-rank 64 \
--lora-modules invoices=./lora-invoices support=./lora-support
curl http://localhost:8000/v1/completions \
-H "Content-Type: application/json" \
-d '{"model": "invoices", "prompt": "Extract the total from: ...", "max_tokens": 64}'
vLLM can also load adapters at runtime through /v1/load_lora_adapter when VLLM_ALLOW_RUNTIME_LORA_UPDATING=True, but its docs warn this carries security risk. I keep it off in production and restart with a new adapter list instead.
Training is a one-time cost. Serving is the bill that keeps coming, so check current per-token prices in my LLM API pricing comparison before you decide self-hosting is cheaper.
When LoRA Is Enough (and When It Isn’t)
LoRA is good at style, format, and narrow-domain behavior: a company’s tone, consistent JSON output, or one translation pair. My Gemma 4 E4B English-Swedish fine-tune is a complete worked example of that pattern, and the small LLMs post shows where a tuned small model beats a large generic one.
It’s weak at injecting lots of new facts. Facts baked into weights go stale the day you ship. Retrieval handles changing knowledge better, and with 1M-token context windows you may not even need a vector store; see 1M-token context vs RAG.
Full fine-tuning still wins for teaching a model a language or domain it barely saw in pretraining, and for broad behavior changes that must hold across every task.
If you’d like help with that choice on your own data, my company Royan AB fine-tunes open models with LoRA and measures them before and after.
Common Pitfalls
- Wrong chat template: the model learns your format and forgets how to stop
- Learning rate too high: loss drops fast, general ability drops with it
- Rank too low for the task: eval plateaus early while train loss keeps falling slowly
- No base-model baseline: you can’t tell if the adapter helped
Sources
- LoRA: Low-Rank Adaptation of Large Language Models (arXiv 2106.09685)
- QLoRA: Efficient Finetuning of Quantized LLMs (arXiv 2305.14314)
- DoRA: Weight-Decomposed Low-Rank Adaptation (arXiv 2402.09353)
- Hugging Face PEFT LoRA guide
- vLLM LoRA adapters
- Transformers bitsandbytes quantization
Frequently Asked Questions
Should I fine-tune or use RAG?
Use retrieval for facts that change. Use fine-tuning for style, format, tone, or narrow behavior that prompts can’t enforce reliably. Many production setups use both: a tuned model that also gets fresh context at request time.
How much data do I need for LoRA fine-tuning?
For narrow tasks, a few hundred to a couple of thousand clean, consistent examples is usually enough. Label consistency matters more than count. Start small, evaluate, then add data where the eval shows errors.
What hardware do I need for LoRA in 2026?
A 7-8B model trains with LoRA in bf16 on one 24-48 GB GPU, depending on sequence length and batch size. A 70B model needs either several 80 GB GPUs in bf16 or QLoRA on a 48 GB card, which is the floor the QLoRA paper reports for 65B.
Is QLoRA worse than LoRA?
It’s slower per step because of 4-bit dequantization, and the base weights are approximated. Use QLoRA when the model doesn’t fit in bf16 on your hardware. If it fits, plain LoRA is simpler and faster.
Can I serve many LoRA adapters on one GPU?
Yes. vLLM loads one base model and serves several adapters with --enable-lora and --lora-modules; the client picks one by model name. This is far cheaper than one merged model per customer or task.