Chapter 08 / 12 · AI Engineering

Fine-tuning, and when a better prompt wins

Retrieval changes what the model reads; fine-tuning changes how it behaves. Find out which problem the assistant has before paying for the second.

Fine-tuning changes a model’s weights so that a behaviour you used to ask for in the prompt becomes the model’s default. This chapter is about deciding when that trade is worth making for our support assistant, and how to make it cheaply when it is.

The assistant from the previous chapter answers from about 1,200 help-centre articles and the product docs, cites them as [HC-1042] and the like, and mostly works. Then three requests land in the same week. The product lead wants it to “know our products better”, because it sometimes quotes the wrong charge for an intraday trade. The support leads want it to hold a consistent tone and format, which it loses on long conversations, and compliance wants the remaining replies that sound like investment advice gone. Finance has noticed the bill: about $17,000 a month at 30,000 conversations a day, even after the prompt reordering from the inference chapter. Someone proposes fine-tuning as the answer to all three. It is a reasonable answer to two of them at most, and working out which two is most of what this chapter teaches.

Read two hundred failures before choosing a tool

The first move is not technical. We pull the 200 most recent conversations that a customer rated badly or that came back as a second contact within two days, and we read them. For each one we write down the first thing that went wrong. The point is to find out what kind of problem we have, because the three tools on the table (a better prompt, better retrieval, a tuned model) fix different kinds.

First thing that went wrongCountWhat fixes it firstDoes tuning help?
Wrong or missing fact104the right doc was not retrieved, or the doc was out of dateno; it makes this worse
Right facts, wrong behaviour46advice-like phrasing, format drift on long conversations, tone the leads dislikeyes, after the prompt has been tried
Wrong action31did not look up the order, or raised a ticket the articles made unnecessaryrarely; fix the tool descriptions first
Needed a human19angry customer, account-specific dispute, genuinely ambiguousno; route these out

Over half of the failures are about facts. The product lead’s request, “know our products better”, describes those 104 cases, and it sounds like a request for training. It is a request for retrieval, and the context chapter’s method of tracing which stage lost the passage applies to every one of them. The 46 behaviour failures belong to the support leads and compliance, and they are the real candidates for tuning. Finance’s problem is separate again: it is a cost problem, and the tool for it is distillation, which is fine-tuning used for a different purpose. We will take them in that order.

Why a model is a bad place to keep facts

When we train on a pair like “What is the account maintenance charge?” followed by “₹300 a year”, gradient descent nudges millions of shared weights so that, for inputs that look like that question, the tokens “₹300” become more likely. Nothing in the model now holds a record called account maintenance charge that we can find, edit or cite. The fact is spread across weights that also encode everything else, and it is entangled with the phrasing of the questions we trained on. To change it, we train again.

Retrieval keeps the same fact in a document. When the charge changes, someone edits the help article at eleven in the morning, the index refreshes, and by a few minutes past eleven the assistant is reading the new number and can show the customer where it came from. That property, an edit that takes effect in minutes with a source attached, is what a support assistant for a regulated business needs. No amount of training gives it back.

Predict first

Suppose the team ignores this and fine-tunes on 3,000 question and answer pairs written from the help centre, including “₹300 a year” for the maintenance charge. Six weeks later the charge becomes ₹240. The help article is updated and retrieval puts the new article into the prompt. What does the tuned model say when asked?

Show the worked answer

It is unpredictable, which is worse than being wrong. Training made “₹300” very likely in that context; the retrieved passage pushes towards “₹240”. Which pull wins depends on how the customer phrased the question and how close it is to the training examples. In practice the team sees a mix of ₹300, ₹240, and inventions such as “₹240 (previously ₹300, may vary by plan)”.

The eval suite does not catch it either, because its reference answers were written before the change. The failure reaches customers first.

