13A.8 Decision Frameworks: Eight Decisions Plus One
Most AI projects go wrong at a decision, not at a line of code: an agent where a three-step workflow would do, a fine-tune where a prompt would do, or full autonomy where a human should have been asked. This lesson collects the eight decisions you will make again and again, plus a ninth about evaluation tooling, and gives each one the same treatment: the question, a decision table or flowchart, a default answer, the signals that should make you switch, the cost of being wrong, a worked example and links to the lessons that teach each option. It ends with a one-page worksheet and a small runnable decision-record helper that scores your answers and writes an architecture decision record.
One of the nine, prompting vs RAG vs fine-tuning, is the decision teams get wrong most often, so it gets the long treatment. Parts 1 to 9 are that decision in depth, and they are the decision guide that lesson 02.6, 13.2 promised and lesson 02.1, 7.4 pointed at: a ladder of interventions from "write a better prompt" up to "change the model's weights", what each rung actually changes, what fine-tuning looks like in 2026 across every major provider, how to prepare data and evaluate a tune, and the economics that decide whether any of it is worth doing. You will not learn to train a model here, because this path teaches building products on top of models, but you will learn exactly when reaching for training is the right engineering call, and when it is the expensive way to solve a prompt problem. Parts 10 to 13 add the framework and the other eight decisions.
What you'll learn
- The eight recurring decisions (workflow vs agent; single vs multi-agent; RAG vs long context; prompting vs RAG vs fine-tuning; human approval vs full autonomy; build vs buy including managed provider tools; quality vs cost vs latency; capability vs security) plus a ninth, bespoke eval harness vs an eval framework: for each, the default, the switch signals, the cost of being wrong and where to learn each option
- How decisions interact (some combinations contradict each other), how to write a short decision record so the reasoning survives the team changing, and a one-page worksheet for design reviews
- The decision ladder: better prompting → structured output and tools → RAG → a better or routed model → fine-tuning → pretraining, with each rung's cost, time-to-change, risk and maintenance burden
- What each technique physically changes in the system (behaviour per call vs knowledge at inference vs behaviour in the weights vs actions), and the symptom → treatment table that maps real failures to the right rung
- When fine-tuning genuinely is the right answer — and the longer list of when it isn't, including how prompt caching and long-context stuffing weaken the case
- The 2026 fine-tuning landscape, verified provider by provider: who still offers hosted fine-tuning, in what format, at what price, and what happened to OpenAI's and Mistral's platforms
- Preference optimisation (DPO), reinforcement fine-tuning (RFT/RLVR) and distillation in plain English, including the legal map of whose outputs you may train on
- Fine-tuning open models yourself with LoRA/QLoRA: the libraries, the hardware arithmetic and a minimal annotated config — awareness, not a training course
- Fine-tuning the components around the model: embedding models and rerankers
- How much data you actually need (with sources), how to clean and split it, and a dataset preparation script you can run today
- How to evaluate a fine-tune honestly: baselines, paired statistics, general-ability regression and catastrophic forgetting
- The cost/benefit arithmetic, a decision flowchart, and five worked case studies
What you don't need
- API keys or GPU access. Everything runnable in this lesson is pure Python with the standard library; the hosted-provider material is reference you read, not code you run. If you later want to call a provider, lesson 03.1 covers keys and setup.
- A machine-learning background. Terms like SFT, LoRA, DPO and RLVR are defined where they first appear; the training-theory depth lives in lesson 02.6.
- Prior fine-tuning experience — that is the point of the lesson.
Setup
Python 3.11+ only; no packages, no keys, no services. Save the three scripts from Parts 1 to 9 (prepare_dataset.py, ftecon.py, fteval.py) into one folder and run them directly:
python3 prepare_dataset.py --demo --outdir demo_prepare
python3 ftecon.py
python3 fteval.py --demoThe decision-record helper in Part 12 is two more files, decisions_data.py and adr.py, run the same way with python3 adr.py. As of 1 December 2026 it also uses only the standard library.
(uv run python prepare_dataset.py ... works too if you prefer running inside a uv project; nothing is installed either way.) Every output shown below is the real output of these commands. The provider facts are dated "as of November 2026" — this market moves monthly, and Part 4 shows you where to re-check each claim.
What you must be able to do after this lesson#
- Climb the decision ladder from prompting to fine-tuning in order, and explain what prompting, RAG and fine-tuning each change
- Decide whether fine-tuning is justified, and explain why it is the wrong tool for adding knowledge
- Prepare and split a fine-tuning dataset
- Evaluate a fine-tune against a baseline with paired statistics and a regression check
- Compare costs to make the final fine-tuning decision
- State the default, the switch signals and the cost of being wrong for each of the nine recurring decisions
- Write a decision record with a measurable revisit trigger, and check that your answers do not contradict each other
Why this matters for an AI engineer#
This is the lesson every earlier module pointed at for one decision, and the one production teams get wrong most often: usually by fine-tuning when a prompt would have done, or by prompting forever when the economics favoured a smaller tuned model. It is also the map for the other decisions you will face, because seniority in this field is mostly judgement about trade-offs. Models and frameworks change every quarter; the shape of the decisions does not. Being able to say "we chose a workflow because the steps are known and we cannot verify an open-ended agent, and we will revisit when the eval says otherwise" is what turns a demo into a system that can be maintained.
| You'll hear... | You'll understand it after... |
|---|---|
| "Should we fine-tune or just improve the prompt?" | Part 1: The decision ladder |
| "The model keeps getting the format wrong." | 2.2 Symptom → treatment |
| "We want the model to know our 4,000-page policy handbook." | 2.4 What fine-tuning cannot fix and Part 3 |
| "OpenAI deprecated fine-tuning — what do we do now?" | 4.2 The hosted landscape, provider by provider |
| "Can we distil GPT outputs into our own small model?" | 5.3 Distillation and the legal map |
| "How much data do we need for SFT?" | 7.1 How much data |
| "Our fine-tune scores better — are we done?" | Part 8: Evaluating a fine-tune |
| "Is fine-tuning even worth it at our volume?" | Part 9: The economics |
| "The base model got an update and our tune went stale." | 9.5 Fine-tune rot |
| "Do we need an agent for this?" | 11.1 Workflow vs agent |
| "Why not just add another agent?" | 11.2 Single vs multi-agent |
| "Can't we just put the PDFs in the prompt?" | 11.3 RAG vs long context |
| "Does a human need to approve this?" | 11.5 Human approval vs full autonomy |
| "Use the provider's built-in tool or build our own?" | 11.6 Build vs buy |
| "It's accurate but too slow and too expensive." | 11.7 Quality vs cost vs latency |
| "Security says no, product says we need it." | 11.8 Capability vs security |
| "Do we need DeepEval, or is our script fine?" | 11.9 Bespoke harness vs framework |
| "How do we write this decision down?" | Part 12: the decision-record helper |
Part 1: The decision ladder#
1.1 Six rungs, cheapest first#
There are only two physical levers for changing what a model does: change the context you send it (the prompt, the retrieved documents, the tool definitions, the conversation state), or change the weights through training. Everything in this lesson is a point on the spectrum between those two poles — and the spectrum is a ladder, because each rung up costs more time, money and risk, and buys capability the rungs below couldn't reach.
| Rung | Intervention | What it changes | Time to ship a change | Recurring cost | Main risk |
|---|---|---|---|---|---|
| 0. Do nothing yet | Measure first: evals, traces, error analysis | Nothing — but tells you which rung you need | Days | None | Skipping it: you buy the wrong fix |
| 1. Better prompt & context | Clearer instructions, better examples, schema design, context selection/budgeting (Module 04) | Behaviour per call | Minutes to days | Prompt tokens only | Prompt bloat; fixes that don't generalise |
| 2. Structured output & tools | Constrained decoding, strict schemas, function calling (03.4, 03.5) | Format guarantees; access to fresh data and actions | Days | Tool round-trips | Schema limits; tool errors become model errors |
| 3. RAG | Retrieve relevant documents into the prompt (Module 07, building on Module 05 and Module 06) | Knowledge at inference time | Weeks | Embedding + search + bigger prompts | Retrieval quality becomes your quality ceiling |
| 4. Better model or routing | A stronger base model, a model cascade, per-task routing (02.9 Part 10, 11B.5) | Capability per call | Days | Higher per-token price | Cost; you may be paying frontier prices for easy queries |
| 5. Fine-tuning | SFT, preference tuning, RFT or distillation on your own data (this lesson) | Behaviour, style, format and narrow skills in the weights | Weeks | Training + serving + maintenance | Stale knowledge; forgetting; a pipeline you now own |
| 6. Pretraining / continued pretraining | Train or extend a base model on raw text | Everything the model knows | Months, millions of dollars | A research programme | Out of scope — see 1.4 |
1.2 The ladder in one picture#
flowchart LR
subgraph cheap ["Cheap, fast, reversible"]
R1["1. Prompt &<br/>context engineering"]
R2["2. Structured output<br/>& tools"]
R3["3. RAG"]
R4["4. Better model<br/>or routing"]
end
subgraph dear ["Expensive, slow, sticky"]
R5["5. Fine-tuning"]
R6["6. Pretraining /<br/>continued pretraining"]
end
R1 --> R2 --> R3 --> R4 --> R5 --> R6
R6 -.->|"almost never for product work"| R1The arrow only points one way for a reason: you climb the ladder when a cheaper rung measurably fails, and you never skip rungs to reach fine-tuning, because each rung below it is both cheaper to try and easier to undo. A prompt change ships in a PR; a fine-tune ships in weeks and then lives in production until someone retrains it.
1.3 Why the order is not optional#
Lesson 04.2, 6.6 documented OpenAI's own escalation path explicitly: zero-shot → static few-shot → dynamic few-shot via retrieval → fine-tune. Lesson 04.9, 2.3 gives the debugging version: fix the prompt → fix the context → fix the schema/tools → try a stronger model → then consider training, "and only when you have hundreds of labelled examples and a measured gap no prompt closes."
The reason is epistemic, not just economic. You cannot know a fine-tune is necessary until the cheaper rungs have been measured and exhausted. Teams that skip to rung 5 routinely discover that their "the model can't do this" was actually "the prompt never said what 'this' looks like", or "the retrieval was returning the wrong chunks", or "the schema rejected half the good answers". A fine-tune trained on top of an undiagnosed failure bakes the failure into the weights.
There is a second, subtler reason: each rung generates the data the next rung needs. Prompt iteration produces the failure analysis that tells you whether retrieval or tuning is the fix. Retrieval logs produce the query distribution a router or a fine-tune should be built on. Eval sets built for rung 1 become the acceptance test for rung 5. Skipping rungs doesn't just cost money — it starves the decision of evidence.
1.4 The five classic mistakes#
- Fine-tuning to add knowledge. Weights are a snapshot; facts go stale the day after training. Knowledge that changes belongs in context (RAG, tools, fresher prompts). 2.4 makes this concrete.
- RAG to fix style. Retrieval supplies what to say, not how to say it. Wrong tone, wrong format, wrong persona — those are behaviour problems, and behaviour lives in the prompt (or, at volume, in the weights).
- Prompt-bloat instead of fine-tuning. Cramming 40 few-shot examples into every call to stabilise format is a tax on every request forever — input tokens, latency, cache pressure. At sufficient volume and stability, baking the behaviour into a small tuned model is cheaper (3.3).
- Skipping evals. OpenAI's fine-tuning guide says it verbatim: "Good evals first! Only invest in fine-tuning after setting up evals." Without a baseline you cannot tell improvement from noise — Part 8 is entirely about this.
- Training on your eval data. If eval items leak into the training set, your metrics measure memorisation, not capability. 7.4 and
prepare_dataset.pyexist to prevent exactly this.
Rung 6 deserves a paragraph because teams do ask. Pretraining and continued pretraining mean training a model on raw text at dataset scale — trillions of tokens, thousands of GPU-hours, research-level data pipelines (lesson 02.6, Parts 2–4). Continued pretraining (domain-adaptive pretraining on your corpus) is the cheap-ish cousin, but it still needs GPU infrastructure, a data pipeline at corpus scale and an evaluation programme — it is a model-research project, not an application feature, and this path deliberately stops at "build on trained models". If a product truly needs a custom foundation model, that is a different job posting.
Part 2: What each technique actually changes#
2.1 Two levers: context vs weights#
Lesson 02.1, 7.4 (optional; 02.6, 13.2 covers the same choice) established the frame this whole lesson runs on: there are only two ways to change an LLM's behaviour. You can change what you send (context) or change the model itself (weights, via training). Everything between those poles is a question of which part of the request pipeline carries the fix.
| Technique | Where the "knowledge" or "behaviour" lives | Changes when... | Billed as... |
|---|---|---|---|
| Prompting / context engineering | Your prompt template, per call | You edit the template | Input tokens, every call |
| Structured output / tools | Your schema and tool definitions, per call | You edit them | Schema tokens + tool round-trips |
| RAG | Your index, retrieved per call | The corpus or the retriever changes | Embedding + search + retrieved tokens |
| Routing / model choice | Your router config, per call | You change the route | Whatever the chosen model costs |
| Fine-tuning (SFT/DPO/RFT) | The model's weights | You run a training job | Training once + inference forever |
| Distillation | A different, smaller model's weights | You train the student | Teacher calls + student training + cheap inference |
| Pretraining | The base model's weights | A research project | Enormous, once |
The production insight hiding in this table: rungs 1–4 are configuration; rung 5 is a build artefact. Config changes are reviewable, testable and revertible in the same way as code. A fine-tune is a model — it has a lifecycle, a deprecation date, an eval history and a serving bill, and it interacts with everything else in your stack (prompt templates, structured-output schemas, tool formats) exactly the way a new base model does.
2.2 The symptom → treatment table#
This is the table to keep open when a feature misbehaves. Read the symptom column honestly — the treatment only works if the diagnosis is right.
| Symptom you observe | Most likely rung | Why not the others |
|---|---|---|
| Wrong format, wrong field names, JSON that won't parse | 1 → 2: prompt/schema work first; constrained decoding (03.4) if the model supports it | Fine-tuning can teach format, but a schema fix is free and instant; try it first |
| Wrong tone, wrong persona, inconsistent voice | 1, then 5 only at volume | RAG can't fix tone; if 50 examples in the prompt can't stabilise it and you have thousands of labelled examples, a tune can |
| Missing facts the model should know (policies, products) | 3: RAG, or 2: tools for live data | Fine-tuning bakes a snapshot that is stale on arrival; see 2.4 |
| Outdated facts (prices, dates, "the model doesn't know it's 2026") | 1: put the date/current data in context; 2: tools | Never fine-tune for freshness — it is stale by design |
| Hallucination on general knowledge | 1/2: grounding, citations, verification, abstention (02.10) | Fine-tuning can reduce a specific hallucination pattern but cannot make a small model knowledgeable; evals decide |
| Long-tail domain jargon the model keeps misreading | 1: glossary in context; 3: domain docs; 5: only if prompting measurably fails at volume | A tune teaches behaviour on jargon, not the jargon itself — unless the jargon is stable and narrow |
| Cost too high at scale | 4: route easy queries to a cheaper model; 1: trim prompts; 5: distil to a small tuned model | Fine-tuning a larger model doesn't reduce cost; tuning a smaller one does (3.3) |
| Latency too high | 1: shorter prompts, less reasoning effort; 2: fewer tool round-trips; 4: faster model tier | Fine-tuning doesn't make decode faster; a smaller tuned model can |
| Inconsistent outputs run-to-run on the same input | 1: tighten instructions, add examples; check sampling settings (02.5) | Fine-tuning reduces variance for a narrow behaviour but never eliminates it |
| Small model quality gap vs frontier on a narrow task | 5: SFT or distillation from the frontier model | This is the canonical fine-tuning case — see Part 3 |
| The model ignores your system prompt on edge cases | 1: few-shot the edge cases; 4: stronger model | Instruction-following is trained behaviour (02.6, 6.3); a tune can deepen it for your distribution |
| You need the model to act (call APIs, update systems) | 2: tool calling — not a knowledge problem at all | Fine-tuning can teach tool-call format (OpenAI's SFT docs literally support tool-call examples) but the actions still need tools |
2.3 The overlap zone: when two treatments both fit#
Real problems rarely sit in one cell. Three recurring overlaps:
- Format + knowledge. A support bot that must answer in a strict JSON schema from the policy docs. Answer: RAG for the knowledge, schema-constrained output for the format, and only fine-tune if the combination still fails at volume. The techniques compose — a fine-tuned model can still call RAG (9.4).
- Style + cost. You want a cheap small model to sound like your brand. Answer: prompts first; if the gap is stable and high-volume, SFT or distillation onto the small model is the textbook case.
- Classification at scale. Routing tickets into 40 categories with subtle boundaries. Answer: structured output with an enum first; if the enum accuracy plateaus below your SLA and you have thousands of labelled tickets, fine-tuning a small classifier is a legitimate rung-5 case — and sometimes a plain classifier model (not an LLM at all) wins; that's a Module 10A evaluation question.
2.4 What fine-tuning cannot fix#
Be clear-eyed about the ceiling before you spend anything:
- It cannot add fresh knowledge. The weights freeze at training time. Ask the tuned model about yesterday's news and you get yesterday's training data — confidently. This is the single most common reason fine-tunes disappoint: people train on documents expecting the model to "know" them forever.
- It cannot cite. A tuned model has no mechanism to point at a source passage the way grounded RAG does (07.5). If your requirement is "show me where this came from", retrieval is the answer, not weights.
- It cannot exceed its base model's raw capability by much. SFT teaches behaviour on your distribution; it does not turn a small model into a frontier model. Distillation (5.3) closes some of that gap by transferring the teacher's output distribution, but the student still has the student's capacity.
- It still hallucinates. A model trained to always answer will always answer — including wrongly. Safety and grounding behaviours are trained in, not assumed (02.10).
- It can make things worse elsewhere. Narrow training data shifts the model's behaviour distribution; general-ability regression and catastrophic forgetting (the tune degrading skills it had before) are real, measurable risks — Part 8 exists to catch them.
2.5 Two cheap levers that change the arithmetic: prompt caching and long context#
Two features sit inside rungs 1 and 3 and are routinely forgotten when people argue for rung 5:
- Prompt caching discounts the part of a prompt that repeats exactly from call to call. The classic fine-tuning argument, "our 8-example few-shot block costs tokens on every request", is much weaker once that block is a cached prefix, because cached input is billed at a fraction of the normal price on the providers that support it (03.7 owns the mechanics; 11B.3, 2.2 owns the prefix design). Caching does not remove the latency of a long prefill or the work of keeping the examples current, so it narrows the fine-tune advantage rather than erasing it; 9.1 lets you measure how much.
- Long-context stuffing (sometimes called cache-augmented generation) puts a small, stable corpus in the prompt instead of building retrieval. It is a legitimate rung-1/3 alternative when the whole corpus fits comfortably and changes rarely; it loses on large, fast-moving or per-user-permissioned corpora, and when you need passage-level citations (07.1, 1.3 has the decision table). It never makes a fine-tune the answer to a knowledge problem.
The rule of thumb for this lesson: before you credit rung 5 with saving prompt tokens, price rung 1 with caching and rung 3 with a cached stable prefix. If the fine-tune still wins on your measured numbers, it earns its place.
Part 3: When fine-tuning is the right answer — and when it isn't#
3.1 The fit checklist: when rung 5 earns its cost#
Fine-tuning is the right answer when most of these are true:
- The task is narrow and stable. Same input shape, same output contract, same domain, month after month. The behaviour you are baking in won't need to change next quarter.
- You have (or can build) hundreds to thousands of high-quality labelled examples. Not dozens — see 7.1 for the sourced ranges. Quality beats quantity, but quantity still matters.
- A measured gap remains after rungs 1–4. You have eval numbers showing the prompted/routed baseline below target, and the failure is behavioural (format, style, judgement on your distribution), not knowledge (missing facts).
- Volume justifies it. Enough requests that per-call savings (shorter prompts, smaller model) or quality gains repay the training and maintenance cost — Part 9 quantifies this.
- You can evaluate honestly. Held-out eval sets, a general-ability regression check, and the discipline to re-run both on every base-model update (Part 8).
- The behaviour is hard to specify in words. "Sound like our senior support lead reviewing a churn-risk account" is easier to demonstrate with 500 examples than to describe in a prompt. This is the deepest reason fine-tuning exists: some behaviours are cheaper to show than to tell.
3.2 The anti-fit checklist: when rung 5 is the wrong answer#
Fine-tuning is the wrong answer — usually the expensive wrong answer — when:
- The knowledge changes. Prices, policies, product specs, "current" anything. Weights freeze; context doesn't. Use RAG or tools.
- The data is small or noisy. Dozens of examples, or hundreds of unreviewed ones, teach the model your errors. Garbage in, weights out.
- You can't define "better". No eval set, no acceptance metric, "we'll know it when we see it". You will never know whether the tune helped.
- The problem is upstream. Bad retrieval, broken schemas, ambiguous product requirements — training amplifies whatever pipeline feeds it.
- The frontier moves faster than your data. If your task is "general helpfulness" or "reasoning", next month's base model beats this month's tune. Fine-tuning pays when the task is stable, not when the capability is a moving target.
- You want an escape hatch. A tuned model on a deprecated base model is a migration project (9.5). If the provider's roadmap is uncertain — and 4.2 shows how uncertain it is — that risk is real.
3.3 The "small model + tune" arbitrage#
The strongest fine-tuning case in 2026 is not "make the model smarter" — it is "make a cheap small model behave like an expensive big one on one narrow task." This is distillation's home turf (5.3) and it is why fine-tuning economics often invert the usual intuition: you are not paying to improve quality, you are paying once to move down the cost curve permanently.
The shape of the argument: a frontier model at $X per million output tokens handles a task at 96% accuracy; a small open model at $X/10 handles it at 78%. Fine-tune the small model on 2,000 teacher examples → 93% accuracy at $X/10 forever after. At sufficient volume the one-time training cost is noise. This only works when the task is narrow enough that "behave like the teacher on this task" is a well-defined target — which is exactly the fit checklist above.
3.4 The decision, compressed#
flowchart TD
Q1{"What's actually<br/>wrong?"}
Q1 -->|"format / instructions"| P["Rung 1-2: prompt, schema,<br/>tools — days, cents"]
Q1 -->|"missing or stale facts"| G["Rung 3: RAG or tools —<br/>the knowledge must stay fresh"]
Q1 -->|"model not smart/fast/cheap enough"| M["Rung 4: better model,<br/>routing, cascade"]
Q1 -->|"stable narrow behaviour<br/>at volume"| F{"Evals show a gap<br/>no prompt closes?"}
F -->|"no"| P
F -->|"yes, and you have<br/>hundreds+ clean labels"| FT["Rung 5: fine-tune —<br/>if the economics clear"]
Q1 -->|"need a custom<br/>foundation model"| X["Rung 6: not this path —<br/>that's a research project"]Part 4: Fine-tuning in 2026 — the hosted landscape#
Reference
Everything in this part is verified against official documentation as of November 2026. This market is consolidating fast — two of the biggest consumer-facing fine-tuning platforms are in managed decline — so treat every "who offers what" claim as a snapshot and re-check the provider's page before planning around it.
4.1 What a hosted fine-tune job actually is#
Strip away the marketing and every hosted offering is the same pipeline:
- Prepare data — a file of input/output examples in the provider's format (almost always JSONL).
- Upload — the file goes to the provider's file store.
- Create a job — you name a base model, the training file, optional validation file, method and hyperparameters. The provider queues a training run on their GPUs.
- Monitor — the job walks states like
queued → validating → running → succeeded/failed; events expose progress and safety checks. - Get a model ID — a new identifier (OpenAI's look like
ft:gpt-4.1-mini:org:suffix:id) you pass to the normal inference API exactly like a base model. - Serve — inference on the tuned model bills at the provider's rates, sometimes with a premium over the base model, sometimes requiring dedicated/provisioned capacity.
Two consequences engineers miss:
- Training and inference are separately billed and separately versioned. The job is a one-time cost; the tuned model then lives on your inference bill indefinitely, and it inherits the base model's deprecation clock (9.5).
- A fine-tune is not portable. A
ft:model ID exists only on the provider that trained it. If you fine-tune on OpenAI you cannot serve that model through Anthropic; if you fine-tune an open model yourself you own the weights and can serve them anywhere (11C.6). This is the deepest strategic difference between hosted fine-tuning (rented, ephemeral, provider-bound) and open-model fine-tuning (owned, portable, ops-heavy).
Planning for lead time and limits. A hosted job is not instant — OpenAI's SFT guide warns that training "may take several minutes or hours" depending on dataset size, and every provider queues jobs behind shared GPU capacity, so budget days rather than hours from "data ready" to "model serving". Job-creation rate limits and concurrent-job caps exist on most platforms (check each provider's quotas page — Fireworks, for example, publishes a training-GPU quota), and a failed validation or safety check sends you back to the start of the queue. Plan the eval-and-rollback window around the training window, not after it.
sequenceDiagram
participant You
participant API as Provider API
participant GPUs as Provider training infra
You->>API: upload train.jsonl (purpose: fine-tune)
API-->>You: file-abc123
You->>API: create job {model, training_file, method, hyperparameters}
API-->>You: ftjob-xyz (queued)
You->>API: poll job / list events
GPUs->>API: checkpoints + metrics
API-->>You: status: succeeded, fine_tuned_model: ft:...
You->>API: call model "ft:..." like any model ID
Note over You,API: inference billed separately, forever, until base model deprecates4.2 The hosted landscape, provider by provider#
The honest summary first: the era of "upload JSONL, get a custom GPT" is winding down at OpenAI and absent from Google's developer API (it survives only on Google Cloud), while open-model fine-tuning is booming on specialised platforms and clouds. Here is the verified state of each route as of November 2026.
| Provider | Hosted fine-tuning? | Methods | What you tune | Pricing shape | Catch |
|---|---|---|---|---|---|
| OpenAI | ⚠️ Winding down | SFT, DPO, RFT | gpt-4.1 family (SFT); o4-mini (RFT, but its base model shut down 23 Oct 2026) | Per-1M training tokens (SFT) / per-hour (RFT) + inference | Closed to new orgs; new jobs end 6 Jan 2027 |
| Google (Gemini API / AI Studio) | ❌ None | — | — | — | Fine-tuning moved to Google Cloud |
| Google Cloud — Gemini Enterprise Agent Platform | ✅ | SFT, preference tuning, RLFT | Gemini 2.5/3.x + Gemma/Llama/Qwen open models | Per-1K/1M training tokens | Cloud project, GCS datasets, not the AI Studio API |
| Anthropic | ❌ Public API | — | — | — | No self-serve FT; the Bedrock Claude route closed 2026 |
| Amazon Bedrock | ✅ | SFT, RFT | Nova, Titan image/embed, Llama 3.x, Claude 3 Haiku (listed, but EOL 10 Sep 2026) + RFT on Nova 2 Lite/gpt-oss/Qwen3 | Per-token/job + serving | Model list is narrow and region-locked |
| Azure — Microsoft Foundry | ✅ | SFT, DPO, RFT, programmed training | gpt-4o/4.1 family, o4-mini, gpt-5 (invite), open models | Training + hosting SKUs | Programmed Training (preview) and gpt-5 RFT need approval; many open models are preview |
| Mistral — La Plateforme | ⚠️ Deprecated | was SFT | was Mistral flagships | was $4/job min + $2/mo storage | API deprecated; use open weights elsewhere |
| Together AI | ✅ | SFT, DPO, LoRA or full | Dozens of open models (Qwen, Llama, gpt-oss, DeepSeek, Kimi, Gemma) | Per-1M tokens (SFT; DPO about 2.5x) + a per-model minimum charge per job (from $4 on small models to $60 on the largest; Together pricing page, checked 12 November 2026) + endpoint/minute | Fine-tuned models need dedicated endpoints |
| Fireworks AI | ✅ | SFT, DPO, RL (Training API: serverless or dedicated; Managed Training is paused) | Open models (serverless list is limited) | Per-token (serverless training) or per-GPU-hour (dedicated, from $8.00) | Quote with its estimator; verify the model list |
| OpenRouter | ❌ | — | — | — | Inference router only; tracks distillable models for compliance |
OpenAI: the wind-down (the biggest story in this table)
OpenAI's fine-tuning deprecation timeline (verified November 2026) is explicit:
- 7 May 2026 — organisations that had never run fine-tuning could no longer create jobs.
- 2 July 2026 — organisations that hadn't run inference on a fine-tuned model in the previous 60 days lost access too.
- 6 January 2027 — remaining eligible customers lose the ability to create new jobs. Inference on existing fine-tuned models continues until the base model is deprecated.
What remains on the table: SFT on the gpt-4.1 family (gpt-4.1-2025-04-14 and -mini — -nano already shut down 23 October 2026) and RFT on o4-mini-2025-04-16 — and each base model has its own shutdown date (the 4.1 family 14 January 2027; o4-mini 23 October 2026). The SFT data format is the chat-completions JSONL shown in 4.3; job creation is a single API call:
curl https://api.openai.com/v1/fine_tuning/jobs \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{"training_file": "file-RCnFCYRhFDcq1aHxiYkBHw",
"model": "gpt-4.1-mini-2025-04-14"}'The completed job returns "fine_tuned_model": "ft:gpt-4.1-mini-2025-04-14:org:...", hyperparameters (n_epochs, batch_size, learning_rate_multiplier), trained_tokens, and method.type ("supervised" for SFT jobs, "dpo" for preference jobs — with a nested dpo.hyperparameters.beta — and a separate RFT flow for o4-mini). Checkpoints are listable mid-training, and moderation_checks events flag safety failures. The lesson for you: if your org already fine-tunes on OpenAI, plan the migration now — your tuned models die with their base models in early 2027, and the replacement path is either another provider's hosted FT or your own open-model pipeline.
Google: fine-tuning left the developer API for the cloud
The Gemini API (AI Studio) no longer supports fine-tuning — Google's own docs state there is currently no tunable model on that API since Gemini 1.5 Flash-001's deprecation. The supported path is Gemini Enterprise Agent Platform (Google Cloud's tuned-model service, the successor to Vertex AI tuning):
- Methods: supervised fine-tuning (SFT), preference tuning (pairwise chosen/rejected), and reinforcement-learning fine-tuning (RLFT) for reasoning models.
- Models: SFT on Gemini 3.5 Flash-Lite/Flash, 3.1 Flash-Lite, 2.5 Pro/Flash/Flash-Lite; preference tuning only on 2.5 Flash/Flash-Lite and RLFT only on 3.5 Flash and 3.1 Flash-Lite (per the tuning page, checked 8 November 2026 — the matrix is uneven, so check it per method); plus open models — Gemma 3/4 IT, Llama 3.x/4, Qwen3 — all served as tuned endpoints.
- Data: JSONL files in Cloud Storage; the tuning docs describe SFT datasets as "hundreds to thousands" of labelled examples, with "100 examples or more" as the point where tuning is recommended over prompting; RLFT takes dozens-to-hundreds of prompts with
referencesmetadata, and preference tuning takes hundreds-to-thousands of pairs. - Hyperparameters: epochs (auto-scaled to dataset size), adapter size (the LoRA rank — bigger learns more complex tasks but needs more data), and a learning-rate multiplier. Gemini models are tuned with adapters only; for open models the page lists, per model, parameter-efficient tuning, full fine-tuning or both.
- Pricing (verified on the Agent Platform pricing page, 14 November 2026): billed per training token (the dataset's token count × epochs) — e.g. Gemini 3.5 Flash SFT $0.01/1K tokens ($10/1M), 3.5 Flash-Lite $0.003/1K ($3/1M), 2.5 Pro $0.025/1K ($25/1M), 2.5 Flash $0.005/1K ($5/1M), open models SFT per-1M ranging ~$0.28–$8.46 by size. RLFT (3.5 Flash) and preference tuning (2.5 Flash/Flash-Lite) share the rate listed for that model's SFT rather than having a separate row. Serving: for Gemini 3 and later, a tuned-model endpoint costs 1.5x the base model's price in non-global regions and the same as the base in the global region.
- Gotcha: for thinking models, SFT data teaches non-thinking behaviour — set thinking budget to 0 (2.5) or level MINIMAL (3.x) for tuned tasks; use RLFT when you want to tune reasoning.
Anthropic: no fine-tuning, by design
Anthropic's glossary states plainly: "The Claude API does not currently offer fine-tuning." The one documented route — Claude 3 Haiku SFT on Amazon Bedrock — closed in 2026 when the model reached end-of-life in its only supported region (us-west-2, September 2026). Anthropic's position is that prompting, retrieval, tool use, prompt caching and (for enterprise customers) custom arrangements cover the need. Practical consequence: if your stack is Claude-heavy, rung 5 means either routing the narrow task to a tunable open model behind your provider-agnostic client (11B.5 owns routing), or an enterprise conversation with Anthropic. Do not plan a Claude fine-tune into a roadmap.
Amazon Bedrock: fine-tuning inside the AWS perimeter
Bedrock's custom-model fine-tuning docs support:
- SFT for Amazon Nova models, Titan image/embedding models, Claude 3 Haiku (us-west-2 only — and it is the model whose Bedrock route just closed with EOL: AWS's model card shows end-of-life on 10 September 2026 in that region even though this fine-tuning page's table still lists it, so treat that row as stale), and Meta Llama 3.1/3.2/3.3 instruct variants.
- Reinforcement fine-tuning (RFT) for Nova 2 Lite,
openai.gpt-oss-20bandqwen.qwen3-32b— with reward functions via Lambda or model-as-judge, and OpenAI-compatible fine-tuning APIs (Files API → job → checkpoints → immediate on-demand inference). - Data in
.jsonl; conversational models want the Converse API message format (system/user/assistant turns).
Bedrock's pitch is governance: your data stays in AWS's boundary, which matters for regulated workloads — at the cost of a narrower model list and region locks. If you are already an AWS shop this is a serious rung-5 route for open models.
Azure / Microsoft Foundry: the broadest managed menu
Microsoft Foundry's fine-tuning overview offers Managed Training (job from data+settings) and Programmed Training (preview, approval-gated, Python-level control). The verified model table includes:
- OpenAI models:
gpt-4o/gpt-4.1family with SFT and DPO (gpt-4o-miniis SFT-only),o4-miniwith RFT,gpt-5RFT (invitation-only). - Open models: Ministral-3B, Qwen3-32B, Llama-3.3-70B, gpt-oss-20b (SFT), plus 2026 preview additions — Muse-Glimmer-30B, qwen3.8-27b, qwen3.6-35b-a3b, gpt-oss-120b, MAI-Code-1.1-Flash (RFT only) — most with SFT and RFT, and several deployable on managed compute (preview), where multiple LoRA adapters share one base deployment. The page's table was last updated in late October 2026 and marks these additions as preview, so check the per-model row before you plan.
If you are an Azure shop, Foundry is currently the widest single-vendor fine-tuning menu — closed and open models under one roof, with DPO and RFT alongside SFT.
Mistral: deprecated, but the weights are open
Mistral's fine-tuning docs now carry a deprecation banner: "This feature is deprecated and is no longer actively supported." The legacy API (jobs API, $4 minimum per job, $2/month storage per tuned model) still documents the shape — JSONL uploads, hyperparameters like learning_rate, integrations such as Weights & Biases — but do not build on it. The strategic point stands: Mistral's models are open-weight, so the fine-tuning path for them is the open-model stack in 5.4 or a hosted platform like Together/Fireworks/Azure that serves them.
Together AI and Fireworks: the open-model specialists
For open-weight fine-tuning, the specialist platforms are the most developed options:
- Together AI offers managed fine-tuning (LoRA and full) for dozens of open models — Qwen3.5/3.6/3.8, Llama 3.1/3.3/4, gpt-oss-20b/120b, DeepSeek, Kimi, Gemma, Mixtral, GLM — billed per 1M training tokens for SFT and preference/DPO training with a per-model minimum charge per job ($4 on small models up to $60 on the largest, on the pricing page checked 12 November 2026), a
fine_tuning.estimate_priceendpoint to quote a job before running it, and dedicated endpoints billed per minute for serving (fine-tuned models don't run on serverless). A separate post-training API runs SFT/DPO/GRPO loops on GPUs you provision, billed per GPU-minute. Their docs give the token formula:total = epochs × train_tokens + evals × val_tokens, and warn that disabling packing billsdataset_length × max_seq_length. - Fireworks AI now trains through its Training API in two forms — Serverless Training (a shared trainer pool with nothing to provision, billed per token) and Dedicated Training (GPUs reserved for your run, billed per GPU-hour, with full-parameter training) — plus Fireworks Lab, where the Fireworks team helps build the model with you. You pick a method (SFT, DPO or RL, including custom loops such as GRPO and distillation); availability is set per model by parameter mode (LoRA or full-parameter) and method, and Serverless Training is limited to a published list of models. The older Managed Training product (SFT and DPO jobs) is paused: its docs say it no longer accepts new jobs, trained models stay deployable, and the docs point to a migration guide. As of 14 November 2026 Fireworks' pricing page lists the Serverless Training API per 1M tokens (prefill, cached prefill, sample and train; for example Qwen 3.6 35B A3B at $2.14 per 1M train tokens and Kimi K3 at $32.55) and Dedicated Training from $8.00 per GPU-hour (H100 or H200); the docs pages themselves print no price. There is a cost estimator and a published training-GPU quota, so quote a job before you plan around it. The intro also notes a promotional free SFT window for Muse Glimmer 30B that ends on 30 November 2026, a reminder that these offers move.
Both are OpenAI-SDK-flavoured (file upload → fine_tuning job → tuned model), which means the shape of the workflow transfers across providers even though endpoints and prices differ.
OpenRouter: routing, not training
OpenRouter does not host fine-tuning jobs — it is an inference router (02.9, Part 5). Its relevant feature for this lesson is compliance metadata: is_trainable_text marks models whose authors allow distillation, and provider.enforce_distillable_text: true routes only to them (02.9, Part 9 covers it). If you distil, OpenRouter can keep you on the right side of provider terms.
4.3 Data formats: JSONL chat, preference pairs and RFT prompts#
The lingua franca is JSONL — one JSON object per line — but the shape inside differs:
{"messages":[{"role":"user","content":"What is the weather in San Francisco?"},{"role":"assistant","tool_calls":[{"id":"call_id","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\": \"San Francisco, USA\", \"format\": \"celsius\"}"}}]}],"parallel_tool_calls":false,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and country, eg. San Francisco, USA"},"format":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location","format"]}}}]}
{"messages":[{"role":"system","content":"You are a support triage assistant."},{"role":"user","content":"My invoice shows a duplicate charge."},{"role":"assistant","content":"I've flagged the duplicate charge and opened a billing ticket."}]}- SFT chat format (OpenAI, Together, most platforms):
{"messages": [...]}withsystem/user/assistantturns; OpenAI's docs also supporttool_callsexamples and atoolsarray per example so the model learns when to call. Some providers want prompt/completion pairs instead — check the provider's dataset doc. Google's Agent Platform and Bedrock's Converse format have their own record shapes. - Preference pairs (DPO): chosen vs rejected responses for the same prompt — OpenAI's
method.type: "dpo"(with abetahyperparameter), Google's preference tuning, Together's preference/DPO training, Azure's DPO on gpt-4o/4.1. - RFT prompts: a prompt file plus a grader — a function (Lambda on Bedrock, a programmable grader on OpenAI/Foundry, up to 16 weighted reward functions on Google) that scores each candidate response. The model learns from graded rollouts, not gold answers — this is how reasoning models are tuned for verifiable tasks (5.2).
4.4 The hyperparameters you actually touch#
You will not tune a model by hand, but hosted jobs expose a small set of knobs worth understanding:
| Knob | What it does | Typical guidance |
|---|---|---|
n_epochs / training steps |
Passes over the dataset | Too few underfits, too many overfits; providers auto-scale to dataset size (Google does) or default ~3 (OpenAI examples show higher) |
batch_size |
Examples per update | Usually "auto"; smaller = more updates, noisier |
learning_rate / learning_rate_multiplier |
Step size | The most common cause of a failed tune; lower if loss spikes or outputs degrade |
adapter_size / LoRA rank (Google, open models) |
Capacity of the trained adapter | Bigger learns more complex behaviour but needs more data and longer training |
Method (supervised/dpo/RFT) |
What signal trains the model | Match the method to the problem: demonstrations vs preferences vs rewards |
The meta-rule: change one thing at a time and keep the eval set fixed — the same discipline as prompt iteration (04.9).
4.5 Pricing structure: train once, serve forever#
Fine-tuning economics have three separate bills:
- Training — per 1M training tokens (OpenAI SFT, Together, Google, open models) or per wall-clock hour (OpenAI RFT at $100/hr for o4-mini). Watch the token formula:
epochs × dataset_tokens + evals × val_tokens— a 3-epoch run over 2M tokens bills ~6M training tokens. - Serving the tuned model — often higher per-token than the base model (OpenAI's tuned inference rates exceed base rates; dedicated endpoints on Together/Fireworks bill per minute regardless of traffic).
- Minimums and storage — per-job minimums (Together's minimums run from $4 to $60 by model; other platforms set their own), monthly storage per tuned model (Mistral's was $2), dedicated-endpoint hourly floors.
The trap: a "cheap" training run can produce an expensive inference bill if the tuned model serves at a premium or requires a dedicated endpoint that idles. Price the serving side before you train — 9.1 does the arithmetic.
4.6 Data retention, privacy and ZDR#
Fine-tuning collides with data governance harder than any other rung:
- Your training data goes to the provider. On hosted FT, the JSONL file is uploaded to their infrastructure. Check the provider's data-retention terms for fine-tuning specifically — some offer zero-data-retention (ZDR) tiers, some don't, and enabling data-sharing discounts usually means your data may be used (OpenAI's RFT discounts are explicitly tied to sharing). Link: 02.9, Part 9 and Module 12 own the full privacy treatment.
- Tuned models may not qualify for the same privacy tier as base models. A ZDR-covered base model's fine-tune is a new model artefact; verify it inherits the same terms before shipping customer data through it.
- PII in training data persists in weights. Unlike a database row you can delete, memorised PII in a fine-tune is effectively permanent — scrub before upload (7.4, and
prepare_dataset.py --redact). - Distillation has its own legal layer — 5.3 maps which providers' outputs you may train on.
Part 5: Beyond supervised fine-tuning#
Reference
SFT teaches the model what good answers look like on your distribution. Three other training signals exist, and knowing which is which prevents a whole class of wasted experiments.
5.1 Preference optimisation (DPO and friends) in plain English#
Direct Preference Optimization (DPO) trains on comparisons, not demonstrations. Instead of "here is the correct answer", your data says "for this prompt, answer A is better than answer B" (a preference pair: chosen vs rejected). The model learns to shift probability mass toward the preferred style — tone, helpfulness, refusal boundaries, formatting preferences — without you having to write the perfect answer yourself.
Lesson 02.6, 7.4 covers the mechanics (it's the cheap cousin of RLHF: same goal — optimise a preference — without training a separate reward model). Where it's offered as of November 2026: OpenAI's fine-tuning platform (method.type: "dpo", with a beta hyperparameter controlling how strictly the model adheres to prior behaviour — the support table lists the gpt-4.1 family, though the guide's own code examples still show gpt-4o-2024-08-06; check the current support table — all inside the wind-down window), Google's preference tuning on the Agent Platform, Together AI's preference/DPO training, and Azure Foundry's DPO on the gpt-4o/4.1 family.
When DPO beats SFT: the task's content is fine but its judgement is off — answers are correct but too verbose, too sycophantic, refusing too much or too little, ranking options wrong. SFT forces you to write ideal answers; DPO lets you harvest preferences from existing traffic (thumbs-down pairs, A/B winners, editor corrections) — often the cheapest high-quality signal you have.
5.2 Reinforcement fine-tuning (RFT/RLVR) where offered#
Reinforcement fine-tuning goes one step further: instead of labelled answers or pairwise preferences, you give the model a grader — a function that scores each attempt — and the training loop generates many candidate responses per prompt, grades them, and reinforces the high scorers. When the grader is a program (unit tests passing, a JSON schema validating, a math answer matching), it's called RL with verifiable rewards (RLVR) — the technique behind reasoning models (02.6, Part 8).
Where offered as of November 2026:
- OpenAI RFT — o4-mini only, billed $100/hour of wall-clock training plus grader token usage; limited to eligible existing customers under the wind-down (the platform was no longer accessible to new users); the base model's shutdown date (23 October 2026) has already passed, so treat it as legacy.
- Google RLFT on the Agent Platform — for Gemini reasoning models; dozens-to-hundreds of prompts with
referencesmetadata and up to 16 weighted reward functions. - Amazon Bedrock RFT — Nova 2 Lite, gpt-oss-20b, Qwen3-32B; reward functions via Lambda or model-as-judge; OpenAI-compatible job APIs.
- Azure Foundry — RFT on o4-mini, gpt-5 (invitation-only), MAI-Code-1.1-Flash and the new open-model previews.
When RFT is the answer: tasks with verifiable success — code that passes tests, extractions that validate against a schema, classifications with a known label, math with a checkable answer. It is overkill and overpriced for taste-and-style problems (that's DPO/SFT territory) and useless where no grader exists.
5.3 Distillation: teacher → student, and the legal map#
Knowledge distillation means using a strong teacher model's outputs to train a smaller student. The student learns to mimic the teacher's distribution — its phrasing, judgement, edge-case behaviour — on your task, at a fraction of the inference cost. Lesson 02.6, Part 10 covers the technique; this is the production view.
The workflow is the same shape as SFT with one extra step: run your traffic (or a curated prompt set) through the teacher, store the completions as training data, then SFT the student on them. OpenAI's old distillation workflow (Stored Completions → Evals → fine-tune) is the canonical version; you can replicate it on any provider pair.
The legal map — this is the part teams get wrong. Using a provider's outputs to train another model is restricted by that provider's terms:
| Provider | Can you train on its outputs? | The rule (as of Nov 2026) |
|---|---|---|
| OpenAI | Only within limits | Services Agreement §3.3(e): no Output to develop competing models. Permitted Exception: internal classifiers/embeddings not distributed, and fine-tuning OpenAI's own models. Distilling GPT→your own open model for a competing product = prohibited. |
| Anthropic | Effectively no | Commercial Terms + Usage Policy: no training competing models / model distillation without prior authorization. Help centre allows non-competing uses (classifiers, extraction) — but the stricter contractual reading governs. |
| Google (Gemini API) | No explicit exception | Additional Terms: no developing competing models; Cloud terms allow output only for Google's own fine-tuning/distillation features. |
| Mistral | Grey area | No explicit text-output clause found; residual risk under general "reverse engineering" language — get written clarification for commercial distillation. |
| Open-weight models | Depends on the licence | Apache-2.0/MIT models: yes. Llama community licence: yes with restrictions (naming, acceptable use, >700M MAU clause). Check each licence — 02.9, 3.3. |
| OpenRouter | It helps you comply | is_trainable_text flags distillable models; enforce_distillable_text: true routes only to them. |
The compliant version of distillation: use teachers whose terms allow it — open-weight models (DeepSeek, Qwen, gpt-oss and other permissively-licensed families, which OpenRouter's distillable filter surfaces), your own frontier model's outputs where the provider permits (OpenAI's exception covers fine-tuning OpenAI models; Google's covers its own tuning features), or outputs you generate and own outright. The economics are identical; only the licence differs.
5.4 Fine-tuning open models yourself: LoRA/QLoRA and the tooling stack#
When you own the weights, the whole game changes: you need GPUs, a training framework and an evaluator — but you get portability, no per-token training bill and no provider gatekeeping.
The method that matters is LoRA (low-rank adaptation) — freeze the base weights, train small injected matrices (the adapter), and serve base+adapter. Lesson 02.1, 7.4 introduced it; QLoRA does it on a 4-bit quantized base so a 65B-class model fits on one 48GB GPU (the QLoRA paper's headline result). Adapters are small (megabytes to a few GB), swappable per task, and — crucially — the base model stays frozen, which is why hosted platforms default to adapter-based tuning (Google's "adapter size", Together's LoRA option).
The tooling stack as of November 2026 (latest versions on PyPI on 14 November 2026; these packages release every few days, so treat the numbers as a snapshot, install by name, and record the version you actually train with):
| Library | Version | What it is |
|---|---|---|
transformers |
5.23.0 | Model loading/inference — the base everything builds on |
peft |
0.21.3 | The LoRA/adapter library: inject, train, save adapters |
trl |
1.18.0 | Post-training: SFTTrainer, DPOTrainer, GRPO/RL trainers |
datasets |
5.2.0 | Dataset loading/processing for training |
axolotl |
0.21.1 | YAML-driven fine-tuning configs — the "I just want it to work" option |
unsloth |
2026.11.4 | Speed/memory-optimised training (free notebooks, local) |
torchtune |
0.6.1 | PyTorch-native tuning recipes — no longer actively maintained (its README says development wound down in 2025), so don't start a new project on it |
bitsandbytes |
0.50.2 | 8/4-bit quantisation for QLoRA |
A minimal annotated axolotl config — awareness level, not a tutorial (the full training loop is a different course; 11C.6 covers serving the result):
# train_lora.yaml — illustrative; verify flags against axolotl docs for your version
base_model: Qwen/Qwen3-8B # or any open-weight chat model
sequence_len: 4096 # longest training example, in tokens
datasets:
- path: data/train.jsonl # chat-format JSONL from Part 7
type: chat_template # axolotl applies the model's own template
num_epochs: 3
learning_rate: 1.0e-4 # LoRA tolerates higher LR than full FT
adapter: lora # PEFT method
lora_r: 16 # adapter rank: capacity vs size
lora_alpha: 32
lora_target_linear: true # put adapters on all linear layers
micro_batch_size: 4 # examples per GPU per step
gradient_accumulation_steps: 8 # effective batch = 4 x 8 = 32 per GPU
bf16: true
output_dir: runs/support-bot-loraHardware arithmetic (the same KV-cache/weight math as 02.1, 4.4 and 11C.6): weights at 4-bit ≈ params × 0.5 bytes, plus optimizer states for the trainable params only under LoRA (tiny), plus activations for your sequence length and batch. A 7–8B model at QLoRA fits comfortably on a single 24–48GB GPU; 32B+ wants 48–80GB or multi-GPU; 70B+ is multi-GPU territory. Cloud GPU rental or a provider's managed training (Together, Fireworks, Azure, Bedrock) removes the hardware question at a per-token or per-hour price — often the right first step before buying GPUs.
Part 6: Fine-tuning the components around the model#
Deep-dive
The LLM isn't the only tunable component. Two neighbours deserve their own rung-5 consideration — and both are smaller, cheaper and more forgiving than tuning the chat model.
6.1 Embedding models#
Your retriever's embeddings determine what RAG can possibly find. When retrieval quality plateaus and the corpus is stable, fine-tuning the embedding model on your domain's (query, relevant-passage) pairs is a legitimate, well-trodden move — it teaches the vector space your jargon and your notion of "relevant".
The landscape as of November 2026:
- Hosted embedding APIs generally can't be fine-tuned. OpenAI's model docs mark fine-tuning "Not supported" for
text-embedding-3-small/3-large; their cookbook's alternative is a learned linear transform on top of frozen embeddings — cheap, but shallower than real tuning. - Open embedding models are fully tunable —
sentence-transformersmodels (the same family 06.9 uses for cross-encoders) train with contrastive loss on query–passage pairs; PEFT/LoRA applies here too. - The data is the hard part: you need real (query → relevant doc) pairs — mined from logs, click data, or generated synthetically (10A.2).
Lesson 06.1 owns the embedding API landscape and 06.10 owns retrieval evaluation — fine-tune an embedder only after those evals show a model gap, not a chunking or metadata gap.
6.2 Rerankers#
Lesson 06.9, 8.5 already scoped this: a cross-encoder reranker fine-tuned on MS MARCO-style (query, relevant, non-relevant) triples — with hard negatives mined from your own first-stage misses — is worthwhile when you have thousands of labelled queries, a persistent domain gap, and the ops appetite. It's the same context-vs-weights trade-off at smaller scale, and the training data is easier to generate than chat SFT data because relevance labels are more objective.
6.3 When component fine-tuning beats end-to-end#
The decision rule mirrors Part 3: fine-tune the component when the component is the bottleneck and its input/output contract is stable. A tuned embedder + tuned reranker + prompted LLM is a legitimate architecture — arguably more maintainable than one giant tuned chat model, because each piece is smaller, cheaper to retrain and independently evaluable. The counterweight: three tuned components is three things to version, monitor and retrain — complexity is the tax.
Part 7: Data for fine-tuning#
Deep-dive
The dataset is the product. Every hosted platform and every training framework assumes you can produce clean input/output pairs; almost none of them help you produce them well. This part is the unglamorous core of rung 5.
7.1 How much data: order-of-magnitude guidance, with sources#
There is no formula — the right size depends on task difficulty, distance from the base model's behaviour, and label quality — but the sourced ranges converge on a picture:
| Source (verified Nov 2026) | Guidance |
|---|---|
| OpenAI SFT guide | Minimum 10 examples; "we see improvements from 50–100"; start with ~50 well-crafted demonstrations, add data only if evals improve |
| Meta Llama fine-tuning docs | "As few as a couple dozen" to start; 50 good, goal of 100–200; quality over quantity |
| Google Agent Platform tuning docs | SFT: "hundreds to thousands" of labelled examples ("100 examples or more" as the point where tuning beats prompting); RLFT: dozens–hundreds of prompts; preference tuning: hundreds–thousands of pairs |
| AWS ML blog — SFT data strategies | ~2,000 as a ballpark; ~500 for simple format/style changes; 10,000+ for complex multi-step reasoning; find the saturation point empirically |
The synthesis for your roadmap:
- Narrow format/style/behaviour tasks: 50–500 good examples can move the needle (OpenAI, Meta, Google all agree).
- Domain behaviour on real distributions: 500–2,000.
- Complex reasoning or genuinely new skills: thousands, and possibly RL/RFT rather than SFT.
- The LIMA lesson: ~1,000 curated examples outperformed ~50,000 machine-generated ones (02.6, 10.2 covers synthetic data). Quality dominates quantity — a small set of correct, diverse, realistic examples beats a large set of noisy ones every time.
7.2 Formats and what makes an example good#
Format: chat JSONL — {"messages": [{role, content}, ...]} ending on an assistant turn — is the common denominator (OpenAI, Together, most platforms; 4.3 shows the shape and the variants). The model learns to produce the assistant turns; everything before them is context (02.6, 6.2 explains the loss masking).
What makes an example good (synthesised from OpenAI's best-practices guide and the provider docs):
- Realistic — actual user phrasing, including typos, edge cases and the awkward middle cases, not polished textbook questions.
- Correct — every assistant answer verified by a human or a trusted process. The model learns your errors as faithfully as your intentions.
- Consistent — if two annotators would disagree on the "right" answer, the model learns the disagreement as noise. Resolve label ambiguity before training.
- Complete — the answer must be derivable from the prompt alone; examples that require information not in the conversation teach hallucination.
- Balanced — if 60% of training answers are refusals but production needs 5%, you will ship an over-refusing model (OpenAI's guide calls this out explicitly).
- Diverse — coverage across your input distribution, not 50 paraphrases of the same three cases. Near-duplicate detection exists because teams ship templated data constantly.
7.3 Synthetic data: power and risk#
Generating training data with a stronger model (teacher outputs, self-instruct style) is the standard way to reach dataset scale — and the standard way to import the teacher's biases. Lesson 10A.2 owns the generation pipeline; for fine-tuning specifically:
- Use it for coverage, not truth. Synthetic examples are excellent for format, style and edge-case coverage; risky for factual content unless a human or verifier checks each one.
- Beware model collapse. Training on your own model's outputs recursively degrades diversity (02.6, 14.6 previews the research). Distil from a different, stronger teacher; don't fine-tune a model on its own outputs.
- Check the licence — 5.3 is the legal map; synthetic data inherits the same restrictions.
- Dedup and decontaminate — generated data clusters tightly; exact and near-duplicate removal matters more, not less.
7.4 PII, licensing and splits#
- PII: scrub emails, phones, IDs, secrets before upload — PII memorised into weights can't be deleted later (4.6).
prepare_dataset.py --redactcatches the common patterns; it's a safety net, not a substitute for review. - Licensing: training data must be yours or properly licensed — customer data needs consent, scraped data needs rights, and provider outputs need the distillation check. When in doubt, don't train on it.
- Splits: hold out validation (for tuning decisions during training) and test (for the final honest number) sets before training, and keep them disjoint from each other and from the eval set used for acceptance. The leakage check in
prepare_dataset.pyexists because "we'll just remove the dupes later" never happens.
7.5 prepare_dataset.py — validate, dedupe, decontaminate, split#
Save this as prepare_dataset.py. Pure standard library — run it today:
python3 prepare_dataset.py --demo --outdir demo_prepare # writes a flawed demo set + eval, processes it
python3 prepare_dataset.py raw.jsonl --eval heldout.jsonl --outdir splits/ --redactIt validates the chat-JSONL shape, scans for PII, removes exact duplicates, drops examples that near-duplicate your held-out eval set (>50% shared 8-word shingles), estimates token counts, splits deterministically into train/val/test, and reports cross-split leakage.
demo files written: demo_prepare/demo_raw.jsonl, demo_prepare/demo_eval.jsonl
input file : demo_prepare/demo_raw.jsonl
records parsed : 30
valid examples : 29
rejected : 1
! demo_raw.jsonl: line 23: invalid JSON (Expecting property name enclosed in double quotes)
! demo_raw.jsonl record 13: last message is not 'assistant' — nothing to learn from
exact duplicates: 2 removed
decontamination : 1 train examples overlapped the eval set (>50% shared 8-grams), dropped
PII findings : {'email': 1, 'phone-like number': 1}
est. tokens/ex : min 39, median 56, max 62; total ~1,462 (@4.0 chars/token — learn your real ratio from provider usage, lesson 03.7)
split sizes : train 20, val 2, test 4 (fractions 0.80/0.10/0.10)
cross-split leakage (>50% shared 8-grams with train): 0
wrote : demo_prepare/splits/{train,val,test}.jsonlNote it exits non-zero when problems are found — that's deliberate, so it can gate a pipeline. One limit to know: validate() requires every message to carry non-empty string content, so a tool-call example whose assistant turn has tool_calls and no content (the first record in 4.3) would be rejected — extend validate() and example_text() if your dataset has those. Every finding above is a real class of production data bug: a malformed line, a conversation with no answer to learn from, duplicates, an eval item that leaked into training, and unredacted PII.
#!/usr/bin/env python3
"""prepare_dataset.py — validate, clean, decontaminate and split a chat-format
fine-tuning dataset. Pure standard library; no network, no model calls.
Input format: JSONL, one JSON object per line, in the chat format used by
OpenAI fine-tuning, Together AI and most hosted APIs:
{"messages": [{"role": "system", "content": "..."},
{"role": "user", "content": "..."},
{"role": "assistant", "content": "..."}]}
(Other providers use other shapes — Google's tuning datasets and Bedrock's
Converse format are covered in lesson 13A.8, Part 4. This tool targets the
chat format because it is the most common denominator.)
The PII patterns below are heuristics: they catch common shapes, not every
variant, and can still false-positive on unusual formats — always review
flagged records before redacting or shipping the splits.
Usage:
python3 prepare_dataset.py raw.jsonl --eval heldout.jsonl --outdir splits/
python3 prepare_dataset.py --demo --outdir demo_splits/
"""
from __future__ import annotations
import argparse
import hashlib
import json
import random
import re
import sys
from pathlib import Path
ROLES = {"system", "user", "assistant"}
CHARS_PER_TOKEN = 4.0 # rough English ratio; lesson 03.7 shows how to learn your own
EMAIL_RE = re.compile(r"[\w.+-]+@[\w-]+\.[\w.]+")
# PHONE_RE: 10+ chars of digit/separator material, not glued to a longer digit
# run, and not shaped like a numeric date — dates (2026-11-07, 07/11/2026,
# 2026 11 07) are the most common false positive in business text and would be
# silently rewritten to [REDACTED:phone] by --redact.
PHONE_RE = re.compile(
r"(?<!\d)"
r"(?!\d{4}[-/.]\d{2}[-/.]\d{2}(?!\d))"
r"(?!\d{1,2}[-/.]\d{1,2}[-/.]\d{2,4}(?!\d))"
r"(?!\d{4}\s+\d{1,2}\s+\d{1,2}(?!\d))"
r"\+?\d[\d\s().-]{8,}\d"
r"(?!\d)"
)
CARD_RE = re.compile(r"\b(?:\d[ -]?){13,19}\b")
KEY_RE = re.compile(r"\b(?:sk|pk|api|key|token|secret)[-_][A-Za-z0-9]{16,}\b", re.IGNORECASE)
def estimate_tokens(text: str, chars_per_token: float = CHARS_PER_TOKEN) -> int:
"""Rough estimate: len(text)/ratio, min 1. Learn your real ratio from provider usage (lesson 03.7)."""
return max(1, round(len(text) / chars_per_token))
def normalize(text: str) -> str:
return " ".join(text.split())
def example_text(ex: dict) -> str:
return "\n".join(f"{m['role']}: {m.get('content', '')}" for m in ex["messages"])
def learn_text(ex: dict) -> str:
"""User+assistant turns only. System prompts are shared boilerplate and would
inflate every near-duplicate score, so shingles and splits use this instead."""
return "\n".join(f"{m['role']}: {m.get('content', '')}"
for m in ex["messages"] if m.get("role") != "system")
def shingles(text: str, n: int = 8) -> set[str]:
"""Word n-gram set used for near-duplicate detection."""
words = normalize(text).lower().split()
if len(words) <= n:
return {" ".join(words)} if words else set()
return {" ".join(words[i : i + n]) for i in range(len(words) - n + 1)}
def validate(obj) -> list[str]:
"""Return a list of problems; empty means the example is usable."""
errs = []
msgs = obj.get("messages")
if not isinstance(msgs, list) or not msgs:
return ["missing or empty 'messages' list"]
for i, m in enumerate(msgs):
if not isinstance(m, dict):
errs.append(f"message {i}: not an object")
continue
if m.get("role") not in ROLES:
errs.append(f"message {i}: role {m.get('role')!r} not in {sorted(ROLES)}")
if not isinstance(m.get("content"), str) or not m["content"].strip():
errs.append(f"message {i}: missing or empty content")
if msgs and isinstance(msgs[0], dict) and msgs[0].get("role") == "assistant":
errs.append("first message has role 'assistant' (conversations start with system/user)")
if msgs and isinstance(msgs[-1], dict) and msgs[-1].get("role") != "assistant":
errs.append("last message is not 'assistant' — nothing to learn from")
return errs
def scan_pii(text: str) -> list[str]:
kinds = []
if EMAIL_RE.search(text):
kinds.append("email")
if PHONE_RE.search(text):
kinds.append("phone-like number")
if CARD_RE.search(text):
kinds.append("card-like number")
if KEY_RE.search(text):
kinds.append("key/token-like string")
return kinds
def redact(text: str) -> str:
text = EMAIL_RE.sub("[REDACTED:email]", text)
# cards before phones: a 16-digit card number is also "phone-like" digits
text = CARD_RE.sub("[REDACTED:card]", text)
text = PHONE_RE.sub("[REDACTED:phone]", text)
text = KEY_RE.sub("[REDACTED:key]", text)
return text
def load_jsonl(path: Path) -> tuple[list[dict], list[str]]:
"""Return (parsed objects, line-level errors)."""
objs, errs = [], []
for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
line = line.strip()
if not line:
continue
try:
objs.append(json.loads(line))
except json.JSONDecodeError as e:
errs.append(f"line {lineno}: invalid JSON ({e.msg})")
return objs, errs
def stable_id(text: str) -> int:
return int(hashlib.sha1(normalize(text).encode("utf-8")).hexdigest()[:12], 16)
def containment(part_shingles: set[str], whole_shingles: set[str]) -> float:
"""Fraction of `part`'s shingles that also appear in `whole`."""
if not part_shingles:
return 0.0
return len(part_shingles & whole_shingles) / len(part_shingles)
def process(raw_path: Path, eval_path: Path | None, outdir: Path,
redact_pii: bool, train_frac: float, val_frac: float) -> int:
problems: list[str] = []
raw_objs, line_errs = load_jsonl(raw_path)
problems += [f"{raw_path.name}: {e}" for e in line_errs]
examples: list[dict] = []
for i, obj in enumerate(raw_objs, 1):
errs = validate(obj)
if errs:
problems.append(f"{raw_path.name} record {i}: {'; '.join(errs)}")
continue
examples.append(obj)
# --- PII scan (before dedupe so counts reflect the raw file) ---
pii_counts: dict[str, int] = {}
for ex in examples:
for m in ex["messages"]:
for kind in scan_pii(m["content"]):
pii_counts[kind] = pii_counts.get(kind, 0) + 1
if redact_pii:
for ex in examples:
for m in ex["messages"]:
m["content"] = redact(m["content"])
# --- Exact dedupe on the full conversation text ---
seen: set[str] = set()
deduped: list[dict] = []
n_dupes = 0
for ex in examples:
key = normalize(example_text(ex))
if key in seen:
n_dupes += 1
continue
seen.add(key)
deduped.append(ex)
# --- Decontamination against the held-out eval set ---
n_flagged = 0
eval_shingles: set[str] = set()
if eval_path and eval_path.exists():
eval_objs, eval_errs = load_jsonl(eval_path)
problems += [f"{eval_path.name}: {e}" for e in eval_errs]
for obj in eval_objs:
if not validate(obj):
eval_shingles |= shingles(learn_text(obj))
kept = []
for ex in deduped:
s = shingles(learn_text(ex))
if containment(s, eval_shingles) > 0.5:
n_flagged += 1
continue
kept.append(ex)
deduped = kept
# --- Token stats (estimate) ---
toks = [estimate_tokens(example_text(ex)) for ex in deduped]
total_tok = sum(toks)
# --- Deterministic split: order by content hash, then slice by fraction ---
# (hash-bucket assignment can starve small datasets; sorted slicing cannot)
ordered = sorted(deduped, key=lambda ex: stable_id(learn_text(ex)))
n = len(ordered)
n_train = int(n * train_frac)
n_val = int(n * val_frac)
splits: dict[str, list[dict]] = {
"train": ordered[:n_train],
"val": ordered[n_train:n_train + n_val],
"test": ordered[n_train + n_val:],
}
# --- Leakage check: val/test examples that near-duplicate a train example ---
train_shingles: set[str] = set()
for ex in splits["train"]:
train_shingles |= shingles(learn_text(ex))
n_leak = 0
for name in ("val", "test"):
for ex in splits[name]:
if containment(shingles(learn_text(ex)), train_shingles) > 0.5:
n_leak += 1
# --- Write ---
outdir.mkdir(parents=True, exist_ok=True)
for name, rows in splits.items():
with (outdir / f"{name}.jsonl").open("w", encoding="utf-8") as f:
for ex in rows:
f.write(json.dumps(ex, ensure_ascii=False) + "\n")
# --- Report ---
print(f"input file : {raw_path}")
print(f"records parsed : {len(raw_objs)}")
print(f"valid examples : {len(examples)}")
print(f"rejected : {len(raw_objs) - len(examples)}")
for p in problems:
print(f" ! {p}")
print(f"exact duplicates: {n_dupes} removed")
if eval_path:
print(f"decontamination : {n_flagged} train examples overlapped the eval set (>50% shared 8-grams), dropped")
print(f"PII findings : {pii_counts or 'none'}")
if redact_pii:
print("PII : redacted in output files")
if toks:
print(f"est. tokens/ex : min {min(toks)}, median {sorted(toks)[len(toks)//2]}, max {max(toks)}; total ~{total_tok:,} "
f"(@{CHARS_PER_TOKEN} chars/token — learn your real ratio from provider usage, lesson 03.7)")
test_frac = 1 - train_frac - val_frac
print(f"split sizes : train {len(splits['train'])}, val {len(splits['val'])}, test {len(splits['test'])} "
f"(fractions {train_frac:.2f}/{val_frac:.2f}/{test_frac:.2f})")
print(f"cross-split leakage (>50% shared 8-grams with train): {n_leak}")
print(f"wrote : {outdir}/{{train,val,test}}.jsonl")
return 0 if not problems else 1
def demo(outdir: Path) -> int:
"""Write a small deliberately flawed dataset + eval set, then process it."""
# 6 genuinely different phrasings per category — templated data is itself a
# finding (it trips the near-duplicate checks), so the demo stays diverse.
examples = [
("billing", "My invoice shows a duplicate charge for March."),
("billing", "I was billed twice on my March statement — can someone check?"),
("billing", "There's an extra line item on this month's invoice."),
("billing", "Why did my card get charged two times for the same subscription?"),
("billing", "The receipt and the invoice disagree by one charge."),
("billing", "I see two identical payments posted yesterday."),
("technical", "The export button returns a 500 error on large reports."),
("technical", "CSV export crashes whenever I pick a range over 90 days."),
("technical", "Downloading the quarterly report gives me an error page."),
("technical", "The dashboard won't render the revenue chart since this morning."),
("technical", "Every PDF export times out after about a minute."),
("technical", "The API returns malformed JSON for the /reports endpoint."),
("account", "I cannot reset my password; the email never arrives."),
("account", "Password reset link isn't in my inbox or spam folder."),
("account", "I'm locked out and the 'forgot password' flow does nothing."),
("account", "Two-factor setup loops back to the start every time."),
("account", "My account shows as suspended but I paid on time."),
("account", "I can't add a teammate — the invite button is greyed out."),
("shipping", "My order was marked delivered but nothing arrived."),
("shipping", "Tracking says 'delivered' yet the parcel isn't here."),
("shipping", "The carrier left the box somewhere wrong — how do I report it?"),
("shipping", "My shipment has been 'in transit' for over a week."),
("shipping", "Wrong item arrived in the box; I ordered the annual plan."),
("shipping", "Do you ship to PO boxes? Mine was returned to sender."),
]
replies = {
"billing": [
"I've flagged the duplicate charge and opened a billing ticket; refunds post in 5-7 days.",
"That's a billing error — I've credited the duplicate and opened a ticket to confirm.",
"Duplicate charge confirmed; refund is processing and you'll see it in 5-7 days.",
],
"technical": [
"Please retry with a date range under 90 days; if it persists I'll escalate to engineering.",
"The 500 is a known limit on large exports — narrow the date range and retry.",
"I've reproduced the failure and escalated it to the platform team.",
],
"account": [
"Check spam for the reset link; if absent, I can trigger a manual reset after verifying your account.",
"Reset emails sometimes land in spam — check there first; I can resend on request.",
"I can send a fresh reset link now; it expires in 30 minutes.",
],
"shipping": [
"I'll open a trace with the carrier and reply within 24 hours with a resolution.",
"Delivered-but-missing — I'm filing a carrier trace and will update you tomorrow.",
"Sorry about that; I've opened an investigation with shipping and will follow up within a day.",
],
}
raw_lines = []
for i, (cat, q) in enumerate(examples):
raw_lines.append(json.dumps({"messages": [
{"role": "system", "content": "You are a support triage assistant. Reply with category and action."},
{"role": "user", "content": q},
{"role": "assistant", "content": replies[cat][i % 3]},
]}))
# flaws on purpose: duplicates, PII, a non-assistant tail, a near-dup of eval
raw_lines.append(raw_lines[0]) # exact duplicate
raw_lines.append(raw_lines[3]) # exact duplicate
raw_lines.append(json.dumps({"messages": [
{"role": "user", "content": "Email me at jane.doe@example.com or call +1 (415) 555-0132 about invoice INV-2041."},
{"role": "assistant", "content": "I've logged the billing issue for invoice INV-2041 and will follow up by email."},
]}))
raw_lines.append(json.dumps({"messages": [
{"role": "user", "content": "Where is my package? Order #88412 shows 'in transit' for 9 days."},
{"role": "assistant", "content": "I'll open a carrier trace for order #88412 and update you within 24 hours."},
]}))
raw_lines.append(json.dumps({"messages": [
{"role": "user", "content": "Quick question about my account settings please."},
]})) # no assistant turn
raw_lines.append("{not json") # broken line
eval_lines = [
{"messages": [
{"role": "user", "content": "The mobile app crashes whenever I open the invoices tab on Android 15."},
{"role": "assistant", "content": "Known issue on Android 15; fixed in app v4.2 — please update and retry."},
]},
{"messages": [
{"role": "user", "content": "Do you offer annual billing discounts for teams over 50 seats?"},
{"role": "assistant", "content": "Yes — annual plans get 15% off; I can send a quote for your seat count."},
]},
{"messages": [
{"role": "user", "content": "How do I export my data before closing the account?"},
{"role": "assistant", "content": "Settings → Privacy → Export data gives a JSON archive; it stays available 30 days after closure."},
]},
]
# A training example that copies an eval item verbatim (different system prompt)
# — exactly the contamination a real pipeline must catch.
leaked = eval_lines[0]
raw_lines.append(json.dumps({"messages": [
{"role": "system", "content": "You are a helpful assistant."},
*leaked["messages"],
]}))
random.Random(3).shuffle(raw_lines)
outdir.mkdir(parents=True, exist_ok=True)
raw_path = outdir / "demo_raw.jsonl"
eval_path = outdir / "demo_eval.jsonl"
raw_path.write_text("\n".join(raw_lines) + "\n", encoding="utf-8")
eval_path.write_text("\n".join(json.dumps(e) for e in eval_lines) + "\n", encoding="utf-8")
print(f"demo files written: {raw_path}, {eval_path}\n")
return process(raw_path, eval_path, outdir / "splits", redact_pii=False,
train_frac=0.8, val_frac=0.1)
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("input", nargs="?", type=Path, help="raw JSONL training file")
ap.add_argument("--eval", type=Path, help="held-out eval JSONL for decontamination")
ap.add_argument("--outdir", type=Path, default=Path("splits"))
ap.add_argument("--redact", action="store_true", help="replace detected PII with [REDACTED:kind]")
ap.add_argument("--train-frac", type=float, default=0.8)
ap.add_argument("--val-frac", type=float, default=0.1)
ap.add_argument("--demo", action="store_true", help="generate a small flawed demo dataset and process it")
args = ap.parse_args()
if args.demo:
return demo(args.outdir)
if not args.input:
ap.error("give an input JSONL file, or --demo")
return process(args.input, args.eval, args.outdir, args.redact,
args.train_frac, args.val_frac)
if __name__ == "__main__":
sys.exit(main())Part 8: Evaluating a fine-tune#
OpenAI's guide says it in bold: "Good evals first!" You do not train to find out if it helped — you train because your evals already proved a gap, and you re-run the same evals to prove the tune closed it. Module 10A owns evaluation methodology; this part applies it to the specific question "did the fine-tune help?"
8.1 The baselines you must beat#
A fine-tune is never evaluated in a vacuum. Your acceptance test compares at least three things on the same eval set:
- The base model with your best prompt (and best schema, plus a stronger model if you tried one — rungs 1, 2 and 4). If the tune doesn't beat this, the prompt was the answer all along.
- The base model with your best prompt + RAG (if applicable) — the rung-3 baseline, priced with prompt caching switched on if it applies (9.1). A tune that only memorises retrieved facts is strictly worse than retrieval.
- The previous fine-tune (if re-training) — regression detection across versions.
And two things it must not break:
- General ability — a broad eval (MMLU-style, or your own wide sample) to detect catastrophic forgetting.
- Adjacent slices — per-category, per-language, per-difficulty breakdowns of the task eval; a tune that lifts the average while tanking a slice is a regression wearing a costume.
8.2 Paired statistics: why "it scored higher" isn't enough#
With ~50–200 eval items, raw pass rates lie by omission: 55% vs 60% on 100 items is well inside noise. The honest test is paired — same items, same scorer, only the model differs — then ask whether the difference is statistically distinguishable from zero. fteval.py does exactly this: Wilson intervals on each pass rate, a paired bootstrap CI on the per-item difference, and a verdict.
Save as fteval.py. Pure standard library:
python3 fteval.py --demo # writes demo result files, compares them
python3 fteval.py base_results.jsonl tuned_results.jsonlInput files are one JSON object per line: {"id": "case-001", "correct": true} (also accepts "pass").
demo files written to fteval_demo/
paired items : 60
base pass rate : 39/60 = 65.0% 95% CI [52.4%, 75.8%]
tuned pass rate : 48/60 = 80.0% 95% CI [68.2%, 88.2%]
items gained : 11 items lost: 2 unchanged: 47
mean difference : +0.150 bootstrap 95% CI [+0.050, +0.267]
verdict : IMPROVEMENT — the tuned model is better on this eval set
Reminder: this compares ONE eval set. Also run it on a general-ability
set (MMLU-style or your own broad sample) to check for forgetting,
and check per-slice breakdowns before shipping (lesson 13A.8, Part 8).The verdict logic is deliberately conservative: improvement only when the bootstrap CI on the mean difference excludes zero. A "maybe better" result is reported as INCONCLUSIVE — the correct engineering response is more eval items or a bigger effect, not hope.
#!/usr/bin/env python3
"""fteval.py — paired comparison of two models' results on the SAME eval items.
Answers the only question that matters after a fine-tune: did the tuned model
actually get better, or is the difference noise?
Input: two JSONL files, one result per eval item, joined on "id":
{"id": "case-001", "correct": true}
{"id": "case-001", "correct": false}
(also accepts "pass" instead of "correct"). Items present in only one file are
reported and excluded from the paired comparison.
Statistics (pure stdlib, deterministic):
* pass rate + Wilson 95% score interval for each model
* mean per-item difference (tuned - base, in {-1, 0, +1})
* paired bootstrap 95% CI on that difference (10,000 resamples, fixed seed)
* verdict: improvement / regression / inconclusive
Usage:
python3 fteval.py base.jsonl tuned.jsonl
python3 fteval.py --demo # writes demo files and runs the comparison
"""
from __future__ import annotations
import argparse
import json
import math
import random
import sys
from pathlib import Path
BOOTSTRAP_N = 10_000
SEED = 11
def wilson_ci(k: int, n: int, z: float = 1.96) -> tuple[float, float]:
"""Wilson score interval for a binomial proportion."""
if n == 0:
return (0.0, 0.0)
p = k / n
denom = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denom
half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
return (max(0.0, centre - half), min(1.0, centre + half))
def load_results(path: Path) -> dict[str, bool]:
out: dict[str, bool] = {}
for lineno, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
line = line.strip()
if not line:
continue
obj = json.loads(line)
rid = obj.get("id")
if rid is None:
raise SystemExit(f"{path.name}:{lineno}: missing 'id'")
ok = obj.get("correct", obj.get("pass"))
if not isinstance(ok, bool):
raise SystemExit(f"{path.name}:{lineno}: 'correct'/'pass' must be true/false")
out[str(rid)] = ok
return out
def paired_bootstrap_ci(diffs: list[int], n_boot: int = BOOTSTRAP_N,
seed: int = SEED) -> tuple[float, float]:
"""95% bootstrap CI for the mean of paired differences."""
rng = random.Random(seed)
n = len(diffs)
means = []
for _ in range(n_boot):
means.append(sum(diffs[rng.randrange(n)] for _ in range(n)) / n)
means.sort()
return means[int(0.025 * n_boot)], means[int(0.975 * n_boot)]
def compare(base_path: Path, tuned_path: Path) -> int:
base = load_results(base_path)
tuned = load_results(tuned_path)
only_base = sorted(set(base) - set(tuned))
only_tuned = sorted(set(tuned) - set(base))
common = sorted(set(base) & set(tuned))
if only_base or only_tuned:
print(f"warning: {len(only_base)} ids only in base, {len(only_tuned)} only in tuned — excluded")
for rid in (only_base + only_tuned)[:10]:
print(f" ! {rid}")
if not common:
raise SystemExit("no common ids — nothing to compare")
n = len(common)
base_pass = sum(base[i] for i in common)
tuned_pass = sum(tuned[i] for i in common)
diffs = [int(tuned[i]) - int(base[i]) for i in common]
gained = sum(1 for d in diffs if d == 1)
lost = sum(1 for d in diffs if d == -1)
mean_diff = sum(diffs) / n
lo, hi = paired_bootstrap_ci(diffs)
b_lo, b_hi = wilson_ci(base_pass, n)
t_lo, t_hi = wilson_ci(tuned_pass, n)
print(f"paired items : {n}")
print(f"base pass rate : {base_pass}/{n} = {base_pass/n:.1%} 95% CI [{b_lo:.1%}, {b_hi:.1%}]")
print(f"tuned pass rate : {tuned_pass}/{n} = {tuned_pass/n:.1%} 95% CI [{t_lo:.1%}, {t_hi:.1%}]")
print(f"items gained : {gained} items lost: {lost} unchanged: {n - gained - lost}")
print(f"mean difference : {mean_diff:+.3f} bootstrap 95% CI [{lo:+.3f}, {hi:+.3f}]")
print()
if lo > 0:
verdict = "IMPROVEMENT — the tuned model is better on this eval set"
elif hi < 0:
verdict = "REGRESSION — the tuned model is worse on this eval set"
else:
verdict = "INCONCLUSIVE — the difference could be noise; add eval items or accept parity"
print(f"verdict : {verdict}")
print()
print("Reminder: this compares ONE eval set. Also run it on a general-ability")
print("set (MMLU-style or your own broad sample) to check for forgetting,")
print("and check per-slice breakdowns before shipping (lesson 13A.8, Part 8).")
return 0
def demo() -> int:
rng = random.Random(7)
outdir = Path("fteval_demo")
outdir.mkdir(exist_ok=True)
n = 60
# tuned model: genuinely better on ~2/3 of items base fails, slightly worse on a few
base_results, tuned_results = [], []
for i in range(n):
rid = f"case-{i:03d}"
base_ok = rng.random() < 0.60
if base_ok:
tuned_ok = rng.random() > 0.10 # 10% chance tuned loses a pass
else:
tuned_ok = rng.random() < 0.55 # 55% chance tuned fixes a fail
base_results.append({"id": rid, "correct": base_ok})
tuned_results.append({"id": rid, "correct": tuned_ok})
(outdir / "base.jsonl").write_text(
"\n".join(json.dumps(r) for r in base_results) + "\n")
(outdir / "tuned.jsonl").write_text(
"\n".join(json.dumps(r) for r in tuned_results) + "\n")
print(f"demo files written to {outdir}/\n")
return compare(outdir / "base.jsonl", outdir / "tuned.jsonl")
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("base", nargs="?", type=Path)
ap.add_argument("tuned", nargs="?", type=Path)
ap.add_argument("--demo", action="store_true")
args = ap.parse_args()
if args.demo:
return demo()
if not args.base or not args.tuned:
ap.error("give base.jsonl and tuned.jsonl, or --demo")
return compare(args.base, args.tuned)
if __name__ == "__main__":
sys.exit(main())8.3 Regressions: general ability and catastrophic forgetting#
The task eval tells you the tune helped on the task. It does not tell you what the tune cost everywhere else:
- Catastrophic forgetting — narrow training data shifts the model's whole behaviour distribution; skills it had (general knowledge, other tasks, refusal calibration) can degrade. The general-ability eval exists to catch this: run it on the base model and the tune, paired, same statistics.
- The mitigation lives in the data. The standard counter is replay: blend general-domain examples into the fine-tuning set so the model rehearses its general skills while it learns the narrow task — the AWS SFT data-strategies post (cited in 7.1) covers mixing strategies. Whatever mix you choose, re-run the general-ability eval after every retrain to confirm the forgetting stayed fixed.
- Behavioural side-effects — a tune trained on terse support answers may become terse everywhere, including contexts that needed nuance. Watch tone/length/refusal-rate metrics, not just task accuracy.
- Slice regressions — lift the average while tanking French tickets, long documents, or edge-case inputs, and you have shipped a regression. Break eval results down by the slices your users actually experience (10A.4 covers slicing methodology).
8.4 The maintenance loop#
A fine-tune is not a one-time event; it is a model you now own:
- Re-evaluate on every base-model update. Providers update base models underneath you; your
ft:model's behaviour can shift when its base does. Pin and re-test — the same discipline as 04.9, 4.4 for prompts. - Retrain on a schedule or on drift. If your data distribution moves (new products, new policies, new user populations), the tune goes stale — the same drift problem as any model, now with your fingerprints on it.
- Version everything. Dataset version, training config, base model, eval results — the same reproducibility discipline as prompt versioning (04.10).
Part 9: The economics and the decision#
9.1 The cost model#
Fine-tuning has a different cost shape than prompting or RAG: a large one-time investment (data + training + eval engineering) against permanently lower per-request cost. Whether it wins depends on volume — the crossover point where cumulative savings exceed the upfront cost.
Save as ftecon.py. Pure standard library; every number is a parameter:
python3 ftecon.py # runs the worked example belowAll prices and token counts below are illustrative parameters baked into the script — swap in your measured tokens and current prices.
=== worked example: support-answer bot, 2M requests/month ===
prompt-only 6,000 in / 300 out | $/request 0.00750 | monthly $ 15,000 | one-time $ 0 | 12-month $ 180,000
frontier model + 8 few-shot examples in every prompt
rag 2,500 in / 300 out | $/request 0.00148 | monthly $ 3,080 | one-time $ 8,000 | 12-month $ 44,960 | recoups in ~0.67 mo
mid model + retrieved chunks + vector DB
fine-tune 800 in / 280 out | $/request 0.00038 | monthly $ 768 | one-time $ 3,500 | 12-month $ 12,716 | recoups in ~0.25 mo
small tuned model, short prompt, pay-per-token hosting
--- sensitivity: months for the fine-tune to recoup its one-time cost ---
50,000 requests/month -> 9.84 months
500,000 requests/month -> 0.98 months
2,000,000 requests/month -> 0.25 months
10,000,000 requests/month -> 0.05 months
=== same workload with prompt caching on the prompt-only baseline ===
prompt-only 6,000 in / 300 out | $/request 0.00318 | monthly $ 6,360 | one-time $ 0 | 12-month $ 76,320
same prompt-only option, 80% of input tokens cached at 0.1x
rag 2,500 in / 300 out | $/request 0.00148 | monthly $ 3,080 | one-time $ 8,000 | 12-month $ 44,960 | recoups in ~2.44 mo
mid model + retrieved chunks + vector DB
fine-tune 800 in / 280 out | $/request 0.00038 | monthly $ 768 | one-time $ 3,500 | 12-month $ 12,716 | recoups in ~0.63 mo
small tuned model, short prompt, pay-per-token hosting
The crossover volume is the number that decides: compute yours.The shape of the lesson: at 2M requests/month the tuned small model is ~20× cheaper per request than the prompted frontier model and recoups its one-time cost in about a week (the pay-per-token hosting assumption means no endpoint floor: add a monthly_fixed for a dedicated endpoint and watch the payback lengthen). At 50k requests/month the same tune needs about ten months to recoup: the prompt-only bill is only ~$375/month, and a payback that long can be overtaken by a base-model deprecation or a retrain. The crossover volume is the decision.
Prompt caching moves the baseline. The few-shot block in the prompt-only option is identical on every call, which is exactly what prompt caching discounts. The second block of output reprices the baseline with 80% of its input tokens served from cache at 0.1× (a parameter: check each provider's cached-read price and minimum-prefix rules, see 11B.3). The baseline falls from $15,000 to $6,360 a month, the tune's payback stretches from ~0.25 to ~0.63 months and RAG's from ~0.67 to ~2.4 months. The tune still wins at this volume, but the saving it claims is less than half what the uncached comparison suggests. Always price the baseline with the caching you could turn on tomorrow before crediting a fine-tune for "removing prompt tokens".
#!/usr/bin/env python3
"""ftecon.py — cost/benefit calculator for the prompting → RAG → fine-tuning
decision. Pure standard library; every number is a parameter you supply.
Models three candidate architectures for the same workload and prices them:
* prompt-only — a strong model with few-shot examples baked into the prompt
* rag — a mid model plus retrieval (index build + per-query chunks)
* fine-tune — a smaller tuned model with a short prompt, plus one-time
dataset/training/eval cost and optional dedicated hosting
Usage:
python3 ftecon.py # runs the worked example below
Edit OPTIONS / PROFILES (or import Option, Workload and run() and pass your own)
for your numbers.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
@dataclass
class Workload:
requests_per_month: float
# tokens billed per request. For prompt-only this includes the few-shot block;
# for RAG it includes retrieved chunks; for fine-tune it is the short prompt.
input_tokens: float
output_tokens: float
@dataclass
class Option:
name: str
price_in: float # USD per 1M input tokens
price_out: float # USD per 1M output tokens
one_time: float = 0.0 # USD: data prep + training/eval + index build, once
monthly_fixed: float = 0.0 # USD/month: vector DB, dedicated endpoint, etc.
notes: str = ""
# Prompt caching (lesson 03.7 / 11B.3): the share of input tokens served from
# the provider's cache, and what a cached token costs relative to a normal
# input token. Both are provider- and model-specific: read your pricing page.
cached_input_share: float = 0.0
cache_read_multiplier: float = 0.10
def effective_price_in(opt: Option) -> float:
"""Blended USD per 1M input tokens after the cached share is discounted."""
s = opt.cached_input_share
return opt.price_in * ((1 - s) + s * opt.cache_read_multiplier)
def cost_per_request(opt: Option, wl: Workload) -> float:
return (wl.input_tokens * effective_price_in(opt)
+ wl.output_tokens * opt.price_out) / 1e6
def monthly_cost(opt: Option, wl: Workload) -> float:
return wl.requests_per_month * cost_per_request(opt, wl) + opt.monthly_fixed
def months_to_recoup(opt: Option, baseline: Option,
opt_wl: Workload, baseline_wl: Workload) -> float | None:
"""Months for `opt`'s monthly savings vs baseline to pay back its one_time cost.
Each side is priced at its OWN request profile: the prompt-only baseline
carries the few-shot block (long prompts), the fine-tune carries the short
prompt. Pricing both sides at one profile would compare configurations that
cannot exist.
"""
saving = monthly_cost(baseline, baseline_wl) - monthly_cost(opt, opt_wl)
if saving <= 0 or opt.one_time <= 0:
return None
return opt.one_time / saving
def run(options: list[Option], profiles: dict[str, Workload], title: str) -> None:
"""Price every option at its own profile; the first option is the baseline."""
base = options[0]
print(f"=== {title} ===")
for opt in options:
wl = profiles[opt.name]
total = 12 * monthly_cost(opt, wl) + opt.one_time
line = (f"{opt.name:<12} {wl.input_tokens:>6,.0f} in / {wl.output_tokens:>4,.0f} out"
f" | $/request {cost_per_request(opt, wl):.5f}"
f" | monthly ${monthly_cost(opt, wl):>7,.0f}"
f" | one-time ${opt.one_time:>6,.0f} | 12-month ${total:>8,.0f}")
if opt is not base:
m = months_to_recoup(opt, base, wl, profiles[base.name])
line += (f" | recoups in ~{m:.2f} mo" if m is not None
else " | never recoups")
print(line)
print(f" {opt.notes}")
print()
def scaled(profiles: dict[str, Workload], requests_per_month: float) -> dict[str, Workload]:
return {k: Workload(requests_per_month, v.input_tokens, v.output_tokens)
for k, v in profiles.items()}
# ---------------------------------------------------------------------------
# Worked example — ILLUSTRATIVE numbers, chosen to show the shape of the
# calculation. Swap in your measured tokens (lesson 03.7/11.2 traces) and the
# current prices from the providers' pricing pages (lesson 03.7 Part 3).
# ---------------------------------------------------------------------------
OPTIONS = [
Option("prompt-only", price_in=1.00, price_out=5.00,
notes="frontier model + 8 few-shot examples in every prompt"),
Option("rag", price_in=0.40, price_out=1.60, one_time=8_000,
monthly_fixed=120, notes="mid model + retrieved chunks + vector DB"),
Option("fine-tune", price_in=0.20, price_out=0.80, one_time=3_500,
notes="small tuned model, short prompt, pay-per-token hosting"),
]
# RAG and fine-tune change the per-request token counts, so every option runs
# against its own request profile.
PROFILES = {
"prompt-only": Workload(2_000_000, 6_000, 300),
"rag": Workload(2_000_000, 2_500, 300),
"fine-tune": Workload(2_000_000, 800, 280),
}
def main() -> None:
run(OPTIONS, PROFILES, "worked example: support-answer bot, 2M requests/month")
print("--- sensitivity: months for the fine-tune to recoup its one-time cost ---")
for rpm in (50_000, 500_000, 2_000_000, 10_000_000):
p = scaled(PROFILES, rpm)
m = months_to_recoup(OPTIONS[2], OPTIONS[0], p["fine-tune"], p["prompt-only"])
print(f"{rpm:>12,.0f} requests/month -> {m:6.2f} months")
print()
# Prompt caching shrinks the baseline: the same few-shot block, mostly cached.
cached_baseline = replace(OPTIONS[0], cached_input_share=0.8,
notes="same prompt-only option, 80% of input tokens cached at 0.1x")
cached = [cached_baseline] + OPTIONS[1:]
run(cached, PROFILES, "same workload with prompt caching on the prompt-only baseline")
print("The crossover volume is the number that decides: compute yours.")
if __name__ == "__main__":
main()9.2 The decision flowchart#
Put the whole lesson in one flow. Start at the top; the first "yes" wins.
flowchart TD
S["Feature underperforms"] --> E{"Evals + traces<br/>diagnose the cause?"}
E -->|"no"| E2["Fix measurement first —<br/>you can't choose a rung blind"]
E2 --> S
E -->|"yes"| K{"Is it a<br/>knowledge problem?"}
K -->|"missing/stale facts"| R["RAG or tools<br/>(rung 3)"]
K -->|"no"| F{"Is it format,<br/>tone or instructions?"}
F -->|"yes"| P["Prompt, schema,<br/>examples (rung 1-2)"]
F -->|"no"| C{"Is it capability<br/>or cost/latency?"}
C -->|"yes"| M["Better model,<br/>routing, cascade (rung 4)"]
C -->|"no"| V{"Stable narrow task,<br/>hundreds+ clean labels,<br/>evals show a gap?"}
V -->|"no"| P
V -->|"yes"| ECON{"Does the<br/>crossover clear?"}
ECON -->|"no — low volume"| M
ECON -->|"yes"| FT["Fine-tune (rung 5)<br/>then re-eval honestly"]
FT --> H{"Evals pass<br/>+ no regressions?"}
H -->|"no"| FT
H -->|"yes"| SHIP["Ship behind a flag;<br/>keep the baseline as fallback"]The same ladder as a decision table — the columns the flowchart compresses:
| Rung | Choose when | Cost to try | Reversibility | Eval that proves it |
|---|---|---|---|---|
| 0. Measure first | Always, before picking any rung | Days | n/a | Evals and traces exist and actually diagnose the failure |
| 1. Prompt & context | Format, tone, instructions or examples are wrong | Minutes–days; prompt tokens per call | Deploy rollback | Paired eval on the task set beats the baseline |
| 2. Structured output & tools | Format guarantees needed; fresh data or actions required | Days; tool round-trips | Deploy rollback | Parse-failure rate and task eval improve |
| 3. RAG | Missing or stale facts the model should cite | Weeks; embedding + search + bigger prompts | Index/config rollback | Retrieval and answer evals (recall, faithfulness) |
| 4. Better model / routing | Capability, cost or latency ceiling of the current model | Days; higher per-token price | Config rollback | Same eval set: the candidate beats the incumbent |
| 5. Fine-tune | Stable narrow behaviour at volume; evals show a gap no prompt closes; hundreds+ clean labels | Weeks, plus training, serving and maintenance | Sticky — a new artefact with its own lifecycle | fteval.py paired comparison vs the best prompt/RAG baseline, plus a general-ability regression check |
| 6. Pretraining | A custom foundation model is genuinely required | Months, research-programme scale | n/a | Out of scope for product work (1.4) |
9.3 Five worked case studies#
Each walks the ladder honestly — including the cases where the answer is "don't tune".
The five cases below are composites built to illustrate the reasoning, not reports of real companies: every percentage and volume in them is an invented, plausible round number.
Case 1 — Invoice-extraction API (format + domain vocabulary). A fintech startup needs structured output from invoices: vendor, totals, line items, dates. Symptoms: JSON parse failures (~12%), wrong field names, missed totals on non-English invoices. Diagnosis: format problem, not knowledge — the model knows what an invoice is. Ladder: rung 1 prompt + JSON schema examples → rung 2 constrained decoding (response_format/strict schema) cuts parse failures to ~0.5%; rung 1 glossary + a few multilingual examples fixes the rest. Verdict: prompt+schema wins; no tune needed. Fine-tuning would have been the expensive way to relearn what a schema already guarantees.
Case 2 — Support triage bot (stable behaviour, high volume). 2M tickets/month; 40 categories; current frontier model + 8 few-shot examples costs ~$15k/month and still misroutes edge cases. Diagnosis: stable narrow classification at volume — the canonical fit. Ladder: rungs 1–4 exhausted (prompt variants, enum schema, routing tried); 3,000 human-labelled tickets exist; eval shows tuned 8B model at 94% vs prompted frontier at 91%. Verdict: distil/SFT the small model (5.3); economics from ftecon.py — recoups in about a week at this volume. Ship behind a flag, keep the frontier model as fallback for low-confidence cases.
Case 3 — "Our model doesn't know our 2026 pricing" (knowledge freshness). Product team asks for fine-tuning after a price change. Diagnosis: pure knowledge problem — the facts change monthly. Ladder: rung 3 RAG over the pricing DB (or rung 2 tools querying it live). Verdict: never fine-tune for freshness; the tune would be stale on arrival and you'd retrain monthly forever. This is the single most common fine-tuning mistake.
Case 4 — Legal-contract clause classification (narrow judgement, regulated). A legal-tech firm classifies contract clauses into 60 types with subtle boundaries; needs auditability and data residency. Diagnosis: stable narrow task, high label quality available from past reviews, volume moderate (~200k/month). Ladder: prompt+schema baseline at 82%; fine-tuned open model on Bedrock/Azure (data stays in-boundary) at 91%. Verdict: fine-tune justified — but only because evals proved the gap, labels exist, and the compliance constraint rules out some hosted options. The audit trail (dataset version, eval results, model ID) is part of the deliverable.
Case 5 — Chatbot "sounds robotic" (subjective quality). Users complain the assistant is bland. Team wants to fine-tune on "better" conversations. Diagnosis: taste problem with no measurable target — the anti-fit checklist. Ladder: rung 1 prompt/style guidance + DPO on preference pairs harvested from user feedback (5.1) if a provider offers it; eval via preference win-rate, not accuracy. Verdict: start with prompts and preference data; SFT only if a measurable gap persists at volume. "Sounds better" is not an eval — Part 8 applies to vibes too.
9.4 Combining techniques#
The techniques compose; the mature architecture is rarely "one rung". Common patterns:
- Tuned small model + RAG — the tuned model learns how to use retrieved context (cite, hedge, format) while retrieval supplies what to say. This is the strongest production pattern: tuning for behaviour, retrieval for knowledge.
- Tuned model + tools — fine-tune teaches tool-call format and domain argument conventions; tools supply live actions. OpenAI's SFT format literally supports
tool_callsexamples (4.3). - Router over tuned + base models — route easy queries to the cheap tuned model, hard/novel ones to the frontier (11B.5). The tune handles 80% of volume cheaply; the frontier handles the tail.
- Tuned embedder + tuned reranker + prompted LLM — component-level tuning (Part 6) when retrieval is the bottleneck.
- Prompt on top of the tune — a fine-tuned model still takes a system prompt; you can steer it per-request without retraining. The prompt doesn't stop working because weights changed.
9.5 Fine-tune rot and the upgrade-vs-retrain question#
Fine-tune rot is the fine-tuning version of model drift: your tuned model was excellent against base-model-vN; the provider ships vN+1 and your ft: model's behaviour shifts — sometimes subtly (tone), sometimes badly (the tune was compensating for a base behaviour that changed). The defence is the same as for prompts: pin versions, re-run evals on every base update, and keep the pre-tune baseline as a fallback you can route back to. Hosted fine-tunes inherit the base model's deprecation clock (4.1) — OpenAI's wind-down (4.2) is the cautionary tale: your tuned model dies when its base does, on the provider's schedule, not yours.
The upgrade-vs-retrain question: when a new base model ships, you have three options — (a) re-run your tune on the new base (cheap if data+pipeline exist, weeks of eval work), (b) test whether the new base + your prompt already beats the old tune (sometimes the frontier moved past your task), (c) stay on the old base until forced off. The eval harness from Part 8 is what makes this a decision instead of a guess.
Part 10: How to use a decision framework#
10.1 Four habits#
- Write the question as a choice between named options. "What should we do about quality?" is not a decision. "Prompt change, RAG, a stronger model or a fine-tune?" is.
- Know the default. A good default is the simplest option that could work and the easiest to undo. You do not need evidence to take the default; you need evidence to leave it.
- List the switch signals before you look at the data. If you decide what would change your mind first, you cannot rationalise afterwards.
- Price the cost of being wrong in both directions. Every decision has two ways to fail. Naming both stops you from optimising only against the failure you fear most.
10.2 What each decision section contains#
Every section in Part 11 has the same parts: the question; a decision table or flowchart; the default; the signals to switch; the cost of being wrong (each way); where to learn each option; and a worked example. The helper in Part 12 stores the same structure as data.
🎓 Fresher note: an architecture decision record (ADR) is a half-page document that captures one decision: the context, what you chose, what you rejected and why, and when to revisit. Teams write them so that in a year nobody has to guess why the system looks the way it does.
10.3 Where decisions live in this course#
General decisions live only here. Lessons that teach one option link back; the evaluation track keeps only the evaluation-specific part. In particular, the tables in 10B.14 section 9.1 and section 9.9 (single vs multi-agent, optional lesson) and 10B.15 section 10.10 (choosing the scaffold, optional lesson) apply the decisions below to evaluation and link here for the general question. The existing decision guides 08A.9 (workflow vs agent) and 13A.1 (when to use an LLM at all) go deeper on their own decisions. For decision 4, the ladder and the fine-tuning decision, this lesson's own Parts 1 to 9 are the deep treatment; this lesson is the map that connects them all.
Part 11: The nine decisions#
Every decision below follows the structure from 10.2. Decision 4 (prompting vs RAG vs fine-tuning) is the one this lesson covers in depth, so its section here is the short version with links into Parts 1 to 9.
11.1 D1: Workflow vs agent#
The question. Do you write the steps, or does the model choose them?
| Your situation | Choose |
|---|---|
| You can write the steps down before the run; one step or a few fixed ones | Workflow (a single call, a chain with checks, a router) |
| The next step depends on what the last tool returned; the environment gives feedback; requests vary widely | Agent loop, with budgets |
| You cannot check whether the outcome is right (no test, schema or rubric) | Not an agent: you cannot safely automate what you cannot verify |
| A user waits and latency is a few seconds; or there are very many cheap tasks | Workflow: each extra model call costs time and money |
flowchart TD
Q1{"Can you name the steps<br/>before the run?"} -->|yes| W["Workflow"]
Q1 -->|no| Q2{"Can you verify outcomes<br/>and budget the run?"}
Q2 -->|yes| A["Agent loop with budgets"]
Q2 -->|no| H["Human in the loop,<br/>or do not automate"]- Default: workflow. A workflow is testable, cheaper and predictable.
- Signals to switch to an agent: the steps depend on discoveries; the environment gives clear feedback each step (test results, API errors); the request types have a long tail you cannot enumerate; and you can verify the outcome.
- Cost of being wrong: choosing a workflow too early gives you a rigid system where each new request type needs a new branch. Choosing an agent too early gives you something slower, costlier and harder to test and secure, and "start with an agent and simplify later" almost never happens.
- Learn it: 08A.9 Workflows vs agents (the decision framework and a refund example three ways), 08A.2 The tool loop, 08A.10 Agent patterns, 08A.1 Agent definitions, autonomy and anatomy (the autonomy spectrum), and 08A.3 Loop control, budgets and stagnation.
- Worked example. A shop wants an assistant that handles refund requests. The steps are known (find the order, check the policy, decide, record, reply), every intermediate result can be checked with code, and a customer is waiting. Choose a workflow with one approval checkpoint for money. A year later 30 percent of requests are odd cases (damaged goods plus a missing parcel plus a coupon). That is the signal to try an agent for the odd cases only, behind the same checkpoint, and to evaluate it against the workflow before you switch.
11.2 D2: Single agent vs multi-agent#
The question. Does one agent with tools do the job, or do you split it into several agents with roles?
| Your situation | Choose |
|---|---|
| All tools and context fit one agent without confusing it | Single agent |
| You have no eval showing a single agent fails | Single agent |
| Evals show wrong tool choice from too many tools; or subtasks are independent and parallel; or a subtask would flood the main context | Multi-agent (often orchestrator and workers, or agent-as-a-tool) |
| Parts need different permissions (a reader of untrusted content and an actor with powerful tools) | Multi-agent, for isolation, not for intelligence |
- Default: single agent. 08D.3 names four taxes on multi-agent systems: cost, errors, coordination and debugging.
- Signals to switch: a measured failure that splitting fixes (not a hunch); independent subtasks that parallelise; context isolation (large searches kept out of the main context); a security split between reading untrusted content and holding powerful tools (12.1 Part 5 and 08A.14 section 2.9 on the lethal trifecta).
- Cost of being wrong: single when you needed several: an overloaded prompt, tool confusion and a context that fills with search noise. Multi when one would do: more cost, errors that propagate between agents, and traces that are hard to read.
- Learn it: 08D.3 section 1.3 and section 2.11 (the taxes and the decision table), 08D.1 One agent or several, 08D.2 Hands-on: a two-agent and a single-agent system compared and 08A.11 Reflection, parallel fan-out and agent-as-a-tool.
- Worked example. A research assistant must search the web and write a report. Search results are huge and would crowd the writing context. Splitting into a researcher (many searches, returns a short summary) and a writer is justified by context isolation, which you can measure (tokens in the main context). A support bot with six tools has no such pressure: keep one agent, and add an eval that would show if it starts picking the wrong tool.
11.3 D3: RAG vs long context#
The question. Put the documents in the prompt, or retrieve the relevant passages?
| Your situation | Choose |
|---|---|
| The whole corpus fits comfortably in the context window and rarely changes | Long context (often with a cached prefix) |
| Few queries per day, or many queries over one stable cached corpus | Long context |
| The corpus is far larger than the window, or grows daily | RAG |
| Different users may see different documents (permissions) | RAG (enforce access inside the retrieval query) |
| You need passage-level citations | RAG |
- Default: if it fits and is stable, try long context first, because it is one less system to build and keep fresh; otherwise RAG.
- Signals to switch: the corpus outgrows the window or churns; per-user permissions appear; you need citations; per-query cost or latency becomes the problem.
- Cost of being wrong: long context when you needed RAG: cost and latency grow with every query, quality can drop in a very large prompt, and you cannot enforce per-user access. RAG when long context would do: an extra system to build, tune and refresh, and retrieval can miss.
- Provider facts, dated. As of 1 December 2026 the current flagship models list context windows of about one million tokens: OpenAI's models page lists 1.05M tokens for its flagship GPT-6 family, and Anthropic's models overview lists 1M tokens for its current Claude models (both read 1 December 2026). A big window is not the same as reliable use of all of it, and every token in the prompt is billed. Providers discount repeated prefixes (Anthropic's overview states that prompt cache reads cost a fraction of the base input price), and pricing pages may include separate long-context rates, so read the pricing page before you cost a long-context design.
- Learn it: 07.1 section 1.3 (RAG vs the alternatives), section 2.5 of this lesson (caching and long context), 03.7 Cost and caching, 11B.8 Cost of agents, long contexts, caching and evals, 04.7 Managing context over time, 07.7 Managed RAG services.
- Worked example. A 40-page employee handbook that changes twice a year, queried a few hundred times a day: put it in a cached prefix and skip retrieval. A knowledge base of 50,000 support tickets that grows hourly, where agents may only see their own region's tickets: RAG, with the region filter inside the index query.
11.4 D4: Prompting vs RAG vs fine-tuning#
The question. When quality is not good enough, which lever do you pull? (The fourth option people forget is a stronger model.)
This is the decision the first nine Parts of this lesson teach in depth, so this section is the one-page version in the same shape as the other eight. Read it as the index into those Parts.
| What the failures look like | Lever | Where it is taught |
|---|---|---|
| You have no eval set yet | None yet: measure first, then better prompt and context | 1.1, rung 0 |
| Wrong format, tone or instructions | Prompt, schema, examples (rungs 1 and 2) | 2.2 |
| Missing or stale facts; knowledge that changes | RAG or tools (fine-tuning cannot keep facts fresh) | 2.4 |
| Reasoning mistakes a stronger model fixes in a trial | Better model or routing (rung 4) | 1.1 |
| A stable format, style or narrow skill at volume that measured prompt and example work did not fix | Fine-tuning (rung 5) | Part 3 |
flowchart LR
M["Measure: evals and error analysis"] --> P["1. Prompt and context"]
P --> T["2. Structured output and tools"]
T --> R["3. RAG"]
R --> B["4. Stronger model or routing"]
B --> F["5. Fine-tuning"]- Default: the cheapest, most reversible rung that the evidence has not ruled out. Climb only when a cheaper rung measurably fails (1.3).
- Signals to switch: a measured failure that the current rung cannot fix, matched to the right lever by the table above. Fine-tuning is a late rung: stable behaviour, hundreds or more clean examples, an eval that proves the cheaper rungs fell short, and volume where the economics clear.
- Cost of being wrong: too low a rung: you keep patching prompts for a problem that needs knowledge or capability. Too high a rung: weeks of work and a model you now maintain, for a problem a prompt would have fixed (1.4).
- Learn it: Part 1 The decision ladder, Part 2 What each technique changes, Part 3 The fine-tuning fit checklist, 9.2 The decision flowchart, and the option lessons 03.4 Structured output, 03.5 Tool calling, Module 07 RAG and 11B.5 Model selection and routing.
- Worked example. An assistant answers questions about a changing price list and often quotes old prices. That is a facts problem: RAG over the live price list. A second assistant must always answer in a strict house style and 30 prompt revisions have not held it. That is a behaviour problem with stable targets: now fine-tuning is a candidate, after you compare against a stronger model with a good prompt (9.3 case studies walk five more).
11.5 D5: Human approval vs full autonomy#
The question. Does a person approve this action, or does the agent act alone?
| Your situation | Choose |
|---|---|
| The action is irreversible or leaves your boundary (pay, send, delete, write shared data) | Human approval (a hard rule, not a preference) |
| The domain is regulated or high stakes | Human approval |
| The agent has no track record on an eval | Human approval until it has one |
| A wrong action is cheap and easy to undo, and accuracy is measured above target | Autonomy for that tier |
| Reviewers would see hundreds of requests a day | Approve by policy for low tiers, humans for the rest |
flowchart TD
A["Proposed action"] --> I{"Irreversible, external,<br/>or regulated?"}
I -->|yes| H["Human approves"]
I -->|no| M{"Measured accuracy meets target<br/>and the action is undoable?"}
M -->|yes| P["Approve by policy,<br/>log and sample"]
M -->|no| H- Default: human approval for anything irreversible or external; autonomy only per tier, earned by measurement. The existing guidance is "tighter approvals, not more autonomy" for high-stakes actions.
- Signals to switch toward autonomy: a measured accuracy that meets your target with confidence over enough cases, an action that is cheap to undo, and evidence that reviewers are approving without reading (fatigue), which means the gate protects nothing.
- Cost of being wrong: approval where autonomy would do: slow and costly work, and reviewers who stop reading. Autonomy where approval was needed: an unreviewed wrong action, with money lost, data sent or trust broken.
- Learn it: 08A.14 section 2.4 and 2.5 (risk tiers and approvals), 08F.12 (LangGraph), 13A.1 section 5.2 (autonomy tiers), 08A.12 Human-in-the-loop and approval gates (the pattern in full) and 14A.6 Agent inventory, risk classification and policy-as-code (classifying agents by risk and autonomy).
- Worked example. The refund assistant may issue refunds up to a small amount automatically (cheap to undo, policy-approved by a named rule) and must ask a human above it. After four weeks the eval shows the auto tier is correct on every audited case; the team raises the limit by one step and watches the audit log. They never remove the human tier for large amounts.
11.6 D6: Build vs buy (including managed provider tools)#
The question. Do you build this part yourself, or use a managed tool or product?
| Your situation | Choose |
|---|---|
| Prototype, internal tool or small corpus | Buy: a managed provider tool or a vendor product |
| The job is generic (meeting summaries, drafting) and a vendor covers it | Buy, after checking it meets your quality bar |
| You must tune retrieval, prompts or evals per stage, or audit what was retrieved or sent | Build the part that needs the knobs |
| Data may not leave your boundary | Build (self-host) or a provider with the right data terms; verify, do not assume |
- Default: buy or use a managed tool to learn fast, own the parts that differentiate you, and keep your prompts, data and evals portable.
- Signals to switch to build: you need knobs the tool hides, you must audit its behaviour, data residency rules rule it out, or data gravity (your corpus and evals living in the vendor's store) would make leaving painful.
- Cost of being wrong: buying when you needed to build: lock-in, hidden knobs and data that is hard to move. Building when you should have bought: months of work and an on-call burden for a commodity feature.
- Managed provider tools, dated. As of 1 December 2026, OpenAI's tools guide lists built-in tools including web search, file search, tool search, remote MCP, shell, computer use and image generation (the code interpreter has its own guide). Anthropic's tool overview lists server tools (run on Anthropic's infrastructure) including web search, web fetch, code execution, an advisor tool, tool search and an MCP connector. What you give up is control and sometimes data handling: for example, Anthropic's documentation says the code execution tool is not eligible for zero data retention and that container data is retained up to 30 days; for OpenAI file search the guide points to a separate page on zero data retention and data residency. Check retention terms for any tool that will see real customer data (14A.7 Data, vendor and supply-chain governance covers vendor terms, and 08A.5 Required agent security, section 6.8 compares the two hosted code tools).
- Learn it: 13A.1 Part 7 (the spectrum and decision table), 08A.8 Provider built-in tools, 07.7 Managed RAG services, 11C.6 Open-weight and local models, 03.11 Provider-agnostic client, 08F.1 Agent frameworks, 10A.10 Part 3 (build vs buy for eval platforms).
- Worked example. A team needs "chat with our docs" for 300 pages in two weeks. They use the provider's managed file search to ship, log the questions, and keep the documents and an eval set in their own storage. Six months later legal asks which passages were retrieved for a disputed answer, and the managed tool does not expose enough. That is the signal to build the retrieval step themselves, keeping the model API.
11.7 D7: Quality vs cost vs latency#
The question. You cannot maximise all three. Which one leads, and what are the other two allowed to cost?
| Your situation | Lead with |
|---|---|
| The quality target is not met yet, or errors are costly or asymmetric | Quality |
| A user is waiting in a live interaction | Latency (stream, shrink prompts, a faster model, fewer sequential calls) |
| High volume and low value per task; or work that can run as a batch | Cost |
| Quality exceeds the target with headroom | Cost (move down to a cheaper model and re-measure) |
- Default: quality first until the target is met, then optimise cost and latency against a fixed quality bar. Optimising cost before you can measure quality just moves errors around.
- Signals to switch: the quality target is met with headroom (trade headroom for cost); the product is interactive (latency becomes a constraint, not a goal); volume makes unit cost the first-order issue.
- Cost of being wrong: quality-first forever: an expensive, slow system nobody can afford to run. Cost-first too early: a cheap system whose errors cost more than it saves. Latency-first: a fast but shallow system.
- Learn it: 11B.1 Cost and latency optimization (the cost model, latency model, measure-first loop and the cost-quality frontier), 11B.5 Model selection and routing, 03.7 Cost and caching, 11B.6 Budgets, quotas, attribution and chargeback, 11B.8 Cost of agents, long contexts, caching and evals, 13A.6 Metrics, experiments and unit economics.
- Worked example. A document-extraction pipeline runs overnight on a million pages. Nobody waits, so use batch processing and a cheaper model, but only after the eval shows the cheaper model meets the accuracy bar on a sample. The chat widget on the same product is interactive, so it leads with latency: stream tokens, keep the prompt short and cache the prefix.
11.8 D8: Capability vs security#
The question. Give the agent a powerful tool, or hold it back to limit damage?
| Your situation | Choose |
|---|---|
| The agent would hold private data, read untrusted content and send data out (the lethal trifecta) | Restrict: cut a leg first |
| The agent reads content an attacker can influence | Restrict by default |
| The core user value needs the capability, and you can scope it (read-only, narrow arguments), sandbox it and gate risky uses | Grant, scoped, sandboxed and gated |
flowchart TD
C["Requested capability"] --> T{"All three trifecta legs<br/>in one agent?"}
T -->|yes| R["Restrict: cut a leg,<br/>or split the agent"]
T -->|no| S{"Scopable, sandboxed<br/>and risky uses gated?"}
S -->|yes| G["Grant, with logging"]
S -->|no| R- Default: restrict (least privilege). Add capability one scoped, gated step at a time.
- Signals to switch toward granting: the capability is the product's core value, it can be scoped to the narrowest form (a read-only database user, an allowlisted host), it runs in a sandbox with no secrets, and risky uses go through an approval gate.
- Cost of being wrong: restrict when you should have granted: a weaker product and users who route around it. Grant when you should have restricted: a hijacked agent holding the power, which means a leak, a bill or a deletion.
- Learn it: 12.8 Red teaming and security testing (testing the controls, including the OWASP checklists and an adversarial suite in CI), 12.1 Part 5 (capability analysis), 08A.14 section 2.9, 12.6, 08A.5 Required agent security and 14A.6 Agent inventory, risk classification and policy-as-code.
- Worked example. Product asks for "let the assistant read the web and mail the summary to the customer". That is untrusted content plus a send channel plus private data in context: all three legs. The fix is not "tell it to be careful"; it is to cut a leg: send only to the customer's own verified address, from a context that has no private data beyond the summary, behind an approval for any other recipient.
11.9 D9: Bespoke eval harness vs an eval framework#
The question. Keep your own small evaluation script, or adopt an eval framework (DeepEval, or Inspect)? This row is the only eval-specific decision in the list; Modules 10A and 10B teach it in detail.
| Your situation | Choose |
|---|---|
| One small eval, one author, no CI gate yet | Bespoke harness (a script or the course's evalkit) |
| You must explain a metric line by line to an auditor | Bespoke or custom metrics with no built-in prompts |
| A second author or a CI gate has appeared | Framework |
| You want ready-made RAG or safety metrics and a pytest-style gate | DeepEval |
| You need agent transcripts, sandboxes, or many-model comparison with reproducible logs | Inspect (optional track) |
| You already live on an eval platform | That platform's SDK |
- Default: a bespoke harness until a named gap appears. "Add the other package later only for a gap you can name."
- Signals to switch: a second author, a CI gate, a need for agent transcripts or sandboxes, a need for metrics you do not want to write; keep datasets, rubrics and thresholds as plain files so moving is a port, not a rewrite.
- Cost of being wrong: harness when you needed a framework: you rebuild runners, statistics and reports. Framework when a script would do: you inherit setup, defaults and a version policy you did not need yet.
- Learn it: 10B.1 section 1.5 (when neither is right), 10B.1 section 8.1 (the decision table), 10B.17 Choosing and combining eval frameworks (optional), 10A.10 Part 3 (platforms), and 10A.7 for what to measure for agents.
- Worked example. One engineer scores a classifier with a 60-line script and a CSV. That is right. When a second engineer joins and the team wants the eval to block merges, the script's argument parsing, retries and reporting start to grow. That is a named gap: try DeepEval for the gate, keep the dataset as the same CSV, and compare the two scores on a frozen sample before you trust the new one.
Part 12: A decision-record helper you can run#
Deep-dive
The helper encodes the nine decisions as data (options, a default listed first, and signals with weights), scores the signals you say are true, applies the hard rules (a signal can forbid an option), keeps the default on ties, and writes an ADR. It is deliberately simple: it is a structured way to argue, not an oracle.
12.1 The data#
# decisions_data.py -- the nine decisions as data: options, default, signals (stdlib only)
from dataclasses import dataclass, field
@dataclass(frozen=True)
class Signal:
id: str
text: str
favors: str # option key this signal points toward
weight: int # 1 (hint) to 3 (strong)
forbids: str = "" # option key this signal rules out (a hard rule), if any
@dataclass
class Decision:
key: str
title: str
options: dict # option key -> label; the FIRST key is the default
wrong: dict # option key -> the cost of choosing it wrongly
signals: list = field(default_factory=list)
@property
def default(self):
return next(iter(self.options))
S = Signal
DECISIONS = [
Decision("D1", "Workflow vs agent",
{"workflow": "Workflow (steps in your code)", "agent": "Agent (model chooses the steps)"},
{"workflow": "Rigid: new request types fail until you add a branch",
"agent": "Unpredictable, slower, costlier; harder to test and secure"},
[S("steps_known", "You can write the steps down before the run", "workflow", 3),
S("steps_depend", "The next step depends on what the last tool returned", "agent", 3),
S("env_feedback", "The environment gives feedback each step (tests, API errors)", "agent", 2),
S("long_tail", "Requests vary widely; a long tail of types", "agent", 2),
S("latency_tight", "A user waits and the latency budget is a few seconds", "workflow", 2),
S("cheap_high_volume", "Very many cheap tasks", "workflow", 2),
S("cannot_verify", "You cannot check the outcome with code, a test or a rubric", "workflow", 1, forbids="agent")]),
Decision("D2", "Single agent vs multi-agent",
{"single": "One agent with tools", "multi": "Several agents with roles"},
{"single": "Overloaded context and tool confusion on big tasks",
"multi": "More cost, coordination bugs and harder debugging for no gain"},
[S("fits_one_context", "All tools and context fit one agent without confusing it", "single", 3),
S("no_eval_evidence", "No eval shows a single agent failing", "single", 3),
S("tool_overload", "Your evals show wrong tool choice from too many tools", "multi", 2),
S("parallel_independent", "Subtasks are independent and can run in parallel", "multi", 2),
S("context_flood", "A subtask would flood the main context (large searches)", "multi", 2),
S("different_trust", "Parts need different permissions (a reader and an actor)", "multi", 2)]),
Decision("D3", "RAG vs long context",
{"long_context": "Put the corpus in the prompt", "rag": "Retrieve passages (RAG)"},
{"long_context": "Cost and latency grow with every query; quality can drop in a huge prompt",
"rag": "An extra system to build, tune and keep fresh; retrieval can miss"},
[S("small_stable", "The whole corpus fits comfortably and rarely changes", "long_context", 3),
S("few_queries", "Few queries per day", "long_context", 1),
S("cached_prefix", "Many queries share one stable cached corpus prefix", "long_context", 1),
S("corpus_large", "The corpus is much larger than the window or grows daily", "rag", 3),
S("per_user_access", "Different users may see different documents", "rag", 3),
S("need_citations", "You need passage-level citations", "rag", 2),
S("latency_tight", "A user waits and latency is tight", "rag", 1)]),
Decision("D4", "Prompting vs RAG vs fine-tuning (and a better model)",
{"prompting": "Better prompt and context", "rag": "RAG", "better_model": "Stronger model or routing",
"fine_tune": "Fine-tuning"},
{"prompting": "You keep patching prompts for a problem that needs knowledge or capability",
"rag": "You build retrieval for a problem that is really format or reasoning",
"better_model": "You pay more per call for a problem a prompt would fix",
"fine_tune": "Weeks of work and a model to maintain, for a problem a cheaper rung fixes"},
[S("no_eval", "You have no eval set yet", "prompting", 3, forbids="fine_tune"),
S("missing_facts", "Failures are missing or stale facts", "rag", 3, forbids="fine_tune"),
S("capability_gap", "A stronger model fixes the failures in a trial", "better_model", 3),
S("style_format", "Failures are a stable format, style or narrow skill that measured prompt work did not fix", "fine_tune", 3),
S("tiny_model_at_volume", "A small tuned model could replace a big one at high volume", "fine_tune", 1),
S("knowledge_changes", "The knowledge changes often", "rag", 2, forbids="fine_tune")]),
Decision("D5", "Human approval vs full autonomy",
{"approval": "Human approves risky steps", "autonomy": "Agent acts alone"},
{"approval": "Slow, costly, and reviewers stop reading",
"autonomy": "An unreviewed wrong action: money lost, data sent, trust broken"},
[S("irreversible", "An action is irreversible or leaves your boundary (pay, send, delete)", "approval", 3, forbids="autonomy"),
S("regulated", "The domain is regulated or high stakes", "approval", 3),
S("new_agent", "The agent has no track record on an eval yet", "approval", 2),
S("low_cost_error", "A wrong action is cheap and easy to undo", "autonomy", 3),
S("measured_high", "Measured accuracy meets the target with confidence", "autonomy", 2),
S("reviewer_flood", "Reviewers would see hundreds of requests a day", "autonomy", 1)]),
Decision("D6", "Build vs buy (including managed provider tools)",
{"buy": "Buy or use a managed tool", "build": "Build and own it"},
{"buy": "Lock-in, hidden knobs, data you cannot easily move",
"build": "Months of work and an on-call burden for a commodity feature"},
[S("prototype", "Prototype, internal tool or small corpus", "buy", 3),
S("commodity", "The job is generic and a vendor covers it", "buy", 2),
S("no_expertise", "The team lacks the skills and wants to learn on a low-stakes feature", "buy", 2),
S("need_knobs", "You must tune retrieval, prompts or evals per stage", "build", 2),
S("must_audit", "You must audit what was retrieved or sent", "build", 2),
S("residency", "Data may not leave your boundary", "build", 3),
S("data_gravity", "Moving your data later would be painful", "build", 1)]),
Decision("D7", "Quality vs cost vs latency (which one leads?)",
{"quality": "Quality first", "cost": "Cost first", "latency": "Latency first"},
{"quality": "An expensive, slow system nobody can afford to run",
"cost": "A cheap system whose errors cost more than it saves",
"latency": "A fast system that is wrong or shallow"},
[S("quality_not_met", "The quality target is not met yet", "quality", 3, forbids="cost"),
S("high_stakes", "Errors are costly or asymmetric", "quality", 3),
S("interactive", "A user is waiting in a live interaction", "latency", 3),
S("batch_ok", "The work can run asynchronously or as a batch", "cost", 2),
S("headroom", "Quality exceeds the target with headroom", "cost", 2),
S("cheap_high_volume", "High volume, low value per task", "cost", 3)]),
Decision("D8", "Capability vs security",
{"restrict": "Restrict (least privilege)", "grant": "Grant the extra capability"},
{"restrict": "A weaker product, and users route around it",
"grant": "A hijacked agent holds the power: leak, spend or delete"},
[S("trifecta", "The agent would hold private data, read untrusted content and send data out", "restrict", 3, forbids="grant"),
S("untrusted_input", "The agent reads content an attacker can influence", "restrict", 1),
S("core_value", "The core user value needs the extra capability", "grant", 2),
S("scopable", "The capability can be scoped to read-only or narrow arguments", "grant", 2),
S("sandboxed", "It runs in a sandbox with no secrets and limited network", "grant", 1),
S("gated", "Risky uses go through a human approval gate", "grant", 1)]),
Decision("D9", "Bespoke eval harness vs an eval framework (DeepEval or Inspect)",
{"harness": "Keep a small bespoke harness", "framework": "Adopt an eval framework"},
{"harness": "You rebuild runners, stats and reports a framework gives you free",
"framework": "You inherit setup, defaults and a version policy you did not need yet"},
[S("one_eval_one_author", "One small eval and one author, no CI gate yet", "harness", 3),
S("must_explain", "You must explain a metric line by line to an auditor", "harness", 2),
S("second_author_or_ci", "A second author or a CI gate has appeared", "framework", 2),
S("agent_transcripts", "You need agent transcripts, sandboxes or many-model comparison", "framework", 2),
S("ready_metrics", "You want ready-made RAG or safety metrics", "framework", 2),
S("on_platform", "You already live on an eval platform (use its SDK)", "harness", 1)]),
]12.2 The scorer and the record writer#
# adr.py -- score a decision from signals and write an architecture decision record (stdlib only)
import datetime
import sys
from decisions_data import DECISIONS, Decision
def score(decision: Decision, true_signals: set) -> dict:
totals = {k: 0 for k in decision.options}
forbidden, used = set(), []
for s in decision.signals:
if s.id in true_signals:
totals[s.favors] += s.weight
used.append(s)
if s.forbids:
forbidden.add(s.forbids)
allowed = {k: v for k, v in totals.items() if k not in forbidden}
best = max(allowed.values())
winners = [k for k in decision.options if k in allowed and allowed[k] == best]
choice = winners[0] # ties go to the default (listed first, simplest)
ranked = sorted(allowed.values(), reverse=True)
margin = ranked[0] - (ranked[1] if len(ranked) > 1 else 0)
return {"choice": choice, "totals": totals, "forbidden": sorted(forbidden), "margin": margin,
"confidence": "high" if margin >= 3 else "medium" if margin >= 1 else "low (default kept)",
"switched": choice != decision.default,
"reasons": [s for s in used if s.favors == choice or s.forbids]}
def adr(decision: Decision, context: str, true_signals: set, owner: str, revisit: str) -> str:
r = score(decision, true_signals)
rejected = [k for k in decision.options if k != r["choice"]]
lines = [f"# ADR: {decision.title}", "",
f"- Status: proposed ({datetime.date(2026, 12, 1).isoformat()})",
f"- Owner: {owner}", f"- Context: {context}", "",
f"## Decision", f"Use **{decision.options[r['choice']]}** (confidence: {r['confidence']}).", "",
"## Why (signals that held)"]
lines += [f"- {s.text}" + (f" [rules out {decision.options[s.forbids]}]" if s.forbids else "") for s in r["reasons"]] or ["- (none: default kept)"]
lines += ["", "## Alternatives not chosen"]
lines += [f"- {decision.options[k]}: would be wrong if we are mistaken like this: {decision.wrong[k]}" for k in rejected]
lines += ["", "## Cost of being wrong", f"- {decision.wrong[r['choice']]}", "",
"## Revisit when", f"- {revisit}"]
return "\n".join(lines)
# Decisions are not independent. These rules catch combinations that contradict each other.
CONFLICTS = [
("D5", "autonomy", "trifecta", "an autonomous agent holding all three trifecta legs: cut a leg or add approval (D8, D5)"),
("D1", "agent", "no_eval", "an agent with no eval set: build the eval first, or stay a workflow (D1, D4)"),
("D7", "cost", "high_stakes", "cost-first on a high-stakes task: errors may cost more than the savings (D7)"),
]
def consistency(results: dict, true_signals: set) -> list:
return [msg for key, option, signal, msg in CONFLICTS
if results[key]["choice"] == option and signal in true_signals]
def run_scenario(name: str, true_signals: set) -> None:
print(f"\n== {name}")
print(f"{'decision':<66} {'recommendation':<36} confidence")
results = {}
for d in DECISIONS:
r = results[d.key] = score(d, true_signals)
flag = " (switched from default)" if r["switched"] else ""
print(f"{d.key} {d.title:<63} {d.options[r['choice']][:36]:<36} {r['confidence']}{flag}")
for msg in consistency(results, true_signals):
print(f"WARNING conflict: {msg}")
if __name__ == "__main__":
unknown = set()
refund = {"steps_known", "latency_tight", "irreversible", "new_agent", "fits_one_context", "no_eval_evidence",
"per_user_access", "need_citations", "no_eval", "prototype", "high_stakes", "cannot_verify",
"one_eval_one_author", "untrusted_input", "scopable", "gated"}
research = {"steps_depend", "long_tail", "env_feedback", "parallel_independent", "context_flood",
"different_trust", "corpus_large", "missing_facts", "knowledge_changes", "trifecta",
"untrusted_input", "second_author_or_ci", "agent_transcripts", "batch_ok", "need_knobs",
"measured_high", "reviewer_flood", "core_value"}
known = {s.id for d in DECISIONS for s in d.signals}
unknown = (refund | research) - known
assert not unknown, f"unknown signal ids: {unknown}"
run_scenario("Scenario A: refund assistant for a shop", refund)
run_scenario("Scenario B: open-web research assistant over private notes", research)
d5 = next(d for d in DECISIONS if d.key == "D5")
print("\n" + adr(d5, "Refund assistant for a shop; refunds above a small amount move money.",
refund, owner="support-platform team", revisit="eval shows >= 99% correct approvals on 200 cases for 4 weeks"))How the scoring works:
- Each true signal adds its weight (1 to 3) to the option it favours.
- A signal with
forbidsremoves an option entirely. Example: "an action is irreversible" forbids autonomy, which is the "hard rule" in D5. - The winner is the highest score among allowed options. A tie goes to the default, the option listed first.
- Confidence is the margin between the best and second-best score. A margin of 0 means "default kept, low confidence", which is a prompt to gather evidence, not a reason to panic.
consistency()checks combinations that contradict each other (for example an autonomous agent that holds all three lethal-trifecta legs).
12.3 Running it#
== Scenario A: refund assistant for a shop
decision recommendation confidence
D1 Workflow vs agent Workflow (steps in your code) high
D2 Single agent vs multi-agent One agent with tools high
D3 RAG vs long context Retrieve passages (RAG) high (switched from default)
D4 Prompting vs RAG vs fine-tuning (and a better model) Better prompt and context high
D5 Human approval vs full autonomy Human approves risky steps high
D6 Build vs buy (including managed provider tools) Buy or use a managed tool high
D7 Quality vs cost vs latency (which one leads?) Quality first high
D8 Capability vs security Grant the extra capability medium (switched from default)
D9 Bespoke eval harness vs an eval framework (DeepEval or Inspect) Keep a small bespoke harness high
== Scenario B: open-web research assistant over private notes
decision recommendation confidence
D1 Workflow vs agent Agent (model chooses the steps) high (switched from default)
D2 Single agent vs multi-agent Several agents with roles high (switched from default)
D3 RAG vs long context Retrieve passages (RAG) high (switched from default)
D4 Prompting vs RAG vs fine-tuning (and a better model) RAG high (switched from default)
D5 Human approval vs full autonomy Agent acts alone high (switched from default)
D6 Build vs buy (including managed provider tools) Build and own it medium (switched from default)
D7 Quality vs cost vs latency (which one leads?) Cost first medium (switched from default)
D8 Capability vs security Restrict (least privilege) high
D9 Bespoke eval harness vs an eval framework (DeepEval or Inspect) Adopt an eval framework high (switched from default)
WARNING conflict: an autonomous agent holding all three trifecta legs: cut a leg or add approval (D8, D5)
# ADR: Human approval vs full autonomy
- Status: proposed (2026-12-01)
- Owner: support-platform team
- Context: Refund assistant for a shop; refunds above a small amount move money.
## Decision
Use **Human approves risky steps** (confidence: high).
## Why (signals that held)
- An action is irreversible or leaves your boundary (pay, send, delete) [rules out Agent acts alone]
- The agent has no track record on an eval yet
## Alternatives not chosen
- Agent acts alone: would be wrong if we are mistaken like this: An unreviewed wrong action: money lost, data sent, trust broken
## Cost of being wrong
- Slow, costly, and reviewers stop reading
## Revisit when
- eval shows >= 99% correct approvals on 200 cases for 4 weeksRead it like a reviewer:
- Scenario A (a refund assistant) lands on the conservative answers: workflow, one agent, human approval, buy to start. D3 switched to RAG because users have different access and need citations, and D8 says grant the capability because it is scoped and gated. That is "medium" confidence on purpose: one untrusted-input signal pulls the other way.
- Scenario B (open-web research over private notes) switches almost everything off the default, which is a sign the design is ambitious and needs more evidence at every step, and the consistency check fires. D8 says restrict (the trifecta), while D5 says the agent acts alone, so the two decisions contradict each other. The helper cannot resolve that, which is the point: it surfaces the conflict so a person decides. The fix is to cut a trifecta leg or to add approval.
- The ADR records why, what was rejected, the cost of being wrong in the chosen direction, and a measurable revisit trigger. Put it in the repository next to the code.
12.4 The one-page worksheet#
Copy this into a design review. Fill one row per decision, then write an ADR for any row where you left the default or where the cost of being wrong is high.
| # | Decision | Default | Our answer | Signals that held | Cost if wrong (chosen direction) | Revisit when | Owner |
|---|---|---|---|---|---|---|---|
| D1 | Workflow vs agent | Workflow | |||||
| D2 | Single vs multi-agent | Single agent | |||||
| D3 | RAG vs long context | Long context if it fits and is stable, else RAG | |||||
| D4 | Prompting vs RAG vs fine-tuning | Cheapest rung the evidence allows | |||||
| D5 | Human approval vs autonomy | Approval for irreversible or external | |||||
| D6 | Build vs buy | Buy or managed to start | |||||
| D7 | Quality vs cost vs latency | Quality first, then optimise | |||||
| D8 | Capability vs security | Restrict | |||||
| D9 | Harness vs framework | Bespoke harness until a named gap |
Three checks before you sign off: (1) did any two answers contradict (D5 and D8 most often)? (2) is there an eval that would tell you each decision is going wrong? (3) is each "revisit when" measurable, with a date or a number?
Part 13: Evaluate it#
Decisions are bets. You evaluate a decision the way you evaluate a system: pick the measure that would show it is going wrong, and check it on a schedule.
13.1 What to measure#
| Decision | Measure that would show it is going wrong |
|---|---|
| D1 workflow vs agent | Fraction of requests the workflow cannot handle; agent task success rate and cost per successful task versus the workflow |
| D2 single vs multi | Task success and cost per successful task for both designs on the same cases; tokens in the main context |
| D3 RAG vs long context | Answer correctness and citation accuracy on a fixed question set; cost and latency per query for both |
| D4 prompting vs RAG vs fine-tuning | The same eval run after each lever; the cheaper rung must lose before the dearer one is tried |
| D5 approval vs autonomy | Unapproved executions (exactly 0 for gated tiers); approval rate, edit rate and decision time (fatigue signals) |
| D6 build vs buy | Quality on your cases for the managed tool vs your build; time to answer an audit question |
| D7 quality, cost, latency | Quality at fixed cost; p50 and p95 latency; cost per successful task |
| D8 capability vs security | Attack success rate on the adversarial suite (12.8); benign pass rate |
| D9 harness vs framework | Do the two give the same score on a frozen sample? Time to add a case |
The concept home for task success, cost per successful task and trajectory metrics is 10A.7 (see Part 4 for trajectory grading and section 5.6 for task success rate and cost per successful task). Many of these decisions compare two designs, so you also need a fair comparison; 10A.8 covers paired comparisons and regression gates.
13.2 A tiny eval design: decision regret#
Inputs: the same 30 representative tasks run through both options of one decision (for D1, the workflow and the agent). Metric: success rate and cost per successful task for each option, plus the count of tasks where the two options disagree. Pass rule: the chosen option must be at least as good on success, and within your cost allowance, with the disagreements reviewed by a person. If the rejected option wins on both, write that down: the decision record's "revisit when" has fired. Because the comparison is an experiment you control, it fits a small bespoke harness. When the comparisons multiply, which tool you use is itself decision D9.
13.3 Evaluating with the Module 10A and 10B toolkit#
Read these in order. The concept lessons tell you what to measure; the tool lessons tell you how.
- Concept lessons: 10A.7 Evaluating agents, 10A.11 Evaluating agent memory and context (relevant to D3 and D4), 10A.12 Evaluating multi-agent systems (D2).
- The decision row for D9, and the one in the eval track: 10B.1 section 1.5 and 10B.1 section 8.1.
- DeepEval track (required): 10B.2 fundamentals, 10B.3 judges and custom metrics, 10B.4 built-in metrics, 10B.5 tracing and agent evaluation, 10B.6 datasets, synthesis and simulation, 10B.7 red teaming, CI and platform.
- Inspect track (optional): 10B.17 Choosing and combining eval frameworks (optional), and, for evaluating the scaffold decision (D1, D2, D5) inside Inspect, 10B.14 Tools and agents (optional) and 10B.15 Sandboxes, limits and approval (optional).
- Also read 10A.7 for what to measure and 10A.10 Part 3 for the platform build-vs-buy decision.
Failure gallery#
| Failure | Symptom | Root cause | The fix |
|---|---|---|---|
| The knowledge tune | Tuned model answers yesterday's questions confidently and wrongly | Trained on documents expecting permanence; weights froze at train time | RAG/tools for facts; tune only for behaviour (2.4) |
| The prompt that was enough | Team spends $8k + 3 weeks on a tune; a 3-example prompt fix would have done | Skipped rungs 1–4; no baseline eval | Run the ladder; measure before training (Part 1) |
| The contaminated eval | Tune "improves" 40 points; production unchanged | Eval items leaked into training data | Decontaminate before upload; prepare_dataset.py --eval (7.5) |
| The forgotten skill | Task accuracy up, general-ability eval down 8 points | Catastrophic forgetting from narrow data | General-ability regression check before shipping (8.3) |
| The deprecated base | ft: model returns errors after provider sunset |
Hosted tune inherits base model's deprecation clock | Pin versions; track provider timelines; keep fallback route (9.5) |
| The licence violation | Legal flags distillation pipeline | Trained on provider outputs against ToS | Check the distillation map before generating data (5.3) |
| The PII-in-weights | Customer data found memorised in tuned model | Trained on unscrubbed production data | Scrub before upload; PII in weights can't be deleted (4.6) |
| The idle endpoint | "Cheap" tune bills more than the API it replaced | Dedicated-endpoint floor + premium inference rates | Price serving, not just training (4.5, 9.1) |
| The templated dataset | Tune learns 3 phrasings, fails on real variety | Synthetic/near-duplicate data | Diversity checks; near-dup detection (7.2) |
| The decision nobody wrote down | A year on, nobody knows why the system is a multi-agent graph or why the tune exists | No record of the default, the signals or the revisit trigger | Write a one-page decision record (12.2, 12.4) |
| The contradicting pair | An autonomous agent that holds private data, reads untrusted pages and can send email | Two decisions answered separately (human approval vs autonomy, capability vs security) | Check combinations before sign-off (12.2) |
| The vibes eval | "It sounds better" ships a regression | No measurable acceptance criterion | Paired evals + stats; fteval.py (Part 8) |
Common misconceptions#
- "Fine-tuning makes the model smarter." It makes the model behave differently on your distribution — it does not add capability the base model lacked, and it cannot add fresh knowledge. Smarter is rung 4 (better model) or rung 6 (pretraining, not this path).
- "RAG and fine-tuning are alternatives." They solve different problems and compose: retrieval supplies knowledge, tuning supplies behaviour. The strongest production pattern is often both.
- "More training data is always better." Improvement is logarithmic; 50 great examples can beat 5,000 noisy ones. Quality, consistency and coverage dominate quantity (7.1).
- "A fine-tuned model is a drop-in replacement." It's a new model artefact — own lifecycle, own eval history, own deprecation clock, own serving bill. It interacts with your prompts, schemas and tools exactly like a new base model does.
- "If the provider offers fine-tuning, we should use it." Availability ≠ wisdom. OpenAI is winding its platform down and Anthropic never offered one; the question is whether your problem clears the rung-5 bar, not whether the button exists.
- "We can fine-tune on GPT outputs to get GPT quality cheaply." Distillation is legally restricted by most providers' terms — check 5.3 before building the pipeline.
- "A framework or tool choice is the architecture." The decisions in Part 11 come first; the framework is a consequence.
- "More agents means more intelligence." More agents means more cost, coordination and failure modes; add them for a measured reason such as context isolation or parallelism (11.2).
- "A 1M-token window makes RAG obsolete." A window is capacity, not reliable use, and every token is billed on every query. Per-user permissions and citations also push toward retrieval (11.3).
- "Human in the loop makes a risky action safe." It makes it authorised, and only if the human sees the real action and is not overwhelmed. Tier your gates (11.5).
- "Buying means we do not own the risk." You still own the data you send, the quality of the output and the consequences. Check retention and residency terms (11.6).
- "Pick quality, cost and latency: we can have all three." You can have two at a time on a given task; decide which leads, and fix the others as constraints (11.7).
- "Security and capability are opposites." They trade off only until you scope, sandbox and gate; scoped capability is usually available (11.8).
- "The scorer's answer is the decision." The helper surfaces your reasoning and conflicts; people still decide (12.3).
- "Once fine-tuned, we're done." Fine-tune rot is real: base-model updates, data drift and eval regressions mean the tune needs the same maintenance discipline as any model you own.
Key takeaways#
- The ladder is the lesson: prompt → schema/tools → RAG → better model/routing → fine-tune → pretraining. Climb only when a cheaper rung measurably fails; each rung generates the evidence for the next.
- Context vs weights is the frame: rungs 1–4 change what you send; rung 5 changes the model. Knowledge that changes belongs in context; stable behaviour at volume can belong in weights.
- Fine-tuning is for behaviour, not facts: format, style, classification, tool-use patterns, narrow judgement — demonstrated by hundreds-to-thousands of clean examples. Fresh knowledge, citations and general capability are not what weights are for.
- The 2026 landscape is consolidating: OpenAI's platform is winding down (new jobs end January 2027), Google's moved to the cloud Agent Platform, Anthropic offers none, Mistral's API is deprecated — while open-model fine-tuning booms on Together, Fireworks, Azure Foundry and Bedrock. Plan provider-neutral; own your data and evals.
- Evals before training, paired stats after: baselines first, decontaminated data, paired comparison with confidence intervals, general-ability regression check, per-slice breakdowns — then ship behind a flag with the baseline as fallback.
- The economics are a crossover: one-time training + eval cost vs permanently lower per-request cost. Compute your crossover volume with
ftecon.py; below it, prompting wins; above it, a small tuned model often wins big. - Nine decisions recur: workflow vs agent; single vs multi-agent; RAG vs long context; prompting vs RAG vs fine-tuning; human approval vs autonomy; build vs buy; quality vs cost vs latency; capability vs security; bespoke harness vs framework. Each has a default (the simplest, most reversible option): leaving it needs evidence, staying needs none (Part 11).
- Write the switch signals and the cost of being wrong in both directions before you look at data, then check that your answers do not contradict each other (an autonomous agent with the lethal trifecta). Record the decision with a measurable revisit trigger (Part 12).
- Evaluate a decision by running both options on the same cases. The rejected option winning on both success and cost means the revisit trigger has fired (13.2).
- Prefer principles over numbers for provider facts (context windows, tool limits): read the docs and date what you quote.
- A fine-tune is a model you own: version the dataset and config, re-eval on every base update, retrain on drift, and keep the pre-tune baseline routable. Fine-tune rot is managed, not avoided.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Decision ladder | The ordered sequence of interventions — prompt, structured output/tools, RAG, better model/routing, fine-tuning, pretraining — from cheapest and most reversible to most expensive and stickiest (Part 1) |
| Context vs weights | The two physical levers for changing an LLM: what you send it per call (context) versus the trained parameters (weights); rungs 1–4 change context, only training changes weights (2.1) |
| Reinforcement fine-tuning (RFT) | Training with a grader that scores candidate responses; when the grader is a program (tests, schema, exact match) it's RL with verifiable rewards — the technique behind reasoning models (5.2) |
| Catastrophic forgetting | The tendency of narrow fine-tuning to degrade a model's previously-held general abilities; requires a general-ability regression eval to detect (8.3) |
| Fine-tune rot | The drift of a tuned model's behaviour when its base model updates or the data distribution moves — the fine-tuning analogue of model drift (9.5) |
| Prompt caching (as a baseline) | Provider discount on a repeated prompt prefix; it lowers the prompt-only cost that a fine-tune must beat, so price the baseline with it on (2.5) |
| Crossover volume | The request volume at which a fine-tune's permanently lower per-request cost repays its one-time training and eval cost — the number that decides the economics (9.1) |
| Decision framework | A repeatable way to choose between named options using a default, switch signals and the cost of being wrong (10.1) |
| Default (option) | The simplest, most reversible option; taken without evidence and left only with evidence (10.1) |
| Switch signal | An observable fact that should move you off the default (10.1) |
| Cost of being wrong | What it costs if the chosen option turns out to be the wrong one, stated for each direction (10.1) |
| Architecture decision record (ADR) | A short document capturing a decision, its context, alternatives, consequences and a revisit trigger (10.2) |
| Hard rule | A signal that rules an option out entirely, for example irreversible actions rule out autonomy (12.2) |
| Decision regret | The gap between the chosen option and the rejected one on the same test cases (13.2) |
| Managed tool | A tool run by the provider (web search, file search, code execution) instead of by your code (11.6) |
| Data gravity | The tendency of data and evals to accumulate in one vendor's store, making leaving costly (11.6) |
| Context isolation | Keeping a subtask's large intermediate data out of the main agent's context (11.2) |
Terms this lesson uses but does not introduce — they are owned by earlier lessons and the glossary: supervised fine-tuning (02.6), preference tuning/DPO (02.6, 7.4), RLVR, knowledge distillation (02.6, Part 10), LoRA/QLoRA/adapters (02.1, 7.4), decontamination and JSONL.
All terms are also collected in the glossary.
Exercises#
-
The ladder, applied. Pick a feature you're building (or imagine one: a contract-review assistant, a pricing bot, an internal search). Write down its three most likely failure modes and map each to a rung on the decision ladder — before touching any code. Which rung would you try first, and what eval would tell you whether it worked?
-
Run the data prep tool.
python3 prepare_dataset.py --demo --outdir demo_prepare— readdemo_prepare/demo_raw.jsonlanddemo_prepare/splits/train.jsonl, and explain in your own words what each check caught and why the eval-leakage drop matters. Then modify the demo generator to add a near-duplicate of a training example (same question, different reply) and see whether the shingle check catches it. -
The economics, your numbers. Open
ftecon.pyand replace the worked example with your real scenario: estimate requests/month, input/output tokens per request for each candidate architecture (use traces if you have them), and current prices from provider pricing pages. At what volume does fine-tuning win? Write the crossover point down — that's the number your architecture review needs. -
Provider landscape scan. Re-verify Part 4's table against the current docs for two providers of your choice (the market moves monthly). Has anything changed since November 2026? Note the date you checked and the URL — this is the habit the whole lesson is built on.
-
The eval design. For the case study you picked in exercise 1, design the eval set: how many items, what slices, what baselines (prompted base, base+RAG, previous tune), and what statistical test would convince you the tune helped. Would
fteval.py's paired bootstrap be sufficient, or do you need something else? -
Run your own scenario. Add a third scenario to
adr.pyfor a system you know (a voice assistant, a code-review bot). Choose which signals are true and run it. Which decisions switch from the default? Hint: pick signals fromdecisions_data.pyand add the set to therun_scenariocalls; the helper asserts that every id exists. -
Add a decision. Add a tenth decision, "Streaming vs non-streaming responses", with a default, two options and four signals. Hint: put it in
DECISIONSwith the simpler option first; reuselatency_tightorinteractiveas signal ids if they fit. -
Add a conflict rule. Add a rule to
CONFLICTSthat warns when D2 chooses multi-agent and D9 chooses the bespoke harness. Why might that combination hurt? Hint: multi-agent runs produce transcripts and traces that a tiny script may not capture; see 10A.12. -
Argue with the default. Take D3 and write the three facts you would measure before leaving "long context" for RAG on a 100-page corpus. Hint: per-query cost and latency, answer correctness on a fixed question set, and whether any user needs access to only part of the corpus.
-
Write an ADR for D4. For an assistant that quotes old prices, run the helper with the signals
missing_factsandknowledge_changesand keep the generated record. Edit the "revisit when" to something measurable. Hint: useadr(...)on the D4 entry and add the revisit line, for example "answer correctness on 100 price questions stays above the target for 4 weeks". -
Decision regret. Design the tiny eval in 13.2 for D2 using 20 tasks. List the three numbers you would report. Hint: success rate, cost per successful task, and the count of tasks where single and multi disagree.
Hints and worked answers for the exercises
- A worked example: a contract-review assistant. (a) It misses a clause that is in the document: retrieval failure, so rung 3 and a retrieval eval (recall at k). (b) It answers in the wrong JSON shape 8% of the time: rung 2, measured by parse-failure rate. (c) Reviewers say its tone is "too definitive": rung 1 first, then DPO on reviewer preference pairs (5.1) only if a measured gap persists. Notice that none of the three needs rung 5 before the cheaper rungs are measured.
- The demo catches: one malformed JSON line, one record with no assistant turn, two exact duplicates, one training example copied from the eval set (different system prompt, same user/assistant turns) and one record with an email and a phone number. For the extension, predict before you run: a training example with the same question but a different reply shares only about a third of its 8-word shingles with the original, so the 50% threshold does not flag it (a paraphrased question with the same reply sits at about 50% and is borderline). That gap is real: question-level duplicates with conflicting answers are label noise the script cannot see. A fix to try: also compute shingles over the user turns alone and report groups of identical or near-identical questions with different replies.
- With the lesson's parameters the fine-tune recoups in ~0.25 months at 2M requests a month and ~9.8 months at 50k. Your numbers will differ; the deliverable is the volume where payback drops below about six months, with the caching variant (
cached_input_share) alongside, and a note of which input you are least sure of. - Pick Google, Together or Fireworks and Azure for variety. For each, record the date, the page URL and what changed against Part 4: model lists and prices move fastest, deprecations next, methods slowest.
- A reasonable design: 200 to 500 items sampled from real traffic (not from the training data), tagged by slice (language, difficulty, category), three arms (best prompt, prompt + RAG, tune), and the paired bootstrap from
fteval.py. It is sufficient for a pass/fail metric on one slice; use it per slice for the headline, add a larger set or a different metric for graded quality (scores from a rubric or judge, Module 10A), and treat many slice comparisons as a multiple-testing risk: do not declare a win on the one slice that happened to improve.
Check yourself#
- What are the two physical levers for changing an LLM's behaviour, and which rungs of the ladder use each?Context (everything sent per call: prompt, retrieved documents, tool definitions, conversation state) and weights (the trained parameters). Rungs 1–4 — prompt/context, structured output/tools, RAG and model choice/routing — change only context; rung 5 (fine-tuning/distillation) is the first to change weights; rung 6 (pretraining) changes them from scratch (1.1, 2.1).
- Why is "fine-tune to add knowledge" almost always wrong, and what should you do instead?Because weights freeze at training time — facts baked in are stale on arrival, and knowledge that changes belongs in context: RAG, tools or a fresher prompt (2.4).
- Name three things a fine-tune cannot fix that a prompt or retrieval can.Any three of: fresh or changing knowledge; citations and attribution; exceeding the base model's raw capability; eliminating hallucination; fixing upstream retrieval failures (2.4).
- What does DPO train on that SFT doesn't, and when is it the better choice?SFT learns from single input/output demonstrations; DPO learns from pairwise comparisons (chosen vs rejected). It's the better choice when the content is right but the judgement — tone, verbosity, refusals, ranking — is off, and when you can harvest preferences from traffic more cheaply than writing ideal answers (5.1).
- Why does distillation have a legal dimension that ordinary fine-tuning doesn't?Because distillation trains on another provider's outputs, which most providers' terms restrict — OpenAI §3.3(e) bars competing models, Anthropic bars distillation without authorisation, Google allows output only for its own tuning features. Ordinary fine-tuning on your own data doesn't import someone else's output (5.3).
- What's the difference between LoRA and full fine-tuning, and why do hosted platforms default to LoRA?Full fine-tuning updates every weight; LoRA freezes the base and trains small injected adapter matrices. Hosted platforms default to adapters because they need less data and compute, train faster, and let one base deployment serve many task adapters (5.4).
- How much training data do you need — give a range and the source.Order-of-magnitude: ~50–500 good examples can move a narrow format/style task (OpenAI: minimum 10, improvements at 50–100, start ~50; Meta: a couple dozen up to a 100–200 goal); ~500–2,000 for domain behaviour on real distributions; thousands-plus for complex reasoning (the AWS ballpark is ~2,000, and 10,000+ for complex tasks). Quality dominates quantity — the LIMA lesson (7.1).
- What must a fine-tune evaluation beat, what must it not break, and why do paired statistics matter?It must beat the base model with your best prompt, the base model with prompt + RAG, and the previous fine-tune — and must not regress general ability or per-slice performance. Paired statistics matter because on ~50–200 items a raw pass-rate gap is usually noise; comparing the same items pairwise with a confidence interval separates real improvement from luck (8.1, 8.2).
- What is catastrophic forgetting and how do you detect it?Catastrophic forgetting is narrow fine-tuning degrading the model's previously-held general abilities. Detect it with a general-ability regression eval run paired on the base model and the tune (8.3).
- What is fine-tune rot, and what's the defence?Fine-tune rot is the drift of a tuned model's behaviour when its base model updates or the data distribution moves. The defence: pin versions, re-run evals on every base update, keep the pre-tune baseline as a routable fallback, and decide upgrade-vs-retrain with the eval harness (9.5).
- Which providers offered hosted fine-tuning as of November 2026, and which didn't?Offered (Nov 2026): Google Gemini Enterprise Agent Platform, Amazon Bedrock, Azure Foundry, Together AI and Fireworks; OpenAI was winding down (new jobs end in January 2027) and Mistral's API was deprecated. Not offered: the Gemini API/AI Studio, Anthropic and OpenRouter (4.2).
- What is the crossover volume, and why is it the number that decides the economics?The crossover volume is the request volume where a fine-tune's permanently lower per-request cost repays its one-time training and eval cost. It decides the economics because below it the prompted/RAG bill is already small and the tune never recoups; above it the per-request savings dominate (9.1).
- What is the default for "workflow vs agent", and what three facts would justify an agent?Workflow. An agent is justified when the steps depend on what the model discovers, the environment gives feedback each step, the request types have a long tail you cannot enumerate, and you can verify outcomes and budget the run (any three of these, with verifiability required).
- Why is "no eval shows a single agent failing" a reason to stay with a single agent?A single agent is simpler, cheaper and easier to debug. Splitting adds cost, errors and coordination bugs, so you need a measured failure that splitting fixes.
- When does long context beat RAG, and when does it lose? Name two facts for each.Long context wins when the corpus fits comfortably and rarely changes, when queries are few, or when many queries share one stable cached prefix. It loses when the corpus is far larger than the window or grows daily, when users have different access rights, or when you need passage-level citations (also when cost or latency per query matters).
- Which kind of failure does fine-tuning fix, and which does it not?Fine-tuning fixes stable behaviour: format, style, a narrow skill. It does not keep facts fresh or add knowledge that changes; use retrieval for that.
- Why is "the action is irreversible" a hard rule against autonomy?An irreversible action cannot be undone if the agent is wrong or hijacked, so the cost of an unreviewed mistake has no upper bound. A human check, or a policy with a named rule, must stand in front of it.
- Name two things you give up when you use a managed provider tool, and one thing to check before sending customer data to it.Control over internals and knobs, and sometimes data handling (retention, residency), plus lock-in through data gravity. Check the retention and zero-data-retention terms and where data is processed before sending customer data.
- In which order should you optimise quality, cost and latency, and why?Quality first until the target is met, then cost and latency against a fixed quality bar, because optimising cost first just moves errors around. Interactive products treat latency as a constraint from the start.
- When is capability worth granting despite the security cost?When the capability is core to the product's value and can be scoped (read-only or narrow arguments), sandboxed, and gated for risky uses, and the lethal trifecta is not complete in one agent.
- What is the default for "harness vs framework", and what named gap should make you adopt one?A bespoke harness until a named gap appears, such as a second author, a CI gate, a need for agent transcripts or sandboxes, or ready-made metrics you do not want to write.
- Why does the helper keep the default on a tie, and what should you do when confidence is low?The default is the simplest, most reversible option, so without evidence to leave it you should stay. Low confidence is a prompt to gather evidence (run both options on the same cases), not to guess.
Further resources#
- Lesson 02.6 — How LLMs are trained: the full training pipeline — pretraining, SFT, preference tuning, distillation, RLVR — that this lesson applies at production scale.
- Lesson 02.1, 7.4: context vs weights — the frame the whole decision ladder runs on.
- Lesson 04.2, 6.6: the prompt-side escalation path (zero-shot → few-shot → retrieval → fine-tune) this lesson generalises.
- Lesson 04.9, 2.3: prompt fixes vs non-prompt fixes — the debugging version of the ladder.
- Lesson 07.1, 1.3: RAG vs the alternatives — the retrieval side of the same decision.
- Module 10A — Evaluation Foundations: the methodology behind the evals this lesson insists on before and after training.
- Lesson 11B.5 — Model selection and routing: where tuned models sit in a routed fleet.
- Lesson 11C.6 — Open-weight and local models: serving the open models you might fine-tune yourself.
- Module 12 — Safety, security and privacy: the governance layer for training data, PII and provider terms.
- 08A.9 — Workflows vs Agents: the decision framework and the refund example three ways (decision 1).
- 13A.1 — Product Thinking for AI Features: when to use an LLM, autonomy tiers and build vs buy vs configure.
- 10B.1 — Eval Frameworks: DeepEval and Inspect and 10B.17 — Choosing and Combining Eval Frameworks (optional): the eval-specific decision (decision 9).
- Michael Nygard, Documenting architecture decisions: the origin of the ADR format.
Provider documentation for the dated facts in Part 11 (read 1 December 2026)#
Provider documentation (verified November 2026)#
- OpenAI fine-tuning deprecation timeline: https://developers.openai.com/api/docs/deprecations
- OpenAI SFT guide: https://developers.openai.com/api/docs/guides/supervised-fine-tuning
- Google Gemini Enterprise Agent Platform tuning: https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/tuning
- Amazon Bedrock custom-model fine-tuning: https://docs.aws.amazon.com/bedrock/latest/userguide/custom-model-fine-tuning.html
- Azure Foundry fine-tuning overview: https://learn.microsoft.com/en-us/azure/foundry/fine-tuning/overview
- Mistral fine-tuning (deprecated): https://docs.mistral.ai/resources/deprecated/finetuning
- Together AI fine-tuning: https://docs.together.ai/docs/fine-tuning/overview
- Fireworks AI fine-tuning: https://docs.fireworks.ai/fine-tuning/finetuning-intro
- OpenRouter distillation/compliance: https://openrouter.ai/docs/cookbook/evaluate-and-optimize/distillation
- OpenAI embedding models (fine-tuning not supported): https://platform.openai.com/docs/models/text-embedding-3-small
← 13A.7 — Case Studies: How Real AI Products Are Built, and How They Fail | Module 13A overview | Module 13B: Capstones →