LoRA and QLoRA: fine-tuning a model on one GPU
What LoRA is, how rank, alpha, and target layers work, what QLoRA adds, the memory math for a 7B model, and how to serve adapters merged or side by side.
- Published
- Reading time
- 13 min read
In short
- LoRA freezes a model's pretrained weights and trains two small matrices per layer whose product is the weight update. On GPT-3 175B its authors cut trainable parameters by 10,000 times and training memory by 3 times.
- QLoRA stores the frozen base in 4-bit NF4 and trains LoRA adapters on top in 16-bit. Its authors fine-tuned a 65B model on one 48GB GPU, down from more than 780GB, without losing 16-bit fine-tuning performance.
- Adapt every linear layer, not just attention. QLoRA's authors found that adapting only the query and value projections did not match full fine-tuning, and that once all layers were adapted the rank mattered little.
- Merge an adapter into the base weights when one model serves one task. Keep adapters separate when one base serves several, and size vLLM's max-loras and max-lora-rank to match, because the defaults are 1 and 16.
LoRA (low-rank adaptation) is a fine-tuning method that freezes a model's pretrained weights and trains two small matrices per layer, whose product is added to the frozen weight. QLoRA applies the same idea to a base model stored in 4 bits, which is what lets a 7B or 13B model be fine-tuned on one workstation GPU. Both cut the memory of supervised fine-tuning by an order of magnitude and produce an adapter of tens to hundreds of megabytes instead of a full copy of the model.
This article covers what LoRA computes, how to set rank, alpha, and target layers, what QLoRA adds, rough memory math for a 7B model, and how to serve the result. Whether to fine-tune at all is a separate question, covered in RAG vs fine-tuning and summarized at the end.
What LoRA does: frozen weights plus a low-rank update
LoRA leaves every pretrained weight matrix unchanged and learns the change to it as the product of two thin matrices. For a frozen weight W₀ of shape d × k, the LoRA paper (Hu and colleagues, Microsoft, 2021) writes the layer's output as:
h = W₀x + (α / r) · B A x
W₀ d × k frozen, no gradients
A r × k trained, random Gaussian init
B d × r trained, zero init
r the rank, much smaller than d and k
α a constant that scales the updateB starts at zero, so BA is zero and the model behaves exactly like the base model on the first training step. Gradients then flow only into A and B. The optimizer never holds state for W₀, which is where most of the memory saving comes from.
The parameter count follows from the shapes. A 4,096 × 4,096 projection has 16.8 million weights, while its adapter at rank 16 has r × (d + k) = 16 × 8,192 = 131,072, about 0.8% of the original.
The paper's headline results are on GPT-3 175B. Compared with full fine-tuning with Adam, LoRA reduced trainable parameters by 10,000 times and GPU memory by 3 times, from 1.2TB to 350GB during training. With rank 4 on the query and value projections, a checkpoint shrank from 350GB to 35MB, and training ran about 25% faster. Because W₀ + BA can be computed once and stored as an ordinary weight, a merged adapter adds no inference latency.
LoRA rank and alpha
Rank r sets how many directions the update can move the weights in, and alpha sets how strongly the update is applied. The two interact through the scale factor α / r.
In the LoRA paper, rank mattered less than expected. Adapting the query and value projections together, "a rank as small as one suffices" on the datasets the authors tested (Table 6). The scale factor exists so that changing r does not force you to retune the learning rate: the authors set α to the first r they tried and did not tune it afterward.
Later work found limits to that. LoRA Learns Less and Forgets Less (Biderman and colleagues, 2024) compared LoRA with full fine-tuning on programming and math, and found that LoRA substantially underperformed under standard low-rank settings. Full fine-tuning learned weight changes with a rank 10 to 100 times higher than typical LoRA configurations. The same study found that LoRA kept more of the base model's ability outside the target domain.
Practical settings, with their sources:
- Defaults. PEFT's
LoraConfigusesr=8andlora_alpha=8, so the scale is 1. - QLoRA's chatbot runs. The QLoRA paper used
r=64andα=16on all linear layers, with dropout 0.1 up to 13B and 0.05 for 33B and 65B. - Rank-stabilized scaling. Setting
use_rslora=Truein PEFT changes the scale from α / r to α / √r, which keeps the update from shrinking as rank grows. - Learning rate. The TRL SFT docs suggest around
1e-4for adapters, higher than the2e-5default for full training, because only new parameters are learned.
Start at rank 16, keep alpha fixed while you vary rank, and raise rank only if evaluation shows the adapter cannot fit the task. Tasks that teach a new skill, such as code in an unfamiliar language, need more rank than tasks that change format or tone.
Which layers to adapt
Adapt every linear layer in the transformer blocks. The original paper adapted only the attention projections, and later results showed that was not enough for large models.
The LoRA paper froze the MLP layers and, with a fixed budget of 18 million parameters on GPT-3, found that adapting both Wq and Wv gave the best result. The QLoRA authors tested the same choice on LLaMA 7B and found that adapting only the query and value projections did not match full fine-tuning. Adapting all linear layers did, and once every layer had an adapter, the rank did not affect performance in their runs. They reported the number of adapted layers as the most important LoRA hyperparameter.
In PEFT, target_modules="all-linear" selects every linear layer and leaves out the output layer, so you do not have to know each architecture's module names. Two cases need more than that:
- New tokens. If you add special tokens to the tokenizer, the embedding and output layers must learn them. List those layers in
modules_to_save, which trains and saves them in full alongside the adapter. - Weight-decomposed LoRA.
use_dora=Truesplits each update into a magnitude and a direction. PEFT notes that it adds overhead compared with plain LoRA and recommends merging the weights for inference.
What QLoRA adds: a 4-bit base and paged optimizers
QLoRA keeps LoRA's adapters and changes how the frozen base is stored. The base weights sit in GPU memory in 4 bits and are dequantized to BF16 when each layer runs, while the adapters train in 16-bit. Gradients pass through the quantized weights into the adapters, and the base is never updated.
The paper (Dettmers and colleagues, 2023) added three pieces:
- 4-bit NormalFloat (NF4). A 4-bit data type whose levels are spaced for normally distributed values, which pretrained weights roughly are. The authors describe it as information-theoretically optimal for that distribution. Weights are quantized in blocks of 64, each with its own scale constant.
- Double quantization. The block constants are quantized again, saving about 0.37 bits per parameter, or roughly 3GB on a 65B model.
- Paged optimizers. Optimizer state is allocated in NVIDIA unified memory, so the memory spikes from gradient checkpointing on a long sequence page out to CPU memory instead of crashing the run.
Together these cut the memory needed to fine-tune a 65B model from more than 780GB to under 48GB, one GPU, while preserving full 16-bit fine-tuning task performance on the paper's benchmarks. The authors' Guanaco models reached 99.3% of ChatGPT's score on the Vicuna benchmark after 24 hours of training on a single GPU.
In Hugging Face Transformers, NF4 and double quantization are four fields on BitsAndBytesConfig, and the Transformers bitsandbytes guide says to use NF4 when training on a 4-bit base. Paged optimizers are an optim value on the trainer: paged_adamw_8bit or paged_adamw_32bit.
QLoRA memory requirements for a 7B model
A 7B model needs roughly 108GB to fine-tune in full, about 14GB with LoRA on a 16-bit base, and a few GB plus activations with QLoRA. The figures below are arithmetic for Llama 2 7B (6.74 billion parameters, 32 layers, hidden size 4,096, MLP width 11,008), before activations, which depend on sequence length and batch size.
| Setup | Base weights | Trainable state | Rough total before activations |
|---|---|---|---|
| Full fine-tuning, mixed-precision Adam | Included in 16 bytes per parameter | 16 bytes per parameter | About 108GB |
| LoRA on a BF16 base, rank 16, all linear layers | 2 bytes per parameter, about 13.5GB | About 40M parameters, under 1GB | About 14GB |
| QLoRA on an NF4 base, same adapter | About 0.5 bytes per parameter, about 3.4GB | Same, under 1GB | About 4 to 5GB |
The 16 bytes per parameter for full training comes from the ZeRO paper: 2 for the 16-bit weights, 2 for the gradients, and 12 for Adam's FP32 copy of the weights and its two moment estimates. LoRA pays that cost only for the adapter. At rank 16 on all seven linear projections in each of 32 layers, the adapter has 39,976,960 parameters, 0.6% of the model.
Measured numbers sit near the arithmetic. The QLoRA paper's memory breakdown for LLaMA 7B puts the 4-bit base at 5,048MB, and the Transformers guide reports fine-tuning a 13B Llama model with nested quantization on a 16GB T4 at a sequence length of 1,024 and a batch size of 1. Activations are what grow with sequence length, so long examples are what push a run past a GPU's memory. Gradient checkpointing, which TRL's SFTConfig enables by default, recomputes activations in the backward pass instead of storing them.
Supervised fine-tuning with LoRA: a QLoRA training run
Supervised fine-tuning trains a model on input and output pairs, minimizing the loss on the output tokens. With TRL, a QLoRA run is a quantization config, a LoRA config, and a trainer.
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
# The frozen base: NF4 weights, quantized constants, BF16 compute.
quantization = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=torch.bfloat16,
)
# The trained part: an adapter on every linear layer.
lora = LoraConfig(
r=16,
lora_alpha=16,
lora_dropout=0.05,
target_modules="all-linear",
task_type="CAUSAL_LM",
)
args = SFTConfig(
output_dir="out/ticket-router",
model_init_kwargs={"dtype": torch.bfloat16},
learning_rate=1e-4,
optim="paged_adamw_8bit",
per_device_train_batch_size=4,
gradient_accumulation_steps=4,
num_train_epochs=2,
)
trainer = SFTTrainer(
model="Qwen/Qwen3-8B",
args=args,
train_dataset=load_dataset("json", data_files="train.jsonl", split="train"),
quantization_config=quantization,
peft_config=lora,
)
trainer.train()
trainer.save_model() # writes the adapter, not the base modelPut the data in TRL's prompt-completion format, one example per line, with prompt and completion fields holding chat messages. For that format, TRL computes the loss on the completion only by default, so the model is not trained to reproduce your prompts. A plain messages dataset trains on the whole conversation unless you set assistant_only_loss=True, which requires a chat template that marks the assistant's turns.
Set model_init_kwargs explicitly. TRL loads a model named by a string in FP32 unless told otherwise, which doubles the memory of every layer that is not quantized.
Hold out examples before training and evaluate the adapter against the base model on them, using the same prompts and the same scoring. LLM evaluation covers how to build that suite. Without a comparison against the base, a falling training loss says only that the model is memorizing the training set.
Serving LoRA adapters: merge or keep separate
Serve a merged model when one fine-tune handles one workload, and keep adapters separate when one base model serves several. Merging removes the adapter's cost at inference, and separate adapters let one GPU serve many fine-tunes.
Merging an adapter into the base weights
Merging computes W₀ + (α / r)BA for every adapted layer and saves the result as an ordinary model. Any inference engine can load it, and it runs at exactly the base model's speed. The cost is a full copy of the weights per fine-tune.
import torch
from peft import AutoPeftModelForCausalLM
# Load the base in BF16, not 4-bit, so the merged weights are not re-quantized.
model = AutoPeftModelForCausalLM.from_pretrained("out/ticket-router", dtype=torch.bfloat16)
merged = model.merge_and_unload()
merged.save_pretrained("out/ticket-router-merged")merge_and_unload() is not in place, so assign its result. Merge into a 16-bit copy of the base even when you trained with QLoRA. The PEFT quantization guide explains that merging into quantized weights dequantizes, adds the adapter, and quantizes again, so unmerging does not restore the original weights and repeated cycles accumulate rounding error. A QLoRA adapter was trained against dequantized NF4 weights, so evaluate the merged 16-bit model rather than assuming it matches.
Serving many adapters on one base with vLLM
vLLM can keep the base weights loaded once and apply a different adapter per request. The vLLM LoRA docs enable it with --enable-lora and register adapters with --lora-modules, and a request picks an adapter by name in its model field:
vllm serve Qwen/Qwen3-8B \
--enable-lora \
--lora-modules ticket-router=./out/ticket-router support-tone=./out/support-tone \
--max-loras 4 \
--max-lora-rank 16
curl http://localhost:8000/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{"model": "ticket-router", "messages": [{"role": "user", "content": "Refund not received after 10 days"}]}'Two engine arguments have defaults that catch people. --max-loras, the number of adapters that can run in a single batch, defaults to 1, so a second adapter's requests wait for the first. --max-lora-rank defaults to 16, and the docs say to set it to the highest rank among your adapters, so an adapter trained at rank 64 needs --max-lora-rank 64. --max-cpu-loras sets how many adapters stay cached in CPU memory and must be at least --max-loras.
vLLM can also load adapters at runtime through /v1/load_lora_adapter when VLLM_ALLOW_RUNTIME_LORA_UPDATING=True is set. The docs warn that this should not be used in production unless the environment is isolated and fully trusted, since anyone who can reach the endpoint can load weights onto the server.
Unmerged adapters cost some throughput, since every adapted layer runs the extra A and B multiplication. Research systems have pushed that cost down: S-LoRA keeps adapters in host memory, pages the active ones onto the GPU alongside the KV cache, and reports up to 4 times the throughput of Hugging Face PEFT and of vLLM's naive LoRA support at the time. Prefix caching still works per adapter, since vLLM includes the adapter ID in the hash of each cached block, as the KV cache article describes.
The choice comes down to how many fine-tunes share a base:
| Situation | Serve as | Why |
|---|---|---|
| One fine-tune, high traffic | Merged model | Base model speed, any engine |
| Several fine-tunes of one base | Separate adapters on one vLLM server | One copy of the base in GPU memory |
| Per-customer or per-tenant adapters | Separate adapters, cached on CPU | Hundreds of small files instead of hundreds of models |
| Local testing on a laptop | Merged, or in the runtime's adapter format | Local runtimes differ in what they load |
For the last row, vLLM vs Ollama covers the formats each local runtime loads.
When to fine-tune at all
Fine-tune when the model has the facts and the instructions and still produces the wrong kind of output. Format, tone, and accuracy on one narrow, repeated task are behavior, and LoRA changes behavior well. Missing knowledge is a retrieval problem, and RAG vs fine-tuning works through that distinction with the studies behind it.
LoRA fits when these hold:
- The task is narrow and stable: classifying tickets, extracting fields, holding a schema or a house style.
- You have labeled examples, or a larger model whose outputs can serve as them.
- Prompting, few-shot examples, and structured outputs have been tried and measured, and still miss.
- You run an open-weight model, or a provider that accepts adapters, and can own the training and evaluation loop.
Two costs follow you after training. An adapter is tied to its base, so a base model upgrade means retraining and re-evaluating. And the Biderman results apply: LoRA at standard ranks learns new skills such as math and code less completely than full fine-tuning, while keeping more of what the base model could already do.
Frequently asked questions
What is LoRA in machine learning?
LoRA, short for low-rank adaptation, is a parameter-efficient fine-tuning method. It freezes the pretrained weights and trains two small matrices per layer, whose product is added to the frozen weight. Only those matrices are trained and saved, so an adapter is a small fraction of the model's size.
What is the difference between LoRA and QLoRA?
QLoRA is LoRA trained on a base model stored in 4-bit NF4 instead of 16-bit. The adapters are the same. QLoRA also quantizes the quantization constants and pages optimizer state to CPU memory during spikes, which together let its authors fine-tune a 65B model on one 48GB GPU.
What LoRA rank should I use?
Start with rank 16 on all linear layers. The QLoRA authors found that once every linear layer had an adapter, rank barely affected results, while the LoRA authors found that rank 1 to 4 was enough on attention layers alone for their tasks. Raise the rank for tasks that teach new skills, such as code or math, where low-rank adapters fall furthest behind full fine-tuning.
Can you fine-tune a 7B model on a single consumer GPU?
Yes, with QLoRA. A 7B model's 4-bit weights take about 3.4GB by arithmetic, and the QLoRA paper measured 5,048MB, which leaves room on a 16GB or 24GB card for the adapter, optimizer state, and activations at moderate sequence lengths. Long sequences are what exceed memory, so keep gradient checkpointing on and reduce batch size before sequence length.
Does LoRA slow down inference?
A merged LoRA adapter adds no latency, because the update is folded into the base weights and the model has its original shape. An unmerged adapter adds an extra small matrix multiplication per adapted layer. That cost buys the ability to serve many adapters on one copy of the base model.
Sources
- 01LoRA: Low-Rank Adaptation of Large Language ModelsarXiv:2106.09685
- 02QLoRA: Efficient Finetuning of Quantized LLMsarXiv:2305.14314
- 03LoRA Learns Less and Forgets LessarXiv:2405.09673
- 04ZeRO: Memory Optimizations Toward Training Trillion Parameter ModelsarXiv:1910.02054
- 05S-LoRA: Serving Thousands of Concurrent LoRA AdaptersarXiv:2311.03285
- 06LoRAHugging Face PEFT docs
- 07QuantizationHugging Face PEFT docs
- 08BitsandbytesHugging Face Transformers docs
- 09SFT TrainerHugging Face TRL docs
- 10LoRA AdaptersvLLM docs
- 11Engine ArgumentsvLLM docs