LoRA fine-tunes an LLM by freezing its original weights and training two small low-rank matrices per layer, usually under 1% of the parameters. QLoRA does the same on a base model compressed to 4-bit NF4, so a 7B model can be tuned on one consumer GPU. Use them for consistent formats and narrow tasks, not for teaching new facts.
Summary: the short version
- Fine-tune only after measuring prompting and retrieval; fine-tuning fixes behaviour (format, tone, task skill), while RAG supplies facts.
- LoRA replaces a full weight update with the product of two thin matrices, B×A, of rank r, scaled by alpha/r; the base model stays frozen.
- QLoRA stores the frozen base in 4-bit NormalFloat (NF4) with double quantization, cutting weight memory to roughly a quarter of 16-bit.
- A few hundred to a few thousand clean, consistent examples in JSONL chat format usually matter more than any hyperparameter.
- Judge a fine-tune against a well-prompted base model on a held-out set; if it does not clearly win, do not ship it.
When should you fine-tune an LLM instead of prompting or using RAG?
Fine-tune when you need consistent behaviour that prompting cannot deliver reliably, such as a strict output format, a house style, or a narrow classification task at high volume; use RAG when the problem is missing or changing facts. This guide is the hands-on LoRA and QLoRA how-to; for the full decision framework, read our comparison of RAG vs fine-tuning. The quick version:
| Approach | Changes | Best for | Data needed | Updating |
|---|---|---|---|---|
| Prompting | Instructions and examples | Most tasks, first attempt | A few examples | Instant |
| RAG | What the model reads | Facts, policies, documents that change | Your documents | Re-index the documents |
| LoRA / QLoRA | Small adapter weights | Format, tone, narrow skills, cheaper small models | Hundreds to thousands of labelled pairs | Retrain the adapter |
| Full fine-tuning | All weights | Large domain shifts, labs with big GPU budgets | Large, curated datasets | Expensive retrain |
A common good reason in Indian companies is control: a small open model tuned for one task can run on your own servers when data cannot leave your environment. If your real problem is facts, start with retrieval-augmented generation (RAG) instead.
Most teams that ask us about fine-tuning do not need it yet. If you have not written a careful prompt with five good examples (see our guide to advanced prompting) and measured it on 50 test cases, you do not know whether fine-tuning will help. Do that first; it takes a day.
What is LoRA and how does it work?
LoRA (Low-Rank Adaptation) freezes the pretrained weight matrix W and learns its update as the product of two small matrices, B and A, so only those small matrices are trained. Hu and colleagues introduced it in 2021, on the observation that the change a model needs for a new task has low "intrinsic rank": it can be described with far fewer numbers than the full matrix. Pretraining (covered in how LLMs are trained) builds W; LoRA only nudges it.
For a d×k weight matrix, LoRA computes h = W·x + (α / r) · B·A·x, where A is r×k, B is d×r, and the rank r is small (often 8 to 64).
Concretely: one attention projection in a 7B-class model is about 4096×4096, or 16.8 million weights. With r = 16, A and B together hold 16 × (4096 + 4096) = 131,072 weights, about 0.8% of the original. B starts at zero, so training begins from exactly the base model's behaviour. B·A can be merged into W after training, so there is no extra inference latency. The LoRA paper reported up to 10,000 times fewer trainable parameters and about three times less GPU memory than full fine-tuning of GPT-3 175B.
How do rank r and alpha affect a LoRA fine-tune?
Rank r sets how much the adapter can learn, and alpha sets how strongly its update is applied, through the scaling factor alpha/r. Higher r means more capacity and memory. Alpha acts like a learning-rate multiplier: doubling it doubles the update for the same weights.
| Setting | Sensible start | When to change it |
|---|---|---|
r | 16 | Drop to 8 for simple format tasks; try 32 to 64 if the model underfits a harder task |
lora_alpha | 2 × r (32 for r = 16) | Keep the ratio fixed while you tune r, or use rsLoRA (alpha/√r) at high ranks |
target_modules | "all-linear" | Restrict to attention projections only if memory is tight |
lora_dropout | 0.05 | Raise to 0.1 on small datasets that overfit |
| Learning rate | 1e-4 to 2e-4 | Lower it if training loss spikes or outputs degrade |
| Epochs | 2 to 3 | Stop earlier if evaluation loss starts rising |
The Hugging Face PEFT LoRA guide notes that adapting all linear layers, as QLoRA does, gets closer to full fine-tuning than attention layers alone.
Change one thing at a time, and change data before hyperparameters. Fixing 50 inconsistent labels usually beats any rank sweep.
What does QLoRA add on top of LoRA?
QLoRA keeps the frozen base model in 4-bit precision instead of 16-bit and trains LoRA adapters on top, so the biggest memory cost, the base weights, shrinks to about a quarter. Dettmers and colleagues introduced it in 2023 with three ideas:
- 4-bit NormalFloat (NF4): a 4-bit data type designed for neural network weights, which are roughly normally distributed.
- Double quantization: the scaling constants used for quantization are themselves quantized, saving a little more memory.
- Paged optimizers: optimizer state can spill to CPU memory to survive memory spikes.
Computation still happens in 16-bit: weights are de-quantized on the fly, and gradients flow through them into the 16-bit adapters. The QLoRA paper fine-tuned a 65B model on a single 48 GB GPU and reported task performance matching full 16-bit fine-tuning in its experiments. The trade-off is speed: de-quantizing costs time, so QLoRA runs slower per step than LoRA on a 16-bit base. Use QLoRA when memory is the constraint and LoRA when it is not.
How much GPU memory do you need for LoRA and QLoRA?
For a 7B model, rough arithmetic puts full fine-tuning above 100 GB, LoRA around 15 GB and QLoRA around 5 GB before activations, which add a few GB more depending on sequence length and batch size.
In practice, QLoRA on a 7B model with short sequences fits a 16 GB T4 on cloud notebooks, and LoRA on a 7B model is comfortable on a 24 GB card. For learning, start with a 1B to 3B model: same workflow, much faster.
How should you prepare training data for fine-tuning?
Write one JSON object per line, each holding a short conversation in the chat format (system, user, assistant), where the assistant turn is exactly the output you want the model to learn. TRL applies the model's chat template automatically when it sees a messages field.
{"messages": [{"role": "system", "content": "Convert the collections call note into JSON with keys intent, promise_date, amount_promised, language, next_action."}, {"role": "user", "content": "Cust ne bola 15 tareekh tak 12,000 bhej dega, salary late hai. Callback 16 ko."}, {"role": "assistant", "content": "{\"intent\": \"promise_to_pay\", \"promise_date\": \"15\", \"amount_promised\": 12000, \"language\": \"hinglish\", \"next_action\": \"callback on 16th\"}"}]}
{"messages": [{"role": "system", "content": "Convert the collections call note into JSON with keys intent, promise_date, amount_promised, language, next_action."}, {"role": "user", "content": "Customer disputes the late fee, wants branch visit. No payment commitment."}, {"role": "assistant", "content": "{\"intent\": \"dispute\", \"promise_date\": null, \"amount_promised\": null, \"language\": \"english\", \"next_action\": \"escalate fee dispute to branch\"}"}]}- Consistency beats volume. If two annotators format dates differently, the model learns both. Write a one-page labelling guide first.
- Cover the hard cases. Disputes, partial payments, Hinglish, missing information: the model only handles what it has seen.
- Hold out an evaluation set of 10 to 20% that never touches training, and deduplicate across the split.
- Mask personal data. Under the DPDP Act 2023, training on customer notes needs a lawful basis and clear purpose; replace names, phone and account numbers with placeholders.
Validate the file before spending GPU time:
import json
import sys
from collections import Counter
REQUIRED_KEYS = {"intent", "promise_date", "amount_promised", "language", "next_action"}
def check(path: str) -> Counter:
problems, seen = Counter(), set()
with open(path, encoding="utf-8") as f:
for line in f:
record = json.loads(line)
messages = record.get("messages", [])
if not messages or messages[-1]["role"] != "assistant":
problems["last turn is not the assistant"] += 1
continue
if any(m["role"] not in {"system", "user", "assistant"} for m in messages):
problems["unknown role"] += 1
key = messages[-2]["content"].strip().lower()
if key in seen:
problems["duplicate input"] += 1
seen.add(key)
try:
target = json.loads(messages[-1]["content"])
if set(target) != REQUIRED_KEYS:
problems["wrong JSON keys"] += 1
except json.JSONDecodeError:
problems["target is not valid JSON"] += 1
return problems
if __name__ == "__main__":
print(check(sys.argv[1]) or "No problems found")How do you fine-tune a model with Hugging Face PEFT and TRL?
Load the base model in 4-bit with BitsAndBytesConfig, describe the adapter with a LoraConfig, and pass both to TRL's SFTTrainer with an SFTConfig. The script below is QLoRA on a small instruct model and runs on a single CUDA GPU.
# pip install -U torch transformers peft trl datasets accelerate bitsandbytes
import torch
from datasets import load_dataset
from peft import LoraConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" # any small instruct model whose licence fits your use
use_bf16 = torch.cuda.get_device_capability()[0] >= 8 # Ampere or newer (A100, L4, RTX 30xx+); a T4 is 7.5
compute_dtype = torch.bfloat16 if use_bf16 else torch.float16
# QLoRA part 1: load the frozen base model in 4-bit NF4
bnb_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)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID, quantization_config=bnb_config, dtype=compute_dtype, device_map="auto"
) # dtype sets the non-quantized layers; transformers older than 4.56 call it torch_dtype
# QLoRA part 2: small trainable LoRA adapters on every linear layer
lora_config = LoraConfig(
r=16,
lora_alpha=32,
lora_dropout=0.05,
target_modules="all-linear",
task_type="CAUSAL_LM",
)
data = load_dataset("json", data_files={"train": "train.jsonl", "eval": "eval.jsonl"})
args = SFTConfig(
output_dir="callnotes-qlora",
num_train_epochs=3,
per_device_train_batch_size=4,
gradient_accumulation_steps=4, # effective batch size 16
learning_rate=2e-4, # adapters tolerate a higher LR than full fine-tuning
lr_scheduler_type="cosine",
warmup_steps=10,
optim="paged_adamw_8bit", # QLoRA part 3: paged optimizer survives memory spikes
max_length=1024,
logging_steps=10,
eval_strategy="epoch",
save_strategy="epoch",
bf16=use_bf16,
fp16=not use_bf16,
gradient_checkpointing=True,
report_to="none",
)
trainer = SFTTrainer(
model=model,
args=args,
train_dataset=data["train"],
eval_dataset=data["eval"],
processing_class=tokenizer,
peft_config=lora_config,
)
trainer.model.print_trainable_parameters()
trainer.train()
trainer.save_model("callnotes-qlora/adapter") # saves only the adapter, a few MB to tens of MBVersion notes, as of November 2026: this follows the current TRL SFTTrainer documentation (TRL 1.x, checked against 1.17) and the Transformers bitsandbytes guide. The tokenizer is passed as processing_class and the sequence cap is max_length; older tutorials use tokenizer= and max_seq_length=, which now fail. SFTConfig turns gradient checkpointing on by default, and 4-bit loading in this script assumes an NVIDIA GPU. If you want loss computed only on the assistant's reply, look at assistant_only_loss=True in SFTConfig, which depends on the model's chat template supporting it.
To use the adapter, load the base model, attach the adapter and generate:
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
# transformers older than 4.56 call this argument torch_dtype; use float16 on a T4
base = AutoModelForCausalLM.from_pretrained(MODEL_ID, dtype=torch.bfloat16, device_map="auto")
model = PeftModel.from_pretrained(base, "callnotes-qlora/adapter") # base + adapter
model.eval()
messages = [
{"role": "system", "content": "Convert the collections call note into JSON with keys "
"intent, promise_date, amount_promised, language, next_action."},
{"role": "user", "content": "Customer bola 20 ko 8,500 dega, baaki next month. Reminder SMS bhejo."},
]
inputs = tokenizer.apply_chat_template(
messages, add_generation_prompt=True, return_tensors="pt", return_dict=True
).to(model.device)
with torch.no_grad():
output = model.generate(**inputs, max_new_tokens=200, do_sample=False)
print(tokenizer.decode(output[0][inputs["input_ids"].shape[-1]:], skip_special_tokens=True))How do you evaluate a fine-tuned LLM?
Run the fine-tuned model, the base model with your best prompt, and ideally a larger hosted model on the same held-out set, and score them with task-specific metrics you agreed before training. Falling training loss only proves the model learned the training format.
| What to measure | How | Why it matters |
|---|---|---|
| Format validity | Share of outputs that parse as JSON with the right keys | Usually the first win from fine-tuning |
| Field accuracy | Exact match per field against labels | Tells you where the model still guesses |
| Hard-case accuracy | Same metrics on a tagged slice (disputes, Hinglish) | Averages hide the cases that hurt |
| General ability | A few unrelated prompts before and after | Catches the model forgetting other skills |
| Cost and latency | Tokens and milliseconds per request | Often the real business case |
Our guide to evaluating LLM applications includes a reusable harness for exactly this comparison.
Worked example: should a Bengaluru NBFC fine-tune for collections call notes?
Yes, if a well-prompted base model fails the format and Hinglish cases on a held-out test and the data cannot leave the company's servers. Consider a mid-sized NBFC in Bengaluru whose collections agents type short notes in mixed Hindi and English after every call. Managers want each note turned into JSON (intent, promise date, amount promised, language, next action) for daily follow-up lists, the kind of structured input a collections agent like the one in our guide to agentic AI depends on.
A sensible path, with illustrative numbers:
- Prompt a hosted model with five examples; score 100 held-out notes.
- Find the failures: wrong JSON keys, missed amounts written as "8.5k", Hinglish dates.
- Label 1,500 masked notes with a one-page guide; validate with check_jsonl.py.
- QLoRA-tune a small open model with r = 16, alpha = 32, three epochs.
- Compare both on the same 100 notes and the Hinglish slice; ship only on a clear win.
Rough training arithmetic: 1,500 examples at about 250 tokens each is roughly 375,000 tokens per epoch, a little over a million across three epochs. On a single modern GPU, a 1.5B model finishes well within an hour. The expensive parts are labelling and the evaluation set, not the GPU. In the LoRA/QLoRA labs of Ivy Professional School's Advanced Generative AI course, the learners who get the best results spend most of their time on the labelling guide; the training script is the quick part.
What is a sensible first fine-tuning project checklist?
Treat it as an experiment with a pass mark, not a default.
- Write down the behaviour you want and the metric that proves it.
- Build a 100-example held-out set and score your best prompt on it first.
- Draft a labelling guide and label 300 to 1,500 examples, masking personal data.
- Validate the JSONL, deduplicate, and split train and evaluation sets.
- Run QLoRA on a 1B to 3B model with r = 16 and alpha = 32 as a baseline.
- Compare against the prompted base model on the full set and on hard slices.
- Version the adapter, data and config together.
Frequently asked questions
What is the difference between LoRA and QLoRA?
Both freeze the base model and train small low-rank adapter matrices. LoRA keeps the frozen base in 16-bit precision. QLoRA stores it in 4-bit NF4 with double quantization, cutting weight memory to about a quarter, so larger models fit on smaller GPUs. QLoRA is slower per step because weights are de-quantized during computation.
How many examples do I need to fine-tune an LLM with LoRA?
For a narrow format or classification task, a few hundred consistent, high-quality examples often show clear gains, and one to a few thousand is a common working range. Quality and coverage of hard cases matter more than raw count. Keep a separate held-out set to measure the gain.
Can fine-tuning teach an LLM new facts?
Poorly. Fine-tuning with LoRA reliably changes behaviour such as format, tone and task skill, but it is an unreliable way to store facts and costly to update. For company policies, product data or anything that changes, use retrieval-augmented generation and keep the documents current.
What rank and alpha should I use for LoRA?
A common starting point is rank 16 with alpha 32, applied to all linear layers, a learning rate around 1e-4 to 2e-4, and two to three epochs. Lower the rank for simple tasks and raise it if the model underfits. Change one setting at a time and judge by held-out metrics.
Can I fine-tune an LLM on Google Colab?
Yes, for small models. QLoRA on a 1B to 3B model, and on a 7B model with short sequences, can fit in the 16 GB of a T4 GPU. A T4 does not support bfloat16, so train in float16. Sessions can time out, so save checkpoints regularly.
Sources
- Hu, E. J. et al. "LoRA: Low-Rank Adaptation of Large Language Models." 2021. https://arxiv.org/abs/2106.09685
- Dettmers, T. et al. "QLoRA: Efficient Finetuning of Quantized LLMs." 2023. https://arxiv.org/abs/2305.14314
- Hugging Face. "LoRA" developer guide, PEFT documentation. https://huggingface.co/docs/peft/developer_guides/lora
- Hugging Face. "SFT Trainer," TRL documentation. https://huggingface.co/docs/trl/sft_trainer
- Hugging Face. "bitsandbytes" quantization guide, Transformers documentation. https://huggingface.co/docs/transformers/quantization/bitsandbytes

By