How to Fine-Tune an LLM with QLoRA on One GPU
Why QLoRA?
Full fine-tuning updates every weight in a model — optimizer states and gradients far beyond what a single consumer GPU can hold for a 7 or 8 billion parameter model. QLoRA combines two ideas: load the base model in 4-bit precision, and train only a small set of extra weights called LoRA adapters while the base model stays frozen.
In practice, an 8B model fine-tunes on a single 16 GB card, and 24 GB gives comfortable headroom. The adapter checkpoint is typically tens of megabytes, not gigabytes, so you can version, share, and swap it without moving the base model.
QLoRA fits when you want to teach a model a style, a format, or domain-specific behavior — support answers in your tone, SQL from your schema, labels for your ticket queue. It is the wrong tool for large amounts of new factual knowledge. For that, retrieval-augmented generation over your documents usually works better, because facts stay in a database you can update instead of being baked into weights.
How QLoRA Works
QLoRA has three ingredients. First, the base model is quantized to 4-bit NormalFloat (NF4) with double quantization. Second, the quantized weights are frozen — no gradients flow into them. Third, a pair of small low-rank matrices, A and B, is attached to selected linear layers. Only A and B are trained, in higher precision, and their product is added to the frozen layer's output.
The rank r controls adapter size; 16 is a solid default for most style and format tasks. The scaling factor alpha is usually set to twice the rank. At inference time you can load the adapter on top of the base model or merge it into the base weights.
Source: openinnovation.ai — LoRA adapters (green) train alongside frozen base-model weights.
Prerequisites
- An NVIDIA GPU with at least 16 GB of VRAM for an 8B model (24 GB is more comfortable).
- Python 3.10 or newer, with a CUDA-enabled PyTorch install. If pip installs a CPU-only wheel, get the CUDA build from pytorch.org first.
- About 30 GB of free disk space for the base model, datasets, and checkpoints.
- A Hugging Face account and access token if your chosen base model is gated.
- A small, clean dataset: 500 to 2,000 high-quality examples beat 50,000 noisy ones.
Step 1: Install the Training Stack
We use TRL for the trainer, PEFT for the LoRA adapters, and bitsandbytes for 4-bit quantization — the libraries behind Hugging Face's official QLoRA documentation.
pip install torch trl peft bitsandbytes datasets accelerate
Step 2: Prepare Your Dataset
Format your data as conversational messages in JSONL, one conversation per line; TRL applies the model's chat template automatically. Keep 50 to 100 examples aside for evaluation, so you can tell whether the model improved or just memorized the training set.
{"messages": [{"role": "user", "content": "How do I reset my password?"},
{"role": "assistant", "content": "Open Settings, choose Security, then Reset password. The link expires in 30 minutes."}]}
{"messages": [{"role": "user", "content": "What is your refund window?"},
{"role": "assistant", "content": "Refunds are available within 30 days of purchase with the original receipt."}]}
Before training, dedupe near-identical examples, strip personal data, and check that assistant replies follow the exact format you want at inference time. The model will reproduce whatever patterns dominate your data — including sloppy ones.
Step 3: Write the Training Script
Save this as train_qlora.py. The key settings follow the official TRL PEFT guide: 4-bit NF4 quantization with double quantization, LoRA rank 16 with alpha 32, and a learning rate of 2e-4, roughly ten times the rate used for full fine-tuning.
import torch
from datasets import load_dataset
from transformers import BitsAndBytesConfig
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer
BASE_MODEL = "Qwen/Qwen3-8B-Instruct" # pick a base that fits your GPU
dataset = load_dataset("json", data_files="train.jsonl", split="train")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16,
bnb_4bit_use_double_quant=True,
)
peft_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
bias="none",
task_type="CAUSAL_LM",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],
)
args = SFTConfig(
output_dir="./qlora-adapter",
per_device_train_batch_size=2,
gradient_accumulation_steps=8, # effective batch size: 16
learning_rate=2e-4,
num_train_epochs=3,
logging_steps=10,
save_strategy="epoch",
bf16=True,
max_length=2048,
packing=False,
optim="paged_adamw_8bit",
warmup_ratio=0.03,
lr_scheduler_type="cosine",
gradient_checkpointing=True,
report_to="none",
)
trainer = SFTTrainer(
model=BASE_MODEL,
args=args,
train_dataset=dataset,
peft_config=peft_config,
quantization_config=bnb_config,
)
trainer.train()
trainer.save_model("./qlora-adapter")
Gradient accumulation lets you reach a healthy effective batch size (16 here) even though only 2 examples fit in memory at once. Gradient checkpointing trades some speed for a large memory saving by recomputing activations instead of storing them.
Step 4: Run a Smoke Test, Then Train
Before a full run, confirm the pipeline works. Set num_train_epochs=1 and add max_steps=20 temporarily, then run python train_qlora.py and watch the loss. It should start in the low single digits and move down steadily. If it explodes or returns NaN, stop — see troubleshooting below. Once the smoke test passes, remove max_steps and run the full job. Depending on dataset size, sequence length, and GPU, expect tens of minutes to a few hours.
Step 5: Test the Adapter
Load the base model, stack the adapter on top with PEFT, then answer your held-out prompts and compare against the base model side by side.
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
BASE_MODEL = "Qwen/Qwen3-8B-Instruct"
base = AutoModelForCausalLM.from_pretrained(
BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto"
)
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
model = PeftModel.from_pretrained(base, "./qlora-adapter")
messages = [{"role": "user", "content": "How do I reset my password?"}]
inputs = tokenizer.apply_chat_template(
messages, return_tensors="pt", add_generation_prompt=True
).to(model.device)
out = model.generate(**inputs, max_new_tokens=200, temperature=0.7)
print(tokenizer.decode(out[0], skip_special_tokens=True))
Judge outputs on your use case, not training loss alone. If the model parrots training phrases on new questions, it overfit — add more varied data or cut epochs.
Step 6: Merge the Adapter for Deployment
Adapters suit experiments, but serving is simpler with one merged model. Load the base model in bfloat16 (not quantized), apply the adapter, and merge:
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
BASE_MODEL = "Qwen/Qwen3-8B-Instruct"
base = AutoModelForCausalLM.from_pretrained(
BASE_MODEL, torch_dtype=torch.bfloat16, device_map="auto"
)
model = PeftModel.from_pretrained(base, "./qlora-adapter")
merged = model.merge_and_unload()
merged.save_pretrained("./merged-model")
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
tokenizer.save_pretrained("./merged-model")
Keep the adapter folder even after merging. It is tiny, and it lets you retrain or combine adapters later without starting over.
Step 7: Serve the Merged Model
The merged folder is a standard Hugging Face model. For GPU serving, follow our vLLM serving guide to expose it behind an OpenAI-compatible API. To run it on a laptop instead, convert the merged model to GGUF with llama.cpp's convert_hf_to_gguf.py (adapter-only exports use convert_lora_to_gguf.py) and follow our GGUF quantization walkthrough. Before spending on hardware, check our hosted vs. self-hosted cost comparison.
Troubleshooting
- Out of memory: drop the per-device batch size to 1, raise gradient accumulation to compensate, shorten
max_length, and keep gradient checkpointing on. Activations and optimizer states, not the 4-bit weights, usually overflow. - Loss is NaN or explodes: drop the learning rate to 1e-4, check that your dataset has no empty or corrupted examples, and confirm the tokenizer's chat template matches the format you trained on.
- The model ignores the fine-tune: usually a chat-template mismatch — your inference prompt must use the same template as training. Also confirm you loaded the adapter and did not test the bare base model.
- Training is very slow: enable packing if your examples are short, raise the batch size if VRAM allows, and save checkpoints at most once per epoch.
- Gated-model access errors: accept the model's license on Hugging Face, then log in with
huggingface-cli loginbefore running the script.
Closing
QLoRA turns fine-tuning from a cluster-sized job into something you can run on one GPU. The recipe is short: a clean dataset in chat format, a 4-bit base model, rank-16 adapters, a 2e-4 learning rate, and a held-out set you actually check. Start with one adapter for one task, measure it on real prompts, then decide whether you need more data, a bigger rank, or a different approach.

Comments
Post a Comment