Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 20 min · revision 2

Should You Fine-Tune? A Decision Framework

Decide between prompting, retrieval and fine-tuning with evidence instead of habit: what each approach changes, how to measure a prompt-only baseline on held-out examples with a real small model, how to compare running costs at different traffic levels, and what each option costs to maintain when data or base models change.

Contentsand lesson path

What you will learn

  • Decide between prompting, retrieval and fine-tuning for a use case using a baseline evaluation, available data, cost and maintenance burden as criteria.

Prerequisites: Transformer Architecture

01. Why it matters

When a language model does not do what you need, there are three main levers. You can change the prompt: the instructions and examples you send with each request. You can add retrieval: look up relevant documents at request time and put them into the prompt, often called RAG (retrieval-augmented generation). Or you can fine-tune: continue training the model on your own examples so that its weights change.

Fine-tuning is the most expensive of the three to build and to keep running, and it is often chosen too early, because "train it on our data" sounds like the most thorough fix. Sometimes it is the right answer; often a better prompt or retrieval gets there faster. This lesson gives you a way to decide with measurements: a baseline score, a cost estimate and an honest list of maintenance work. The scripts use HuggingFaceTB/SmolLM2-135M-Instruct, a small open-weight instruct model that runs on a laptop CPU; its first use downloads about 270 MB.

Terminal
mkdir -p ft-decide && cd ft-decide
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "transformers==5.23.*"

02. What each lever changes

The useful question is not "which is best?" but "what is actually missing?". Each lever fixes a different gap.

  • Prompting changes only the input. It is the cheapest to try and to change: a new version is a text edit, testable in minutes. It works when the model already has the knowledge and skill and only needs clear instructions, a few examples or an output schema.
  • Retrieval also changes only the input, but fills it with facts the model does not have, such as your product catalogue or this week's policies. Updating the knowledge means re-indexing documents, not training, and answers can cite their sources. It adds a search step, more prompt tokens per request and its own quality problem: finding the right passage.
  • Fine-tuning changes the weights. It is good at teaching behaviour: a strict output format, a house style, a narrow skill such as extracting fields, or doing the same job with a shorter prompt or a smaller model. It is poor at keeping facts current, because every change needs a new training run, and the model gives no sources for what it learnt.

The levers combine. A support assistant can use retrieval for facts and a fine-tuned model for its reply format. So the decision is per gap: a missing fact points to retrieval, a behaviour the prompt cannot pin down reliably points to fine-tuning, and anything else points to a better prompt first.

03. Measure a baseline before you decide

You cannot judge whether fine-tuning helps without a number to beat. Start with an evaluation set: examples with known correct answers that you never use for prompt writing or training. Then score the best prompt-only approach on it. That score is the baseline.

The script does this for a tiny task: label a customer message as late, damaged, wrong_item or refund. It has 16 held-out messages and compares two prompts on the same model: zero-shot (instructions only) and 4-shot (instructions plus one worked example per label). It counts answers that are a valid label and answers that are correct, and prints the prompt length in tokens. Decoding is greedy (no sampling), so the run repeats exactly on the same library versions.

Python · baseline.py
"""Measure the prompt-only baseline before deciding anything."""
import warnings

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers.utils import logging

logging.set_verbosity_error()
logging.disable_progress_bar()
warnings.filterwarnings("ignore", category=FutureWarning)
torch.set_num_threads(4)
MODEL = "HuggingFaceTB/SmolLM2-135M-Instruct"
LABELS = ["late", "damaged", "wrong_item", "refund"]
TASK = ("Classify the customer message. Answer with one word: "
        "late, damaged, wrong_item or refund.")
SHOTS = [("My parcel was due on Monday and is still not here.", "late"),
         ("The glass bowl arrived in pieces.", "damaged"),
         ("I ordered size M and you sent size XL.", "wrong_item"),
         ("Please give me my money back for the speaker.", "refund")]
