Fine-Tuning Open-Source LLMs with LoRA and QLoRA: A Developer's Field Guide A developer published a field guide to fine-tuning open-source LLMs with LoRA and QLoRA, arguing that QLoRA's 4-bit NF4 quantization cuts VRAM roughly 4x, letting a 7B model train in about 6-8GB on a consumer RTX 3060. The guide recommends QLoRA for models under 13B parameters, LoRA in fp16 when quality matters most, and warns that fine-tuning teaches behavior and format rather than new facts, for which RAG is the better tool. The first time you fine-tune a 7B model on your own dataset, you realize something interesting. You don't need a $20,000 GPU anymore. You don't even need a $2,000 GPU if you're willing to let it train overnight. QLoRA quietly rewrote the economics of model customization more than any paper I've read in the last three years, and yet most teams I talk to still default to prompt engineering or pay-per-call fine-tuning APIs without even trying it on their own hardware. This is the guide I wish I'd had when I bricked my first Llama 2 checkpoint by saving it wrong. We're going to go from a messy JSONL file to a merged, deployable model. I'll show you every pothole along the way, because most of them don't show up in the HuggingFace docs. Let's get the obvious out of the way. If your problem is "I want GPT-4 quality answers," fine-tuning a 7B model won't get you there. Fine-tuning is not magic. What it is, is a way to teach a model your domain's vocabulary, your output format, your style, and your specific reasoning patterns-without paying per token forever. The four scenarios where fine-tuning actually wins: Where fine-tuning fails: injecting new factual knowledge. If you want the model to know your docs, use RAG. Fine-tuning teaches behavior, not facts. I've seen teams spend weeks fine-tuning a model on their wiki, only to discover it confidently hallucinates policy numbers. Use the right tool. Quick refresher for anyone who's been ignoring the PEFT literature. LoRA Low-Rank Adaptation freezes the original model weights and trains a small set of "adapter" weights-low-rank decompositions of the weight deltas. Train 0.5-2% of the parameters, get 95%+ of the fine-tune quality. The base model stays untouched, the adapter is a few hundred MB instead of 14GB, and you can hot-swap adapters at inference time. QLoRA is LoRA with one extra trick: the base model is loaded in 4-bit precision using bitsandbytes 's NF4 quantization before the LoRA adapters are trained on top in full precision. This drops VRAM requirements by roughly 4x. A Llama-2-7B that needs ~28GB in fp16 for full fine-tuning, or ~14GB for LoRA, trains in about 6-8GB with QLoRA. That's a 7B model fitting on a consumer RTX 3060. | Approach | Trainable Params | VRAM 7B model | Adapter Size | Quality vs full FT | Use When | |---|---|---|---|---|---| | Full fine-tuning | 100% | 80GB+ | 14GB full model | 100% baseline | You have A100s and a real budget | | LoRA fp16 | 0.5-2% | 14-20GB | 50-500MB | 92-98% | You have a 16GB+ GPU | | QLoRA 4-bit | 0.5-2% | 6-10GB | 50-500MB | 90-96% | Consumer GPU or free Colab | | Prompt tuning | 0.01% | 4-8GB | <1MB | 70-85% | Quick experiments, weak results | My default: QLoRA for everything under 13B parameters, LoRA in fp16 if I have an A100 and care about every last percent of quality. Full fine-tuning only when I'm training a foundation model for release. You'll need: bitsandbytes is still rough as of late 2024. If you're on a free Colab T4, you can train a 7B with QLoRA. I've done it. It's slow but it works. Create a fresh venv. Don't pollute your system Python- bitsandbytes and accelerate versions are picky and you'll thank yourself later. BashCopy python -m venv .venv source .venv/bin/activate pip install --upgrade pip pip install "torch==2.4.0" --index-url https://download.pytorch.org/whl/cu121 https://download.pytorch.org/whl/cu121 pip install "transformers==4.44.2" "datasets==2.21.0" "peft==0.12.0" "trl==0.9.6" "accelerate==0.34.2" "bitsandbytes==0.43.3" pip install "wandb" "evaluate" "sentencepiece" "protobuf" Pin your versions. I cannot stress this enough. The HuggingFace stack moves fast and breaks things. I once lost two days because trl 0.10 silently renamed SFTTrainer arguments between patch versions. Pin everything, commit your requirements.txt . txtCopy plaintext torch==2.4.0 transformers==4.44.2 datasets==2.21.0 peft==0.12.0 trl==0.9.6 accelerate==0.34.2 bitsandbytes==0.43.3 wandb==0.17.9 sentencepiece==0.2.0 protobuf==5.28.2 Verify bitsandbytes sees CUDA: BashCopy python python -c "import bitsandbytes as bnb; import torch; print bnb. version ; print torch.cuda.is available " markdown If you get False on CUDA availability or a RuntimeError: CUDA Setup failed , your CUDA toolkit version doesn't match the PyTorch wheel. Go back and match them. This is the single most common install failure I see. Models are easy. Data is hard. I've reviewed dozens of fine-tuning projects and the failure mode is almost always the same: someone scraped 50,000 examples, didn't look at them, trained for 3 epochs, and shipped a model that "feels smarter" but actually regressed on key tasks. For supervised fine-tuning SFT , use a chat-formatted JSONL. Each line is one conversation: JSONCopy json {"messages": {"role": "system", "content": "You are a concise technical writer."}, {"role": "user", "content": "Explain what a mutex is."}, {"role": "assistant", "content": "A mutex is a synchronization primitive..."} } If your model uses a specific chat template Llama 3, ChatML, Mistral , match it. We'll handle the templating during tokenization-don't pre-format strings by hand, it's a recipe for subtle bugs. Here's a real dataset prep script I use. It deduplicates, filters by length, and shuffles: PythonCopy python import json import random from pathlib import Path INPUT PATH = Path "data/raw conversations.jsonl" OUTPUT PATH = Path "data/train.jsonl" VALIDATION PATH = Path "data/val.jsonl" VAL FRACTION = 0.05 MIN ASSISTANT TOKENS = 20 MAX ASSISTANT TOKENS = 2048 def load examples path : examples = with path.open as f: for i, line in enumerate f : line = line.strip if not line: continue try: ex = json.loads line except json.JSONDecodeError: print f"Skipping malformed line {i}" continue if not is valid ex : continue examples.append ex return examples def is valid ex : if "messages" not in ex or len ex "messages" < 2: return False roles = m "role" for m in ex "messages" if roles -1 = "assistant": return False assistant text = ex "messages" -1 "content" token estimate = len assistant text // 4 rough: 4 chars/token if not MIN ASSISTANT TOKENS <= token estimate <= MAX ASSISTANT TOKENS : return False if any not m.get "content", "" .strip for m in ex "messages" : return False return True def dedupe examples : seen = set out = for ex in examples: key = json.dumps ex, sort keys=True if key in seen: continue seen.add key out.append ex return out def main : examples = load examples INPUT PATH print f"Loaded {len examples } examples" examples = dedupe examples print f"After dedupe: {len examples }" random.seed 42 random.shuffle examples n val = max 1, int len examples VAL FRACTION val = examples :n val train = examples n val: OUTPUT PATH.parent.mkdir parents=True, exist ok=True with OUTPUT PATH.open "w" as f: for ex in train: f.write json.dumps ex, ensure ascii=False + "\n" with VALIDATION PATH.open "w" as f: for ex in val: f.write json.dumps ex, ensure ascii=False + "\n" print f"Wrote {len train } train, {len val } val" if name == " main ": main Look at your data. I mean it. Sample 20 examples, read them aloud, ask "would I want the model to imitate this?" If the answer is no, your fine-tune will faithfully reproduce the bad behavior. Garbage in, garbage out, but with extra confidence. Now the actual code. We'll load a Llama-3.1-8B-Instruct in 4-bit and attach a LoRA adapter. PythonCopy import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, from peft import LoraConfig, get peft model, prepare model for kbit training from datasets import load dataset from trl import SFTTrainer, SFTConfig MODEL ID = "meta-llama/Llama-3.1-8B-Instruct" TRAIN FILE = "data/train.jsonl" VAL FILE = "data/val.jsonl" OUTPUT DIR = "outputs/llama31-8b-sft" ADAPTER DIR = "outputs/llama31-8b-sft/adapter" def build bnb config : return BitsAndBytesConfig load in 4bit=True, bnb 4bit quant type="nf4", bnb 4bit compute dtype=torch.bfloat16, bnb 4bit use double quant=True, def load model and tokenizer : bnb config = build bnb config tokenizer = AutoTokenizer.from pretrained MODEL ID, trust remote code=True if tokenizer.pad token is None: tokenizer.pad token = tokenizer.eos token model = AutoModelForCausalLM.from pretrained MODEL ID, quantization config=bnb config, device map="auto", trust remote code=True, torch dtype=torch.bfloat16, model = prepare model for kbit training model return model, tokenizer if name == " main ": model, tokenizer = load model and tokenizer print f"Model loaded. VRAM: {torch.cuda.memory allocated / 1e9:.2f} GB" A few non-obvious choices: nf4 over fp4 . bnb 4bit use double quant=True . bnb 4bit compute dtype=torch.bfloat16 . prepare model for kbit training . The LoRA config is where you make the quality vs. speed trade-off. Higher rank = more capacity = more VRAM. PythonCopy def build lora config : return 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", , def train : model, tokenizer = load model and tokenizer lora config = build lora config model = get peft model model, lora config model.print trainable parameters Expect: trainable params: ~40M / 8B 0.5% dataset = load dataset "json", data files={"train": TRAIN FILE, "validation": VAL FILE}, sft config = SFTConfig output dir=OUTPUT DIR, num train epochs=3, per device train batch size=2, gradient accumulation steps=8, effective batch = 16 gradient checkpointing=True, gradient checkpointing kwargs={"use reentrant": False}, optim="adamw torch", learning rate=2e-4, lr scheduler type="cosine", warmup ratio=0.03, weight decay=0.0, max grad norm=0.3, logging steps=10, save strategy="epoch", eval strategy="epoch", save total limit=3, bf16=True, report to="wandb", run name="llama31-8b-sft-v1", max seq length=2048, packing=True, trainer = SFTTrainer model=model, args=sft config, train dataset=dataset "train" , eval dataset=dataset "validation" , tokenizer=tokenizer, trainer.train trainer.save model ADAPTER DIR tokenizer.save pretrained ADAPTER DIR print f"Adapter saved to {ADAPTER DIR}" if name == " main ": train Key knobs and why they matter: r=16, lora alpha=32 . target modules includes all linear layers. learning rate=2e-4 . packing=True . max seq length=2048 . Adapters are great for swapping, but for deployment you usually want one merged model. PythonCopy import torch from transformers import AutoModelForCausalLM, AutoTokenizer from peft import PeftModel BASE MODEL = "meta-llama/Llama-3.1-8B-Instruct" ADAPTER PATH = "outputs/llama31-8b-sft/adapter" MERGED PATH = "outputs/llama31-8b-sft/merged" def merge : base = AutoModelForCausalLM.from pretrained BASE MODEL, torch dtype=torch.bfloat16, device map="cpu", merge on CPU to avoid VRAM issues tokenizer = AutoTokenizer.from pretrained BASE MODEL model = PeftModel.from pretrained base, ADAPTER PATH model = model.merge and unload model.save pretrained MERGED PATH, safe serialization=True, max shard size="4GB" tokenizer.save pretrained MERGED PATH print f"Merged model saved to {MERGED PATH}" if name == " main ": merge Merge on CPU. The merged model is full fp16/bf16 size, so you need enough system RAM 16GB+ for a 7B . Merging on GPU is a recipe for OOM. After this, you have a standalone model directory you can quantize to GGUF https://mangodeveloper.com/articles/how-to-upgrade-llama-cpp-v1-0-0-run-gguf-models-windows-ml , serve with vLLM, or push to the Hub. PythonCopy MODEL PATH = "outputs/llama31-8b-sft/merged" def main : tokenizer = AutoTokenizer.from pretrained MODEL PATH model = AutoModelForCausalLM.from pretrained MODEL PATH, torch dtype=torch.bfloat16, device map="auto", messages = {"role": "system", "content": "You are a concise technical writer."}, {"role": "user", "content": "Explain what a mutex is in two sentences."}, prompt = tokenizer.apply chat template messages, tokenize=False, add generation prompt=True inputs = tokenizer prompt, return tensors="pt" .to model.device with torch.no grad : out = model.generate inputs, max new tokens=256, do sample=True, temperature=0.7, top p=0.9, repetition penalty=1.05, response = tokenizer.decode out 0 inputs "input ids" .shape 1 : , skip special tokens=True, print response Run this before you even think about deploying. If the output looks wrong here, it'll look wrong in production-but worse, because prod has no humans watching. Deployment. Don't serve fine-tuned models with raw transformers . Use vLLM 10-20x throughput or, for CPU/edge, llama.cpp with a GGUF conversion. I deploy with vLLM in Docker on a single L4 or A10, and that comfortably serves 50-100 RPS for an 8B model. Quantization for serving. After merging, quantize to 8-bit AWQ or GPTQ for ~2x throughput at minimal quality loss. GGUF Q8 0 is fine for CPU. I avoid 4-bit for serving unless I'm seriously VRAM-constrained-the quality drop on fine-tuned models can be more noticeable than on base models. Versioning. Every adapter gets a version tag and a git commit with the training data hash. When a model regresses in prod, you need to know what data and config produced it. Use DVC or just commit data diffs to a separate repo. Evaluation. Build a held-out eval set of 50-200 prompts with reference answers. Run it after every fine-tune. Measure pass@1 for code tasks, BLEU/ROUGE for generation with a grain of salt , and-most importantly-human review on a sample. I use lm-evaluation-harness for standardized benchmarks. Caching. At inference time, cache by model version, prompt hash in Redis. Fine-tuned models are deterministic at temperature=0. Don't recompute identical prompts. Monitoring. Log every prompt and response with PII scrubbing . Watch for: response length drift model degrading , repetition a classic overfit symptom , and out-of-domain queries your fine-tune might break on inputs it never saw . Multi-adapter serving. If you have multiple fine-tunes for different customers, vLLM and LoRAX support hot-swapping LoRA adapters at inference time. Don't spin up separate model servers per customer-that's 14GB of VRAM per tenant. Mistake: Catastrophic forgetting. Model gets great at the new task but loses general capability. Cause: too many epochs, too high a learning rate, or training data too narrow. Detect: run a general benchmark MMLU, MT-Bench before and after. Fix: fewer epochs 2-3 max , lower LR, mix in 10-20% general instruction data. Mistake: Training on the system prompt. If your dataset includes the system message in every example and you compute loss on it, the model learns to produce system messages. Cause: not masking the prompt tokens. Detect: model outputs <|system| tokens unprompted. Fix: use SFTTrainer with the messages format-it masks correctly. If you're tokenizing manually, set labels to -100 for non-assistant tokens. Mistake: Tokenizer mismatch. You trained with one chat template, serve with another. Cause: apply chat template defaults differ across model versions. Detect: model output is gibberish or starts with stray tokens. Fix: pin the tokenizer version, save it with the adapter, and verify the template matches at inference. Mistake: Forgetting pad token . Llama tokenizers don't have a default pad token. Cause: legacy. Detect: AttributeError or silent wrong batching. Fix: set tokenizer.pad token = tokenizer.eos token and model.config.pad token id = tokenizer.eos token id . Mistake: OOM at save time. Training is fine, saving crashes. Cause: save pretrained tries to materialize fp32 weights. Fix: use safe serialization=True and torch dtype explicitly. Or save on CPU. Mistake: Training on truncated examples. Your max seq length=2048 but examples are 3000 tokens. The end gets cut off, including the assistant response. Cause: not filtering by length in data prep. Detect: model generates incomplete answers. Fix: filter pre-training, or increase max seq length with the VRAM cost . RuntimeError: CUDA out of memory during backward pass. VRAM spikes during backward. Lower per device train batch size to 1, increase gradient accumulation steps . Enable gradient checkpointing=True . If still OOM, lower max seq length . Last resort: lower LoRA r . Loss is NaN after a few steps. Almost always fp16 overflow. Switch to bf16=True Ampere+ GPUs or use fp16=True with max grad norm=0.3 and a lower LR. If you're on an older GPU without bf16 support, you're in for a bad time-consider QLoRA with bnb 4bit compute dtype=torch.float16 and aggressive gradient clipping. Validation loss decreases then sharply increases. Classic overfitting. You're training too long. Cut epochs to 2, add lora dropout=0.1 , mix in general data. Model produces repetitive output. Either overfit see above or repetition penalty too low at inference. Try repetition penalty=1.1-1.3 . If it persists, your training data probably has repetition-dedupe harder. Training is painfully slow. Check: gradient checkpointing=True slows ~20%, saves VRAM-worth it . packing=True for short examples. dataloader num workers=4 . Use flash attention 2 if installed pip install flash-attn --no-build-isolation . AttributeError: 'NoneType' object has no attribute '...' in TRL. Version mismatch. trl 0.9 vs 0.10 have breaking API changes. Pin to one version, read that version's docs. Rough numbers as of late 2024, for fine-tuning a 7B model with QLoRA on 5,000 examples, 3 epochs: The economics flip at scale. Once you have the GPU and the pipeline, fine-tuning your own 7B is nearly free per iteration. API fine-tuning charges you every time. | Option | One-time cost | Per-iteration cost | You own the model? | Quality ceiling | |---|---|---|---|---| | QLoRA on rented A10 | $0 script | ~$5 | Yes | 7B/13B model quality | | Full FT on A100 80GB | $0 script | ~$20-50 | Yes | Higher, especially for 70B | | OpenAI GPT-4o-mini FT | $0 | ~$7 per 5K ex | No | GPT-4o-mini class | | Anthropic fine-tuning | $0 | Varies | No | Claude class | {category, urgency, suggested owner} . 92% accuracy vs 78% zero-shot. Fine-tuning open-source https://mangodeveloper.com/category/dev LLMs with QLoRA is one of the highest-leverage skills in modern ML engineering. The barrier to entry has collapsed-what used to require a cluster now runs on a consumer GPU overnight. The actual ML is maybe 20% of the work. The other 80% is data prep, eval, and deployment. Get those right and the model part mostly takes care of itself. If you take one thing from this guide: build your eval set before you train. Not after. Before. If you don't have a way to measure whether your fine-tune is better, you're just vibes-tuning. Originally published on Mango Developer https://mangodeveloper.com/articles/fine-tune-llm-lora-qlora .