MODULE 2.4

🎛️ Fine-Tuning and Customization

When it’s worth training a model, and when a better prompt or RAG will do. You’ll understand the decision ladder and what the LoRA changes how it responds, how to build a solid dataset, train a real adapter with Hugging Face, and measure whether it performs better than the base model.

7
Topics
~60
Minutes
Advanced
Level
Practical
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🪜 The decision ladder

Fine-tuning (fine-tuning) means continuing to train an existing model with your examples so it changes how it responds. It’s the most expensive tool in the toolbox—and the one most often requested by people who haven’t tried the others yet. Before training, climb the ladder one rung at a time: the problem is almost always solved on a lower rung that costs less and is easier to maintain.

The question that determines the choice is what the model is missing. If it’s missing clear instructions, use the prompt rung. If it’s missing knowledge (the company catalog, internal policy, today’s price), use the RAG — retrieve the right passage and add it to the context, as you saw in Module 2.3. Only when it’s missing behavior — a strict format, a consistent tone, a narrow task repeated thousands of times—is training the right choice.

What it is

The decision ladder is the order in which you try to customize a model: a well-written prompt, then examples in the prompt (few-shot), then RAG, and only then fine-tuning. Each rung costs more to set up and maintain than the one before it.

1 · Clear promptinstructions are missing 2 · Few-shotthe format needs to be shown 3 · RAGknowledge is missing 4 · Fine-tuningbehavior is missing cost and maintenance increase with each rung
How to read: Start at the bottom left. Move up only after you’ve tested the current rung with real examples and it failed. The line beneath each box says what the model is missing—that diagnosis, not the trend, determines which rung to use.

✓ Fine-tuning makes sense

  • ✓Output with a strict format (JSON for a legacy system, a standardized report).
  • ✓A narrow task repeated at high volume, where a trained small model can replace a large one.
  • ✓A tone or style that the prompt can’t maintain consistently.
  • ✓Run locally or offline, without sending data elsewhere.

✗ Don’t train for this

  • ✗Teaching changing facts (prices, inventory, policies): use RAG.
  • ✗Fixing a prompt that no one has properly tested.
  • ✗Having a “company model” just to say you have one.
  • ✗When you don’t have a test set for comparison.

Why learn

Training without a need creates a model you have to version, host, and retrain every time you switch the base model. Knowing when to step down the ladder saves weeks—and knowing when to step up delivers what no prompt can.

Key concepts

Few-shot
examples in the prompt
RAG
knowledge retrieved at the time
Fine-tuning
behavior encoded in the weights
Diagnosis
what the model is missing
2

🧬 What training changes

A model is a collection of weights (the numbers adjusted during training). Fine-tuning shows examples of inputs and desired outputs, measures the error (the loss, or loss) and nudges the weights in the direction that reduces that error. After repeating this for all examples over a few epochs (full passes through the dataset), the model starts to imitate the pattern in your data.

There are two families of fine-tuning you’ll encounter. SFT (supervised fine-tuning) teaches with question → ideal answer pairs. Preference tuning — such as DPO (Direct Preference Optimization, from 2023)—shows two answers to the same question and indicates which one is better. It helps refine tone and choices when you can’t write the perfect answer but can recognize it. In practice, start with SFT.

What it is

Fine-tuning means continuing to train a pretrained model with your examples. The model doesn’t “memorize a document”; it adjusts weights to reproduce the behavior pattern in the examples—format, tone, and decisions.

TypeTraining dataWhen to use it
SFTConversations with the ideal answer written out.Format, narrow task, style. This is the starting point.
Preference tuning (DPO and similar methods)Question + chosen answer + rejected answer.Refine tone and choices after SFT.
Continued pretrainingRaw domain text, without questions.Highly specialized vocabulary; expensive and uncommon outside labs.
DistillationAnswers from a large model used to train a small one.Reduce cost and latency; check the teacher model’s terms of use.

💡 Tip