EVAL = [  # held out: none of these phrasings appear in SHOTS
    ("Order 5521 should have come last week.", "late"),
    ("Still waiting for my lamp, it is five days overdue.", "late"),
    ("Tracking has not moved since Friday.", "late"),
    ("When will my order finally arrive?", "late"),
    ("The screen of the tablet is cracked.", "damaged"),
    ("The box was wet and the book inside is ruined.", "damaged"),
    ("One leg of the chair snapped when I unpacked it.", "damaged"),
    ("The kettle leaks from the bottom.", "damaged"),
    ("This is a blue jacket, I asked for green.", "wrong_item"),
    ("You sent me someone else's order.", "wrong_item"),
    ("I got a toaster instead of a blender.", "wrong_item"),
    ("The book in the parcel is not the title I bought.", "wrong_item"),
    ("I returned the shoes, where is my refund?", "refund"),
    ("Cancel my order and refund the card please.", "refund"),
    ("I want to send the rug back for a full refund.", "refund"),
    ("Can I get my 40 pounds back?", "refund"),
]

tokenizer = AutoTokenizer.from_pretrained(MODEL, padding_side="left")
model = AutoModelForCausalLM.from_pretrained(MODEL, dtype=torch.float32).eval()


def ask(conversations):
    batch = tokenizer.apply_chat_template(conversations, add_generation_prompt=True,
                                          padding=True, return_tensors="pt",
                                          return_dict=True)
    with torch.no_grad():
        out = model.generate(**batch, max_new_tokens=6, do_sample=False,
                             pad_token_id=tokenizer.pad_token_id)
    new = out[:, batch["input_ids"].shape[1]:]
    return [t.strip().lower().rstrip(".") for t in
            tokenizer.batch_decode(new, skip_special_tokens=True)]


def prompt(message, shots):
    turns = [{"role": "system", "content": TASK}]
    for text, label in shots:
        turns += [{"role": "user", "content": text},
                  {"role": "assistant", "content": label}]
    return turns + [{"role": "user", "content": message}]


for name, shots in [("zero-shot", []), ("4-shot", SHOTS)]:
    answers = ask([prompt(text, shots) for text, _ in EVAL])
    valid = sum(a in LABELS for a in answers)
    right = sum(a == gold for a, (_, gold) in zip(answers, EVAL))
    ids = tokenizer.apply_chat_template(prompt(EVAL[0][0], shots))["input_ids"]
    print(f"{name:9}  valid label {valid:2}/16  correct {right:2}/16  "
          f"prompt tokens {len(ids)}")
    first_words = [a.split()[0] if a else "-" for a in answers[:6]]
    print("           first 6 answers:", " ".join(first_words))
Terminal
python baseline.py
Expected output
zero-shot  valid label  0/16  correct  0/16  prompt tokens 43
           first 6 answers: the i'm tracking i'm the the
4-shot     valid label 14/16  correct  8/16  prompt tokens 134
           first 6 answers: last_week_order refund refund refund wrong_item damaged

Read the two lines separately. Zero-shot, this small model never answers with a label at all: it starts chatting. With four examples it answers in the right format 14 times out of 16, but only half of the labels are right. So the examples fixed the format, and the choice is still weak. That diagnosis tells you what to try next. A larger model, clearer label definitions or more examples per label might close the gap with prompting alone; if they do not, the remaining problem is a narrow behaviour, which is what fine-tuning is good at. Notice also the cost of the fix: the 4-shot prompt is three times longer, and you pay for those tokens on every request.

Sixteen examples are enough to show the idea, not to make a decision. For a real one you want a few hundred held-out cases that cover the inputs you expect, scored with the same metric you will use after any fine-tuning.

04. Compare running costs and maintenance

Quality is one criterion; cost and latency are the others. Per request you pay for input and output tokens, and a long few-shot prompt or a block of retrieved passages adds input tokens every time. A fine-tuned small model can need a short prompt, but hosting it is a fixed cost whether you send it one request or a million. The script compares three options at two traffic levels. All prices and token counts are made-up assumptions for the example; the point is the shape of the calculation, which you repeat with your own figures.