Walk through how the team gets out of this. The first instinct is to retrain with the new number. That works until the next change, and a broker’s charges, holiday calendars, margin rules and form requirements change every few weeks. The second instinct is to stop tuning altogether. The better fix keeps the tuning but changes what it teaches. We rebuild the training set so that every example contains the retrieved passages, exactly as the production prompt would, and the target answer quotes from them. Then we add a few hundred examples where the passage says something the model might not expect (a charge that went up, a rule with an exception), so that following the passage is the behaviour being rewarded. The model learns “answer from what is in front of you” rather than “this question has this answer”.

That fix has a cost. The data pipeline must now run retrieval for every training example, training prompts get longer, and the eval suite needs cases where the documents change between runs. It is still cheaper than a model that holds stale beliefs about what we charge.

What tuning is good at: behaviour the prompt cannot hold

The 46 behaviour cases look different. The facts in those answers are right. What goes wrong is the shape: a customer asks whether to sell before quarterly results, and the assistant replies with “many investors choose to book profits before results”, which is advice wearing a disguise. On the eighth turn of a long conversation, replies stop citing articles and grow to nine paragraphs. Another answer is correct and curt in a way the support leads would never accept from a person.

The prompt has already been worked hard. The prompting chapter’s three stop-loss examples brought opinions on advice-seeking questions from about one in four to one in forty, and a separate check holds flagged replies for human review. One in forty is still a problem at this volume. If one conversation in twelve contains an advice-seeking question, that is 2,500 a day, and about 60 replies a day reach the review queue or slip past the check. Each further rule or example now costs elsewhere: it competes for attention with the others, fixing one phrasing regresses another, and every example is paid for on every call.

This is the shape that fine-tuning fits. The behaviour is consistent and describable by example, the prompt has stopped improving it, and it has to hold across long conversations where the system prompt is far behind the latest turn. Tuning moves the behaviour from the prompt into the weights. The model no longer needs to be reminded, on every call, how to decline a stock tip politely, because declining is now what it does. The output check stays, because a tuned model lowers a failure rate just as a prompt does.

How LoRA makes tuning cheap enough to try

Full fine-tuning updates every weight. For a model with 8 billion parameters, training with the usual Adam optimiser in mixed precision needs roughly 16 bytes per parameter: the weights, their gradients, two optimiser statistics per weight and a full-precision master copy. That is about 128 GB before counting activations, which means several large GPUs for one experiment, and a full 16 GB copy of the model for every variant we keep.

LoRA (low-rank adaptation) starts from an observation: the change a narrow fine-tune makes to a weight matrix tends to have far fewer independent directions than the matrix has rows. So instead of learning a full update to a 4096 × 4096 matrix W, we freeze W and learn two thin matrices, A of shape r × 4096 and B of shape 4096 × r, whose product BA has the same shape as W. The layer computes Wx + (α/r)·BAx. B starts at zero, so at step zero the model is exactly the base model and training moves it away gradually.

one projection inside one transformer layerxW · frozen4096 × 409616,777,216 weightsA16 × 4096B4096 × 16trainable · 131,072 weights+hh = Wx + (α/r)·BAxB starts at zero, sostep 0 is the base modelafter training, BA can bemerged into W, or keptapart and swapped per taskrank 16 trains 0.78% of this matrix · the base model never changes
LoRA on one projection matrix: the base weights stay frozen, and a rank-16 detour through A and B carries everything the fine-tune learns

The arithmetic is worth doing once. W has 4096 × 4096 = 16,777,216 weights. With rank r = 16, A and B have 16 × 4096 = 65,536 weights each, so 131,072 in total, which is 0.78% of the matrix. Put adapters on the four attention projections in each of 32 layers (treating all four as 4096 × 4096 for round numbers) and we train about 16.8 million parameters, roughly 0.2% of the model. The frozen base sits in memory once at 2 bytes per weight, 16 GB, and the trainable part with its optimiser state adds a few hundred megabytes. One GPU is enough. If the base is quantised to 4 bits while training the adapters (the QLoRA variant), it drops to around 5 GB.

