Polski

Article · Fine-tuning · Local LLMs

Fine-tuning language models: when it pays off, LoRA and QLoRA in practice

How fine-tuning differs from prompting and RAG, when it really makes sense, how to prepare data, how LoRA and QLoRA work and how to measure whether the tuned model is better – with code in Python, TypeScript and C#.

By · · 15 min read

Fine-tuning is further training of an existing model on your examples – you change its weights, not just its instructions. It sounds like the most powerful tool in the box, which is exactly why it gets overused: most problems teams try to solve with it are solved better and cheaper with a good prompt or RAG. This article shows when fine-tuning pays off, how to do it cheaply (LoRA, QLoRA) and how to check the result honestly.

< 1%
of parameters are trained by LoRA – the rest of the model stays frozen
48 GB
one card was enough to fine-tune a 65B model – a result from the QLoRA paper (2023)
3
levers to try before fine-tuning – prompt, examples in the prompt, RAG

The problem: two ideas, one good

Halina's Pierogi team has two fine-tuning ideas:

  1. "Let's teach the model our menu and terms" – so the assistant knows every dish, price and refund rule.
  2. A complaint classifier on a small local model – complaints contain personal data, so they must be processed on our own server (see Local LLMs). An 8B model with a prompt containing 40 examples works, but it is slow, and one answer in ten has broken JSON.

The first idea is a classic mistake: the menu changes every week, and a model tuned on last week's menu will confidently quote old prices – and still hallucinate details. Knowledge that changes and must be exact belongs in the context (RAG), not in the weights. The second idea is a textbook case for fine-tuning: a narrow, repetitive task, a fixed output format and the need for a small, fast model.

Prompt, RAG or fine-tuning?

LeverWhat it changesCost of a changeWhen
Prompt and examples (few-shot)instructions and format in the contextminutesalways, to start
RAGknowledge available in a given calldayscompany facts, changing data, citing sources
Tools (tool use)access to current data and actionsdaysorder status, calculations, external systems
Fine-tuningweights: style, format, a narrow skillweeks (data + training + evaluation)a stable task, a small model, a long prompt to shorten
Diagram: Decision tree: fine-tuning only when cheaper levers are not enough

It is also worth knowing where fine-tuning is available at all. Some providers offer tuning of their models through an API or cloud platforms; the Claude API does not offer self-serve fine-tuning, so for Claude models the main levers are prompts, examples, RAG and tools. Full control comes from tuning open models (Llama, Qwen, Gemma, Mistral) with libraries from the Hugging Face ecosystem.

How LoRA works

Full fine-tuning updates all the model's weights – for 8 billion parameters you need memory for the weights, gradients and optimizer states, which comes to well over 100 GB. LoRA (Low-Rank Adaptation, Hu et al., 2021) freezes the original weights and adds to selected matrices a correction in the form of a product of two narrow matrices: W' = W + B·A, where B is d×r and A is r×k, with a small rank r (e.g. 8–64).

For a 4096×4096 matrix, a full update is about 16.8 million parameters, while LoRA with r = 16 is only 16·(4096 + 4096) = 131,072, or about 0.8%. The resulting adapter weighs a few to a few dozen megabytes; you can keep it separate, swap it per task or merge it into the base model.

QLoRA (Dettmers et al., 2023) goes a step further: it loads the frozen base model in 4 bits (the NF4 format) and trains only the adapters at higher precision. This makes tuning models with several to a dozen or so billion parameters fit on a single consumer card.

Approximate GPU memory to fine-tune an 8B model – Illustrative estimate without activations and KV cache: full fine-tuning ≈ 16 bytes/parameter (weights, gradients, Adam states), LoRA on an FP16 base ≈ weights + adapters, QLoRA ≈ 4-bit weights + adapters. Real usage depends on sequence length and batch size.
GPU memory
Full fine-tuning128 GB
LoRA (FP16 base)18 GB
QLoRA (4-bit base)7 GB

Data: this is where you win or lose

The model learns exactly what you show it – including label errors. A few rules:

  • Chat format (JSONL with a messages field) – the same role layout as in production: system prompt, user message, expected assistant answer.
  • Quality over quantity. A few hundred consistently labelled examples usually give more than a few thousand sloppy ones. Two people labelling the same sample should agree – if they don't, fix the category definitions.
  • Coverage of hard cases – rare categories, ambiguous complaints, messages in English, "this is not a complaint" examples.
  • No personal data. A model can memorize fragments of its training data and repeat them. Mask phone numbers, addresses and names before training.
  • A control set held out before training – it never goes into training and is used to compare models.

