Most teams never fine-tune. Not because it would not help, but because somewhere along the way they absorbed the idea that fine-tuning means a cluster of 8xA100s, a data team, and a six-figure cloud bill. So they stuff more instructions into the system prompt, bolt on a retrieval pipeline, and quietly accept a model that is 80 percent right on their domain.

That assumption is three years out of date. A 7B model in full precision needs around 14 GB just to hold the weights, and a naive fine-tune needs roughly four times that for gradients and optimizer state. LoRA and QLoRA collapse that number. On a single 24 GB consumer card - a 3090, a 4090, a used A5000 - you can fine-tune a 7B model on your own data over a weekend. I have done it on a 4090 sitting under a desk. This post is the actual recipe: dataset, training loop, evaluation, and the honest list of when it is worth doing.

Why full fine-tuning does not fit

Start with the naive approach and watch it fail, because the failure is what LoRA is designed around.

Full fine-tuning updates every weight in the model. For a 7B model in bf16, the memory budget looks like this:

ComponentFormulaMemory (7B, bf16)
Model weights2 bytes x params~14 GB
Gradients2 bytes x params~14 GB
Adam optimizer state8 bytes x params~56 GB
Activationsdepends on batch and seq len5-20 GB
Total~90-100 GB

Adam keeps two moment estimates per parameter in fp32, and that optimizer state alone is four times the size of the model. You cannot fit 90 GB on a 24 GB card. You cannot fit it on an 80 GB A100 without sharding. This single table is why “fine-tuning needs a research budget” became conventional wisdom. It is correct - for full fine-tuning.

The insight that breaks the assumption: you almost never need to move every weight. A domain adaptation - legal tone, a support voice, a structured output format, a narrow classification task - is a low-rank change. You are nudging the model, not rebuilding it.

LoRA: train a tiny delta instead of the whole model

LoRA (Low-Rank Adaptation) freezes the original weights entirely and injects small trainable matrices beside them. For a weight matrix W of shape (d, k), instead of learning a full update dW, you learn two thin matrices A (d, r) and B (r, k) where the rank r is small - typically 8, 16, or 32. The effective update is their product, scaled.

Original forward pass:        LoRA forward pass:

      W                             W   (frozen)
      |                             |
  x --+--> h                    x --+----------> (+) --> h
                                    |             ^
                                    +--> A --> B --+   (trainable, rank r)

The frozen W never receives gradients. Only A and B train. For a 7B model with rank 16 adapters on the attention projections, you are training roughly 4 to 10 million parameters instead of 7 billion - often less than 0.2 percent of the model. The optimizer state, which was the memory killer, now applies only to those few million parameters. The 56 GB line in the table above drops to a few hundred megabytes.

Because the base weights are untouched, the trained adapter is a small file - tens of megabytes. You can keep one base model in memory and hot-swap adapters for different tasks, which is a genuinely underrated operational property.

QLoRA: quantize the frozen base and free even more VRAM

LoRA shrinks the optimizer and gradient memory but you still hold the full base model. At 14 GB for the frozen weights plus activations plus the adapters, a 7B fine-tune is tight on 24 GB and a 13B is impossible.

QLoRA fixes the last piece. It loads the frozen base model in 4-bit (the NF4 data type, a normal-float quantization tuned for weight distributions), and keeps only the LoRA adapters in bf16. The base is quantized, so it is read-only - exactly what we need, since we never update it anyway. During the forward and backward pass, 4-bit weights are dequantized block by block just in time, used, and discarded.

QLoRA memory on a 24 GB card (7B model):

  4-bit frozen base weights ............ ~4-5 GB
  LoRA adapters (bf16) ................. <0.5 GB
  Optimizer state (adapters only) ...... <0.5 GB
  Activations + gradient checkpointing . 3-8 GB
  --------------------------------------------
  Total ................................ ~9-14 GB

That is a roughly 90 percent cut from the full fine-tune. A 7B QLoRA run leaves headroom on a 24 GB card, and a 13B fits comfortably. The three tricks that make it work are NF4 quantization, double quantization (quantizing the quantization constants themselves to save a bit more), and paged optimizers that offload optimizer state to CPU RAM during memory spikes.

ApproachTrainable paramsVRAM (7B)Quality gap vs full FTFits 24 GB?
Full fine-tune7B (100%)~90 GBbaselineNo
LoRA (bf16 base)~5M (0.07%)~18-20 GBsmallBarely
QLoRA (4-bit base)~5M (0.07%)~10-14 GBsmall to moderateYes, with room

The quality gap between QLoRA and full fine-tuning is real but narrow for most domain-adaptation tasks. The original QLoRA work showed 4-bit adapters matching 16-bit full fine-tuning on instruction-following benchmarks. For a formatting or tone task, you will not notice the difference.

The dataset: format is where most runs go wrong