Python · costs.py
"""Monthly cost of three ways to run one task. Every number is an assumption:
replace them with your own traffic, token counts and your provider's prices."""
OUTPUT_TOKENS = 60
OPTIONS = {
    # name: (input tokens per request, $ per 1M in, $ per 1M out, fixed $ per month)
    "large model, few-shot":  (1_200, 3.00, 15.00, 0),
    "large model, retrieval": (2_000, 3.00, 15.00, 150),   # + a search service
    "small tuned model":      (150, 0.20, 0.80, 400),      # + a GPU host
}


def monthly(name, requests):
    tokens_in, price_in, price_out, fixed = OPTIONS[name]
    per_request = (tokens_in * price_in + OUTPUT_TOKENS * price_out) / 1e6
    return per_request * requests + fixed


for requests in (20_000, 600_000):
    print(f"{requests:,} requests a month")
    for name in OPTIONS:
        print(f"  {name:24} ${monthly(name, requests):7,.0f}")
    saving = monthly("large model, few-shot", requests) - monthly("small tuned model",
                                                                  requests)
    print(f"  tuned vs few-shot: {'saves' if saving > 0 else 'costs'} "
          f"${abs(saving):,.0f} a month")
Terminal
python costs.py
Expected output
20,000 requests a month
  large model, few-shot    $     90
  large model, retrieval   $    288
  small tuned model        $    402
  tuned vs few-shot: costs $312 a month
600,000 requests a month
  large model, few-shot    $  2,700
  large model, retrieval   $  4,290
  small tuned model        $    447
  tuned vs few-shot: saves $2,253 a month

At low traffic the fixed hosting cost of the tuned model is larger than the whole token bill of the prompt approach, so tuning loses money. At high traffic the per-request saving dominates. Latency often follows the same pattern: fewer input tokens and a smaller model usually mean a faster answer, while retrieval adds a search call before generation can start.

Then list the maintenance burden, the work that recurs after launch:

  • A prompt needs re-evaluation when the model behind it changes, and an edit when requirements change.
  • A retrieval system needs its index kept current, its search quality monitored and its documents cleaned.
  • A fine-tuned model needs a labelled dataset kept up to date, a training pipeline, a new run and a new evaluation whenever the task, the data or the base model changes. When a provider retires the base model you tuned, the adapter does not move to the new model: you train again.

A short checklist brings it together. First, write the task, the metric and the evaluation set. Second, score the best prompt baseline, then a larger model. Third, if answers lack or misstate facts, add retrieval. Fourth, consider fine-tuning only when a measured gap in behaviour remains, you have enough good examples (hundreds to a few thousand for a narrow task with a LoRA adapter), and the expected gain in quality, cost or latency is worth the recurring work.

05. Check your understanding

Practice check · 3 questions

Prompt, retrieve or fine-tune?

Use the outputs of baseline.py and costs.py.

Q1. In `baseline.py`, zero-shot gives 0 of 16 valid labels, while 4-shot gives 14 valid and 8 correct. Which reading of these results is best supported?
Q2. In `costs.py`, at 20,000 requests a month the small tuned model costs more than the large model with a few-shot prompt. Which term causes that?
Q3. Six months after launch, the provider retires the base model under your LoRA adapter and offers a newer one. What work does this create?
Practice only: not graded, not saved, not evidence.

06. Apply it

For your project (tuning a small open-weight instruct model for JSON field extraction), write a one-page decision record before you train anything. Define the fields and the metrics (exact match per record and schema validity), set aside a held-out evaluation set, and score a few-shot prompt on the base model and on a larger model. Fill in costs.py with your own traffic and price assumptions. List the recurring work each option creates. End with a decision and the result that would make you change it, for example "if few-shot exact match stays below 85% on the held-out set, fine-tune with QLoRA". You will reuse the same evaluation set when you compare the base and tuned models in the last lab of this skill.

07. Review prompt

Without looking back, answer in your own words:

  1. What does each lever (prompting, retrieval, fine-tuning) change, and which kind of gap does each fix?
  2. What is a baseline, and why must it be scored on examples that were not used to write the prompt?
  3. Why can a cheaper model per request still cost more per month?
  4. What recurring work does a fine-tuned model create that a prompt does not?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check