Training also takes things away. This effect is called catastrophic forgetting — the model becomes great at your task and worse at other tasks it used to do well. That’s why your test set needs some general cases, not just cases from the new task.

Why learn

Knowing what training changes helps avoid the most common false expectation: “I’ll train it on the company’s PDFs and it’ll know everything.” Fine-tuning encodes behavior; facts that need to be accurate and up to date still belong in RAG.

Key concepts

Loss
the error training reduces
SFT
pairs with ideal answers
DPO
better × worse answer
Forgetting
improves here, gets worse there
3

🧩 LoRA and QLoRA

Adjusting all billions of weights ( full fine-tuning) requires a lot of GPU memory and creates a full copy of the model for each version. LoRA (Low-Rank Adaptation, published in 2021, freezes the original model and trains only two small matrices alongside a few layers. The result is an adapter: a file measured in megabytes that fits into the base model, instead of gigabytes.

The trick is in the rank (o r). Instead of learning a large change of size d × d, LoRA learns two thin matrices, B (d × r) e A (r × d), whose product has the same shape. With a r rank between 8 and 64, the number of trainable weights drops to a small fraction of the total. QLoRA (2023) goes further: it loads the frozen model in quantized 4-bit form—each weight is stored with less precision and uses less memory—and trains LoRA on top of it.

What it is

LoRA is an efficient fine-tuning technique (PEFT, parameter-efficient fine-tuning) that keeps the original model intact and trains a small low-rank adapter. QLoRA is the same approach, with the base model quantized to 4 bits to fit in less memory.

x tokens W original d × d weights frozen (not trained) A r × d B d × r LoRA adapter (only this is trained and saved) + tokens W·x + B·A·x
How to read: The input follows two paths. Above is the original path, shown in gray because it is frozen. Below is the thin A → B branch in cyan, which is the only part that is trained. The two outputs are added together. Remove the adapter and you get the original model back; swap the adapter and you swap its “specialty.”
ApproachWhat gets trainedMemoryWhat you keep
Full fine-tuningAll weightsThe mostA full copy of the model
LoRAA and B matricesMuch lessMegabyte-sized adapter
QLoRAA and B on a 4-bit baseThe least of the threeMegabyte-sized adapter

Why learn

LoRA is what made fine-tuning accessible outside major labs: small models can be trained on a consumer GPU or in Colab, and you can version adapters the way you version code. In 2026, it’s the standard approach for customizing open models.

Key concepts

Adapter
small plug-in file
Rank (r)
width of the trainable branch
Quantization
weights with fewer bits
PEFT
train a little, gain a lot
4

🗂️ Data that delivers

The model learns exactly what the examples show—including their flaws. A lazy answer in the dataset becomes a lazy answer in the model. That’s why the heavy lifting in fine-tuning isn’t the training: it’s building and reviewing the examples. A few hundred good, varied examples often teach more than thousands of repetitive ones.

The most common format is JSONL: a text file with one JSON object per line. For chat models, each line has a list called messages with the roles system, user e assistant —the same format as the chat API. Training teaches the model to generate the assistant. Always set aside some examples for validation: data the model never sees during training, used to measure whether it has generalized.

What it is

Preparing data means collecting, cleaning, standardizing, and splitting ideal input and output examples into a format the trainer understands (JSONL messages), with a separate portion for validation and testing.

✓ Good dataset

  • ✓Covers difficult and edge cases, not just easy ones.
  • ✓Answers reviewed by someone who knows the subject.
  • ✓The same system prompt and format on every line.
  • ✓Personal data removed or replaced with placeholders.

✗ Bad dataset

  • ✗Duplicates and near-duplicates (the model memorizes them).
  • ✗Test examples leaking into the training data.
  • ✗AI-generated answers without human review.
  • ✗CPF numbers, phone numbers, and customer names in the examples.

💡 Tip

A trained model may repeat passages from its training data. Under the LGPD (Brazil’s data protection law), personal data in a dataset counts as processing personal data: it requires a legal basis and a purpose. The simplest approach is to anonymize it first—“Customer A,” “CPF-X”—and protect the dataset as carefully as a customer database.

Goal: validate, deduplicate, and split your JSONL into training and validation sets.

# preparar_dados.py — Python 3 standard library only
# usage: python3 preparar_dados.py <exemplos.jsonl>
import json, random, re, sys

entrada = sys.argv[1]
CPF = re.compile(r"\d{3}\.?\d{3}\.?\d{3}-?\d{2}")
validos, vistos, problemas = [], set(), []

with open(entrada, encoding="utf-8") as f:
    for n, linha in enumerate(f, 1):
        linha = linha.strip()
        if not linha:
            continue
        try:
            ex = json.loads(linha)
            msgs = ex["messages"]
            papeis = [m["role"] for m in msgs]
            assert papeis[-1] == "assistant", "última mensagem precisa ser do assistant"
            assert all(m["content"].strip() for m in msgs), "mensagem vazia"
        except Exception as e:
            problemas.append(f"linha {n}: {e}")
            continue
        texto = json.dumps(msgs, ensure_ascii=False)
        if CPF.search(texto):
            problemas.append(f"linha {n}: parece ter CPF — anonimize")
            continue
        chave = texto.lower()
        if chave in vistos:
            problemas.append(f"linha {n}: duplicada")
            continue
        vistos.add(chave)
        validos.append(ex)

random.seed(42)
random.shuffle(validos)
corte = max(1, int(len(validos) * 0.1))   # 10% para validação
for nome, parte in (("val.jsonl", validos[:corte]), ("train.jsonl", validos[corte:])):
    with open(nome, "w", encoding="utf-8") as f:
        for ex in parte:
            f.write(json.dumps(ex, ensure_ascii=False) + "\n")

print(f"válidos: {len(validos)}  treino: {len(validos) - corte}  validação: {corte}")
print("\n".join(problemas[:20]) or "nenhum problema encontrado")

# formato de cada linha do <exemplos.jsonl>:
# {"messages": [{"role": "system", "content": "Você classifica chamados."},
#               {"role": "user", "content": "A impressora não liga."},
#               {"role": "assistant", "content": "{\"categoria\": \"hardware\"}"}]}

How to check: the script creates train.jsonl e val.jsonl and prints the counts. Intentionally add one repeated line and another with a fake CPF number to the input file: both should appear in the list of issues and be left out of the generated files.

Why learn

Dataset quality determines the result more than any hyperparameter. People who master data preparation run fewer blind training jobs and get a better model with fewer examples—and without leaking personal data into the weights.

Key concepts

JSONL
one example per line
Validation
data the model doesn't see during training
Deduplication
prevent memorization
Anonymization
LGPD before training
5

🏋️ Train a LoRA in practice

With the data ready, the training itself fits in a short script. You’ll use three libraries from the Hugging Face ecosystem: transformers (loads the model), PEFT (creates the LoRA adapter), and TRL (uses the SFTTrainer, which already understands the format messages). The example model is Qwen2.5 0.5B Instruct: small enough to train on a modest GPU or a free Colab notebook—and it runs, slowly, even on a CPU.

Three hyperparameters (settings you choose, not ones the model learns) matter most at first: the learning rate (the size of each adjustment step; for LoRA, around 2e-4 is a common starting point), the number of epochs (start with 2 or 3), and the rank r. Change one at a time and record the result of each run.

What it is

A local LoRA training run: load the base model, attach the adapter with LoraConfig, pass the files train.jsonl e val.jsonl to the SFTTrainer , and save the adapter to a folder.

Step 1. Create a virtual environment: python3 -m venv .venv && source .venv/bin/activate.

Step 2. Install: pip install torch transformers datasets peft trl accelerate.

Step 3. Put train.jsonl e val.jsonl (from Topic 4) in the same folder as the script.

Step 4. Run python3 treinar_lora.py and track the training and validation loss in the terminal.

Try this: train your first LoRA adapter.

# treinar_lora.py — LoRA with Hugging Face (transformers + peft + trl)
from datasets import load_dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

BASE = "Qwen/Qwen2.5-0.5B-Instruct"   # replace with <another open model> if you want

dados = load_dataset("json", data_files={"train": "train.jsonl",
                                         "validation": "val.jsonl"})

lora = LoraConfig(
    r=16,                         # adapter rank
    lora_alpha=32,                # deviation scale (usually 2 × r)
    lora_dropout=0.05,
    target_modules="all-linear",  # applies LoRA to linear layers
    task_type="CAUSAL_LM",
)

config = SFTConfig(
    output_dir="saida-lora",
    num_train_epochs=3,
    per_device_train_batch_size=2,
    gradient_accumulation_steps=4,
    learning_rate=2e-4,
    logging_steps=5,
    eval_strategy="epoch",        # measures validation loss at the end of each epoch
    save_strategy="epoch",
    report_to="none",
)

trainer = SFTTrainer(
    model=BASE,
    args=config,
    train_dataset=dados["train"],
    eval_dataset=dados["validation"],
    peft_config=lora,
)
trainer.model.print_trainable_parameters()   # shows how many weights are trainable
trainer.train()
trainer.save_model("saida-lora/adapter")
print("adapter saved in saida-lora/adapter")

How to check: the print_trainable_parameters line should show a small percentage of trainable parameters. The folder saida-lora/adapter should contain adapter_config.json e adapter_model.safetensors, which is only a few megabytes. If you get an argument error, your TRL version may have changed a parameter name: check the SFTConfig documentation—the names change, but the method stays the same.

loss epochs 1 2 3 4 5 best checkpoint validation rises: overfitting training validation (illustrative curves)
How to read: The solid line (training) always goes down—it only shows that the model is memorizing the examples. The dashed line (validation) is the one that matters: when it stops going down and starts rising, the model has started memorizing instead of learning. Keep the checkpoint from the point where the dashed line is lowest.

Why learn

Running a small training job end to end takes fine-tuning out of the realm of theory. You learn to read loss curves, recognize overfitting (when the model memorizes the training examples), and use data to decide whether it’s worth scaling up to a larger model.

Key concepts

Hyperparameter
chosen by you
Learning rate
step size
Overfitting
memorized, didn't learn
Checkpoint
snapshot of the model at one epoch
6

📏 Evaluate for real

A low loss doesn't prove the model became useful. The real question is: On your test set, does the fine-tuned model get more answers right than the base model with a good prompt? To answer that, you need an eval —a fixed set of cases with expected answers and a success criterion that a script can check.

When the output is structured (a category or JSON), the criterion is simple: an exact match, or valid JSON with the right field. When the output is free-form text, combine a rubric (a list of criteria) with human review of a sample, or use another model as an evaluator—keeping in mind that the evaluator can also make mistakes. The important thing is that the test stays the same from one run to the next; otherwise, you can't compare anything.

What it is

Evaluation means running the base model and the fine-tuned model on the same test set, using the same criterion, and comparing their accuracy—including a few general cases to detect forgetting.

Try this: compare the base model and the adapter on the same test, with and without LoRA enabled.

# avaliar_lora.py — compares the base model × adapter on <teste.jsonl> (same format as training)
import json, sys
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel

BASE = "Qwen/Qwen2.5-0.5B-Instruct"
ADAPTER = "saida-lora/adapter"
tok = AutoTokenizer.from_pretrained(BASE)
modelo = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(BASE), ADAPTER)
modelo.eval()