Preparing training data

prepare_data.py
import json
import random
import re

SYSTEM = "Classify the complaint. Reply with JSON: {\"category\": ..., \"urgent\": true|false}."
PHONE = re.compile(r"\b\d{3}[ -]?\d{3}[ -]?\d{3}\b")

def to_example(row: dict) -> dict:
    text = PHONE.sub("[PHONE]", row["text"])  # never train on personal data
    answer = json.dumps({"category": row["category"], "urgent": row["urgent"]})
    return {"messages": [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": text},
        {"role": "assistant", "content": answer},
    ]}

rows = [json.loads(line) for line in open("labeled_complaints.jsonl", encoding="utf-8")]
unique = list({r["text"].strip().lower(): r for r in rows}.values())  # drop duplicates
random.seed(42)
random.shuffle(unique)

split = int(len(unique) * 0.9)  # held-out set is never used for training
for name, part in (("train.jsonl", unique[:split]), ("eval.jsonl", unique[split:])):
    with open(name, "w", encoding="utf-8") as f:
        for row in part:
            f.write(json.dumps(to_example(row), ensure_ascii=False) + "\n")
print(f"train={split} eval={len(unique) - split}")
prepare-data.ts
import { readFileSync, writeFileSync } from "node:fs";

type Row = { text: string; category: string; urgent: boolean };
const SYSTEM = 'Classify the complaint. Reply with JSON: {"category": ..., "urgent": true|false}.';
const PHONE = /\b\d{3}[ -]?\d{3}[ -]?\d{3}\b/g;

const toExample = (row: Row) => ({
  messages: [
    { role: "system", content: SYSTEM },
    { role: "user", content: row.text.replace(PHONE, "[PHONE]") }, // never train on personal data
    { role: "assistant", content: JSON.stringify({ category: row.category, urgent: row.urgent }) },
  ],
});

const rows: Row[] = readFileSync("labeled_complaints.jsonl", "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l));
const unique = [...new Map(rows.map((r) => [r.text.trim().toLowerCase(), r])).values()]; // drop duplicates
for (let i = unique.length - 1; i > 0; i--) { // Fisher-Yates shuffle
  const j = Math.floor(Math.random() * (i + 1));
  [unique[i], unique[j]] = [unique[j], unique[i]];
}

const split = Math.floor(unique.length * 0.9); // held-out set is never used for training
const toJsonl = (part: Row[]) => part.map((r) => JSON.stringify(toExample(r))).join("\n") + "\n";
writeFileSync("train.jsonl", toJsonl(unique.slice(0, split)));
writeFileSync("eval.jsonl", toJsonl(unique.slice(split)));
console.log(`train=${split} eval=${unique.length - split}`);
PrepareData.cs
using System.Text.Json;
using System.Text.RegularExpressions;

const string SystemPrompt = "Classify the complaint. Reply with JSON: {\"category\": ..., \"urgent\": true|false}.";
var phone = new Regex(@"\b\d{3}[ -]?\d{3}[ -]?\d{3}\b");

var unique = File.ReadLines("labeled_complaints.jsonl")
    .Where(l => l.Trim().Length > 0)
    .Select(l => JsonSerializer.Deserialize<Row>(l, new JsonSerializerOptions(JsonSerializerDefaults.Web))!)
    .DistinctBy(r => r.Text.Trim().ToLowerInvariant())          // drop duplicates
    .OrderBy(_ => Random.Shared.Next())
    .ToList();

int split = (int)(unique.Count * 0.9);                            // held-out set is never used for training
Write("train.jsonl", unique.Take(split));
Write("eval.jsonl", unique.Skip(split));
Console.WriteLine($"train={split} eval={unique.Count - split}");

void Write(string path, IEnumerable<Row> rows) =>
    File.WriteAllLines(path, rows.Select(r => JsonSerializer.Serialize(new
    {
        messages = new object[]
        {
            new { role = "system", content = SystemPrompt },
            new { role = "user", content = phone.Replace(r.Text, "[PHONE]") },   // never train on personal data
            new { role = "assistant", content = JsonSerializer.Serialize(new { category = r.Category, urgent = r.Urgent }) },
        },
    })));

record Row(string Text, string Category, bool Urgent);

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • Training: QLoRA with PEFT and TRL
  • Evaluation: was it worth it?
  • When to fine-tune, and when not to
  • A short history of fine-tuning
  • Checklist
  • Test yourself
  • What's next

Create a free account · Sign in