What Is Fine-Tuning

Updated · 7 min read
mediumPython 3.13aillmfine-tuningragpromptingcustomization

Fine-tuning means continuing to train a pretrained model on your own examples, so its weights change and it behaves the way you want: a fixed format, a house style, a narrow task done reliably. It is not the same as uploading documents to a chatbot. Uploaded or retrieved documents go into the prompt for one conversation; fine-tuning changes the model itself, for every conversation.

"RAG vs Fine-Tuning vs Long Context" introduced the choice. This chapter does it for real, with a small open model on a laptop.

Three Ways to Customize a Model

MethodDescription
PromptingIt is used to describe the task, rules and examples in the prompt; nothing about the model changes
RAG (retrieval)It is used to put relevant documents into the prompt, so answers use up-to-date facts
Fine-tuningIt is used to train the model on many examples of inputs and ideal outputs, changing its weights
Full fine-tuningUpdates every weight; needs the most memory and compute
Parameter-efficient fine-tuningUpdates a small add-on, such as LoRA, while the original weights stay frozen

Example: Facts Come from Documents

The programs in this chapter need pip install torch transformers peft scikit-learn. They use SmolLM2-135M-Instruct, the small open model from "Instruction Tuning and RLHF", which runs on an ordinary laptop. The download and loading messages are left out of the output shown.

This program asks the model about a school fee, first on its own, then with the school's document in the prompt.

Documents supply facts; fine-tuning shapes behavior
Python
from transformers import AutoModelForCausalLM, AutoTokenizer
 
name = "HuggingFaceTB/SmolLM2-135M-Instruct"
tokenizer = AutoTokenizer.from_pretrained(name)
model = AutoModelForCausalLM.from_pretrained(name)
 
def ask(content):
    ids = tokenizer.apply_chat_template([{"role": "user", "content": content}], add_generation_prompt=True,
                                        return_tensors="pt", return_dict=True)["input_ids"]
    out = model.generate(ids, max_new_tokens=40, do_sample=False, pad_token_id=tokenizer.eos_token_id)
    return tokenizer.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
 
question = "How much is the library fee at Lincoln High School?"
print("Question alone:")
print(" ", ask(question))
 
document = "The library fee is $15 a year and covers book loans and printing."
print("\nWith the school's document in the prompt:")
print(" ", ask(f"Document: {document}\n\nQuestion: {question}"))
Output
Question alone:
  The library fee at Lincoln High School is $10 per year.
 
With the school's document in the prompt:
  The library fee at Lincoln High School is $15 per year.

Explanation:

  • On its own, the model invents a number: $10. It has never seen this school's fees, so it writes something that sounds right. See "Why LLMs Hallucinate".
  • With the document in the prompt, it answers $15, the real fee. This is RAG in its simplest form.
  • Fine-tuning would be the wrong tool for this. Training the fee into the weights would take many examples, could still produce wrong numbers, and would need retraining every time a fee changes. A document is updated in seconds.

When Fine-Tuning Is Worth It

QuestionPoints toward fine-tuning when...
Use caseThe model must follow a precise format or style every time, or do one narrow task at high volume
Prompting tried first?A clear prompt with examples still fails your evaluation
DataYou have hundreds or thousands of good, consistent examples, or can create them
EvaluationYou have a test set to prove the fine-tuned model is better; see "Building an Evaluation Set"
CostA small fine-tuned model can replace a large, expensive one, or shorter prompts save money at scale
UpkeepSomeone can retrain and re-test it when the base model or the task changes

Prompting vs RAG vs Fine-Tuning

NeedBest first choiceWhy
Answer from company documentsRAGFacts stay current and answers can cite sources
A fixed output format or house stylePrompting, then fine-tuningFine-tune only if prompting can't make it reliable
A new skill, such as a rare language or code styleFine-tuningPrompts can't teach what the model has never seen enough of
Cheaper, faster answersFine-tune a smaller model, or distillA small specialist can match a big generalist on one task
Up-to-date informationRAG or toolsWeights are frozen at training time
Both facts and styleRAG plus fine-tuningThe chapter checkpoint does exactly this

Common Mistakes

Fine-tuning to teach facts. Use RAG; fine-tuned facts go stale and can still be made up.

Fine-tuning before trying prompting. It costs data, compute and upkeep; a better prompt is often enough.

No evaluation set. Without one, you can't tell whether the fine-tuned model is better or just different.

Thinking uploading a file to a chatbot is fine-tuning. The file goes into the prompt; the model doesn't change.

Interview Corner

When would you fine-tune instead of using RAG?

Fine-tune to change behavior: a consistent format, style or narrow skill that prompting can't make reliable. Use RAG to supply facts, especially ones that change. Many systems use both, and the decision should be backed by an evaluation.

What is the difference between full fine-tuning and parameter-efficient fine-tuning?

Full fine-tuning updates every weight; parameter-efficient methods like LoRA freeze the model and train a small add-on. The efficient methods need far less memory and storage and usually perform close to full fine-tuning.

Practice

Exercise: change the fact. Change the document in the program to say the fee is $18. Does the answer follow the document? What would you need to do if the fee had been fine-tuned into the model instead?

Check your understanding:

  1. What did the model answer without the document, and why?
  2. Why is fine-tuning a poor way to keep fees up to date?
  3. Name two signs that fine-tuning might be worth it.

Quick check: fine-tuning

4 questions
1What does fine-tuning change?
2What did the model say the library fee was without the document?
3Which is the best first choice for answering from company documents?
4What should you try before fine-tuning?

Key Takeaways

Quick reference

NeedChoose
Current facts with sourcesRAG
Rules and a few examplesPrompting
Reliable format, style or narrow skillFine-tuning (usually LoRA)
A cheaper model for one taskFine-tune a small model, or distill
Proof it helpedAn evaluation set, before and after

Was this tutorial helpful?

Lesson 151 of 186