The adapter saved to disk is about 34 MB. That changes how we operate tuned models. We can merge BA into W after training, so serving costs nothing extra, or keep adapters separate and load several onto one shared base: one for compliance phrasing, one for a different product line, swapped per request. The limitation is the flip side of the mechanism. A low-rank update is good at steering what the model already knows how to do, and poor at teaching it a large body of new material. That suits behaviour, and it is one more reason facts belong in retrieval.

What a training example has to look like

The most common mistake with tuning data is training on a different input from the one production sends. If production prompts contain a system prompt, five retrieved passages, the conversation so far and an order lookup result, the training examples must contain those things in the same format. A model tuned on bare question and answer pairs has learned to answer bare questions. One record in the training file looks roughly like this:

{"messages": [
  {"role": "system", "content": "<short system prompt, ~400 tokens>"},
  {"role": "user", "content": "<articles><article id="HC-0311"> ...
     </article><article id="HC-1042"> ... </article></articles>
     Should I sell my INFRA shares before results? Also what is the AMC?"},
  {"role": "assistant", "content": "I can't advise on whether to buy or sell a
     particular stock. If you want to limit a fall, a stop-loss order ...
     [HC-0311] The account maintenance charge is ₹240 a year, billed
     quarterly [HC-1042]."}
]}

For behaviour, a few hundred to a couple of thousand examples is usually enough, and consistency matters more than volume. If two senior support agents write the targets and one always opens with an apology while the other never does, the model learns to apologise about half the time. We write a one-page style guide for the people producing targets, review a sample of their work against it, and remove near-duplicates so that no eval question has a twin in the training set. The eval set stays held out from the start; a tuned model scored on its own training data tells us nothing.

Preference tuning teaches the difference between two answers

Supervised tuning shows the model one good answer per input. It cannot show what to avoid, and many compliance problems are about avoiding something. The answer that says “I can’t tell you whether to sell, but here is how a stop-loss order works” and the one that says “many investors book profits before results” are both fluent and both mention the customer’s stock. The difference between them is exactly what we want the model to learn.

Preference tuning trains on pairs: one prompt, a chosen answer and a rejected one. In DPO (direct preference optimisation), the training objective raises the probability of the chosen answer relative to the rejected one, measured against a frozen copy of the starting model. A parameter usually called β controls how far the tuned model may drift from that copy, which is the guard against it forgetting how to do everything else. The larger-scale version used by model labs, RLHF, trains a separate reward model on human preferences and then optimises against it; for an application team, DPO on a thousand or so pairs is the practical form.

The pairs come most usefully from the model itself. We sample two or three answers from the current model for each of a thousand advice-shaped questions, and compliance reviewers mark which ones they would allow. Pairs drawn from the model’s own outputs teach more than pairs where a human wrote the good answer, because they target the mistakes this model actually makes. The failure to watch for is over-correction: after a strong preference tune, the model may start declining “what is a stop-loss order?” because it looks like the questions it learned to decline. So the eval suite needs a set of harmless questions that look risky, and its refusal rate must not move.

Distilling into a smaller model to cut the bill

Finance’s request is about cost. Start from the inference chapter’s conversation: four turns, 22,500 input tokens of which 9,300 are read from the cache once the prompt is ordered well, and 1,000 output tokens. At that chapter’s illustrative prices ($1 per million input tokens, $5 per million output, $0.10 per million cached) it costs $0.0191, or about $573 a day at 30,000 conversations.

A tempting first idea is that tuning saves money by shortening the prompt. Suppose the 1,500-token system prompt shrinks to 400 because its rules and examples now live in the weights. That removes 1,100 tokens from each of four turns, 4,400 tokens a conversation, but they were all cached tokens, worth $0.00044. At 30,000 conversations that is about $13 a day. Caching already took most of the prompt’s cost away. The saving that matters comes from the price of the model, and that means a smaller one.

Per conversationLarge model, 1,500-token promptSmall tuned model, 400-token prompt
Uncached input13,200 × $1/M = $0.013213,200 × $0.10/M = $0.00132
Cached input9,300 × $0.10/M = $0.000934,900 × $0.01/M = $0.00005
Output1,000 × $5/M = $0.0051,000 × $0.50/M = $0.0005
Total$0.0191, about $573 a day$0.0019, or $0.0037 if the host charges double for tuned models: about $112 a day

The small model’s prices ($0.10 per million input, $0.50 output, $0.01 cached) are illustrative, set at a tenth of the large model’s to show the shape; check your own provider’s price sheet. The shape holds across vendors: a model an order of magnitude smaller costs roughly an order of magnitude less per token, and it is usually faster too.

Distillation is how the small model learns to behave like the large one. We take 20,000 real customer questions, run them through the current production system (large model, full prompt, real retrieval), and grade every output with the kind of eval checks the evaluation chapter builds later in this pathway. About 14,000 pass. Those become the training set for the small model, with the short prompt. The large model is the teacher; the graders are the filter that keeps its mistakes out of the student.

Then we score the student on the held-out eval set. Suppose it reaches 76% where the teacher scores 79%. The average hides the important part: on account-closure questions, which involve several forms and depend on the account type, the student scores 71% against the teacher’s 85%. The usual answer is routing. A cheap classifier sends the common, well-covered intents to the student and the rare or tangled ones to the large model. If 85% of traffic goes to the student, the daily bill is about 0.85 × $112 + 0.15 × $573, roughly $181, and quality on the hard slice is unchanged. That saves about $390 a day, close to $12,000 a month.

Predict first

The distillation project takes two engineers about three weeks and a few hundred dollars of compute, and afterwards someone must re-distil whenever policies or products change materially. At 30,000 conversations a day it saves about $390 a day after routing. Is it still worth doing at the pilot’s 2,000 conversations a day?

Show the worked answer

No. Costs scale with traffic, so the saving scales down by a factor of 15, to about $26 a day or under $800 a month. The second model does not get cheaper to own: it has its own eval runs, its own regressions to investigate, its own re-training when the base model is retired. One engineer-day a month of that work erases the saving.

Even at 30,000 a day the case is moderate: six engineer-weeks to build, recovered in a few months, plus the upkeep. It becomes clear-cut only at several times that volume, or when the smaller model is needed for latency anyway. At low volume, the better moves are the ones from the inference chapter: prompt ordering for caching, fewer and better passages, and a smaller general model for the easiest intents.

When to leave the weights alone

Most of the reasons not to fine-tune have appeared already, and they share a root: a tuned model is a second system to own. If there is no eval suite yet, there is no way to tell what the tune bought or broke, so the suite comes first. If the problem is facts, or the behaviour depends on rules that change faster than we can retrain, the problem belongs in retrieval or in the prompt. If the volume is low, the savings will not pay for the upkeep. And if a newer general model would handle the behaviour from a short prompt, waiting a quarter may beat training now; tuned models are pinned to a base that the provider will eventually retire, and each retirement means re-tuning and re-evaluating.

The decision is worth revisiting when the facts change in the other direction: when the system prompt keeps growing to hold behaviour that the model keeps dropping, when traffic grows enough that the model’s per-token price dominates, or when a latency target can only be met by a smaller model. Written down as a sentence a colleague could challenge, our decision reads: we will fix the 104 fact failures in retrieval, tune for tone, format and advice phrasing because the prompt has stopped improving them at one in forty, and distil to a small model for the top intents only once traffic doubles, because at today’s volume the saving of about $12,000 a month barely covers the upkeep of a second model.

So far the assistant only answers. The next chapter, on agents and tools, gives it the ability to act: look up a specific customer’s order and raise a ticket. That changes the failure modes from wrong sentences to wrong actions, and it is where the loop, its budgets and its stopping rules come in.