Building with LLMs › Fine-tuning and training
What is fine-tuning? Adapting a trained model to your task
Fine-tuning trains an existing model a little more on your own data. How it works, why LoRA makes it cheap, and when a prompt or RAG is the better choice.
If you read about language models for a while, you’ll run into the word fine-tuning sooner or later. The chat versions of open models are usually described as fine-tuned, and plenty of tutorials say you can do it on your own laptop. Still, perhaps it isn’t quite clear what actually happens to a model when someone fine-tunes it.
Fine-tuning means taking a model that has already been trained and training it a little more on your own data, so that it behaves the way you want. You start from a model that already knows language well and nudge it toward your task, your format, or your tone. One reason the word comes up so often these days is that it has become much cheaper. Methods such as LoRA train only a tiny slice of the model, which is why the example below took less than a minute on a laptop.
What a model already knows, and what fine-tuning adds
A language model first goes through pretraining, where it reads an enormous amount of text and learns to predict the next token, over and over. A token is a small piece of text, such as a word or part of one. According to the model card of SmolLM2-135M-Instruct, the model I use below, the base model it was built on was pretrained on 2 trillion tokens. Reusing what a model learned this way for a different job is called transfer learning. It’s a bit like an experienced cook joining a new restaurant, who doesn’t relearn how to hold a knife and only needs to learn the house menu.
The chat models you use are usually made by fine-tuning too. The SmolLM2 model card says its instruct version was built with supervised fine-tuning (SFT) followed by DPO. SFT shows the model pairs of prompts and good answers so it learns to answer like them, while preference learning teaches it which of two answers people like better. In 2022, InstructGPT used RLHF, which means reinforcement learning on rankings that people gave the model’s outputs. Then in 2023, DPO reached the same goal without the reinforcement learning step, by putting a simple classification loss on pairs of preferred and rejected answers.
Changing every weight, or only a few
What a model knows is stored in its parameters, the numbers that training adjusts little by little. Full fine-tuning changes all of them, which gives the model the most room to change. But training then has to keep gradients and optimizer state for every weight in memory, and the result is as large as the original model. That’s why people use PEFT (parameter-efficient fine-tuning), which trains only some of the parameters. Hugging Face’s PEFT library says these methods greatly cut compute and storage costs while performing comparably to full fine-tuning.
A representative method is LoRA (Low-Rank Adaptation), published by Edward Hu and colleagues in June 2021. LoRA freezes the original weights, attaches a pair of small matrices next to some of the layers, and trains only that pair. Compared with fully fine-tuning GPT-3 175B, the paper reports 10,000 times fewer trainable parameters and a third of the GPU memory. And because the trained matrices can be merged into the original weights, LoRA adds no delay when the model runs (PEFT’s LoRA guide).
Teaching a small model one answer format
Now let’s teach a model to read a customer’s message and reply with nothing but one line of JSON saying which team should handle it and whether it’s urgent. I wrote 36 examples by hand, 12 each for billing, shipping, and account, and saved them in a JSONL file, which holds one example per line. Here’s the first line.
{"messages": [{"role": "user", "content": "I was charged twice for my order last week."}, {"role": "assistant", "content": "{\"team\": \"billing\", \"urgent\": false}"}]}
The model is SmolLM2-135M-Instruct, released under the Apache 2.0 license. Answers are generated by always picking the most likely token, so the same weights always give the same answer.
import json, torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from peft import LoraConfig, get_peft_model
torch.manual_seed(0)
device = "mps" if torch.backends.mps.is_available() else "cpu"
name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name).to(device)
data = [json.loads(line) for line in open("tickets.jsonl")]
def ask(text):
msgs = [{"role": "user", "content": text}]
ids = tok.apply_chat_template(msgs, add_generation_prompt=True,
return_tensors="pt", return_dict=False).to(device)
out = model.generate(ids, max_new_tokens=16, do_sample=False)
return tok.decode(out[0][ids.shape[1]:], skip_special_tokens=True)
Next, I wrap it with LoRA. r is the rank of the small matrices, and a lower rank means fewer parameters to train, while lora_alpha scales how much the small matrices add. target_modules names the layers that get them, and here I picked the query and value projections in the attention layers.
config = LoraConfig(r=8, lora_alpha=16, target_modules=["q_proj", "v_proj"],
task_type="CAUSAL_LM")
model = get_peft_model(model, config)
model.print_trainable_parameters()
trainable params: 460,800 || all params: 134,975,808 || trainable%: 0.3414
Only 0.34 percent of the parameters will be trained. In the training loop, the prompt part of the labels is set to -100 so the loss counts only the answer. The loss is a number for how far the model’s predictions are from the correct answers, and an epoch is one pass over all 36 examples.
def encode(example):
msgs = example["messages"]
prompt = tok.apply_chat_template(msgs[:1], add_generation_prompt=True, return_dict=False)
full = tok.apply_chat_template(msgs, return_dict=False)
labels = [-100] * len(prompt) + full[len(prompt):] # learn only the answer
return torch.tensor([full]).to(device), torch.tensor([labels]).to(device)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
model.train()
for epoch in range(5):
total = 0.0
for example in data:
ids, labels = encode(example)
loss = model(input_ids=ids, labels=labels).loss
loss.backward()
opt.step()
opt.zero_grad()
total += loss.item()
print(f"epoch {epoch + 1}: average loss {total / len(data):.3f}")
model.eval()
epoch 1: average loss 0.980
epoch 2: average loss 0.075
epoch 3: average loss 0.051
epoch 4: average loss 0.023
epoch 5: average loss 0.004
Including the time to load the model, it took about 20 seconds. With training done, let’s ask about messages that weren’t in the training data. Inside disable_adapter() LoRA is switched off, so the answer there is the original model’s answer from before training. I also added one question that has nothing to do with support.
tests = ["The app charges me twice every month.",
"My package never arrived and I need it tomorrow!",
"What is the boiling point of water?"]
for text in tests:
with model.disable_adapter():
before = ask(text)
print(f"{text}\n before: {before!r}\n after: {ask(text)!r}")
The app charges me twice every month.
before: "I'm sorry for the misunderstanding, but as a chatbot designed to assist with"
after: '{"team": "billing", "urgent": false}'
My package never arrived and I need it tomorrow!
before: "I'm sorry for the inconvenience, but as a chatbot, I don't"
after: '{"team": "shipping", "urgent": true}'
What is the boiling point of water?
before: 'The boiling point of water is approximately 212 degrees Fahrenheit (10'
after: '{"team": "billing", "urgent": false}'
Before training, the model answered like a chat assistant until it hit the 16-token limit. After training, both messages came back in the same JSON shape, with fitting teams and urgency. But when asked about the boiling point of water, it filed a billing ticket. It had only ever seen support messages, so it learned that every message is a support request. Two runs with the same seed gave identical output, though on a different machine or version it may come out slightly different.
Fine-tuning, prompt engineering, and RAG
Fine-tuning isn’t the only way to change a model’s answers. Prompt engineering refines the instructions and examples sent with each request, and RAG (retrieval-augmented generation) searches your documents when a request comes in and puts the relevant parts into the prompt.
| Approach | What it changes | Fits well when |
|---|---|---|
| Prompt engineering | The instructions sent with each request | You’re starting out, or the task changes often |
| RAG | The documents placed in the prompt | Answers depend on private or changing facts |
| Fine-tuning | The model’s weights | You need the same format or tone on many requests |
On where to begin, the official guides agree. OpenAI’s model optimization guide says prompt engineering may be all you need, and describes fine-tuning as a way to keep response formats consistent or to shorten prompts and save tokens. Google’s tuning guide for Gemini likewise says to start with prompting and move on to fine-tuning only if required.
The authors of LIMA fine-tuned a 65B LLaMA model on 1,000 carefully chosen examples and then proposed a hypothesis. A model’s knowledge and abilities come almost entirely from pretraining, they suggest, and alignment, the work of shaping a model to fit what people intend, mostly teaches it what format to answer in. It’s still a hypothesis, but what my model picked up in the example was also the shape of an answer. So if your answers depend on documents that change every week, RAG is often the more natural choice.
Good data over lots of data
OpenAI’s supervised fine-tuning guide says you need at least 10 examples that pair an input with the output you want, that it sees improvements from 50 to 100, and that you should start with 50 well-crafted ones and evaluate. And quality matters more than count. The answers must not contradict one another, and the examples should cover the inputs you’ll really see. My data had no message that wasn’t a support request, and that’s why the boiling-point question became a billing ticket.
What it costs, and what can go wrong
One risk you’ll often hear about is forgetting. Neural networks tend to abruptly lose what they learned earlier when they learn a new task, which is called catastrophic forgetting. A 2024 paper, LoRA Learns Less and Forgets Less, reports that in standard low-rank settings, LoRA falls well short of full fine-tuning on the target task, but keeps more of the original performance on other tasks. In my example too, switching the adapter off brought the original answer back, but with it on, one narrow habit took over every question.
There’s upkeep as well. A fine-tuned model is tied to its base model, so when the base model goes away, you have to train again. OpenAI’s supervised fine-tuning guide, for example, notes that gpt-4.1-nano-2025-04-14 and its fine-tuned versions shut down on October 23, 2026. That’s why the same guide recommends setting up evals first, a set of test inputs with the answers you expect, so you can check whether the model really got better.
Where you can fine-tune today
As of October 27, 2026, OpenAI is winding down its self-serve fine-tuning platform. According to its deprecations page, organizations that have never fine-tuned haven’t been able to create jobs since May 7, 2026, and active existing customers won’t be able to create new ones from January 6, 2027. Inference on models already fine-tuned continues until their base models are deprecated, though. The Gemini API has had no model that supports fine-tuning since Gemini 1.5 Flash-001 was deprecated in May 2025, and Google points to Gemini Enterprise Agent Platform on Google Cloud instead. With open models, you can do it yourself with PEFT as above, or with TRL, which has trainers for SFT and DPO.
Where to start
If you’re new to this, I’d suggest writing 20 or 30 test inputs with the answers you expect before running any training, and checking how far a prompt alone gets you. If the format still wobbles, try LoRA on a small open model with about 50 clean examples. I ran this example on October 27, 2026, on an Apple M4 laptop with 16 GB of memory, using Python 3.13.12, PyTorch 2.14.1, Transformers 5.20.2, and PEFT 0.21.2.
AI tools helped with the research for this post.