def responder(msgs):
    prompt = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
    ids = tok(prompt, return_tensors="pt").to(modelo.device)
    with torch.no_grad():
        out = modelo.generate(**ids, max_new_tokens=128, do_sample=False)
    return tok.decode(out[0][ids["input_ids"].shape[1]:], skip_special_tokens=True).strip()

casos = [json.loads(l) for l in open(sys.argv[1], encoding="utf-8") if l.strip()]
placar = {"base": 0, "lora": 0}
for c in casos:
    entrada, esperado = c["messages"][:-1], c["messages"][-1]["content"].strip()
    with modelo.disable_adapter():          # disables LoRA: pure base model
        r_base = responder(entrada)
    r_lora = responder(entrada)             # LoRA enabled
    placar["base"] += r_base == esperado
    placar["lora"] += r_lora == esperado

n = len(casos)
print(f"cases: {n}")
print(f"base: {placar['base']}/{n}   lora: {placar['lora']}/{n}")

How to check: run python3 avaliar_lora.py val.jsonl and then a teste.jsonl separate test set that was never used in training. The LoRA score should beat the base model's score on the test. If it only improves on the val.jsonl and ties on the test, or performs worse on general cases, the adapter memorized the data — go back to the dataset.

💡 Tip

Include a third competitor in the comparison: the base model with the best few-shot prompt you can write. If it ties with LoRA, you don't need training — and you've just saved yourself the maintenance work.

