Fine-tuning is the most over-reached-for tool in the AI toolkit. It sounds like the serious move — you're training the model — so teams jump to it to fix problems a prompt or a retrieval call would have solved in an afternoon. This chapter draws the line precisely: fine-tuning teaches a model new form, behavior, and skill; it does not teach it new facts. Get that distinction right and everything downstream — LoRA, data prep, preference tuning, serving — falls into place.
Everyone knows the ladder: prompt, few-shot, retrieval, then weights. What matters is why the rungs are ordered the way they are. Each rung down increases three things at once: the time before you learn whether it worked (minutes, then hours, then days), the number of artifacts you have to version (a string, then an index, then a checkpoint pinned to a base), and how hard it is to undo. A prompt change rolls back in a deploy. A fine-tune that taught the model to bluff rolls back only if you kept the old checkpoint, the old routing and the eval that proves the old one was better. Only when the gap is stubbornly about how the model behaves (a rigid output contract, a house style, a narrow skill it can't be prompted into) and the arithmetic below works out does the bottom rung earn its cost.
Prompt engineering
reword the instruction
Few-shot examples
show 2–5 examples in-context
RAG / retrieval
inject fresh facts at query time
Fine-tuning
train weights on your data
Cost, latency-to-ship, and irreversibility all rise as you descend. Most teams reach for the bottom rung far too early — fine-tuning to fix something a better prompt or a retrieval call would have solved for free.
The single most useful sentence in this chapter: fine-tuning changes behavior, retrieval changes knowledge. If you fine-tune a model on your product docs to make it "know" your product, you'll get a model that has absorbed the style of your docs while confidently hallucinating specifics — and the moment the docs change, your expensive training run is stale. Facts drift; behavior is stable. Train the stable thing.
The slogan needs a correction, though. Fine-tuning can write facts into weights, just badly. It takes many paraphrased exposures per fact. Worse, published work on SFT with unfamiliar knowledge (Gekhman et al., 2024) found that training on facts the base model doesn't already know raises its hallucination rate: the model learns to answer confidently about things it can't ground. So the failure isn't only "the facts are stale". Your SFT set can also teach the model to bluff. Audit the targets. If a response states a specific the base model couldn't have produced, rewrite it to use retrieved context, or drop it.
The ladder's other blind spot is that it's usually argued on quality, but the case for fine-tuning is usually economic. A 3,000-token system prompt with twenty few-shot examples costs 3,000 prefill tokens on every call. At an illustrative 20M calls/month, that's 60B input tokens a month spent re-teaching the same behavior. Put that behavior into a small tuned model and it can run on a model a tier cheaper and a prompt 10× shorter. That can pay for the training, the eval harness and the ongoing maintenance within a quarter. The same arithmetic runs the other way: at 50k calls/month, the long prompt is a rounding error and fine-tuning is pure liability.
Work it through with illustrative prices, since yours will differ. A large hosted model at $3 per million input tokens and $15 per million output, called with a 3,000-token prefix, 300 tokens of user input and 400 tokens of output, costs about $0.016 per call. A tuned small model at $0.30 / $1.20 per million, with the prefix cut to 300 tokens, costs about $0.0007. The difference is roughly $0.015 per call. Against it, put the fixed cost of owning a fine-tune: an engineer's share, the eval harness, a retrain each quarter and a serving floor. Call it $16k a month. Break-even is 16,000 ÷ 0.015, about 1M calls a month. At 20M calls it's roughly $320k against $30k. At 100k calls you're paying $16k a month to save $1.5k.
Prompt caching pushes break-even from about 1M to about 2.2M calls a month, which more than doubles the volume you need before fine-tuning pays. Below that, the flat gold line is ownership cost with nothing to show for it.
The conventional pitch, "fine-tune to shorten your prompt", is now mostly wrong, and prompt caching is why. Most providers bill a cached prefix at a steep discount; assume 10% of the input rate for the arithmetic. Once the 3,000-token prefix is cached, the large model's per-call cost roughly halves in this example, and what's left is dominated by output tokens at the large model's rate. So the real saving from fine-tuning is the model tier, not the prompt length. That changes the evaluation you need. The question is no longer "does the tuned model match the prompted one on the same base?" It's "does a model one or two tiers smaller, tuned, match the large one on every slice that matters?" That's a much harder bar, and it's the one worth measuring before anyone books GPUs.
Decision criteria
Full fine-tuning moves every weight and yields a full model copy per task. PEFT freezes the base and trains well under 1% of the parameters, producing a checkpoint in megabytes that sits alongside hundreds of others on one base. For applied work PEFT is the default and LoRA its dominant form. The part that's usually misunderstood is what PEFT saves. It saves memory and storage. It saves much less compute than people assume.
Training compute for a dense transformer is roughly 6 · N · D FLOPs: 2ND for the forward pass, and about 4ND for the backward pass, split evenly between gradients with respect to activations and gradients with respect to weights. LoRA skips most of the weight-gradient half, because the base weights are frozen. It cannot skip the activation-gradient half, because the gradient still has to flow back through every frozen layer to reach the adapters below it. So a LoRA step costs about 4ND, around two-thirds of a full step, not 1%. Work it through for an illustrative SFT run: 5,000 examples at 1,500 tokens for 3 epochs is 22.5M tokens. On an 8B model that's 6 × 8e9 × 2.25e7 ≈ 1.1e18 FLOPs for full fine-tuning. An H100 is rated near 1e15 dense bf16 FLOP/s; at 40% utilization that's under an hour of one GPU. Even a 70B model is single-digit GPU-hours of arithmetic.
That's the first quantitative point senior engineers should take away: for SFT at applied scale, GPU compute is a rounding error. A run that costs tens of dollars in GPU time, hyperparameter sweep included, sits on top of weeks of dataset curation, an eval harness, safety re-testing and a retrain obligation at every base upgrade. Budget, headcount and roadmap conversations that start from "training is expensive" are arguing about the wrong line item. What PEFT really buys is that the optimizer state no longer dominates memory, which decides whether the run fits on one card or needs a sharded cluster, and that serving many variants becomes possible (4.6).
The memory math shows why. Mixed-precision AdamW keeps about 16 bytes per trainable parameter: bf16 weights and gradients, an fp32 master copy, and two fp32 moment tensors. For an 8B model that's about 128 GB before a single activation, so full fine-tuning goes multi-GPU with sharded optimizer state (ZeRO-3/FSDP) straight away. With LoRA that 16 B/param applies only to the adapter's tens of millions of parameters, and the frozen base costs its bf16 footprint.
Two consequences people miss. First, once the optimizer term disappears, activations become the budget. An 8K-context SFT run with a few sequences per micro-batch can OOM an 80 GB card that's holding a 17 GB model, so gradient checkpointing (roughly a third more compute) and sequence packing matter more than the choice of rank. Second, "frozen base means no forgetting" is too strong. LoRA forgets less, but the adapter still steers every forward pass. The failure that reaches production is alignment erosion: fine-tuning a safety-tuned chat model on entirely benign task data has been shown (Qi et al., 2023) to measurably weaken its refusals. Whatever safety eval the base passed, re-run it on the adapter. Don't inherit the result.
LoRA bets that the update a fine-tune needs is low-rank, and learns it as W + BA with a rank r that's tiny next to d. The bet has a consequence people rarely state: a rank-r update can only move the model along r directions per matrix. That's plenty for behavior (format, tone, when to refuse, which tool to call), which the base already knows how to do and only needs steering toward. It's not enough for a large new body of knowledge or a new language, which is where full fine-tuning or continued pretraining still win. Biderman et al. (2024) put a title on it: "LoRA Learns Less and Forgets Less". Those are one property, not two, and you choose it on purpose.
Merged or unmerged is a serving decision with real latency consequences. Merged (W' = W + BA computed once), the adapter costs nothing at inference, but you now have a full model copy and lose multi-adapter batching. Unmerged, every adapted linear layer does two extra skinny matmuls per token. For a single adapter that's a few percent of FLOPs, but at decode those extra kernels are launch- and memory-bound rather than compute-bound, so the measured latency overhead is larger than the FLOP count suggests. Measure it on your stack before promising a TTFT or inter-token SLO. Two training-side facts save a sweep. LoRA generally wants a learning rate roughly an order of magnitude higher than full fine-tuning of the same model. And B is initialized to zero, so step 0 is exactly the base, which makes "adapter at step 0 vs base" a cheap sanity check of your eval pipeline.
QLoRA stores the frozen base in 4-bit NF4 (about a quarter of its bf16 footprint, visible as the bottom row of the 4.2 budget) and trains a bf16 adapter on top. The base never updates, so its quantization error is fixed rather than compounding. The QLoRA paper's headline result was a 65B fine-tune on a single 48 GB GPU. The bill arrives as step time: every matmul dequantizes NF4 blocks to bf16 on the fly, so a QLoRA step is typically noticeably slower than the same LoRA step on a bf16 base. Use it when memory is the constraint, not by default.
Failure mode
On rank: the knob that actually moves results is usually which modules get adapters, not r. Attention-only LoRA (the original q/v recipe) underfits behavioral changes that the MLP blocks carry. Adapting all linear layers at r=16 generally beats q/v-only at r=64, for a similar parameter count. And because the update is scaled by α/r, raising r without re-tuning α or the learning rate changes the effective step size. That's how a "just try a bigger rank" experiment gets confounded.
"Quality over quantity" is true and useless. What senior teams need is the mechanism: SFT is maximum-likelihood imitation, so the model reproduces the distribution of your targets, errors and inconsistencies included. If 8% of targets use a different date format, you've trained an 8% date-format bug. If two annotators disagree on when to refuse, the model learns to refuse at random. Most of the work is deciding which examples not to train on, and the yield from raw logs is usually brutal.
Raw production transcripts
sampled from 90 days of logs
After exact + near-dup removal
MinHash on normalized prompts; templated traffic collapses
After PII / policy / consent filter
tenant opt-out, retention, redaction
Target rewritten or judged correct
current model's wrong answers dropped or fixed
Stratified to slice quotas
cap head intents, top up rare ones
Frozen eval set (never trained on)
held out before any other step
Bar length is square-root scaled so the tail stays visible. The largest cut is the correctness step: logs record what the current model said, and training on them unfiltered teaches the new model its predecessor's mistakes.
The funnel hides three traps. First, production logs are the incumbent model's outputs. Train on them unfiltered and you distill the old model's failure modes into the new one, and each generation compounds the last. Every target needs to be judged correct against a rubric or rewritten, and that step is where the headcount goes. Second, dedup must run on the prompt side after normalization. Templated traffic (the same form with different IDs) looks unique byte-for-byte and is a single example semantically. Left in, it lets 40% of the set teach one intent. Third, the eval split has to be carved out first and frozen, before dedup and before any rewriting, and then near-dup-checked against the train set. Otherwise near-duplicates leak across and the eval measures memorization.
How many examples you need is an empirical question with a cheap answer. Train on 25%, 50% and 100% of the set and plot the eval score. If the step from 50% to 100% is inside the eval's noise, more data of the same kind won't help; fix quality or coverage instead. If the curve is still climbing steeply, the next dollar goes to data, not to rank or epochs. That noise band is wider than most teams think. At an 80% pass rate, a 200-item eval has a 95% confidence interval of about ±5.5 points (√(0.8·0.2/200) ≈ 2.8%). A 1,200-item eval gets you to about ±2.3. Two independent runs need roughly 2,600 items each (80% power) to reliably detect a 3-point difference. Score both models on the same items and compare them item by item. Only the items where they disagree carry signal, which cuts the requirement sharply. A 200-item vibe check cannot see the regressions that matter.
The rendering layer is where "it trained fine" turns into "it's broken in prod". The chat template must be byte-identical to what the serving stack renders: role markers, special tokens, whitespace after the assistant tag, and the system prompt you'll actually ship, not the one from the notebook. Loss masking must cover only assistant tokens and the end-of-turn token. Train on user tokens and the model learns to continue the conversation as the user. Mask the EOS and it learns never to stop. The first you'll notice is a rising output-token bill, not an eval failure, because most evals truncate. Packing several short examples into one row is worth 2–4× throughput when examples are short relative to the context length, but without per-document attention masking, example two attends to example one. That shows up as answers that borrow entities from unrelated conversations, a bug nobody finds by reading loss curves.
Failure mode
Synthetic data from a larger teacher model (distillation) is the default way to bootstrap a set now, and it fails in its own ways. The student inherits the teacher's errors and verbal tics, and generated prompts cluster far more tightly than real traffic does. Embed a sample of production prompts and a sample of synthetic prompts, then check coverage. Regions of real traffic with no synthetic neighbors are where the tuned model will fall back to base behavior, or worse. Also read your teacher provider's terms: several restrict using outputs to train competing models, and that's a legal review item, not an engineering one.
SFT can only say "produce this". Preference tuning can say "this rather than that", and that's the only way to teach judgments that have no single correct target: how terse to be, when to ask a clarifying question, when to decline. The first design-review question is whether you actually have a preference gap. If the tuned model's failures are wrong answers or broken formats, more or better SFT data is the fix. Preference tuning on top of a weak SFT model optimizes the margin between two bad answers.
RLHF · reward model + PPO
Collect prefs
chosen vs rejected
Train reward model
predicts a score
PPO optimize
policy chases reward
DPO · direct preference optimization
Collect prefs
chosen vs rejected
Direct loss
raise chosen, lower rejected
Operationally, the comparison is about moving parts. RLHF with PPO keeps four models live (policy, frozen reference, reward and value), generates inside the training loop, and has a reward model the policy will learn to exploit given enough steps. DPO shows that the same objective, under a KL constraint to the reference, can be optimized as a classification-style loss directly on (chosen, rejected) pairs. That leaves one offline stage with two models, the policy and a frozen reference, whose log-probs can be precomputed. β sets how far the policy may drift from that reference; values around 0.1 are the common starting point. When your signal is thumbs-up and thumbs-down on single responses rather than pairs, KTO-style objectives use it without inventing pairings. For teams tuning open models, DPO or a variant is the pragmatic default. Online RL earns its complexity mainly when you have a verifiable reward, such as tests that pass or answers that check, rather than a learned one.
"Simpler and more stable" hides three failure modes that show up in production:
The diagram is the monitoring spec. Every DPO dashboard shows the green line, and it looks healthy right up to the point where the model has started producing text neither the reference nor your annotators would recognize. The run has to log the chosen and rejected log-probs separately, and it has to evaluate a held-out behavioral check at every checkpoint: format validity, refusal rate, mean output length. Select the checkpoint on those, not on final-step loss. Two mitigations are cheap. Add an SFT term on the chosen response to the preference loss, which several DPO variants do, so the chosen likelihood is anchored. And keep preference runs to one or two epochs over fresh, on-policy pairs rather than many epochs over a stale set.
On volume, a few thousand high-agreement pairs usually outperform tens of thousands of noisy ones, for the same reason as in 4.4. Pairs where annotators or judges disagree teach nothing but noise to a margin loss. Measure inter-rater agreement on a sample. Where agreement is near chance, the preference itself is ill-defined, and that's a product decision to settle, not a training problem. If an LLM judge produces the labels, its position and length biases become the model's biases. Randomize the order, and length-normalize or length-match pairs before you trust any win rate.
LoRA's real operational payoff shows up at serving time. Because an adapter is tiny and the base is shared, you don't need a dedicated deployment per fine-tune. Multi-LoRA serving keeps one base model resident in GPU memory and a bank of small adapters ready to swap in. A router picks the right adapter per request, and modern serving stacks even batch requests for different adapters together — applying each request's adapter within the same batched forward pass (the S-LoRA approach).
This changes the unit economics completely: you can serve hundreds of distinct fine-tunes — one per customer, per tenant, per task — off a single base at a fraction of the cost of dedicated deployments. The alternative is merging an adapter into a dedicated deployment: you fold W + BA into a standalone model with zero adapter-routing overhead and the simplest possible serving path. Merge when a fine-tune is high-volume and stable enough to earn its own box; keep adapters hot-swappable when you have many low-to-medium-traffic fine-tunes to amortize.
The capacity math says where "near the cost of the base" stops being true. An r=16 all-linear adapter on an 8B model is about 42M parameters, roughly 84 MB in bf16; at r=64 it's about 340 MB. Pinning 64 of the smaller ones in GPU takes about 5.4 GB, and that memory comes out of the KV cache, not out of thin air. On a card where the KV cache got, say, 40 GB, you've given up about an eighth of your concurrent sequences to hold adapters (illustrative). Then there's compute: heterogeneous-adapter batches need gather-style kernels (Punica/S-LoRA's SGMV-type kernels). Their per-token overhead grows with the number of distinct adapters in a batch and with the largest rank present, so one r=128 tenant slows every request batched with it. Cap ranks at the platform level.
GPU slots · hot
pinned next to the KV cache
load: ≈ 0 ms
Host RAM · warm
PCIe copy of tens of MB
load: single-digit ms
Object store · cold
fetch + deserialize + copy
load: 100s of ms → s
thrash cascade
The fix is not a bigger LRU. It is admission control: size GPU slots to the p95 count of distinct adapters active in a batch window, route each tenant to a small set of replicas so the working set per replica stays bounded, and prefetch from warm on routing, not on first token.
Decision thresholds, in rough terms: merge and give it its own deployment once one adapter keeps a replica busy on its own traffic. At that point, shared-batching overhead and slot pressure cost more than the idle risk. Keep it multi-LoRA while each adapter's traffic is a small fraction of a replica and the distinct-active-adapter count per replica fits the GPU slots at p95. Watch the long tail: 500 tenants with Zipf-shaped traffic means a few hot adapters and hundreds that go cold, and every cold request pays a cold-tier load on its first token. Either promise those tenants a looser TTFT SLO, or pre-warm on session start.
The build-vs-buy call for fine-tuning is usually made on training convenience, which is the least important dimension. A hosted fine-tuning API makes the training run trivial and hands you a model ID. What you've actually bought is a model you can't export, whose base the vendor will retire on its own schedule, often billed per token at a premium over the untuned base. Owning open weights inverts every one of those: the weights are portable and the base never retires, but you now pay a serving floor around the clock whether traffic arrives or not.
Make the floor concrete with illustrative numbers. One 80 GB GPU at $2.50 an hour is about $1,800 a month. Two replicas for availability, which you need the moment the fine-tune sits on a user path, is $3,600 a month before engineering time, idle or not. A hosted fine-tune at an illustrative $0.002 per call costs the same at 1.8M calls a month. Below that the lease is cheaper; above it, the mortgage wins, and it wins faster with multi-LoRA, because the second through hundredth adapters ride on the same floor. Capacity planning for that floor is covered in GPU Infrastructure & Scheduling.
The underpriced risk on the hosted side is the deprecation calendar. When the vendor retires the base, every fine-tune on it has to be retrained on the successor and re-evaluated against the incumbent, on the vendor's timeline rather than yours. If the retrain dataset or the eval harness has rotted in the meantime, the choice becomes "fall back to the prompted large model at roughly 20× the per-call cost of the 4.1 example" or "miss the date". Teams that go hosted should treat the dataset, the rendering code and the eval suite as the real asset, and the model ID as a disposable build output. On the owned side, the matching failure is a platform nobody staffs: GPU drivers, the inference server, autoscaling and adapter residency all become your pager.
The identity of a fine-tune is not the checkpoint. It's the tuple (base version, quantization, dataset hash, rendering code, recipe, seed), and change any element and you have a different model. Store the tuple as the release record, and make promotion a gate over it, not over a file in a bucket: beat the incumbent on the frozen eval, per slice, at serving precision, then roll out behind the same canary and shadow machinery described in Reliability, Cost & Rollouts. Rollback should be a routing change to the previous adapter, which means the previous adapter stays resident, or at least warm, until the new one has survived a full traffic cycle.
~6ND
full-FT FLOPs; LoRA ≈ 4ND
< 1 GPU-h
8B SFT, 22M tokens (illus.)
±5.5 pts
95% CI, 200-item eval at 80%
~84 MB
r=16 adapter, 8B, bf16
Every fine-tune is a standing liability with three renewal triggers. The base upgrades, and the adapter is welded to the old weights. The input distribution drifts: new product surfaces and new user phrasings land in regions the training set never covered, and the tuned model degrades there more sharply than a prompted model would, because it was pulled toward a narrower distribution. And the data obligations change. That third trigger is the one architects underestimate, so it gets its own paragraph below. Drift detection for tuned models belongs in Observability & Evaluation Ops. What matters here is that each trigger costs a retrain, and the retrain is only cheap if the pipeline is.
Base v1 → v2
vendor release or deprecation date
N adapters orphaned
a v1 adapter is noise on v2 weights
Retrain × N
needs the pinned dataset + recipe for each
Re-eval × N
each vs its own incumbent, not a global score
Dual-serve, migrate
both bases resident during cutover
The diagram is why reproducibility isn't bureaucracy. The retrain step fails in the boring way: the dataset was a notebook export that no longer exists, a tenant's data was deleted under a retention policy, or the chat template changed between base versions and nobody re-rendered the examples. Each of these turns an automated migration into a manual, per-tenant rescue. The eval gate has its own trap. A single aggregate score can go up while one slice regresses badly, typically the refusal slice, the structured-output slice, or the long-context slice. Gate on per-slice non-regression with explicit tolerances, and include the base model's general-capability suite so you catch the forgetting from 4.2.
Weights are derived data, and derived data inherits obligations. If a tenant's transcripts trained an adapter and the tenant invokes deletion or leaves, the defensible position is usually to retrain without their data, not to argue that the weights don't "contain" it. Fine-tuned models can regurgitate rare training strings verbatim, and that has been demonstrated on real models. The architecture follows from this. Train per-tenant adapters on per-tenant data wherever a shared adapter isn't clearly worth it, so deletion is "drop an adapter and retrain one" rather than "retrain the model every tenant shares". Never train a shared adapter on pooled tenant data without redaction and contractual cover, because memorized strings leak across tenants: tenant A's customer names can surface in tenant B's completions. And keep a lineage map from each training row to every artifact built from it, since the day you need it is the day a regulator or a customer asks.
Questions to ask in a design review
Where next