Sub topic 13
Where Fine-Tuning Fits, and Where It Does Not
Prerequisites
This chapter assumes you know the classic ML lifecycle (training, validation, deployment). It also assumes you can call a hosted model API from Python and have read the earlier chapters on versioned prompts, evaluation, and release gates. Fine-tuning here means supervised fine-tuning of a pretrained model on example input and output pairs. Training a model from scratch is out of scope.
Why this is a late decision
Classic MLOps starts with training. In LLMOps, training is usually the last lever you pull, because the cheaper levers are faster to change, easier to roll back, and easier to evaluate:
- Rewrite the prompt and add examples.
- Add or fix retrieval so the model sees the right facts.
- Try a stronger or different base model.
- Fine-tune.
Each step costs more to iterate on than the one before. A prompt change takes minutes and ships as a new version ID. A fine-tune takes data collection, a training job, an evaluation run, and a new model identifier to manage.
What fine-tuning changes
Fine-tuning updates the weights of a model, or a small adapter attached to it, so that certain behavior becomes the default instead of something you request in every prompt. It is good at changing how the model responds. It is poor at changing what the model knows.
| Goal | Fine-tuning fit | Better first option |
|---|---|---|
| Consistent output format or tone | Strong | Few-shot prompt, structured output settings |
| Shorter prompts at high volume | Strong | Prompt trimming, caching |
| Matching a house style on thousands of examples | Strong | Longer prompt with examples |
| Distilling a large model's behavior into a smaller, cheaper one | Strong | Switching to a smaller base model |
| Answering from your current documents | Weak | Retrieval and context assembly |
| Facts that change weekly | Poor | Retrieval |
| Fixing a prompt injection weakness | Poor | Guardrails, input handling, least privilege |
| Adding a capability the base model lacks entirely | Unreliable | A different base model |
Why knowledge is a bad fit
Teams often fine-tune to "teach the model our documentation". This tends to disappoint for three reasons:
- The model absorbs style and patterns more reliably than individual facts, and it can state wrong facts fluently.
- Facts go stale. Updating a retrieval index takes minutes. Updating weights means retraining and re-evaluating.
- You cannot cite a source from weights, and you cannot delete one document from a trained model. Retrieval handles both.
If the failure is "the model did not know X", fix the context pipeline. If the failure is "the model knew X but answered in the wrong shape", consider fine-tuning.
A decision flow
Every branch ends at the same place: the evaluation gate. Fine-tuning gets no exemption from it.
Good reasons to fine-tune
- Format reliability. You need a strict output shape on every call and prompting reaches about 90%. Fine-tuning on a few hundred correct examples can push this higher. Compare it against structured-output features first, since they may be enough.
- Prompt cost at scale. A long few-shot prompt is billed on every request. If a tuned model needs only a short instruction, the saving repeats on each call.
- Latency. Shorter prompts and a smaller tuned model usually respond faster.
- Distillation. You have a large model producing good outputs and want a smaller model to imitate it on one narrow task.
- A stable, narrow task. Classification, extraction, and rewriting with fixed rules are typical examples.
A rough break-even calculation
Training has an up-front cost, and the saving accrues per request. A small calculation shows whether the volume justifies it. The prices below are illustrative, so replace them with your provider's numbers. Include the cost of building the dataset and running evaluation in training_cost, not only the training job.
import math
def breakeven_requests(
training_cost: float,
base_input_tokens: int,
tuned_input_tokens: int,
base_price_per_mtok: float,
tuned_price_per_mtok: float,
):
"""Return the request count at which fine-tuning pays for itself,
or None if the tuned model is not cheaper per request."""
base_cost = base_input_tokens * base_price_per_mtok / 1_000_000
tuned_cost = tuned_input_tokens * tuned_price_per_mtok / 1_000_000
saving = base_cost - tuned_cost
if saving <= 0:
return None
return math.ceil(training_cost / saving)
n = breakeven_requests(
training_cost=400.0,
base_input_tokens=1800,
tuned_input_tokens=300,
base_price_per_mtok=2.0,
tuned_price_per_mtok=3.0,
)
print(n)With these numbers the saving is $0.0027 per request, so break-even is roughly 148,000 requests. At 1,000 requests a day that takes about five months, and a base model upgrade in that window could erase the benefit. The function ignores output tokens and quality gains, so treat the result as an order-of-magnitude check.
Training data is the real artifact
The model weights are an output. The dataset is the input you must version, review, and own. Three problems recur:
- Bad labels. The model reproduces the mistakes in your examples, including inconsistent ones.
- Leakage. If an evaluation input also appears in the training set, your pass rate measures memorization. Keep the golden set strictly separate.
- Sensitive data. Anything in the training data may later surface in outputs. Apply the same data-handling rules you use for logs.
The script below checks a chat-format JSONL file for structural problems and detects overlap with an evaluation set.
import json
ALLOWED_ROLES = {"system", "user", "assistant"}
def validate_line(line_no, line):
"""Return a list of problems for one JSONL line (empty if valid)."""
try:
record = json.loads(line)
except json.JSONDecodeError:
return [f"line {line_no}: not valid JSON"]
messages = record.get("messages") if isinstance(record, dict) else None
if not isinstance(messages, list) or len(messages) < 2:
return [f"line {line_no}: needs a 'messages' list with at least 2 items"]
problems = []
for m in messages:
ok = (
isinstance(m, dict)
and m.get("role") in ALLOWED_ROLES
and isinstance(m.get("content"), str)
and m["content"].strip() != ""
)
if not ok:
problems.append(f"line {line_no}: bad message {m!r}")
if not problems and messages[-1]["role"] != "assistant":
problems.append(f"line {line_no}: last message must be from the assistant")
return problems
def user_inputs(lines):
texts = set()
for line in lines:
record = json.loads(line)
for m in record["messages"]:
if m["role"] == "user":
texts.add(m["content"].strip().lower())
return texts
def find_leakage(train_lines, eval_inputs):
eval_set = {t.strip().lower() for t in eval_inputs}
return sorted(user_inputs(train_lines) & eval_set)
train = [
json.dumps({"messages": [
{"role": "user", "content": "My invoice shows a duplicate charge."},
{"role": "assistant", "content": "Customer reports a duplicate charge on an invoice."},
]}),
json.dumps({"messages": [
{"role": "user", "content": "I cannot log in."},
{"role": "user", "content": "Please help."},
]}),
]
for i, line in enumerate(train, start=1):
for problem in validate_line(i, line):
print(problem)
valid_train = [l for i, l in enumerate(train, start=1) if not validate_line(i, l)]
print(find_leakage(valid_train, ["My invoice shows a duplicate charge."]))The second example fails because it ends with a user message. The leakage check then reports the duplicate-charge input, which is in both sets and must be removed from one of them.
Operating a fine-tuned model
A tuned model adds operational work that a prompt change does not:
- Version everything together. Extend the prompt version record from earlier chapters with the base model ID, the tuned model ID, the dataset hash, and the training settings. A tuned model with no dataset hash cannot be reproduced.
- Evaluate against baselines. Compare the tuned model with the best prompted baseline on the same golden set, using the same repeated runs. A tuned model that beats a weak prompt but ties a good one has not earned its upkeep.
- Check for regressions outside the target task. Narrow tuning can degrade general behavior. Include cases that should be unaffected.
- Plan for base-model changes. Providers retire base models. When yours is retired, you must rebuild the tuned model on a new base, re-evaluate it, and re-release it. Prompts port to a new model more easily than weights do.
- Keep a rollback. Keep the previous model ID and prompt version deployable until the new one has survived production monitoring.
- Monitor drift. The tuned model reflects the data distribution at training time. When user inputs change, quality falls, and the fix is new data and another round of training.
Common mistakes
- Fine-tuning before building an evaluation set, so there is no way to tell whether it helped.
- Using model outputs as training labels without review. This bakes the teacher model's errors into the student.
- Training on a few dozen examples and expecting broad behavior change.
- Mixing several tasks in one dataset, which makes failures hard to trace.
- Measuring only the training loss. Loss falling says nothing about whether your checks pass.
Exercise
Exercise
Your support-summary app fails 30% of eval cases because the model invents refund policies that are not in the ticket or the policy documents. A teammate proposes fine-tuning on 500 past summaries. What should you check first, and why might fine-tuning not fix the problem?
Show answer
First check whether the policy text reaches the model at all, by inspecting traces of the assembled context and fixing retrieval if it does not. The failure is about missing or ignored facts, which fine-tuning handles poorly: it teaches style more reliably than facts, the policies can change, and the model may still produce confident but wrong statements. Fix context and prompt instructions (for example, "use only the provided policy text"), re-run the eval, and consider fine-tuning only if the remaining failures are about output shape or tone and a measured baseline justifies the cost.