Why learn

Without evaluation, fine-tuning is a gamble. With evaluation, each run becomes a number you can compare, defend in a meeting, and reproduce when the base model changes. It’s the same habit that separates a prototype from a production system.

Key concepts

Eval
fixed test with clear criteria
Test set
never seen during training
Rubric
criteria for free-form text
Baseline
what to match
7

💰 Costs, serving, and maintenance

The cost of fine-tuning isn't just the GPU time for training. Add the time spent building and reviewing the dataset, failed runs, inference (running the model to respond every day), and retraining when a better base model comes out. A fine-tuned small model may cost less per response than a large general-purpose one — but only if the volume justifies the work of maintaining it.

There are two ways to serve the adapter. You can merge LoRA into the weights (merge_and_unload() in PEFT) and export a single model — for example, convert it to GGUF and import it into Ollama with a Modelfile. Or keep the adapter separate on a server that loads multiple LoRAs on the same base model, such as vLLM; Ollama itself also accepts the instruction ADAPTER for some architectures. Check the tool's documentation first: support changes from version to version.

What it is

This is the fine-tuned model's life cycle: total cost (data, training, inference, retraining), serving method (merged or adapter), versioning alongside the dataset and eval, and the base model's license.

Cost itemWhat drives the costHow to reduce it
DataExpert hours spent reviewing examples.Start small and expand only where the eval fails.
TrainingGPU hours, failed runs.LoRA/QLoRA, a small model, one hyperparameter at a time.
InferenceAlways-on server or cost per token.Quantize for serving; use a smaller model when the eval allows it.
MaintenanceRetraining with each new base model.Versioned, reusable dataset and eval.

