# Fine-Tuning Open-Source LLMs with LoRA and QLoRA: A Developer's Field Guide

> Source: <https://dev.to/mango7777/fine-tuning-open-source-llms-with-lora-and-qlora-a-developers-field-guide-b2a>
> Published: 2026-11-27 19:30:00+00:00

**Recommendation:** Use QLoRA for fine-tuning models under 13B on consumer GPUs, and pin your transformers, peft, trl and bitsandbytes versions to avoid silent API breaks.
More in the playbook "Fine-tuning and data": <https://wpnews.pro/playbooks/training-data>

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).