The model does not learn from a pile of documents. It learns from examples shaped like the task you want at inference time. For instruction tuning, that means prompt-and-response pairs. The most reliable format in 2026 is a chat-style JSONL file, one JSON object per line, with a messages array.

{"messages": [{"role": "system", "content": "You are a support agent for Acme Cloud. Answer in two sentences, cite the relevant doc section."}, {"role": "user", "content": "My deploy is stuck in PENDING for 20 minutes."}, {"role": "assistant", "content": "A deploy stuck in PENDING usually means the build queue is saturated; check Status > Build Queue for your region. If it persists past 30 minutes, cancel and retry, which re-queues at normal priority (see Deploys > Troubleshooting)."}]}
{"messages": [{"role": "system", "content": "You are a support agent for Acme Cloud. Answer in two sentences, cite the relevant doc section."}, {"role": "user", "content": "How do I rotate an API key?"}, {"role": "assistant", "content": "Go to Settings > API Keys, click Rotate next to the key, and confirm; the old key stays valid for a 24-hour grace window. Update your environment variables before the window closes (see Security > Key Rotation)."}]}

A few rules that matter more than the model choice:

  • Match training format to inference format exactly. If you serve with a system prompt, train with one. If the system prompt is constant in production, keep it constant in training so the model does not waste capacity learning its variation.
  • Quality over quantity. For a focused task, 500 to 2,000 clean, consistent examples beat 50,000 noisy ones. The model will faithfully learn your inconsistencies, including the typos and the one labeler who answered in a different voice.
  • Cover the edges. Include refusals, out-of-scope questions, and the awkward cases. If every training answer is confident, the model learns to be confident when it should not be.
  • Hold out a real test split. Pull 10 to 15 percent before training and never let the trainer see it. You will need it for the evaluation step, and a leaked test set makes a bad model look great.

The tokenizer has to apply the model’s chat template so the special tokens line up with what the base was trained on. Use tokenizer.apply_chat_template rather than hand-building the prompt string; getting the turn markers wrong is the single most common reason a fine-tune produces garbage.

The training loop with PEFT

Hugging Face’s PEFT library plus transformers and bitsandbytes is the path of least resistance. The whole thing is maybe 40 lines. Here is a QLoRA setup for a 7B model.

import torch
from datasets import load_dataset
from transformers import (
    AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, TrainingArguments
)
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
from trl import SFTTrainer

MODEL = "mistralai/Mistral-7B-Instruct-v0.3"  # any 7B open model works

# 1. Load the base model in 4-bit (the QLoRA part)
bnb_config = BitsAndBytesConfig(
    load_in_4bit=True,
    bnb_4bit_quant_type="nf4",
    bnb_4bit_compute_dtype=torch.bfloat16,
    bnb_4bit_use_double_quant=True,
)
model = AutoModelForCausalLM.from_pretrained(
    MODEL, quantization_config=bnb_config, device_map="auto"
)
model = prepare_model_for_kbit_training(model)  # enables grad checkpointing, casts norms

tokenizer = AutoTokenizer.from_pretrained(MODEL)
tokenizer.pad_token = tokenizer.eos_token

# 2. Attach LoRA adapters to the attention and MLP projections
lora_config = LoraConfig(
    r=16,                 # rank; 8-32 is the useful range
    lora_alpha=32,        # scaling, commonly 2x the rank
    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"],
)
model = get_peft_model(model, lora_config)
model.print_trainable_parameters()
# -> trainable params: ~42M || all params: ~7.2B || trainable%: ~0.58

# 3. Load the dataset (the JSONL from the previous section)
dataset = load_dataset("json", data_files={"train": "train.jsonl"})

# 4. Train
args = TrainingArguments(
    output_dir="./acme-support-lora",
    per_device_train_batch_size=2,
    gradient_accumulation_steps=8,   # effective batch size 16
    num_train_epochs=3,
    learning_rate=2e-4,              # LoRA tolerates higher LR than full FT
    lr_scheduler_type="cosine",
    warmup_ratio=0.03,
    bf16=True,
    logging_steps=10,
    save_strategy="epoch",
    optim="paged_adamw_8bit",        # paged optimizer, the QLoRA trick
)

trainer = SFTTrainer(
    model=model,
    args=args,
    train_dataset=dataset["train"],
    processing_class=tokenizer,
    max_seq_length=2048,
)
trainer.train()
trainer.model.save_pretrained("./acme-support-lora")  # saves only the adapter

A few knobs are worth understanding rather than copying:

  • Rank (r) and alpha. Higher rank means more capacity and more memory. For tone and format tasks, 8 to 16 is plenty. For teaching genuinely new behavior, 32 or 64. Set lora_alpha to roughly 2x rank as a starting point; it scales how strongly the adapter influences the output.
  • target_modules. Adapting only q_proj and v_proj is the classic minimal LoRA and trains fastest. Including the MLP projections (gate/up/down) gives more capacity and usually better results on real tasks, at a modest memory cost.
  • Learning rate. LoRA runs happily at 1e-4 to 3e-4, far higher than the 1e-5 range full fine-tuning needs, because you are training a small, fresh set of parameters.
  • Epochs. Two to four. Past that, small datasets overfit fast and the model starts parroting training examples verbatim.