✓ Version together

  • ✓Dataset, training script, and hyperparameters.
  • ✓Exact name and version of the base model.
  • ✓Eval results for each adapter.

✗ Common pitfalls

  • ✗Ignoring the base model and data licenses.
  • ✗Adapter with no record of which base model it used.
  • ✗Retraining without running the same eval as before.

💡 Tip

API providers (OpenAI, Google, and others) also offer hosted fine-tuning: you upload the JSONL and get a fine-tuned model. The data format you've learned here is practically the same. Prices and available models change often — check the official page before budgeting.

Why learn

Fine-tuning that works in a notebook and dies in production is the most common outcome. Thinking about the lifecycle from the start — how to serve it, how much it costs per month, how to retrain it — is what turns the experiment into an asset the team can maintain.

Key concepts

Inference
cost of each response
Merge
LoRA merged into the weights
GGUF
format for running locally
License
what the base model allows

✅ Module summary

✓
Climb the ladder in order — prompt, few-shot, RAG; train only when behavior is missing.
✓
LoRA trains a small adjustment — the base model stays intact and the adapter is only a few megabytes.
✓
The data decides — clean, varied, split, and free of personal data.
✓
No eval, no fine-tuning — compare base and fine-tuned models on the same test, every run.

Next module:

2.5 — Agents and Complex Workflows 🕸️