A 7B language model requires approximately 14 GB just to store its weights in FP16. Training requires additional memory for activations, gradients, and optimizer states.
For developers working with a 8 GB, 12 GB, or 16 GB GPU, loading and fine-tuning such a model can quickly become a problem.
QLoRA provides a practical solution.
It loads the pretrained model in 4-bit quantized form, freezes its original weights, and trains small LoRA adapters instead. This significantly reduces the memory required for fine-tuning without updating billions of parameters.
In this guide, we'll use Hugging Face, Transformers, PEFT, TRL, and bitsandbytes to fine-tune an open-weight 7B model with QLoRA.
1. How QLoRA Solves the GPU Memory Problem
QLoRA combines two techniques:
- 4-bit quantization: Reduces the memory required to load the pretrained model.
- LoRA adapters: Train a small number of additional parameters while keeping the original model frozen.
For a 7B parameter model, the approximate base-weight storage looks like this:
| Model precision | Approximate weight memory |
|---|---|
| FP32 | 28 GB |
| FP16 / BF16 | 14 GB |
| INT8 | 7 GB |
| 4-bit | 3.5 GB |
These figures represent raw weight storage, not total training memory.
QLoRA commonly uses the NF4 quantization format, which is designed for neural network weights. Double quantization further reduces the overhead associated with quantization metadata.
The result is a much smaller frozen base model with trainable LoRA adapters.
The important point: QLoRA reduces the base-model memory requirement, but it does not remove the memory needed for activations, temporary computations, and other training operations.
2. Prepare the Training Environment
We'll use the following stack:
- PyTorch for model computation.
- Transformers for loading the pretrained model.
- bitsandbytes for 4-bit quantization.
- PEFT for LoRA adapters.
- TRL for supervised fine-tuning.
- Datasets for loading training examples.
Install the libraries:
pip install -U transformers peft trl bitsandbytes accelerate datasets
Install a PyTorch build compatible with your CUDA environment before running the training script.
Check GPU availability:
import torch
if not torch.cuda.is_available():
raise RuntimeError("A supported CUDA GPU is required.")
print("GPU:", torch.cuda.get_device_name(0))
print("VRAM:", round(
torch.cuda.get_device_properties(0).total_memory / 1024**3,
2
), "GB")
3. Choose a Base Model
For this walkthrough, we'll use:
model_id = "Qwen/Qwen2.5-7B-Instruct"
The model is instruction-tuned and suitable for demonstrating supervised fine-tuning.
Before choosing a model, check its license, supported architecture, tokenizer, and hardware requirements.
If a 7B model still exceeds your available GPU memory, start with a smaller 3B or 1.5B model and use the same workflow.
4. Load the Model in 4-Bit
This is the main step that makes QLoRA different from ordinary LoRA fine-tuning.
Instead of loading the entire base model in FP16 or BF16, configure bitsandbytes to load it in 4-bit NF4 format.
import torch
from transformers import (
AutoTokenizer,
BitsAndBytesConfig
)
model_id = "Qwen/Qwen2.5-7B-Instruct"
use_bf16 = torch.cuda.is_bf16_supported()
compute_dtype = (
torch.bfloat16
if use_bf16
else torch.float16
)
quantization_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_use_double_quant=True,
bnb_4bit_compute_dtype=compute_dtype
)
tokenizer = AutoTokenizer.from_pretrained(model_id)
Here's what matters in this configuration:
load_in_4bit=Trueloads the base model using 4-bit weights.bnb_4bit_quant_type="nf4"selects the NF4 representation.bnb_4bit_use_double_quant=Truereduces quantization metadata overhead.bnb_4bit_compute_dtypeselects BF16 or FP16 for computation.
The model's weights are stored in 4-bit form, but computations do not necessarily happen in 4-bit precision.
5. Configure LoRA Adapters
Next, define the trainable adapter configuration.
from peft import LoraConfig
lora_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
target_modules="all-linear"
)
target_modules="all-linear" applies LoRA adapters to the model's linear layers, following a common QLoRA configuration.
The most important settings are:
r: Controls adapter rank and trainable capacity.lora_alpha: Controls the scaling of adapter updates.lora_dropout: Applies dropout to reduce overfitting.
Start with rank 16. Increase it only when evaluation shows that the adapter needs more capacity.
6. Prepare the Dataset
For supervised fine-tuning, prepare examples containing an instruction and its expected response.
Create three files:
dataset/
train.jsonl
validation.jsonl
test.jsonl
A conversational JSONL example:
{
"prompt": [
{
"role": "user",
"content": "Explain database indexing."
}
],
"completion": [
{
"role": "assistant",
"content": "Database indexing improves data retrieval by maintaining an additional data structure that helps locate records efficiently."
}
]
}
Keep the following rules in mind:
- Use accurate and relevant examples.
- Remove duplicated records.
- Follow the selected model's chat format.
- Keep validation and test examples separate from training data.
- Remove sensitive information before training.
The training set teaches the model, the validation set helps monitor training, and the test set measures final performance.
7. Train the Model with QLoRA
Now combine the quantized model configuration, LoRA adapters, and dataset using TRL's SFTTrainer.
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
dataset = load_dataset(
"json",
data_files={
"train": "dataset/train.jsonl",
"validation": "dataset/validation.jsonl"
}
)
training_args = SFTConfig(
output_dir="./qlora-output",
num_train_epochs=2,
per_device_train_batch_size=1,
per_device_eval_batch_size=1,
gradient_accumulation_steps=8,
gradient_checkpointing=True,
learning_rate=2e-4,
max_length=1024,
completion_only_loss=True,
bf16=use_bf16,
fp16=not use_bf16,
eval_strategy="epoch",
save_strategy="epoch",
logging_steps=10,
report_to="none"
)
trainer = SFTTrainer(
model=model_id,
args=training_args,
train_dataset=dataset["train"],
eval_dataset=dataset["validation"],
processing_class=tokenizer,
quantization_config=quantization_config,
peft_config=lora_config
)
trainer.train()
TRL loads the base model using the quantization configuration and attaches the LoRA adapters through PEFT.
The training parameters are deliberately conservative:
- Batch size of 1 limits the number of sequences processed simultaneously.
- Gradient accumulation of 8 increases the effective batch size without increasing the micro-batch.
- Gradient checkpointing reduces activation memory.
- A sequence length of 1024 keeps the initial experiment manageable.
These are starting settings, not guaranteed hardware requirements. Adjust them according to the available GPU memory and dataset.
8. What If You Still Get CUDA Out-of-Memory Errors?
4-bit quantization does not guarantee that every large model will fit on every GPU.
If training fails with CUDA out-of-memory errors, adjust the configuration in this order:
| Change | Configuration |
|---|---|
| Reduce sequence length | max_length=512 |
| Keep micro-batch minimal | per_device_train_batch_size=1 |
| Increase gradient accumulation | gradient_accumulation_steps=16 |
| Enable activation checkpointing | gradient_checkpointing=True |
| Use a smaller base model | Choose a 3B or smaller model |
Also close other GPU-intensive applications and check actual memory usage with:
nvidia-smi
Do not increase batch size or sequence length simply because the model loads successfully. Training requires additional memory beyond model loading.
If the model still does not fit, reduce model size rather than repeatedly attempting the same configuration.
9. Save and Evaluate the Fine-Tuned Model
Once training finishes, save the adapter:
trainer.save_model("./qlora-adapter")
tokenizer.save_pretrained("./qlora-adapter")
This stores the trained LoRA adapter separately from the original base model.
To evaluate on the held-out test set:
test_dataset = load_dataset(
"json",
data_files="dataset/test.jsonl",
split="train"
)
test_results = trainer.evaluate(
eval_dataset=test_dataset
)
print(test_results)
This provides test loss and other trainer metrics. It should be combined with actual response-quality testing.
Compare the original model and the QLoRA-adapted model using the same test prompts.
Check whether the fine-tuned model:
- Produces more accurate task-specific responses.
- Follows the expected response format.
- Handles examples it has never seen.
- Retains its general-purpose capabilities.
- Avoids memorizing training examples.
A lower training loss is not sufficient evidence of improvement. Evaluate the actual outputs against the requirements of your application.
10. QLoRA vs LoRA: Which One Should You Choose?
The decision mainly depends on how much GPU memory is available.
| Situation | Better starting point |
|---|---|
| Base model fits comfortably in GPU memory | LoRA |
| Base model does not fit in FP16/BF16 | QLoRA |
| Limited GPU memory | QLoRA |
| Avoiding 4-bit quantization | LoRA |
| Fine-tuning larger models on constrained hardware | QLoRA |
QLoRA introduces quantization overhead and can have different training speed or numerical behavior from ordinary LoRA.
LoRA may be simpler when sufficient memory is available.
Neither method automatically produces better model quality. Evaluate the final model on the same task-specific test set.
Conclusion
QLoRA solves a practical problem: fine-tuning a large pretrained language model when GPU memory is limited.
The workflow is straightforward:
- Select a suitable base model.
- Load it in 4-bit NF4.
- Configure trainable LoRA adapters.
- Prepare instruction-response examples.
- Train with TRL's
SFTTrainer. - Reduce sequence length or model size if memory runs out.
- Save the adapter and evaluate it against the original model.
The important thing is to choose a model and training configuration that fit your actual hardware.
You do not need to update billions of pretrained parameters to adapt a large language model to a specific task.