On a 4090, a 1,500-example dataset at these settings finishes in well under an hour. That is the whole reason this is a weekend project and not a quarter-long initiative.

Evaluation: prove it beat the base model

This is the step teams skip, and skipping it is how you ship a fine-tune that is worse than where you started. A training loss that goes down tells you the model memorized your data. It does not tell you the model got better. You need to compare the fine-tuned adapter against the base model on your held-out split.

Load the base, then load the base plus adapter, and run both over the test set.

from peft import PeftModel

base = AutoModelForCausalLM.from_pretrained(
    MODEL, quantization_config=bnb_config, device_map="auto"
)
tuned = PeftModel.from_pretrained(base, "./acme-support-lora")

def generate(model, messages):
    prompt = tokenizer.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
    out = model.generate(**inputs, max_new_tokens=200, do_sample=False)
    return tokenizer.decode(out[0][inputs.input_ids.shape[1]:], skip_special_tokens=True)

For scoring, pick the method that matches the task:

  • Deterministic tasks (classification, structured extraction, strict JSON output): exact-match or field-level accuracy on the held-out set. This is the cleanest signal and the easiest to trust.
  • Open-ended tasks (tone, style, support answers): an LLM-as-judge pass. Feed a strong model the input, the base answer, and the tuned answer, ask it to pick the better one against a rubric, and run it blind with the order randomized so the judge cannot favor a position.

A simple pairwise win-rate tells the story. If the tuned model wins 70 percent of head-to-head comparisons against the base, you have something. If it wins 52 percent, the fine-tune did nothing a prompt could not, and you should stop. Always eyeball a dozen outputs by hand too - aggregate metrics hide failure modes like the model learning to always cite a doc section even when none applies.

Watch specifically for regression. A fine-tune that nails your task but forgets how to count or follow basic instructions has overfit. Keep a handful of general-capability prompts in your eval and make sure they did not fall off a cliff.

When fine-tuning actually beats a great system prompt

Fine-tuning is not the first lever. In 2026 a well-built prompt solves most problems, and if the issue is missing knowledge, retrieval is usually the right fix. Fine-tuning earns its place in a specific set of cases. (If you want the full prompting-vs-RAG-vs-fine-tuning trade-off, I wrote a separate decision framework; this section is just the fine-tuning side.)

Fine-tuning wins when:

  • Behavior, not knowledge, is the gap. You need a consistent tone, a house style, or a specific output shape on every single response. A prompt describes the behavior; a fine-tune makes it the default, reliably, without you spending tokens re-explaining it each call.
  • The format is strict and the model keeps drifting. If you need exact JSON or a rigid template and even a careful prompt fails 5 percent of the time, fine-tuning drives that failure rate down hard. Those 5 percent failures are often the expensive ones.
  • The prompt has become enormous. When your system prompt is 3,000 tokens of rules and few-shot examples, you are paying for all of it on every request and still getting inconsistency. Fine-tuning folds that knowledge into the weights, shrinks the prompt, and cuts per-call latency and cost.
  • You need a small model to punch above its weight. A fine-tuned 7B can match a much larger general model on a narrow task, at a fraction of the inference cost. This is the economic case - serve cheap, serve fast, keep it in-house.
  • Latency or privacy rules out a frontier API. On-prem or edge deployment means you are running an open model anyway. Fine-tuning is how you make a small local model good enough.

Fine-tuning loses when the real problem is missing facts (use RAG), when your task changes weekly (you will be retraining constantly), or when you have fewer than a few hundred good examples (not enough signal, and a prompt will do better).

Honest assessment

What works: QLoRA on a single 24 GB GPU is real, cheap, and fast for domain adaptation. The memory math checks out, the tooling is mature, and a focused 7B fine-tune on a clean dataset genuinely outperforms the base model on narrow tasks. The weekend-project framing is not marketing - the training run is the short part.

What does not: the dataset is 80 percent of the work and nobody warns you. Collecting, cleaning, and formatting a few thousand consistent examples takes far longer than the training loop, and a sloppy dataset produces a confidently wrong model. Fine-tuning also does not add knowledge reliably - if you need the model to know new facts, you want retrieval, not a fine-tune that will happily hallucinate around the gaps. And a fine-tuned model is a frozen snapshot; the day your domain shifts, you are back at the dataset.

What to actually do: exhaust prompting first, then retrieval if the gap is knowledge. If the gap is behavior, format, or cost, and you have a few hundred clean examples, spend the weekend. Start with QLoRA at rank 16 on a 7B model, build a real held-out eval before you train anything, and judge the adapter against the base model blind. If it does not win clearly, delete it and go back to the prompt. The barrier to trying was never the hardware - it is that most teams never build the eval that tells them whether it worked.