LESSON 11 Β· UNDERSTANDING LLMs

Fine-tuning

Fine-tuning takes a pre-trained model and trains it further on a smaller, focused dataset so its behavior becomes better suited to a particular task, format, domain, or style.

25 min readβ€’Beginnerβ€’Generative AI

By the end of this lesson, you will be able to:

  • Explain how fine-tuning builds on a pre-trained model.
  • Choose examples that teach a model the behavior you actually want.
  • Understand training pairs, epochs, learning rate, validation, and overfitting.
  • Distinguish fine-tuning from prompting, RAG, pre-training, and instruction tuning.
  • Run a small Python experiment that shows how focused training changes model behavior.
1

Fine-tuning in one picture

Pre-training gives a model broad capabilities. Fine-tuning starts from those learned parameters instead of starting from random values. You then expose the model to examples that represent a narrower target behavior.

1Pre-trained modelalready learned broad language patterns
β†’
2Focused datasetexamples of the desired input and output behavior
β†’
3Train furtherupdate parameters with a smaller learning rate
β†’
4Evaluatecheck useful behavior and unwanted changes
Simple idea: pre-training teaches broad patterns; fine-tuning nudges an already capable model toward a specific behavior.
2

Why fine-tune a model?

Fine-tuning is useful when repeated prompts are not enough to reliably produce the behavior you need. The training examples can teach consistent output structure, terminology, classification behavior, or a domain-specific response style.

FormatTeach a consistent structure such as JSON fields, short labels, or a specific response template.
Task behaviorTeach a repeated task such as classification, extraction, or transformation.
Domain styleAdapt vocabulary and response patterns for a specialized domain.

Important: fine-tuning is not automatically the best way to add changing company facts. If the model needs fresh external knowledge, retrieval can be a better fit.

3

Step 1: design a useful fine-tuning dataset

The model learns from the examples you provide. Good examples make the desired behavior clear and consistent. Poor examples can teach the wrong behavior just as efficiently.

EXAMPLE A Β· STRONG TRAINING SIGNALInput: β€œMy order arrived damaged.”

Output: β€œI’m sorry your order arrived damaged. Please send your order number and a photo of the package so we can help with a replacement.”

EXAMPLE B Β· WEAK TRAINING SIGNALInput: β€œMy order arrived damaged.”

Output: β€œThat is unfortunate. Contact support.”

Dataset rule: examples should represent the behavior you want at production time. Consistency matters more than simply collecting a large number of loosely related examples.
4

Step 2: structure training examples

For supervised fine-tuning, each example describes an input and the response the model should learn to produce. The exact format depends on the training API, but the teaching idea is the same: show the model the behavior, not just a description of it.

</> Python
training_example = {
    "messages": [
        {"role": "user", "content": "Classify: My card was charged twice."},
        {"role": "assistant", "content": "billing"},
    ]
}

print(training_example)

This example teaches a mapping from a customer message to a target label. A real dataset would contain many carefully reviewed examples covering the variations you expect.

5

Step 3: train with small, careful updates

Fine-tuning usually starts from a capable model, so you generally do not need the huge updates used to learn language from scratch. Training settings such as learning rate, batch size, number of epochs, and sequence length affect how strongly the dataset changes the model.

Learning rateControls the size of each parameter update. Too high can damage useful behavior; too low may learn slowly.
EpochsHow many passes the optimizer makes over the training examples. More is not always better.
ValidationExamples kept out of training help reveal whether the learned behavior generalizes.
Exampleinput + target
β†’
Predictionmodel response
β†’
Losscompare to target
β†’
Updateadjust parameters
β†Ί
6

Watch for overfitting

A model can become too specialized to the examples it saw. If training loss keeps improving while performance on held-out examples gets worse, the model may be memorizing the training set instead of learning a useful general pattern.

Healthy adaptationTraining examples improve and new examples also receive the intended behavior.Generalizes
OverfittingTraining examples look excellent, but small changes in wording cause poor or overly rigid responses.Memorizes
Practical check: keep a validation set with realistic variations that the model did not see during training.
7

Fine-tuning vs other techniques

PromptingChange instructions at request time. Best when behavior can be controlled by clear instructions.
RAGRetrieve external information at runtime. Best for changing or private knowledge.
Fine-tuningTrain the model on examples. Best for repeated behavior, format, or task adaptation.
Pre-trainingBuild broad model capabilities from massive datasets. Much larger and more expensive.

Decision rule: if your problem is β€œthe model does not know today's policy,” think retrieval. If the problem is β€œthe model repeatedly fails to follow this output behavior,” fine-tuning may be appropriate.

8

Run a small behavior experiment

You can understand the core idea without training a large model. The following Python example uses a tiny text classifier to show what focused training does: the model starts with general numeric features and learns a narrower mapping from examples to labels.

</> Python
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression

texts = [
    "card charged twice",
    "refund is missing",
    "password reset link",
    "cannot sign in",
]
labels = ["billing", "billing", "account", "account"]

vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)
model = LogisticRegression(max_iter=1000)
model.fit(X, labels)

new_message = ["I was charged twice"]
prediction = model.predict(vectorizer.transform(new_message))
print(prediction[0])
Expected outputbillingThe classifier has been trained on focused examples that teach a narrow behavior. Large language model fine-tuning follows the same broad idea, but updates the parameters of a neural language model rather than a small classifier.
PRACTICE

Test your understanding

1You need a chatbot to use the latest internal HR policy.Use retrieval/RAG when the policy changes and should remain external to the model.
2You need the model to consistently return a particular classification label format.Fine-tuning can be useful when many examples show the exact repeated behavior you want.
3Your validation results get worse while training results improve.Suspect overfitting. Review the dataset, training duration, regularization, and evaluation examples.
QUICK QUIZ

What does fine-tuning start with?

30-SECOND RECAP

Remember these five ideas

  • Fine-tuning adapts an existing pre-trained model.
  • Your examples define the behavior the model is encouraged to learn.
  • Learning rate and epochs control how strongly training changes the model.
  • Validation helps detect overfitting and unwanted specialization.
  • Use prompting, RAG, fine-tuning, or pre-training for different problems.