Skip to Content
Recodocs

LLM fine-tuning

Training a language model on your own data has become cheap and commoditised. Whether it pays depends on whether you can define and check the behaviour you want, and whether you own the result. A review of the methods, the evidence and the 2026 market, followed by a builder's guide.

169 min read

An invoice parser might keep putting the tax in the wrong JSON field, even when the prompt is clear. A different assistant might quote last month's policy because the policy changed. The first failure could be a learned behaviour problem; the second is usually a problem of fetching the current fact. Both look like 'the model is wrong', but they need different fixes.

Fine-tuning changes the model's learned parameters. To decide whether it is worth doing, compare it with a better prompt, retrieval and deterministic checks. The rest of this chapter explains what each training method changes, how to measure whether it helped, and what it costs to own that change in production.

In 2026 the market for fine-tuning flipped. On 7 May, OpenAI began closing fine-tuning to organisations that had never used it. On 2 July it closed the door to organisations with no recent fine-tuned inference, and from 15 December 2026, a date brought forward from 6 January 2027, no organisation can start a new self-serve job. The base models under existing fine-tunes (the GPT-4o and GPT-4.1 families) are scheduled to be removed on 14 January 2027, and the fine-tunes go with them. The page recommends newer base models but names no successor fine-tuning product. The oldest closed fine-tuning service is winding down.

Over the same months, training an open-weight model became a metered utility. As of November 2026, Together AI lists fine-tuning of Llama 3.1 8B at $0.34 per million tokens processed in training, with a $4 minimum, and Thinking Machines lists $0.44 for Qwen3-8B on Tinker (vendor list prices, October 2026). On 3 November Snowflake put Cortex Training into public preview, billed by GPU time. A fine-tuning run that needed a cluster and a research team in 2022 is now an API call priced in cents per million tokens.

The two moves share a logic, though not one cause. Fine-tuning a small model is cheap compute, so it is easy to sell and easy to commoditise. Fine-tuning a closed frontier model ties your artefact to a base model that its owner retires on its own schedule, and serving many custom variants of a large model is costly for its owner; OpenAI has not published its reasons. What is left to decide, once the price has fallen to almost nothing, is not whether you can afford to train. It is whether you can say what behaviour you want, whether you can check that you got it, and whether, when the run ends, you own what you made.

That is the thesis of this review. Cheap training moves the difficulty to the definition and the check. Most fine-tuning that disappoints does so because the target was vague, the evaluation leaked, or the gap was one of fresh, discrete facts, which training handles badly (broader domain knowledge, such as a codebase's idioms or a specialised vocabulary, is another matter, and continued pretraining can teach it). Most that pays does so because the behaviour was narrow, the check was exact and the weights could be taken elsewhere. The rest of the page tests that claim against the literature, the market evidence and the builders' tools.

The argument in brief

  1. Fine-tuning changes behaviour more reliably than knowledge. Format, style, tool use and policy are learned; facts the model lacks are learned slowly and can raise hallucination.
  2. The check sets the ceiling. You can only tune towards what you can reliably measure, and the stronger the optimiser, the more a weak check is exploited.
  3. The price collapsed; the evaluation did not. Small-model LoRA runs cost cents to dollars, while building data, held-out tests and a release gate is still most of the work.
  4. Every change costs something. LoRA learns less and forgets less than full fine-tuning, but it still forgets, and narrow training can shift behaviour broadly.
  5. Reinforcement learning pays where an exact checker exists. Least certain: whether it teaches new ability or only sharpens what the base model could already do.
  6. Own the weights. Closed tuning is retreating, and portability varies sharply between managed services.

How to read this review

Three paths. Leaders, 5 minutes: this opening, the findings and the closing essays. Builders, 45 minutes: Decide, Foundations, the one method chapter you need, and Operate. Researchers: the whole Understand half, with the closed panels and references.

Two halves. Understand covers the theory, the literature and the market evidence. Build shows how to run each method, with current libraries, code, gates and costs. Each Build chapter mirrors an Understand chapter.

Evidence labels. Numbers are as reported by their authors. A company's figures about its own systems are marked lab-reported or vendor-reported and are unaudited. Results on different benchmarks are not comparable. Prices and product statuses are dated November 2026. Our own judgements are marked Our view.

Half one

Understand

Theory, literature and market evidence.

Part I — Foundations

What counts as fine-tuning

Think of a pretrained model as someone who already knows how to read and write. A prompt gives instructions for today's job; retrieval puts today's reference material in front of them. Fine-tuning changes the model's learned patterns through training. Prompting and retrieval leave its weights unchanged, but they belong on the same decision ladder because they are cheaper alternatives to test first. The eight steps differ in how deeply they change the system.

The customisation ladderEight ways to customise a model, read from the bottom up, lightest first: prompting, retrieval, supervised fine-tuning, preference tuning, reinforcement learning with verifiable rewards, distillation, continued pretraining and pretraining. Prompting and retrieval leave the weights frozen. Each rung lists what it changes and a qualitative effort cue; the bar lengths show order only, not measured cost. Supervised fine-tuning, preference tuning and reinforcement learning with verifiable rewards are highlighted as the behaviour-tuning rungs.RungWhat it changesEffort cue (qualitative order, not measured)Pretrainingweights learned from scratchEverything the model knowsand can do.Frontier-lab scaleContinued pretrainingweights changeDomain knowledge, via morenext-token training on text.Large domain corpusDistillationweights changeA smaller model copies alarger teacher's outputs.Teacher outputs and a runRL with verifiable rewardsweights changeBehaviour that a checker canscore: tests, exact answers.Verifier and many rolloutsPreference tuningweights changeWhich of two answers themodel leans towards.Ranked answer pairsSupervised fine-tuningweights changeFormat, style and taskbehaviour, from examples.Labelled examples, one runRetrievalweights frozenWhat the model can seewhen it answers.Index and pipelinePromptingweights frozenThe instructions andexamples in the request.A text editrungs that tune behaviour with training data, the subject of this pageclimb only as far as the gap needs

Three rungs tune behaviour with training data, and they are the subject of this page. Supervised fine-tuning shows the model examples of the output you want. Preference tuning shows it pairs of answers and says which is better. Reinforcement learning with verifiable rewards lets it try, scores each attempt with a checker such as a test suite or an exact-answer match, and reinforces what passes. The rungs above them, distillation and continued pretraining, change the model more deeply and cost more; the rung at the very top is pretraining itself, which is out of scope here.

The ladder's lesson is to climb only as far as the gap needs. Most failures people reach for fine-tuning to fix are fixed lower down, and the first question is what kind of gap you have.

The cheapest rungs deserve a fair trial. Prompting with a strong set of examples, and with many examples in a long context, is a serious baseline, and it needs no training pipeline. Its cost grows with the length of every request, while fine-tuning pays once up front and then answers with a short prompt. That trade is why fine-tuning wins at volume and loses on a one-off task. A claim that a small tuned model beats a large one means little unless the large model was given an equally careful prompt.

What fine-tuning changes and what it does not addTwo panels. Left: fine-tuning reliably changes behaviour: format, style, tone, tool use, policy and refusal behaviour. Right: it struggles to add new facts. Gekhman et al. 2024 found that examples with facts the model does not already know are learned slowly and raise hallucination; training on only such examples scored 25.8 at convergence against 37.5 with early stopping. Retrieval is the route for knowledge: in one study retrieval scored 0.875 against 0.504 for fine-tuning on current events.Reliably changes: behaviourThe model already can; training makes it do so by default.FormatJSON, schema, report layoutStylehouse voice, length, registerTonehow it addresses the readerTool usewhen and how to call a toolPolicywhat to do in your casesRefusal behaviourwhat it declines, and howStruggles to add: new factsFacts the model does not already know are learnedslowly, and once fitted they raise hallucination.Test accuracy, training only on unknown factsEarly stopping37.5At convergence25.8Gekhman et al. 2024, PaLM 2-S, closed-book QA.One model family and one task; treat as direction,not a law.so route knowledge hereRetrieval: the route for knowledgeCurrent events,Mistral-7B, Ovadia 2024Retrieval0.875Fine-tuned0.504

Fine-tuning reliably changes how a model behaves: the format it answers in, the voice it uses, when it calls a tool, what it does in your edge cases, and what it refuses. It is much weaker at adding facts. Gekhman and colleagues fine-tuned PaLM 2-S on closed-book questions and found that examples containing facts the model did not already know were learned slowly, and that once fitted they raised hallucination roughly linearly. Fine-tuned on only such examples, test accuracy fell from 37.5 with early stopping to 25.8 at convergence (lab-reported; one model family and one task). On current events, Ovadia and colleagues found retrieval scored 0.875 against 0.504 for fine-tuning on Mistral 7B, where the fine-tuning used raw text and paraphrases lifted it only to 0.588.

Illustrative. Suppose an accounts team wants a model to read supplier invoices and return a fixed JSON record. The shortfall is behaviour: the base model reads invoices well but formats the output differently each time. That is a fine-tuning gap. If the team also wants it to know this year's supplier contract terms, that is a knowledge gap, and retrieval is the better route. Our view: "retrieval for knowledge, fine-tuning for behaviour" is a good first cut, but not a law. Continued pretraining on synthetic text can add facts (chapter U6), and fine-tuning can teach a model to use retrieved text better; neither is the same as storing facts in a few thousand supervised examples.

Six eras, and what ended each

The history is usually told as a timeline. It is more useful as a chain of causes: each era ended at a cost or a limit that the next found a way round.

Six eras of fine-tuningA timeline in two rows of three bands, read left to right. 2018 to 2020, transfer learning: ULMFiT, BERT. 2021 to 2022, multitask instruction tuning: FLAN, T0. 2022, RLHF: InstructGPT. 2021 to 2023, parameter-efficient fine-tuning democratised: LoRA, QLoRA, Alpaca. 2023 to 2025, preference and reinforcement learning post-training: DPO, GRPO and verifiable rewards. 2025 to 2026, serverless training utilities such as Tinker and Snowflake Cortex Training, highlighted.2018–2020Transfer learningPretrain once, thenadapt to each task.ULMFiT 2018BERT 2018Don't Stop Pretraining 20202021–2022Multitaskinstruction tuningTrain on many tasks writtenas instructions.FLAN 2021T0 2021Flan-PaLM 20222022RLHFHuman preferences shape themodel; small beat large.InstructGPT 2022Self-Instruct 20222021–2023PEFT democratisedTrain a small adapter, notevery weight.LoRA 2021QLoRA 2023Alpaca 2023LIMA 20232023–2025Preference and RLpost-trainingPairs and checkable rewardsreplace human labelling.DPO 2023GRPO 2024Tulu 3 2024DeepSeek-R1 20252025–2026Serverless trainingutilitiesTraining as an API call;no cluster to run.LoRA Without Regret 2025Tinker 2025Snowflake Cortex Training 2026Years from the research reviews; eras overlap, so the order is by when each became standard practice.

Transfer learning (2018–2020). Pretrain once on text, then adapt to each task. ULMFiT and BERT made this the standard template. The cost was one tuned copy of the model per task.

Multitask instruction tuning (2021–2022). FLAN and T0 trained one model on many tasks written as instructions, so that it could handle tasks it had not seen. Flan-PaLM's instruction tuning used about 0.2% of the compute of pretraining. The limit was the data: academic task mixtures did not look like what users ask for.

RLHF (2022). InstructGPT trained on about 13,000 human-written demonstrations, then on human rankings, and a 1.3B model was preferred to the 175B GPT-3. Human labelling was the bottleneck, and the pipeline of reward model plus reinforcement learning was heavy to run.

PEFT democratised (2021–2023). LoRA trains a small add-on instead of every weight; on GPT-3 175B it cut trainable parameters about 10,000-fold and the checkpoint from 350 GB to 35 MB. QLoRA put a 65B model on one 48 GB GPU. Alpaca, with data that cost under $500 to generate, and LIMA, with 1,000 curated examples, showed that capable chat models could be made cheaply, and also how easily a cheap model looks better to raters than it is.

Preference and RL post-training (2023–2025). DPO replaced the reward-model loop with a single supervised-style loss. GRPO dropped the value model, and DeepSeek-R1 showed that rule-based rewards on checkable problems could drive large reasoning gains. Tulu 3 published a full open recipe. The limit moved from labels to checkers: RL needs a task and a trustworthy scorer.

Serverless training utilities (2025–2026). Thinking Machines' LoRA Without Regret argued that LoRA suffices for most post-training, and Tinker exposed training as an API. Managed services followed, from Fireworks and Together to Snowflake. The closed-model route went the other way, as the opening described. This era has not ended, and its weakness is portability: whether you can take the result away.

Read as a chain, the history has one moral: every era made training cheaper and exposed the next constraint. Per-task copies led to instruction tuning; labelling cost led to cheap imitation data; full-weight cost led to adapters; reward-model cost led to DPO and verifiable rewards. Today training is no longer the constraint, and the constraint is knowing whether it worked.

The theory: what fine-tuning can teach

Three questions run through the literature, and each has a live argument behind it: how much of the change is style, whether training can add knowledge, and what it costs the model elsewhere.

The superficial alignment hypothesis says that a model learns nearly everything in pretraining, and that fine-tuning only teaches it which format to use. LIMA gave it its name: 1,000 curated examples on a 65B model produced responses judged equal or better than GPT-4's in 43% of comparisons, on a human study of a few hundred prompts. Lin and colleagues found that base and aligned models decode almost identically at most positions, with the differences concentrated in stylistic tokens, and that three stylistic examples in the prompt could align a base model. Against this, Raghavendra and colleagues measured task performance rising as a power law in the number of fine-tuning examples on maths, code and multi-step questions, and called the hypothesis "at best an over-simplification". Production recipes agree with them: Tulu 3 used 939,344 examples for supervised tuning. Our view: the hypothesis holds for what a rater sees and fails for what a benchmark checks. Style is cheap to teach, and capability is not.

The second question, new knowledge against behaviour, is where the Gekhman result applies. Fine-tuning mostly teaches a model to use what it already knows, and unfamiliar facts are the part it resists. Relabelling the unknown examples as "I don't know" removed most of the damage in their study. Allen-Zhu and Li found, in a controlled setting with small models, that facts which appeared only once in pretraining could be memorised and still give 0% extraction accuracy after instruction tuning, unless the pretraining data had been paraphrased. How a fact is presented matters as much as whether it appears.

The third is forgetting, the price of every change.

What changes inside the modelLeft: full fine-tuning updates every weight in the weight matrix W. Right: LoRA freezes W and adds a low-rank update, the product of a tall thin matrix B and a wide thin matrix A, so only the small matrices are trained. Below, the price of either route is forgetting: some of the base model's general ability is lost. LoRA tends to learn less and forget less than full fine-tuning. Shapes are a concept sketch, not to scale.Full fine-tuningEvery weight can move.Wall weights updateda full copy to store per taskLoRAWeights frozen; a small update added.WW frozen+BA×only B and A are traineda small adapter (low rank r)The price: forgettingWhatever the update moves, some of the base model's general ability moves with it. Full fine-tuninglearns more and forgets more; LoRA learns less and forgets less, but still forgets.Biderman et al. 2024; Kalajdzievski 2024. Shapes are a concept sketch, not to scale.

Full fine-tuning can move every weight; LoRA freezes the original matrix W and learns a small low-rank update. Biderman and colleagues compared them on Llama-2-7B and titled the result LoRA Learns Less and Forgets Less. On code continued pretraining at 20 billion tokens, full fine-tuning reached 0.263 on HumanEval against 0.224 for the best LoRA, while on instruction data its forgetting score was 0.414 against LoRA's 0.509 (higher is better; one base model, two domains). On maths, LoRA at rank 256 forgot about as much as full fine-tuning. Kalajdzievski found that LoRA's forgetting still follows a power law in the number of steps and is not avoided by stopping early. The standard remedies, re-warming the learning rate and replaying a share of the original data, have been measured at pretraining scale, where replay of 5% to 25%, with the learning rate re-warmed and re-decayed, matched full retraining. We found no measured replay rule for small supervised runs, so treat any quoted percentage for them as a starting point to test, not a result.

Forgetting is not only capability. Qi and colleagues showed that ten adversarial examples broke the guardrails of GPT-3.5 Turbo for under $0.20, and that benign data also eroded safety, less severely. Betley and colleagues found that training on insecure code shifted behaviour on unrelated prompts, an effect called emergent misalignment, whose mechanism is still open. A narrow data set can change a broad disposition. Our view: this makes every release a two-sided test. You check that the new behaviour appeared, and that the old behaviour and the safety properties did not leave.

A framework for the whole review

Five concepts explain most of what follows, and each returns in the Build half as a gate.

Five concepts for fine-tuning that holds upFive concept cards around a centre label, "Fine-tuning that holds up". Behaviour gap: is the shortfall in how the model acts rather than what it knows. Data quality: a few clean, varied examples beat many sloppy ones. Check quality, highlighted: you can only tune towards what you can reliably measure. Forgetting budget: every change costs some general ability. Ownership: someone owns the data, the checks and the model after it ships.Fine-tuningthat holds upBehaviour gapIs the shortfall in how the modelacts, not in what it knows?Data qualityA few clean, varied examplesbeat many sloppy ones.Check qualityYou can only tune towards whatyou can reliably measure.Forgetting budgetEvery change costs some generalability; decide what you can lose.OwnershipSomeone owns the data, the checksand the model after it ships.

The behaviour gap asks whether the shortfall is in how the model acts and not in what it knows; it decides whether to fine-tune at all. Data quality is the part of the LIMA and Tulu 3 argument that survives both camps: whatever the volume, clean and varied examples beat sloppy ones. Check quality is the idea we put at the centre. You can only tune towards what you can reliably measure, and a check the training can reach, or that the data leaked into, will report a gain that is not there. The forgetting budget is the decision, made before training, about which general abilities you can afford to lose and how you will test that you kept them. Ownership asks who maintains the data, the checks and the model after it ships, and whether the weights can leave the vendor that trained them.

The first three predict whether a fine-tune works; the last two predict whether it survives. The chapters that follow are organised by method, but each is judged against these five.

The loop

Every method in this review runs inside the same loop.

The fine-tuning loopSix steps in a loop: data, train, evaluate, gate, serve and monitor, with monitoring feeding failures back into data. Evaluate and gate are drawn with a dashed accent outline because they are protected: training must not be able to change its own checks or the release gate.only a passto servefailures and new casesbecome new datafail: back to data or train1Datacurated, deduplicated2Trainadapter or full weights3Evaluateheld-out checks4Gatebetter, no regressions?5Servethe tuned model goes live6Monitorlive quality, drift, costprotected: the training step cannot edit its own evaluation or the release gate

Data is curated and deduplicated, and the held-out set is separated before anything is trained. Train changes the weights, as a full run or an adapter. Evaluate scores the result on held-out checks, including the old abilities you want to keep. The gate promotes the model only if it is better and nothing has regressed. Serve puts the tuned model live, and monitor watches quality, drift and cost, feeding failures and new cases back into the data.

Two steps are drawn with a dashed outline because they are protected. Fresh test sets show how much leakage can hide: on a newly written matched set of grade-school maths problems, some models fell by up to 8% from their published scores, which suggests contamination of the old set or adaptive overfitting to it, or both. Evaluation and the gate must be out of the training step's reach: the data must not leak into the held-out set, and no optimisation loop should be able to edit its own scorer. This is a fine-tuning loop, not an agent: no model chooses its own next action, and people decide what enters the data and what passes the gate. The same shape returns in Part V as a reference architecture, in each Build chapter as a flow, and in Part VII as the operating cycle.

Part II — The literature, as six methods

The literature on fine-tuning runs to thousands of papers, but it sorts into six methods, each defined by what it trains on and what it changes: labelled examples, a small adapter instead of the whole model, judgements between answers, a reward from a checker, a larger model's outputs, and raw text from a new domain. Each chapter makes one claim about its method, works through an example, sets out the evidence, names the live disagreement and gives our verdict. The papers sit in a closed panel at the end of each chapter, and each chapter mirrors a Build chapter that shows how to do it.

U1. Supervised fine-tuning and instruction data

Supervised fine-tuning learns from examples of the answer you want. For invoice extraction, each example pairs a document or request with a checked structured answer. If the example is wrong, the training signal is wrong too.

Mirrors B1 · Supervised fine-tuning in the Build half.

Supervised fine-tuning, or SFT, is the step that turns a text-completing base model into one that follows instructions: the model is shown prompts paired with the answers you want and is trained to produce those answers. Our claim is that the examples decide what SFT teaches, and how many you need depends on what you are teaching. A thousand well-chosen examples can change style and format; capability needs far more, and every successful set, large or small, was selected rather than collected.

Curation matters at every scaleTwo panels. LIMA used 1,000 hand-picked examples on a 65B model and its answers were judged equal or better than GPT-4 in 43 percent of comparisons, Bard 58 percent and DaVinci003 65 percent. Llama 2 used 27,540 of its own vendor annotations instead of millions of third-party examples, and Tulu 3 used 939,344 prompts chosen from 23.3 million candidates, about 4 percent. A log-scale strip shows the three selected sets spanning roughly a thousandfold in size.Small and hand-builtLIMA: 65B LLaMA, no reinforcement learning1,000curated examples750 forum posts + 250 hand-writtenabout 750,000 tokens, 15 epochsAnswers judged equal or better than:LIMA answers equal or better than GPT-4: 43%GPT-443%LIMA answers equal or better than Bard: 58%Bard58%LIMA answers equal or better than DaVinci003: 65%DaVinci00365%A human preference result, not a benchmark score.Share of side-by-side comparisons.Large and selectedLlama 2 and Tulu 3Llama 2, supervised stage27,540own vendor annotations,millions of third-party examples set asideTulu 3, supervised stage939,344prompts kept from23.3M candidatesBar = all 23.3M candidates; the filled part is the 4.0% kept.Another 425,145 prompts went into preference tuning.Selection at scale is still selection.Size of the selected training setlog scale, examples1,00010,000100,0001,000,000LIMA: 1,000 examplesLIMA 1,000Llama 2: 27,540 examplesLlama 2 27,540Tulu 3: 939,344 examplesTulu 3 939,344The sets differ by about 1,000 times in size. The need to choose what goes in does not.
Sources: LIMA (Zhou et al., 2023); Llama 2 (Touvron et al., 2023); Tulu 3 (Lambert et al., 2024).

The figure shows the two ends of the range. LIMA fine-tuned a 65B LLaMA on 1,000 curated pairs (750 from community forums, 250 written by hand, about 750,000 tokens, 15 epochs, no reinforcement learning). Its answers were judged equal to or better than GPT-4's in 43% of comparisons, Bard's in 58% and DaVinci003's in 65%. On the other side, Llama 2 set aside millions of third-party examples and used 27,540 annotations from its own vendors, and Tulu 3 kept 939,344 prompts out of 23.3 million candidates, about 4%. The sets differ by roughly a thousand times in size. All three were chosen with care.

The history of the method is a search for cheaper demonstrations. First, FLAN and T0 rephrased existing academic tasks as instructions, and a model trained on them did better on tasks it had never seen. Then InstructGPT showed that chat-style demonstrations written by paid labellers worked better for real users: its SFT set was only about 13,000 prompts, and a 1.3B model tuned this way was preferred to the 175B GPT-3. Human demonstrations are slow to write, so Self-Instruct and Stanford's Alpaca had a model write them: 52,000 examples for under $500 of API calls and under $100 of training on eight A100 GPUs. LIMA then asked how little curated data was enough. Llama 2 and Tulu 3 answered for production: more than LIMA, but chosen.

Worked example (illustrative). A finance team wants a model to turn supplier emails into a fixed invoice record. It has 40,000 past emails with the final records attached. A first set takes all of them. The tuned model learns the record layout quickly, but also copies the clerks' habits: it fills in a missing tax number with a plausible one, because many past records did. A second set keeps 2,000 emails, chosen so that each supplier type, currency and missing-field case appears, with the guessed values removed. The layout is learned just as well and the invented tax numbers stop. The team did not teach the model anything about invoices. It stopped teaching it the clerks' shortcuts.

The evidence on what instruction tuning delivers is consistent on one point and divided on another.

Reported gains from instruction tuning, by data sourceHorizontal bars of reported gains in points. Flan-PaLM over PaLM, normalised average: plus 15.5 at 8B, plus 10.4 at 62B, plus 9.4 at 540B. Flan-T5 over prior open instruction sets: plus 3 to plus 17. Self-Instruct over vanilla GPT-3 on Super-NaturalInstructions: plus 33 absolute. The first four use human-written academic tasks; the last uses data written by the model itself. Each row is on its own benchmark.human-written task collectionsdata the model wrote itself05101520253035gain, pointsFlan-PaLM 8B: +15.5 (academic task mix, vs PaLM 8B)Flan-PaLM 8Bacademic task mix, vs PaLM 8B+15.5Flan-PaLM 62B: +10.4 (academic task mix, vs PaLM 62B)Flan-PaLM 62Bacademic task mix, vs PaLM 62B+10.4Flan-PaLM 540B: +9.4 (academic task mix, vs PaLM 540B)Flan-PaLM 540Bacademic task mix, vs PaLM 540B+9.4Flan-T5 (Flan Collection): +3 to +17 (vs prior open instruction sets)Flan-T5 (Flan Collection)vs prior open instruction sets+3 to +17Self-Instruct: +33 (GPT-3 + 52,445 self-written, on Super-NI)Self-InstructGPT-3 + 52,445 self-written, on Super-NI+33Each row is on its own benchmark and unit (Flan-PaLM: normalised average; Self-Instruct: Super-NI; Flan-T5: evaluation settings).Read the size of each gain, not a ranking. Flan-T5 is a range across settings, drawn from 3 to 17.Sources: Chung et al. 2022; Longpre et al. 2023; Wang et al. 2022 (Self-Instruct).

On the consistent point: instruction tuning is cheap next to pre-training and gives real gains. Flan-PaLM cost 0.2% of PaLM's pre-training compute and added a normalised 15.5, 10.4 and 9.4 points at 8B, 62B and 540B. The gain shrinks as the model grows. Self-Instruct's bootstrapped data lifted vanilla GPT-3 by 33 points on Super-NaturalInstructions, though it stayed 5 points behind InstructGPT-001 on expert-written novel tasks. Each row is on its own benchmark, so the chart compares sizes of reported gains, not methods.

The divided point is what the gain consists of. The Alpaca authors' blind comparison against text-davinci-003 came out 90 to 89, but the judges were the five student authors, and the blog itself says the model hallucinates more. The False Promise of Imitating Proprietary LLMs found that crowd raters thought imitation models matched ChatGPT while benchmark scores showed little gain on anything the imitation data did not cover. AlpaGasus filtered Alpaca's 52,000 examples to 9,229 that ChatGPT scored 4.5 or higher; a 7B model trained on the subset took 14 minutes instead of 80 and was preferred by a GPT-4 judge. The filter and the judge are both models, so the result partly measures their shared taste. Gekhman and colleagues added the sharpest warning: examples whose facts the model did not already know were fitted slowly and, once fitted, raised hallucination roughly linearly. SFT mostly teaches a model to use what it has.

One claim must be corrected. It is often said that "quality beats quantity" and that Tulu showed this. As stated, that is wrong: Tulu 3's supervised stage is nearly a million examples, plus 425,145 for preference tuning. LIMA's result is a preference result on about three hundred prompts, and its authors used 2,000 examples, not 1,000, for their 7B ablations because 1,000 was less stable. No paper sets a minimum number of examples, and a rule of "500 to 1,000" has no source.

The fault line. Is alignment superficial? On one side, LIMA, the URIAL study (base and aligned models decode almost identically except at stylistic tokens, and three in-context examples are enough to align a base model) and Gekhman say SFT unlocks existing ability. On the other, Raghavendra and colleagues find task performance rising as a power law in the number of examples for maths, code and multi-hop questions, and Tulu 3 and Llama 2 spend tens to hundreds of thousands. Both can be right: style saturates early and capability does not. What would settle it is a fixed-model scaling study scored on objective benchmarks, not preference, that separates style tokens from skills absent from pre-training. Until then, treat every small-data result judged by people or models as a statement about style. For a builder this means deciding in advance whether the target is a format the model can already produce or a skill it lacks, and sizing the set, and the check, to match. Lab 02 (data curation and leakage) and Lab 03 (full-parameter SFT) work through that choice.

Our assessment

SFT is the cheap, dependable step, and its inputs matter more than its method. Curate hard, check the result against something other than a model's opinion, and do not infer a data-size rule from LIMA. If you want the model to know new facts, SFT is the wrong tool. Confidence: high on the role of curation, medium on how much data capability needs.

U2. Parameter-efficient fine-tuning

Training every weight is not the only option. An adapter adds a relatively small set of trainable parameters to a frozen base, allowing different behaviours to share the same base model. It saves training resources; it does not guarantee equal accuracy.

Mirrors B2 · LoRA and QLoRA in the Build half.

Parameter-efficient fine-tuning, or PEFT, trains a small number of added parameters and leaves the base model frozen. Our claim is that LoRA won by being cheap to train, small to store and free to serve, not by being better than full fine-tuning. It matches full fine-tuning when the data fits its capacity and trails it when it does not, and the many variants built on it have not shown a lead over a well-tuned plain version.

How LoRA and QLoRA workLeft: LoRA keeps the pretrained weight matrix W frozen and learns a low-rank update B times A, with A of size r by d and B of size d by r. The output is W x plus B A x, and only A and B are trained. For GPT-3 175B at rank 4 on the query and value matrices this cut trainable parameters 10,000 times, GPU memory from 1.2 TB to 350 GB and the checkpoint from 350 GB to 35 MB. Right: QLoRA stores W in 4-bit NormalFloat and keeps the adapters in 16-bit; on Pile-CC perplexity NF4 with double quantisation scored 27.41 against 34.34 for Int4.LoRAFreeze W, learn a small low-rank changeQLoRAThe same adapters over a 4-bit basexWfrozend × dAr × dBd × r+hfrozen: no gradienttrained: A and B onlyxW4-bit NF4frozen, d × dAr × dBd × r+hfrozen, stored smalltrained, kept in 16-bith = W x + B A xr is much smaller than d, so A and B are tiny next to W.GPT-3 175B, r = 4 on query and value matricesTrainable parameters10,000× fewerGPU memory1.2 TB → 350 GBCheckpoint on disk350 GB → 35 MBAfter training B·A can be added into W, so serving adds no latency.Same h = W x + B A xOnly the storage of W changes. Perplexity, lower is better:Int4: Pile-CC perplexity 34.34Int434.34FP4 (E2M1): Pile-CC perplexity 31.07FP4 (E2M1)31.07FP4 (E3M0): Pile-CC perplexity 29.48FP4 (E3M0)29.48NF4 + double quant.: Pile-CC perplexity 27.41NF4 + double quant.27.41Double quantisation saves about 0.37 bits perparameter (~3 GB at 65B). Result: a 65B modelfine-tuned on one 48 GB GPU.
d and r are symbolic. Sources: LoRA (Hu et al., 2021); QLoRA (Dettmers et al., 2023).

The idea in the left panel is short. A layer computes h = Wx. LoRA, from Hu and colleagues at Microsoft, freezes W and learns a correction BA, where A and B share a small inner size r, the rank. Only A and B are trained, and after training BA can be added into W, so the served model is the same size and speed as the original. QLoRA, on the right, changes only how W is stored: in 4-bit NormalFloat, with the adapters kept in 16-bit. The paper's own comparison on Pile-CC perplexity put NF4 with double quantisation at 27.41 against 34.34 for plain 4-bit integers.

The method displaced its predecessors by removing their costs. Houlsby adapters (2019) added about 3.6% parameters per task but sat in series with the model, adding latency. Prefix tuning and prompt tuning trained about 0.1% of parameters but spent context, and prompt tuning only caught full tuning at multi-billion-parameter scale. LoRA offered a similar parameter budget with nothing added at inference.

Worked example (illustrative). A legal-operations team tunes an 8B model on 5,000 contract clauses labelled with their risk category. Their first run puts rank-8 adapters on the attention matrices only, at the learning rate they used for full tuning. Training loss barely moves, and they conclude that LoRA does not work. A second run adapts every linear layer, raises the rank to 32 and uses a learning rate about ten times higher. It trains normally and lands within noise of a full fine-tune on their held-out set. The method was fine. The first recipe was a leftover from 2021.

GPU memory to fine-tune, by methodHorizontal bars in gigabytes, grouped by model. GPT-3 175B: full fine-tuning with Adam needs 1.2 TB, LoRA at rank 4 needs 350 GB. LLaMA 65B: 16-bit full fine-tuning needs more than 780 GB, QLoRA fits on one 48 GB GPU. A 70B model: weights alone are 140 GB at 16-bit and about 35 GB at 4-bit, and FSDP with QLoRA trains it on two 24 GB GPUs.16-bit, full fine-tuningLoRA or 4-bit base0 GB300 GB600 GB900 GB1200 GBGPT-3 175BLoRA paperGPT-3 175B, Full fine-tuning, Adam: 1.2 TBFull fine-tuning, Adam1.2 TBGPT-3 175B, LoRA, rank 4: 350 GBLoRA, rank 4350 GBLLaMA 65BQLoRA paperLLaMA 65B, 16-bit full fine-tuning: more than 780 GB16-bit full fine-tuningmore than 780 GBLLaMA 65B, QLoRA: fits one 48 GB GPUQLoRAfits one 48 GB GPU70B modelAnswer.AI70B model, Weights alone, 16-bit: 140 GBWeights alone, 16-bit140 GB70B model, Weights alone, 4-bit: about 35 GBWeights alone, 4-bitabout 35 GB70B model, FSDP + QLoRA, whole job: two 24 GB GPUsFSDP + QLoRA, whole jobtwo 24 GB GPUsDifferent models and setups: compare within a group, not across. The QLoRA and FSDP bars show the GPU memory they fit in.Sources: Hu et al. 2021 (LoRA); Dettmers et al. 2023 (QLoRA); Answer.AI and Hugging Face, March 2024 (FSDP+QLoRA).

The memory chart is where the cost argument becomes concrete. In the LoRA paper's GPT-3 175B test, training memory fell from 1.2 TB to 350 GB, trainable parameters fell 10,000 times and the checkpoint from 350 GB to 35 MB. QLoRA put a 65B model on a single 48 GB GPU, against more than 780 GB for 16-bit full fine-tuning, and fine-tuned a 33B model in under 12 hours on one 24 GB card. Answer.AI and Hugging Face then sharded a 4-bit 70B base across two 24 GB GPUs. One correction: a common claim attributes "a 70B model on one 80 GB GPU" to the QLoRA paper. The paper reports 65B on 48 GB. The 70B figure is a separate and tool-dependent claim.

Quality is the part with conditions. Biderman and colleagues compared the two methods on Llama-2-7B for code and maths. In continued pretraining on 20B code tokens, full fine-tuning reached 0.263 on HumanEval and the best LoRA (rank 256) 0.224. In instruction tuning on code, LoRA at rank 256 matched full fine-tuning (0.498 against 0.497) but at rank 16 scored 0.358. LoRA also forgot less of the base model: a source-domain benchmark average of 0.617 against 0.545 for full tuning after code pretraining (higher means less forgotten), and 0.509 (rank 64) against 0.414 after code instruction. Hence the title, "LoRA Learns Less and Forgets Less". The best LoRA learning rates were also about ten times higher than full tuning's (5e-4 against 5e-5 on code). Shuttleworth and colleagues traced part of the difference to "intruder dimensions" that LoRA adds and that accumulate across sequential tasks. Thinking Machines reached a more favourable reading in a blog post: on small and medium instruction and reasoning sets, LoRA matched full fine-tuning; the best LoRA learning rate was about ten times the full-tuning rate and moved by less than two times between ranks 4 and 512; adapting all layers beat attention-only; and in reinforcement learning rank 1 was enough. That company sells a LoRA-only training service, which is worth knowing when weighing its conclusion.

The variants have thinner support. DoRA reports commonsense averages rising from 74.7 to 78.4 on LLaMA-7B; PiSSA reports 72.86 against 67.7 for LoRA on GSM8K with Mistral-7B; LoRA+ and rsLoRA adjust learning rates and scaling. All are author-run on their own protocols. PiSSA's own appendix shows that switching full fine-tuning between bf16 and fp32 moves GSM8K by seven points, as large as the claimed gain. DoRA adds training overhead. We found no independent comparison with equal tuning budgets.

Serving is where the design pays again. Punica and S-LoRA run many adapters over one base copy; S-LoRA reports up to 2,000 adapters on one GPU and up to 4 times the throughput of Hugging Face PEFT and vLLM's naive LoRA support, per the authors (2023 baselines). vLLM and SGLang now select an adapter per request. Adapters can also be merged: TIES and DARE combine fine-tuned deltas, though the evidence of merged quality is mostly leaderboard-level and LoraHub did not beat in-context learning on Big-Bench Hard.

The fault line. Does LoRA match full fine-tuning? Thinking Machines says yes while data fits capacity and layers are covered; Biderman says it substantially underperforms on code and maths at typical ranks, especially in continued pretraining. The two agree that capacity binds as data grows, and differ on where the limit sits. The test is a matched sweep on identical data at several dataset-to-capacity ratios, at sizes beyond 7B, with learning rate and alpha tuned per method. Whether lower forgetting is a virtue or lost plasticity is a second open question, since intruder dimensions suggest forgetting can concentrate rather than disappear. Labs 04 to 06 (LoRA, QLoRA, and a rank and learning-rate ablation) let you run the comparison on your own data.

Our assessment

Use LoRA, with every linear layer and a learning rate well above the full-tuning one, as the default for instruction-scale tuning. Move to higher rank or full tuning when the task is to absorb a lot of new material. Treat variants as options to try once the plain recipe is tuned, not as upgrades. Confidence: high on cost and serving, medium on quality parity.

U3. Preference optimisation

Sometimes two answers are both valid, but one is better for the job. Preference data records which answer is preferred and under what criteria, rather than treating every answer as a single gold target.

Mirrors B3 · Preference tuning in the Build half.

Supervised fine-tuning needs someone to write the right answer. Preference tuning needs only someone to say which of two answers is better, which is a far easier thing to judge than to produce. That is the reason it exists, and it is also its weakness: the model learns whatever the judge prefers. Our claim is that the machinery of preference tuning has become cheap and simple, so the quality of the preference data and of the judge now decides the result, and the headline gaps between the newer methods mostly reflect what an LLM judge rewards, including length.

Three preference-tuning pipelines: RLHF, DPO and KTORLHF needs ranked comparisons and runs three stages: a supervised model, a reward model trained on the rankings, and PPO with a KL penalty. DPO needs chosen and rejected pairs and removes the reward model and the sampling loop, training with one direct loss. KTO needs only single answers labelled good or bad and removes the reward model, the sampling and the pairing.What data it needsSteps it runs (dashed = removed)RLHF: needs ranked comparisons. The full pipeline; nothing removed.RLHFRanked comparisonsanswers to one prompt, rankedSFT modelsupervised starting pointReward modellearns the rankingsPPO with a KL penaltysample, score, update;KL keeps it closeThe full pipeline; nothing removedDPO: needs chosen / rejected pairs. Removes the reward model and sampling.DPOChosen / rejected pairsthe same pair data RLHF ranksSFT modelalso serves as the referenceReward modelremovedDirect loss on pairsclassification-style loss;no samplingRemoves the reward model and samplingKTO: needs thumbs up / thumbs down. Removes the reward model, sampling and the pairing.KTOThumbs up / thumbs downsingle answers, labelled; no pairsStarting modelsupervised starting pointReward modelremovedLoss on the labelsprospect-theory loss;labels onlyRemoves the reward model, samplingand the pairingSources: Ouyang et al. 2022 (InstructGPT), Rafailov et al. 2023 (DPO), Ethayarajh et al. 2024 (KTO).

The figure sets three pipelines side by side. RLHF, the original recipe, starts from a supervised model, trains a separate reward model on ranked comparisons, then runs PPO against that reward model with a KL penalty that keeps the policy close to its starting point. Each of those parts costs something. The reward model must be trained and trusted; PPO needs the policy, a reference copy, a value model and the reward model in play at once, and the Secrets of RLHF authors conclude that stable PPO training "remains unsolved". DPO showed that the same objective can be solved in closed form with a classification-style loss on chosen and rejected pairs, so the reward model and the sampling loop disappear. KTO goes one step further and drops the pairing: it needs only single answers marked good or bad, which is what a thumbs-up button already records. ORPO folds the preference penalty into the SFT stage, and SimPO uses length-normalised log-probability as its reward; both remove the reference model. IPO keeps pairs but removes DPO's assumption that preferences follow a Bradley–Terry model of pointwise rewards.

The consequence is practical. Managed platforms adopted DPO early because it is a supervised job they already knew how to schedule, and open recipes followed: the Tülu 3 stack runs SFT, then length-normalised DPO, then verifiable-reward RL, and does not use PPO in its final models. For a team, the question is no longer how to run an RLHF cluster. It is where the pairs come from.

Worked example (illustrative). A support team has two thousand draft replies in which an agent's draft was either sent as written or edited by a person before sending. They treat the edited version as chosen and the original draft as rejected, and run DPO on a model already tuned on their house style. Their internal scorer, another LLM, shows a double-digit rise in win rate. A reviewer reading fifty replies notices why: the tuned model apologises twice, restates the question and adds a closing paragraph. The editors' changes were mostly corrections of facts and tone, but the pairs also contained a quiet habit: the longer reply was usually the one that had been kept. Re-scored with length held fixed, most of the gain disappears. The method worked. It learned the data's accident rather than its intent.

The literature has the same shape, with better numbers on one side. The strongest evidence for preference tuning at all is InstructGPT: the 175B model was preferred to GPT-3 in 85 ± 3% of labeller comparisons and to few-shot GPT-3 in 71 ± 4%, closed-domain hallucination fell from 41% to 21%, and a 1.3B InstructGPT was preferred over the 175B base model. The training added about 60 petaflops/s-days of PPO compute against 3,640 for pretraining GPT-3, with roughly 40 contractors producing the data. The same paper shows the costs: no improvement on bias benchmarks, and regressions on several public tasks that a pretraining-mix term only partly repaired.

Reported results of preference tuning and the length-bias caveatInstructGPT 175B was preferred over GPT-3 by 85 plus or minus 3 percent of labeller comparisons and over few-shot GPT-3 by 71 plus or minus 4 percent; closed-domain hallucination fell from 41 percent to 21 percent. SimPO reports up to 6.4 points on AlpacaEval 2 and 7.5 points on Arena-Hard over DPO, both scored by an LLM judge that tends to reward longer answers. Controlling for length changes DPO win rates by up to 20 percent.judged by human ratersjudged by an LLMbaseline!length-bias debate appliesHuman-rated: RLHF (InstructGPT)0255075100%Preferred over GPT-3 (175B), InstructGPT 175B, labeller preference: 85% ± 3Preferred over GPT-3 (175B)InstructGPT 175B, labeller preference85% ± 3Preferred over few-shot GPT-3, InstructGPT 175B, labeller preference: 71% ± 4Preferred over few-shot GPT-3InstructGPT 175B, labeller preference71% ± 4Closed-domain hallucination, GPT-3, lower is better: 41%Closed-domain hallucinationGPT-3, lower is better41%Closed-domain hallucination, InstructGPT, lower is better: 21%Closed-domain hallucinationInstructGPT, lower is better21%LLM-judged: direct methods (author-reported)0246810 ptsSimPO over DPO, AlpacaEval 2, best reported: up to +6.4 points, scored by an LLM judgeSimPO over DPOAlpacaEval 2, best reported+6.4 pts!SimPO over DPO, Arena-Hard, best reported: up to +7.5 points, scored by an LLM judgeSimPO over DPOArena-Hard, best reported+7.5 pts!!The length-bias debateLLM judges tend to reward longer answers, so a win rate can partly measure verbosity.Park et al. report up to 20% win-rate improvement for DPO once length is controlled; SimPO says itsgains come without substantially increasing length. Rankings among methods stay weakly established.Sources: Ouyang et al. 2022; Meng et al. 2024 (SimPO); Park et al. 2024. Separate studies, not one controlled comparison.

The two panels in the figure come from different studies and must not be read as one comparison. The top panel is human-rated. The lower panel is the author-reported LLM-judged gains of SimPO over DPO: up to 6.4 points on AlpacaEval 2 and 7.5 on Arena-Hard. These are real measurements, but LLM judges are known to reward verbose answers, and Park and colleagues found DPO exploits that, reporting up to a 20% win-rate improvement once length is controlled for. Other findings cut the same way. Chen and colleagues measured most preference-tuned models below 60% accuracy at ranking the very answers they were trained on. RewardBench found reward models over-refuse and reason weakly. And Gao and colleagues showed in a synthetic setting that pushing harder against a proxy reward eventually lowers the true score, so every preference method has a point where more optimisation hurts.

Human labels are the bottleneck, so the field has tried to replace them. Constitutional AI has a model critique and revise its answers under written principles; RLAIF versus RLHF found AI-labelled preferences comparable to human ones on summarisation and dialogue; online AI feedback keeps the data fresh by judging new samples from the current model. This works well for style and harmlessness. It changes the failure mode rather than removing it, because the model now inherits the judge's biases at the speed of a training loop.

The fault line. Does the direct family beat online reinforcement learning? On one side, DPO is simple and stable, and needs no sampling; Tülu 3 chose it over PPO. On the other, Xu and colleagues found a carefully tuned PPO ahead of the alternatives in every case they tested, RLOO found simple REINFORCE-style updates beating both PPO and DPO, and the online-feedback work shows that fresh on-policy samples matter: Tang and colleagues found the gap between online and offline methods persists across loss functions and is not explained by data coverage alone, pointing to on-policy sampling itself. Iterative DPO, which samples from the current model each round, sits between the two camps. Among the reference-free variants the picture is murkier still: SimPO, KTO and ORPO each report wins, mostly on LLM-judged benchmarks, and the KTO authors themselves find that no single loss wins everywhere. The experiment that would settle it is a boring one: one model, one preference set, one compute budget, offline and on-policy runs kept separate, and the result scored by length-controlled and human evaluation. It has not been done at scale.

Our assessment

Preference tuning is cheap now, and DPO or KTO is the sensible first try when you have pairs or thumbs. The method choice among the variants is the least important decision; the quality of the pairs, the length of the answers they favour and an evaluation that controls for length matter more. Treat any gain scored only by an LLM judge as provisional. Confidence: medium. The mechanism is well supported; the ranking of methods is not.

U4. Reinforcement learning with verifiable rewards

A reward is a measurement of an outcome, not a description of the answer. For example, a checked calculation can be rewarded for returning the correct total. The reward must represent the real goal and remain independent of the candidate.

Mirrors B4 · RL with verifiable rewards in the Build half.

Preference tuning asks a person or a model whether an answer is good. Reinforcement learning with verifiable rewards asks a program. If the answer to a problem can be checked exactly, by comparing a number, running unit tests or validating a format, the model can be trained on thousands of its own attempts without any human in the loop. Our claim is that RLVR is a way of sharpening what a model can already sometimes do, and its payoff is set by the quality of the verifier: gains are large where a program can check the answer and the base model already gets it right some of the time, and they do not reliably extend a model's reach.

The GRPO loop with a verifiable rewardA prompt goes to the policy, which samples a group of answers. A verifier scores each answer. Each answer's advantage is its reward minus the group mean, so no value model is needed. The policy is updated and samples the next group. The verifier is protected: the policy cannot change it.1 · Prompt2 · Sample a group3 · Verify each answerPrompta task with acheckable answer:maths, code,exact formatPolicy samples a groupanswer 1answer 2answer 3answer 4Verifierprotectedexact-answer check, unit tests,format rule: a program, not a modelreward 1 if correct, else 0the policy can never edit itAdvantage vs the groupadvantage = reward − group meanno critic, no value modelrewardsadvantage1001+0.5−0.5−0.5+0.5group mean = 0.5illustrative numbers, not measuredPolicy updateraise the odds of answers abovethe group mean, lower the rest;clipped step, optional KL termvalue model (critic)updated policy samplesthe next groupGRPO: Shao et al. 2024 (DeepSeekMath); applied with rule-based rewards in DeepSeek-R1. Dashed gold outline = protected component.Dr. GRPO and DAPO alter the length and std-normalisation terms; the loop shape stays the same.

The loop is short. The model samples a group of answers to each prompt; the verifier scores every answer; each answer's advantage is its reward minus the group average; and the model is nudged towards the answers that beat the average. GRPO, introduced with DeepSeekMath, replaced PPO's learned value model with this group baseline, which removes a whole network from memory. Two properties matter more than the algebra. The verifier is outside the model: a program, not a neural judge, and the policy must have no way to edit it. And the signal is relative: an answer only learns anything if the group contains both wins and losses, which is why this works on problems the model sometimes solves and stalls on those it never does.

Worked example (illustrative). A logistics team wants a model to answer freight-quote requests: read a shipment description and return the price from a published rate card, with the working shown. A short program recomputes the price from the rate card and checks the output format. The reward is the fraction of checks passed. Early on, the group of eight attempts for a typical request has mixed scores, so there is a clear signal and accuracy rises quickly. Then the model finds a shortcut. When it is unsure of a surcharge, it leaves it out and adjusts the base rate so the total still matches; the checks pass and the working is wrong. The team adds a check that every surcharge named in the request appears in the working, and the shortcut closes. The lesson is not that the method failed; the verifier, not the optimiser, defined what the model got good at.

The best-known result is DeepSeek-R1-Zero, trained by GRPO with rule-based rewards for answer accuracy and format and no neural reward model. In the paper version we fetched in November 2026 its pass rate on the 2024 AIME maths competition rose from 15.6% to 77.9%; earlier versions report different figures, so cite the version. The open community then found plain GRPO fragile. DAPO added four changes, among them wider clipping and filtering out groups where every answer is right or wrong, and its ablation moved a 32B model from 30 to 50 on the same benchmark, beating the 47 of R1-Zero-style training on that base while using half the steps. Dr. GRPO found that GRPO's normalisation terms inflate the length of wrong answers and offered a corrected version. These are repairs to a recipe, which is a useful signal about how recent the recipe is.

Gains from reinforcement learning with verifiable rewards, and what they do and do not showDeepSeek-R1-Zero rose from 15.6 to 77.9 on AIME 2024 and DAPO from 30 to 50. On Qwen2.5-Math-7B, random rewards gave plus 21.4 points on MATH-500 against plus 29.1 for ground-truth rewards, an effect that fails on Llama 3 and OLMo 2. Yue et al. found pass@1 rose from 26.1 to 42.5 while pass@256 fell from 67.2 to 64.3, and on AIME 24 at k of 1024 the base model solved 13.3 percent of problems the RL model missed while the RL model solved none the base missed.exact / ground-truth reward, or gainrandom reward, or a drop / base-onlybeforeafterHeadline gains (not comparable)0255075100%DeepSeek-R1-Zero, AIME 2024 pass@1, current paper version: 15.6 to 77.9 (+62.3)DeepSeek-R1-ZeroAIME 2024 pass@1, current paper version77.9+62.3DAPO, Qwen2.5-32B, AIME 2024 avg@32, naive GRPO to full: 30 to 50 (+20)DAPO, Qwen2.5-32BAIME 2024 avg@32, naive GRPO to full50+20Do rewards need to be right?0102030 ptsRandom reward: +21.4 points on MATH-500Random rewardQwen2.5-Math-7B, MATH-500+21.4Ground-truth reward: +29.1 points on MATH-500Ground-truth rewardQwen2.5-Math-7B, MATH-500+29.1Qwen onlyfails on Llama 3,OLMo 2Sharpening or new ability?0255075100%pass@1, base to RL-trained, Yue et al.: 26.1 to 42.5 (+16.4)pass@1base to RL-trained, Yue et al.42.5+16.4pass@256, base to RL-trained, Yue et al.: 67.2 to 64.3 (−2.9)pass@256base to RL-trained, Yue et al.64.3−2.9AIME 24 at k = 1024: 63.3% solved by both, 13.3% by base only, 0.0% by the RL model onlyAIME 24 at k = 1024share of problems solved byboth 63.3%base only 13.3%RL only 0.0%Read togetherRL lifts the first try but did not widen what the base model can solve at large k; ProRL contests thisfor longer training. Gains on Qwen bases partly reflect what pre-training already held.Sources: DeepSeek-R1 (arXiv version fetched Nov 2026; earlier versions differ), Yu et al. 2025 (DAPO), Shao et al. 2025, Yue et al. 2025.

The lower panels of the figure are why the claim above is worded as it is. Two caveats follow the headline numbers. First, the base model matters a great deal. In the spurious-rewards study, random rewards raised Qwen2.5-Math-7B by 21.4 points on MATH-500, against 29.1 with the true reward, yet the effect failed on Llama 3 and OLMo 2; the authors link it to the training procedure amplifying behaviour already present in pretraining. A further study argues Qwen results are contaminated and that on leak-free data only accurate rewards help. Second, the gain may be one of efficiency, not reach. Yue and colleagues compared base and RL-trained models at many attempts per problem. On the training set, pass@1 rose from 26.1 to 42.5, yet pass@256 fell from 67.2 to 64.3, and on AIME 24 at 1,024 attempts the base model solved 13.3% of problems that the RL model missed while the RL model solved none that the base missed. Read very large k with care: AIME answers are integers below 1,000, so a thousand samples can stumble on the right answer by chance, which flatters any model at the top of the curve. This held for six RL algorithms.

Meanwhile RLVR has moved into products, and the pattern there is a warning about dependence. Amazon Bedrock offers reinforcement fine-tuning for Nova 2 Lite, gpt-oss-20B and Qwen3 32B, with rewards supplied as Lambda code or a model judge, and advises starting with 100 to 200 examples, skipping RFT if the baseline reward already exceeds 95%, and using SFT first if it is near zero. Google's Vertex offering was pre-GA and "not for production" when checked; Microsoft Foundry's requires model-access approval. OpenAI's ran on o4-mini (a secondary guide says it was the only base), and o4-mini and its fine-tuned variants were removed on 23 October 2026; from 15 December 2026 no organisation can create new self-serve fine-tuning jobs. A recipe that rides on someone else's model is rented, not owned. The scarce asset is the environment: a task plus a scorer you trust. Reward hacking in realistic coding environments has been shown to generalise into sabotage and alignment faking, so a leaky verifier is a safety issue, not only a quality one.

The fault line. Does RL add ability or only sharpen it? The sharpening side has Yue et al.'s pass@k curves, the Qwen-specific results and the observation that distillation, rather than RL, is what added new reasoning patterns. The expansion side has ProRL, which reports that prolonged training with KL control and reference resets reaches tasks the base model fails at any number of attempts, and the work reporting that outcome-reward RL generalises where SFT memorises. The settling experiment needs matched compute, several base families, uncontaminated tasks and a very large number of attempts, and training far longer than earlier studies. For a builder the dispute matters less than it sounds: a model that gets the answer on the first try rather than the fifth is cheaper to run, even if its ceiling has not moved.

Our assessment

RLVR works when three things hold: the output can be checked by a program, the base model already succeeds some of the time, and nobody can game the check. It is the best tool for improving reliability on checkable tasks and a weak one for teaching a model what it cannot do. It does not reliably widen what the base model can reach. Confidence: medium-high on the first claim, medium on the second; the long-training question is open.

U5. Distillation and synthetic data

A teacher model can produce examples for a smaller student. The student learns from those examples, not from the teacher's reputation. Independently check the examples and evaluate the student on unseen work.

Mirrors B5 · Distillation in the Build half.

Distillation is the cheapest way to buy a capability you do not have to build: a stronger model writes the examples, a smaller one learns from them. Our claim is that distillation transfers what the teacher shows, not what it knows. It pays when the task is narrow, the teacher is good at it and you are allowed to use its outputs; it disappoints when any of those three fails.

Distillation from teacher to student: off-policy and on-policyBefore a teacher is used, a licence and terms check confirms its outputs may be used for training. Off-policy distillation: fixed prompts go to the teacher, which writes outputs that become a stored dataset, and the student is fine-tuned to imitate them. On-policy distillation: the student generates its own samples, the teacher grades each token or supplies logits on those samples, and the student is updated, in a loop.Gate: licence and terms check on the teacherMay its outputs be used to train another model? Open-weight licences differ; some API terms forbid it.Off-policy: imitate fixed teacher outputsCheap and simple; the student never sees its own mistakes.Fixed promptschosen in advanceTeacher writes outputsstored as a datasetStudent fine-tunedSFT on teacher textOn-policy: grade the student's own samplesDense feedback where the student actually goes wrong.Promptsa fresh batch each stepStudent generatesits own samplesTeacher gradesper-token score or logitsupdate the student, then sample againOn Qwen3-8B-Base, AIME 2024: SFT on 400k teacher prompts reached about 60%; on-policy distillation reached 70% in about 150 steps.Teacher Qwen3-32B; the same source cites 1,800 GPU-hours for on-policy distillation against 17,920 for RL (Qwen3 report).On-policy needs teacher logits or a scorer, so an API-only teacher may not fit.Source: Thinking Machines, Oct 2025 (self-published). Ancestry: Kim and Rush 2016 (off-policy), GKD 2023 (on-policy).

The figure shows two ways to do it, behind a gate that most teams reach too late. Off-policy distillation is the original form. Kim and Rush's sequence-level distillation trained a student on the teacher's own outputs rather than its probabilities and produced a translation model about ten times faster, and every modern "fine-tune on GPT-written answers" recipe descends from it. Its weakness is that the student only ever sees text the teacher wrote, so it never practises recovering from its own mistakes. On-policy distillation fixes this. MiniLLM and Google's GKD let the student generate, then have the teacher score what the student actually wrote. The signal is dense, because every token is graded, and it lands exactly where the student goes wrong. The price is needing the teacher's token probabilities, or another scorer, at training time; a text-only API will not do.

Worked example (illustrative). A finance team wants a small model that sorts supplier queries into twelve categories and drafts a one-line reply. A large model labels and answers 20,000 past queries; an 8B student is fine-tuned on them. Offline accuracy looks excellent. In production the student meets a query format that its training set never contained, a forwarded email chain with the question buried at the bottom, and answers confidently from the wrong paragraph. The training set held no student mistakes to learn from. Grading the student's own drafts with the teacher would have caught it. Then legal reads the teacher's terms and finds that its outputs may not be used to train another model. The team has built a good student it may not ship.

The strongest evidence is the reasoning case. DeepSeek trained small Qwen and Llama models by plain supervised fine-tuning on 800,000 samples curated from its R1 model, with no reinforcement learning on the students.

Small distilled models against an RL-only run on AIME 2024AIME 2024 pass@1 for DeepSeek-R1 distilled students trained only by supervised fine-tuning on 800 thousand samples: Qwen 1.5B 28.9, Llama 8B 50.4, Qwen 7B 55.5, Qwen 14B 69.7, Llama 70B 70.0 and Qwen 32B 72.6. The same Qwen 32B base trained with reinforcement learning alone reached 47.0.distilled: SFT on teacher samplesRL only, same Qwen 32B base0255075100%AIME 2024 pass@1Distilled, Qwen 1.5B: 28.9 (SFT on 800k samples)Distilled, Qwen 1.5BSFT on 800k samples28.9Distilled, Llama 8B: 50.4 (SFT on 800k samples)Distilled, Llama 8BSFT on 800k samples50.4Distilled, Qwen 7B: 55.5 (SFT on 800k samples)Distilled, Qwen 7BSFT on 800k samples55.5Distilled, Qwen 14B: 69.7 (SFT on 800k samples)Distilled, Qwen 14BSFT on 800k samples69.7Distilled, Llama 70B: 70 (SFT on 800k samples)Distilled, Llama 70BSFT on 800k samples70.0Distilled, Qwen 32B: 72.6 (SFT on 800k samples)Distilled, Qwen 32BSFT on 800k samples72.6RL only, Qwen 32B: 47 (RL for 10K+ steps, no distillation)RL only, Qwen 32BRL for 10K+ steps, no distillation47.0On the same Qwen 32B base, distilling 72.6 beat RL-only 47.0 (GPQA Diamond 62.1 against 55.0).Source: DeepSeek-R1 paper, arXiv 2501.12948, Tables 5 and 6. Different base models, so compare within a base only.

On AIME 2024 the 32B Qwen student reached 72.6% pass@1, and even the 7B reached 55.5%. The paper's own comparison is the telling part: reinforcement learning applied directly to the same 32B base reached 47.0% after more than ten thousand steps, and the authors conclude that distilling from a stronger model beat discovering the behaviour from scratch. Open datasets followed: OpenThoughts reports a 7B student 15 to 20 points above DeepSeek's distilled 7B on three benchmarks. s1 got competition-level maths from only 1,000 traces, and LIMO from a small curated set, though both rest on strong Qwen bases.

The on-policy case is newer and self-published. Thinking Machines reports that on Qwen3-8B-Base, on-policy distillation from a 32B teacher reached 70% on AIME 2024 in about 150 steps, where supervised fine-tuning on 400,000 prompts reached about 60%; the 70% figure for the SFT route is an extrapolation to two million prompts, not a run. They cite the Qwen3 report's own figures for a cost comparison of 1,800 GPU-hours against 17,920 for reinforcement learning (74.4% against 67.6%). Thinking Machines did not measure that ratio itself, so treat it as Qwen's reported figure. It corrects the assumption that on-policy means more compute: it costs more per example than plain SFT but needs far fewer examples.

These gains are not magic. Gudibande and colleagues showed in The False Promise of Imitating Proprietary LLMs that crowd raters found imitations of ChatGPT competitive while benchmarks showed little or no gap closed on anything the imitation data did not cover: style transfers, facts do not. And the data itself needs care. Microsoft's Orca taught a 13B model with GPT-4 explanation traces and beat a comparable open model by large relative margins, but under zero-shot, model-graded comparisons. Selection beats volume at small scale: AlpaGasus kept 9,000 of Alpaca's 52,000 examples and cut 7B training time from 80 to 14 minutes, using ChatGPT as the scorer. Contamination is the quiet failure. Yang and colleagues showed that rephrased test questions defeat n-gram filters, that a 13B model can reach GPT-4-like scores if they remain in training data, and that GPT-3.5 and GPT-4 synthetic data already contained such leaks. Deduplication helps (Lee and colleagues cut memorised output tenfold at pretraining scale) but cannot replace a held-out set written after the data was built.

Synthetic data is not poison by default. Model collapse appears when each generation replaces real data with the last one's output; accumulating synthetic data beside the real data bounds the error, and NVIDIA's Nemotron-4 pipeline used over 98% synthetic alignment data. The terms are the other constraint. Anthropic's commercial terms, in the version effective June 2025, bar using the service to train competing models, and in February 2026 the company described over 16 million exchanges through some 24,000 fraudulent accounts as distillation by three labs, while calling distillation itself legitimate. The Llama 3.1 licence requires "Llama" at the start of the name of any model improved with its outputs, and Stanford's Alpaca data is non-commercial. Open-weight teachers such as DeepSeek-R1 (MIT) avoid the problem.

The data business is moving the same way. As human-written instruction sets became commodities, vendors began selling expert rubrics, verifiers and RL environments instead. Mercor announced in July 2026 that it would acquire the environment start-up Deeptune (no price found), and Surge AI's CoreCraft paper reports transfer gains of 4.5 to 7.4 points on outside agent benchmarks, though it is vendor-authored. Treat the figures with care. Meta's stake in Scale AI was reported at $14.3 billion for 49% of non-voting shares, not $14.8 billion; the best APEX-Agents score was 24.0% in January 2026, before a September 2026 version 1.1 release with a different leaderboard; and "2,500 environments" on Prime Intellect's hub has no primary source. "Environments are the new scarce input" is a vendor thesis, not an audited market measure.

The fault line. Does distillation beat reinforcement learning for small models? For: DeepSeek's 72.6 against 47.0, and Thinking Machines' tenfold cost claim. Against: distillation is bounded by a teacher that has to exist and be usable, and a narrow verifiable task can favour RL; Ramp reports a 35B open model trained with RL beating a frontier model by four points on one retrieval task, though that is RL, not distillation. A matched-compute comparison on one base, with a current RL recipe, a teacher whose terms allow the use and tasks outside the teacher's strength, would settle it. Nobody has published one.

Our assessment

Distillation is the best-evidenced route to a small, cheap model for a task a larger one already does well, and on-policy variants look cheaper than they sound. It does not create ability the teacher lacks, it imports the teacher's blind spots, and it can be contractually off limits. Check the terms first, mix real data with synthetic, and test on questions written after the data. Confidence: high on reasoning distillation from open teachers; medium on on-policy cost claims; low on any vendor-market figure.

U6. Continued pretraining and domain adaptation

Continued pretraining changes the model by exposing it to more domain text. That differs from teaching an exact output format with labeled examples. Choose the method that matches the missing capability.

Mirrors B6 · Continued pretraining in the Build half.

Continued pretraining means training a model further on raw domain text, with no instructions and no answers, so that it absorbs a field's vocabulary and facts. It is the heaviest tool on this page and the one most often chosen for the wrong reason. Our claim is that domain adaptation buys real gains when the domain is far from the model's training data and the model is small, and it always charges for them in general ability. The question is how much, and whether you measured it.

Domain gain against general-capability forgetting (illustrative)An illustrative concept chart with no measured values. Over training steps on a domain corpus, domain skill rises and flattens. General capability falls steadily when training uses only domain text, and falls much less when general data is mixed into the corpus.Illustrative shape, not measured valuestraining on the domain corpus (steps or tokens)capabilitystartDomain skillGeneral capability,with general data mixed inGeneral capability,domain text onlyforgetting avoidedby mixingMixing general data (replay) slows the loss and costs some domain gain; the right mix is found by measuring both curves.

The figure is a concept sketch, not data. Train on domain text and domain skill rises, then flattens. General capability, meanwhile, drifts down, because the weights that served general language are the same weights being rewritten. Mixing some general data back in, usually called replay, slows the drift and costs a little domain gain. The whole discipline is choosing the mix by measuring both curves.

The idea is older than the large models. Gururangan and colleagues' Don't Stop Pretraining took RoBERTa through a second phase on in-domain text and gained, for example, 63.0 to 75.4 macro-F1 on a citation-intent task and 77.3 to 80.8 on a scientific-relations task. They also found that adapting to an irrelevant domain usually did worse than not adapting, and that a news domain close to the original gained nothing. The lesson, which has held since, is that the gain scales with the distance from the base model's data. Forgetting was mentioned there rather than measured. It is now the measured part.

Worked example (illustrative). A marine-insurance firm continues pretraining a 7B model on 3 billion tokens of its policy wordings and surveyor reports. Its clause-recall test rises from 41% to 68%. Six weeks later an ordinary summarisation prompt returns text in the stiff syntax of a policy schedule, and a tool-calling routine that worked before now emits malformed JSON. The team re-runs with 25% general text and a lower learning rate: clause recall reaches 64%, and the JSON failures vanish. All the numbers here are invented; the pattern is the common one, and the fix is a mixture rather than a bigger corpus.

The best controlled measurement is LoRA Learns Less and Forgets Less, which compared full fine-tuning with LoRA on Llama-2-7B for code and maths, in both continued pretraining and instruction tuning.

LoRA learns less and forgets less than full fine-tuningLlama-2-7B, full fine-tuning against LoRA. Learning on the target domain: code continued pretraining 0.263 full against 0.224 LoRA, math continued pretraining 0.293 against 0.203, code instruction tuning 0.497 against 0.498. Keeping the source domain, where higher means less forgetting: code continued pretraining 0.545 full against 0.617 LoRA, code instruction tuning 0.414 against 0.509, math continued pretraining 0.613 against 0.616.full fine-tuningLoRA (rank in brackets)higher is better in both blocksLearnsscore on the new domain0.00.20.40.6Code, continued pretraining, HumanEval, 20B tokens: full fine-tuning 0.263, LoRA (r=256) 0.224Code, continued pretrainingHumanEval, 20B tokens0.2630.224 (r=256)Math, continued pretraining, target-domain score: full fine-tuning 0.293, LoRA (best LoRA) 0.203Math, continued pretrainingtarget-domain score0.2930.203 (best LoRA)Code, instruction tuning, HumanEval peak: full fine-tuning 0.497, LoRA (r=256) 0.498Code, instruction tuningHumanEval peak0.4970.498 (r=256)Keepsscore on the original domain after training0.00.20.40.6Code, continued pretraining, source-domain average: full fine-tuning 0.545, LoRA (r=256) 0.617Code, continued pretrainingsource-domain average0.5450.617 (r=256)Code, instruction tuning, source-domain average: full fine-tuning 0.414, LoRA (r=64) 0.509Code, instruction tuningsource-domain average0.4140.509 (r=64)Math, continued pretraining, source-domain average: full fine-tuning 0.613, LoRA (r=256) 0.616Math, continued pretrainingsource-domain average0.6130.616 (r=256)LoRA trails on learning in continued pretraining and holds more of the source domain, except in math where it forgets as much.Source: Biderman et al. 2024, arXiv 2405.09673. Llama-2-7B, code and math only; a trade-off, not a free lunch.

Learning first. After 20 billion tokens of code, full fine-tuning scored 0.263 on HumanEval; the best LoRA, at rank 256, scored 0.224, and on maths continued pretraining the gap was wider, 0.293 against 0.203. In instruction tuning the gap closed: rank-256 LoRA matched full fine-tuning on code (0.498 against 0.497). Then keeping. On a source-domain average, LoRA retained 0.617 against 0.545 in code continued pretraining and 0.509 (rank 64) against 0.414 in code instruction tuning, but in maths continued pretraining the two forgot alike (0.616 against 0.613). The authors attribute the difference to the size of the change: full fine-tuning perturbed weights at a rank 10 to 100 times higher than typical LoRA settings. The result is a trade, not a free lunch. Kalajdzievski adds that forgetting with LoRA follows a power law in parameters tuned and steps, that fine-tuning performance and forgetting are strongly inversely related, and that early stopping does not avoid it. Shuttleworth and colleagues find that LoRA adds "intruder dimensions" that full fine-tuning does not, and that sequential LoRA tasks accumulate them.

For replay, the measured evidence is at pretraining scale. Ibrahim and colleagues matched a full re-train on loss and benchmark averages by re-warming and re-decaying the learning rate, with 5% replay for a weak shift and 25% for English-to-German. We found no measured rule for a mix at instruction-tuning scale, and none for a minimum corpus either: the "at least one billion tokens" figure in circulation has no primary source. The nearest evidence points the other way. Synthetic continued pretraining expanded a 1.3-million-token corpus into 455 million synthetic tokens and lifted closed-book accuracy on a reading-comprehension benchmark from 39.49% to 56.22%, while plain training on the raw documents scored 38.15%. The facts were few; the paraphrases did the work.

That fits what instruction tuning cannot do. Gekhman and colleagues found that facts new to a model are learned slowly and then raise hallucination. Ovadia and colleagues found that on post-cutoff events unsupervised fine-tuning did not reliably beat the base model, and that retrieval alone beat fine-tuning plus retrieval for all three models tested. Pretraining-stage work is increasingly treated as a late phase of pretraining itself: Llama 3 annealed on upsampled high-quality data at the end of pretraining (about 40 billion tokens for the 8B model; the final 40 million tokens of the 405B run), lifting the 8B model by 24.0% on the GSM8K and MATH validation sets, with negligible effect at 405B; OLMo 2 spends 5 to 10% of its compute on mid-training. Gains shrink with model size. Forgetting can also be repaired afterwards: Thinking Machines reports that mid-training on internal documents lifted a model's knowledge-QA score from 18% to 43% but dropped instruction-following from 85% to 45%, and that a 70/30 document–chat mix followed by on-policy distillation reached 41% and 83%. Their instruction-following score never fully recovered by mixing alone.

The fault line. Is continued pretraining worth it against fine-tuning plus retrieval? For: large gains for distant domains, the Llama 3 and OLMo 2 practice, and synthetic expansion for facts that must be known without a retrieval step. Against: gains vanish for big models, facts are hard to extract unless they appeared in many paraphrased forms, and retrieval is cheaper to update. A matched-budget comparison of Q&A-style fine-tuning, synthetic continued pretraining and retrieval on facts that postdate the model, scored for recall and for hallucination on facts the model already knew, would settle it. We found no such study. The learning-versus-forgetting frontier across more base models is equally unmapped. One cheap remedy deserves a trial before any of this: WiSE-FT interpolates the weights of the starting and the tuned model, and on image models it recovered robustness the fine-tune had lost at no extra training cost. Whether the same holds for language models after continued pretraining has not been settled, but a sweep of the mixing weight costs only evaluations.

Our assessment

Continued pretraining is justified when the domain is distant, the model small and the facts must live in the weights; otherwise retrieval plus a light fine-tune is usually cheaper and easier to undo. Forgetting is measurable and manageable, with replay, a low learning rate and LoRA, but it is a trade: LoRA forgets less because it learns less. Always report the domain score next to a general score. Confidence: high that forgetting is real and that LoRA trades learning for retention; medium on replay ratios, which come from pretraining-scale work; low on any minimum corpus size.

Part III — What the evidence adds up to

Across the studies in Part II, one pattern recurs. Fine-tuning reliably changes how a model behaves: its format, its style, its skill at a narrow checkable task. It unreliably changes what a model knows. The gains that last are the ones measured against a strong, honestly tuned baseline on a clean test, and the losses that hurt are the ones nobody measured. This part puts the evidence for the first choice side by side, gives four questions for reading any new claim, offers our verdicts on the ten questions the field is still arguing about, dates the market as it stands in November 2026, and sets out twelve ways fine-tuning fails, grouped by cause.

Fine-tune, retrieve or prompt?

Ask whether the information is missing, the instruction is unclear, or the behaviour remains unreliable with the right evidence and clear instruction. Only the third is a strong reason to investigate training.

Fine-tune, retrieve or prompt?A conceptual map. The horizontal axis is what is missing, knowledge on the left and behaviour on the right. The vertical axis is how fast it changes, fast at the top and slow at the bottom. Retrieval sits top left and prompting with examples top centre, neither changes the weights. Continued pretraining sits bottom left, SFT with LoRA bottom right and preference tuning and reinforcement learning above it, all change the weights. Fine-tuning combined with retrieval sits in the middle. Note A: Ovadia and colleagues found on Mistral-7B current events that retrieval scored 0.875 against 0.504 for fine-tuning. Note B: Soudani and colleagues found fine-tuning on top of ideal retrieval helps models up to 3 billion parameters and hurts 7 billion and larger.leaves the weights alonechanges the weightsplacement is conceptual, not measuredchanges fastchanges slowly← knowledge is missingbehaviour is missing →what is missingRetrieval (RAG): fresh, citable factsRetrieval (RAG)fresh, citable factsAPrompting + examples: cheap first movePrompting + examplescheap first moveFine-tune + retrieval: teach it to use contextFine-tune + retrievalteach it to use contextBContinued pretraining: domain vocabularyContinued pretrainingdomain vocabularyPreferences and RL: taste, checkable skillPreferences and RLtaste, checkable skillSFT / LoRA: format, style, behaviourSFT / LoRAformat, style, behaviourANew facts: retrieval beats fine-tuningOvadia et al. 2023, Mistral-7B, current events.Retrieval 0.875, fine-tuned 0.504, base 0.481.Llama2-7B fine-tuned: 0.219, below its base 0.353.BFine-tune plus retrieval: size mattersSoudani et al. 2024, PopQA, ideal retrieval.≤3B gains: StableLM2-1.6B 76.14 → 82.09.7B+ loses: Mistral-7B 80.25 → 78.44.

The map is conceptual, not measured: it places each lever by what is missing (knowledge on the left, behaviour on the right) and by how quickly that thing changes. Two sourced findings, marked A and B, anchor it.

Note A is the case against fine-tuning for facts. Ovadia and colleagues injected post-cutoff current events into Mistral-7B two ways. Retrieval lifted accuracy from 0.481 to 0.875. Unsupervised fine-tuning reached 0.504, and 0.588 when the facts were paraphrased. Llama2-7B fell from 0.353 to 0.219 after fine-tuning. The mechanism is visible in Gekhman and colleagues' study of PaLM 2-S: examples the model did not already know were fitted slowly, and training on a set of them reached 25.8% accuracy at convergence against 37.5% with early stopping. Teaching a model facts it lacks teaches it, at least in part, to guess.

Note B is the case for fine-tuning a model to use retrieved text. Soudani and colleagues compared twelve models with ideal retrieval. Fine-tuning on top of it helped models up to 3 billion parameters (StableLM2-1.6B went from 76.14 to 82.09), hurt 7B-class models such as Mistral-7B (80.25 to 78.44) and made no significant difference to Llama-3-8B. Fine-tuning that teaches the model how to read context, as in RAFT, is a different intervention from fine-tuning that stores facts, and the evidence favours the first. An agricultural case study by Balaguer and colleagues found the two stacked, with fine-tuning adding over 6 points and retrieval about 5 more, on one domain and a model judge.

Prompting is the third rival, and it has grown stronger. Medprompt showed that a prompted generalist model can beat a medically tuned one. Many-shot in-context learning scales to thousands of examples, and Bertsch and colleagues found that for most classification datasets LoRA never exceeded long-context prompting, while full fine-tuning with more data than fits in context gave the best score. Prompting wins when examples are few. Fine-tuning wins when volume is high and per-query cost matters. Nobody has published the break-even with prompt caching at today's prices, but it is simple to compute for your own case: fine-tuning pays once N × (c_long − c_short) exceeds C_tune, where N is the number of requests over the adapter's life, c_long the cost per request of the long cached prompt on the large model, c_short the cost per request of the short prompt on the tuned model (serving included), and C_tune the one-off cost of data, training and evaluation.

The most quoted pro-fine-tuning result needs the same care. LoRA Land reports 310 small models, of which 224 beat GPT-4, with the best tuned model per task averaging 0.756 against 0.661. But GPT-4 was given plain zero- or one-shot prompts with no prompt engineering, by design, the 0.756 picks the best of ten models on each task, and GPT-4 still won 6 of the 31 tasks, including coding and MMLU. Read it as strong evidence for narrow classification and weak evidence for the general claim.

Four questions to read any fine-tuning claim

Fine-tuning results usually arrive as one number and a model name. Four questions separate the numbers that will hold from the ones that will not.

Question 1
What was the baseline: prompted or tuned?
A tuned model that beats an unprompted baseline has beaten very little. LoRA Land's GPT-4 had no prompt engineering, and none of the vendor case pages we read publish the baseline prompt. Ask what an equally patient engineer could get from prompting, retrieval and many-shot examples.
Question 2
Is the test set clean?
Rephrased test data defeats n-gram filters: Yang et al. showed a 13B model reaching GPT-4-level scores on MMLU, GSM8K and HumanEval that way. On a fresh matched set, GSM1k, some models dropped by up to 8%. Fine-tuning on in-distribution data makes accidental overlap easier.
Question 3
What was traded away?
Gains arrive with a bill: forgetting, a weaker safety posture, a shifted persona. Ten harmful examples took GPT-3.5 Turbo from 1.8% to 88.8% harmful, and benign data alone took it from 5.5% to 31.8%. A report with no before-and-after on general ability and safety has measured half the change.
Question 4
Who measured it, and at what price?
Most strong numbers are vendor-reported on the vendor's own task. Bridgewater's 84.66% against 78.2% for a frontier model is on Thinking Machines' own page, on six tasks, for a 235B model. Ask for the held-out set, the confidence interval and the cost per query, not only the accuracy.

A fifth question belongs in any budget discussion: is the claim about knowledge or about behaviour? Most of the confusion in this literature comes from mixing the two. A result that fine-tuning "improved factual answers" can mean it taught new facts (rarely true), taught the model when to say "I don't know" (often true), or taught it to read the retrieved passage (true, and the thing worth paying for).

Ten open questions

The field is trying to answer ten questions. For each we give our verdict and our confidence in it. Several verdicts split a question in two, because the honest answer differs by setting.

Can fine-tuning add knowledge?
Retrieval beat fine-tuning on every fact-injection test we found (0.875 against 0.504 in one, 80.25 against 30.70 in another), and fitting unknown facts raised hallucination. Paraphrase augmentation and question-answer training help, but no study has settled whether they close the gap at scale.
VerdictNot reliably; retrieval is the safer route.
Does fine-tuning plus retrieval beat retrieval alone?
Teaching a model to read distractor-laden context helps (RAFT, RA-DIT). Teaching it facts helps small models and hurt a 7B-class model under ideal retrieval, with no significant effect on another 8B model. Real retrieval is imperfect, and the sweep over retrieval quality has not been run.
VerdictDepends on what the fine-tune teaches.
Does a small tuned model really beat a frontier one?
Narrow classification near 90% accuracy is a robust win, and customer pages report large cost cuts. Against a tuned prompt, many-shot examples or retrieval, the margin is untested, and the frontier model kept coding and broad knowledge.
VerdictOn narrow tasks against a weak prompt, yes; in general, no.
Does many-shot prompting make fine-tuning redundant?
With few examples, prompting matches or beats LoRA. Inference cost grows with every example in the prompt, while a tuned model pays once. The break-even with prompt caching has not been published; the formula above computes your own.
VerdictAt low volume, often; at high volume, no.
Does LoRA match full fine-tuning?
Biderman and colleagues found LoRA learns less and forgets less: code continued pretraining reached HumanEval 0.224 against 0.263, while math instruction tuning was nearly level. Comparisons that tune learning rate per method are scarce.
VerdictWhen the data fits its capacity, yes; on hard continued pretraining, no.
Can the safety loss be avoided?
Mixing safety examples cut harmfulness from 91.8% to 23.0% in the adversarial case, and a token-constrained objective cut attack success from 88.9% to 4.6% on Llama-2-7B-Chat. Benign data mixed with 250 to 1,000 safe examples still left harm at about 20% against a 5.5% start.
VerdictReduced, not removed.
Why does emergent misalignment happen?
A toxic-persona feature predicts and controls it, a few hundred benign examples reverse it, and an "educational" framing of the same insecure code removes it. Nobody can yet predict which datasets will trigger it before training.
VerdictUnsettled; persona and intent are the leading accounts.
Can a model grade its own reinforcement learning?
Exact verifiers resist gaming; learned and rubric graders diverge from true quality as optimisation grows. DeepSeek avoided neural reward models for that reason, and the products selling model graders publish no audit method.
VerdictOnly when the grader is checked as hard as the model.
Is training on a frontier model's outputs safe to rely on?
Anthropic's commercial terms bar using the service to train competing models, Llama's licence requires naming, and open-weight teachers are unrestricted. No court has ruled on enforceability; enforcement so far is account bans.
VerdictTechnically easy, contractually fragile.
Is closed-API fine-tuning ending?
OpenAI's own deprecations page closes self-serve fine-tuning in stages through January 2027 and ties each tuned model to a retiring base. Open-weight fine-tuning on other vendors is growing. Whether a successor appears is unknown.
VerdictFor OpenAI, it is being wound down; elsewhere it persists.

The market in 2026

Price per 1M training tokens for small-model fine-tuning, November 2026Vendor-reported prices read on 2026-11-07. Together AI charges 0.34 dollars per million training tokens for a Llama 3.1 8B LoRA run and lets you download the weights. Tinker charges 0.44 dollars for Qwen3-8B and lets you download any checkpoint. Fireworks charges 0.50 dollars for models up to 16 billion parameters and is reported to allow export. OpenAI's closest model, gpt-4o-mini, costs 3 dollars, does not export weights and is being wound down. Snowflake Cortex Training bills per GPU-hour rather than per token and does not let you download weights.USD per 1M training tokensWeights exportable?documentedreportedno$0$1$2$3Together AI, Llama 3.1 8B, LoRA SFT: $0.34; weights export: yes, documentedTogether AILlama 3.1 8B, LoRA SFT$0.34yes, documentedTinker, Qwen3-8B, price at Oct 19 2026: $0.44; weights export: yes, any checkpointTinkerQwen3-8B, price at Oct 19 2026$0.44yes, any checkpointFireworks, models up to 16B, LoRA SFT: $0.50; weights export: reported yesFireworksmodels up to 16B, LoRA SFT$0.50reported yesOpenAI, gpt-4o-mini, closest; not 8B: $3.00; weights export: no; winding downOpenAIgpt-4o-mini, closest; not 8B$3.00no; winding downSnowflake Cortex Training, public preview: billed per GPU-hour; weights export: noSnowflake Cortex Trainingpublic previewper GPU-hour, not per tokennoVendor-reported list prices, read 2026-11-07; they change often. LoRA SFT on small open models unless noted.Not shown, no verified per-token 8B price: Bedrock, Vertex, Foundry, Databricks, Nebius, Predibase.Sources: vendor pricing and docs pages; Fireworks weight export comes from a secondary snippet.

Every figure below is vendor-reported and read in early November 2026, so treat it as a dated snapshot: prices change often, and at least one has risen since launch.

Closed APIs are retreating. OpenAI's deprecations page records the wind-down of its self-serve platform. On 7 May 2026 it closed to organisations that had never fine-tuned. On 2 July it closed to those with no fine-tuned inference in 60 days. From 15 December 2026, brought forward from 6 January 2027, no organisation can create new self-serve jobs. The page recommends newer base models but names no successor fine-tuning product. Tuned models do not outlive their base: gpt-4o, gpt-4o-mini, gpt-4.1 and gpt-4.1-mini are scheduled for removal on 14 January 2027, and their fine-tunes go with them. The bar in the chart is the last published price for the closest model, $3 per million training tokens for gpt-4o-mini, with no weight export.

Price collapsed where the weights are open. LoRA training on an 8B-class open model now costs $0.34 to $0.50 per million tokens at Together AI, Tinker and Fireworks. The floor is not monotonic: Tinker's Qwen3-8B price was reported at $0.40 in October 2025 (not re-checked) and was $0.44 on 19 October 2026. An illustrative 150-million-token run at $0.44 costs about $66.

Serverless training APIs appeared because reinforcement learning cannot be expressed as an upload-and-wait job. Tinker, Fireworks' Serverless Training API and Snowflake's Cortex Training (public preview) expose the training loop itself, billed per token or per GPU-second. Microsoft Foundry's Programmed Training is in preview. Hyperscalers bill reinforcement fine-tuning by the hour, $80 per training hour on Bedrock for two open models, because rollout length is unpredictable.

Portability is the real dividing line, not price. Together documents a download of merged, adapter or full checkpoints; Tinker offers an endpoint for any saved checkpoint; Fireworks is reported to allow adapter download but serves tuned models only from dedicated deployments. Snowflake's docs tell users not to download model weights, and OpenAI offers no export. A downloaded adapter is only as portable as the base model it was trained on.

Infrastructure and data companies are buying the tooling. Rubrik announced its acquisition of Predibase in June 2025, reported at over $100 million. Cloudflare announced Replicate in November 2025. Nscale agreed to buy Anyscale in July 2026, at a price Bloomberg put near $1.65 billion; those figures are unofficial and the closings were not confirmed. Databricks folded its separate Foundation Model Fine-tuning API into a wider product. Cohere's fine-tuning is deprecated, and AutoTrain is described as no longer maintained (secondary: an aggregator; its repository's README says the same). Standalone fine-tuning is becoming a feature of larger platforms.

Our reading: what is cheap is the training run. What is scarce, and what vendors compete on, is the data, the evaluation and the right to take the result with you.

How fine-tuning fails

Twelve failure modes recur across the literature. Read singly they look like a list of bugs. Read together they say one thing: fine-tuning optimises what you measured, and everything you did not measure changes anyway. The model moves in directions the training data never mentioned, the test set is rarely independent of the training set, and the finished artefact belongs, in part, to someone else's base model and terms.

The twelve fall into four groups by cause.

The weights change more than you meant.

Forgetting
What happens
General ability erodes as the model specialises.
Real case
LoRA retains more than full fine-tuning but still forgets, on a power law that early stopping does not avoid.
Guard
A regression suite on general ability as a hard gate on every candidate.
Safety erosion
What happens
Refusals are shallow and a few gradient steps overwrite them.
Real case
Qi et al.: ten harmful examples took GPT-3.5 Turbo from 1.8% to 88.8% harmful for under $0.20; benign Alpaca data took it from 5.5% to 31.8%.
Guard
Mixed-in safety data, a token-constrained objective, and a safety evaluation before and after every run.
Emergent misalignment
What happens
Narrow training shifts the whole persona.
Real case
Betley et al.: 6,000 insecure-code examples left GPT-4o giving misaligned answers about 20% of the time on selected questions, against 0% for controls.
Guard
Check behaviour far from the training task; treat dataset intent as a risk, not only content.

The model learns the wrong thing.

New-fact hallucination
What happens
Fitting facts the model never knew teaches it to guess.
Real case
Gekhman et al.: unknown examples fitted late; 25.8% at convergence against 37.5% with early stopping.
Guard
Keep facts in retrieval; early-stop; teach 'I don't know' for what the model lacks.
Overfitting
What happens
The model memorises examples instead of the behaviour.
Real case
Tuned on a few hundred rows, a model can recite its training set and fail on a paraphrase (illustrative).
Guard
A held-out set split before training, early stopping on it, and a count of epochs.
Reward hacking
What happens
The model raises the score without raising the quality.
Real case
Gao et al.: true quality falls as a learned proxy is over-optimised; DPO exploits length, and controlling for it moved win rates by up to 20%.
Guard
Prefer exact verifiers; hold a gold metric the trainer never sees.

The check does not match production.

Contamination
What happens
The test set was in the base model's training data.
Real case
GSM1k: some models dropped up to 8% on a fresh matched set; GPT-4 was flagged for several benchmark datasets.
Guard
A private, rotated held-out set written after the base model's cutoff.
Data leakage
What happens
Test items, or near-copies, sit in the tuning data.
Real case
Yang et al.: 8% to 18% of HumanEval overlapped public training corpora; rephrased copies slip past n-gram filters.
Guard
Near-duplicate and semantic dedup between train and test; split by source, not by row.
Format brittleness
What happens
It works in the notebook and breaks behind the real endpoint.
Real case
An adapter tuned under one chat template and served under another may lose its output format (illustrative; no study measures how often).
Guard
Evaluate through the exact serving path, template and decoding settings.

You do not fully own the result.

Licence and terms
What happens
Training data or a base model carries conditions.
Real case
Anthropic's commercial terms (June 2025) bar training competing models; Llama's licence requires 'Llama' in the name; Alpaca was non-commercial.
Guard
Record teacher, licence and terms version for every training row; prefer open-weight teachers.
Lock-in
What happens
The tuned model cannot leave the vendor that trained it.
Real case
Snowflake's docs say not to download weights; OpenAI offers no export; an adapter is tied to its base.
Guard
Choose a route that exports weights, and test one round trip: train, export, serve elsewhere.
Silent drift on base upgrade
What happens
The base moves or retires and the adapter changes with it.
Real case
OpenAI ties each fine-tune to its base: gpt-4o and gpt-4.1 fine-tunes are scheduled for removal on 14 January 2027.
Guard
Pin the base version, keep the data and recipe, and schedule a re-tune and re-evaluation per base release.

One design principle follows from all twelve. Decide what behaviour you want in a form a machine can check, build that check before the first training run from data the trainer never touches, and keep the recipe, the data and the right to move the weights. Fine-tuning pays when the check is exact and the result is yours. It fails when the score is a proxy, the test is borrowed or the artefact is rented. Part IV turns that into a decision procedure, and Part V shows how to build the check.

Half two

Build

Decide, set up, build, operate.

Part IV — Decide

The first half argued that what decides whether fine-tuning pays is whether you can define and check the behaviour you want, and whether you own the result. The second half turns that into practice, starting where most teams skip ahead: whether to fine-tune at all. A fine-tune is a standing commitment with its own data, evaluation, hosting and retirement date. It earns its place when the gap is behaviour rather than knowledge, a cheaper fix has been tried and measured, and the data and weights are yours to keep.

Should you fine-tune, and which method?

Should you fine-tune, and which method?A decision tree. First question: is the gap knowledge or behaviour? If knowledge, use retrieval and do not fine-tune for facts. If behaviour, second question: has prompting with examples been exhausted? If not, prompt first. If so, choose by symptom: wrong format, tone or behaviour leads to B1 and B2 supervised fine-tuning with LoRA; wrong taste or preferences to B3 DPO or KTO; a checkable skill with a verifier to B4 reinforcement learning with a verifier; too slow or too costly to B5 distillation; domain vocabulary the model lacks to B6 continued pretraining. A closing strip lists reasons not to fine-tune yet.BehaviourYesKnowledgeNoIs the gap knowledge or behaviour?Has prompting with examples been exhausted?What is the symptom?Use retrieval;don't fine-tunefor factsPrompt first:examples, structure,then re-testWrong format,tone or behaviour→B1 · B2SFT withLoRAWrong taste orpreferences→B3DPO orKTOA checkable skillwith a verifier→B4RL with averifierToo slow ortoo costly→B5DistillationDomain vocabularyit lacks→B6ContinuedpretrainingDon't fine-tune yet whenthere is no baseline or held-out set · the data is not yours to train on· the facts change weekly · nobody owns rollback

What companies actually chose, and why, is charted across 76 documented programmes in Business cases. The tree asks two questions before it offers any method. Is the gap knowledge or behaviour? If the model lacks facts, especially changing ones, retrieval is the better tool. On a set of post-cutoff current events, Mistral-7B scored 0.481 unaided, 0.875 with retrieval and 0.504 after unsupervised fine-tuning (Ovadia et al.). With ideal retrieval, the same model reached 80.25 on a rare-entity question set against 30.70 for fine-tuning (Soudani et al.). Gekhman et al. found that unknown facts are fitted slowly and push a model towards hallucination. Fine-tuning's role beside retrieval is teaching the model how to read what was retrieved: RAFT trained a 7B model that way and scored 73.30 on a biomedical question set, against 58.8 for the same base with retrieval alone.

Has prompting with examples been exhausted? When examples are few, in-context learning beat LoRA in Bertsch et al., and a prompting-only pipeline beat a specially tuned medical model in Medprompt. Small-model wins deserve suspicion too: LoRA Land's tuned models beat a GPT-4 that had no prompt engineering (see Part III). Give the baseline the effort you gave the tuned model.

Only then does the symptom choose the method. Wrong format, tone or behaviour points to supervised fine-tuning, in practice with LoRA (B1, B2). Wrong taste, where people can say which of two answers they prefer, points to preference tuning (B3). A skill a program can check points to reinforcement learning with a verifier (B4). A model too slow or dear points to distillation (B5). Vocabulary it has never met points to continued pretraining (B6).

Read the strip at the foot of the tree twice. Do not fine-tune yet with no baseline or held-out set, because you could not tell a gain from a loss; when the data is not yours to train on; when the facts change weekly; or when nobody owns rollback. And not when you cannot test safety before and after: a handful of harmful examples, or even benign data, can undo a model's guardrails (Qi et al., Part I).

One cheap probe catches the commonest mistake, which is training to fix what a better prompt would fix. Take fifty real failures and write the strongest prompt you can in a day, with retrieved examples. If that closes most of the gap, stop.

Are you ready?

Without a baseline you cannot say whether training helped, without a held-out set you measure memorisation, and without a rollback every bad release is an incident. This is the minimum before any Build chapter.

Readiness
  • Baseline. The untuned base model scored on your task with your best prompt, in the harness the tuned model will use.
  • Held-out set. Examples you never train or tune on, large enough that its standard error is below the gain you hope for.
  • Rights-cleared data. Every example has a known source and you may train on it, including terms on other models' outputs.
  • Owner. A named person approves releases, reads failures and answers for the model after it ships.
  • Rollback. The previous model or adapter stays deployable, and switching back is one change.
  • Budget. A ceiling for training, evaluation and failed runs, and an estimate of what a one-point gain is worth.

The item most often faked is the second. A held-out set also used to pick the learning rate or checkpoint is a validation set with a better name.

What will it cost?

Cost and GPU memory of a fine-tuning runCost equals training tokens times epochs times price per million tokens. Worked examples with vendor-reported prices and illustrative token counts: SFT with LoRA, 5 million tokens for 3 epochs at 0.34 dollars per million is 5.10 dollars; DPO, 3 million tokens for 2 epochs at 0.84 is 5.04 dollars; reinforcement learning on Tinker, 20 million sampled tokens at 0.60, 20 million prefill at 0.195 and 5 million trained at 0.44, is 18.10 dollars; distillation student training, 50 million tokens at 0.34, is 17 dollars plus teacher generation; continued pretraining, a billion tokens at 0.38, is 380 dollars. GPU memory rule of thumb: full fine-tuning needs more than 780 gigabytes for a 65 billion model; LoRA needs about a third of full on GPT-3 175B; QLoRA fits 65 billion on one 48 gigabyte GPU and 70 billion on two 24 gigabyte GPUs; other methods are illustrative.Cost of onetrainingrun=Training tokenstokens in your dataset,after formatting×Epochspasses overthe dataset×Price per 1M tokensvendor's rate for yourmodel size and methodWORKED EXAMPLES, 8B-CLASS MODELB1 · B2 SFT with LoRA5M tokens × 3 epochs × $0.34 per 1M = $5.10 (Together, Llama 3.1 8B)price vendor-reported · tokens illustrativeB3 DPO3M tokens × 2 epochs × $0.84 per 1M = $5.04 (Together, Llama 3.1 8B)price vendor-reported · tokens illustrativeB4 RL with a verifier20M sampled × $0.60 + 20M prefill × $0.195 + 5M trained × $0.44 = $18.10 (Tinker)price vendor-reported · tokens illustrativeB5 Distillation (student step)50M tokens × 1 epoch × $0.34 per 1M = $17, plus teacher generation (Together)price vendor-reported · tokens illustrativeB6 Continued pretraining1,000M tokens × 1 epoch × $0.38 per 1M = $380 (Together 8B, likely full-parameter rate)price vendor-reported · tokens illustrativePrices: Together AI and Tinker list prices read 2026-11-07 (Tinker as of Oct 19 2026); they change. Use your own token counts.Excludes evaluation, failed runs and serving. RL is billed on three meters, not one.GPU MEMORY RULE OF THUMBFull fine-tuningWeights, gradients and optimizer state all sit in GPU memory.>780 GB for a 65B model in 16-bit (QLoRA paper).LoRABase weights frozen; only the small adapter has gradients and state.3× less than full on GPT-3 175B: 1.2 TB → 350 GB (LoRA paper).QLoRAFrozen base stored in 4-bit, LoRA adapter on top.65B on one 48 GB GPU (QLoRA); 70B on two 24 GB GPUs (Answer.AI).Other methodsDPO also holds a reference model; RL adds a rollout engine; distillationneeds the teacher; CPT is sized like full fine-tuning. Illustrative, not measured.

The cost of one training run is the number of training tokens, times the number of epochs, times the vendor's price per million tokens. The prices in the figure are vendor-reported, Together's read on 7 November 2026 and Tinker's as listed on 19 October 2026; the token counts are illustrative, so use your own, counted after formatting. On these numbers a LoRA run on an 8B-class model costs a few dollars, a reinforcement-learning run tens, and a billion-token continued-pretraining run hundreds.

The formula understates real budgets in two ways. The training run is often the smallest line: evaluation, failed runs, data preparation and an engineer's time come first, and serving is a standing cost. And the result depreciates. Fine-tunes follow their base model into retirement: OpenAI's deprecations page schedules the gpt-4o and gpt-4.1 families, and their fine-tunes, to shut down on 14 January 2027. A fine-tune is a lease on a base model, so budget for retraining at the next upgrade. When a cached many-shot prompt costs less per query than a tuned model is a question no study we found has priced; work it out for your own volume.

The lower half of the figure is the memory rule of thumb; Part V shows where those gigabytes go.

Build, rent or buy?

Build or buy: three ways to fine-tuneA comparison of a self-hosted open-source stack, a serverless training API where you write the loop and the provider runs the GPUs, and a managed fine-tuning service. Self-hosted gives full control and outright weight ownership, priced in GPU hours such as 3.95 dollars an hour for an H100 on Modal, at the highest effort. Serverless training APIs such as Tinker give control of the loop, let you download checkpoints on Tinker but not on Snowflake, and bill per token, for example 0.44 dollars per million training tokens, at medium effort. Managed services such as Together AI, Fireworks, Amazon Bedrock, Microsoft Foundry and OpenAI give the least control and the lowest effort; Together lets you export weights, OpenAI does not.Self-hostedopen-source stackyou run everythingServerless training APIyou write the loop,they run the GPUsManaged fine-tuningserviceupload data, pick a methodControlEverything: data, loop,kernels and hardwareYour loop and data;their GPUsModel, method andsettings from a menuWeight exportYou own the weightsoutrightTinker: download anycheckpoint. Snowflake: noTogether: yes.OpenAI: noPrice modelGPU hours: Modal H100$3.95/hr, A100-80 $2.50Per token: Tinker $0.44train, $0.60 sample per 1MPer training token:Together $0.34 per 1MEffortHighest: drivers, trainer,tracking and servingMedium: write the loop,no GPU operationsLowest: upload data,pick a methodExamplesTRL, Axolotl,LLaMA-Factory on yourGPUs or rented onesTinker, FireworksServerless Training API,Snowflake Cortex TrainingTogether AI, Fireworks,Amazon Bedrock, Foundry,OpenAI (winding down)Vendors, prices and export facts from provider pages read 2026-11-07; they change. Control and effort are ourassessment, not measured. Fireworks sells both a serverless training API and managed training.

There are three ways to get the GPUs and the loop. Self-hosting means TRL, Axolotl or LLaMA-Factory on machines you own or rent. You own everything and pay by the GPU hour (Modal listed an H100 at about $3.95), and you also own the drivers, tracking and serving. A serverless training API such as Tinker runs the GPUs while you write the loop, which suits reinforcement learning because you supply your own rollouts and rewards. A managed service takes your data and a method choice and returns a model: the lowest effort, the least control.

The deciding question is portability, not price. Together AI lets you download a merged model, an adapter or full weights that Hugging Face tooling loads. Tinker has an endpoint to download any saved checkpoint. Snowflake's Cortex Training, in public preview, tells users not to download model weights, and Fireworks' documentation says on-demand dedicated deployment is the only supported way to serve a trained model, although a secondary source reports that its command-line tool can download adapters. OpenAI's route is closing: organisations that had never fine-tuned lost job creation from 7 May 2026, those with no recent fine-tuned inference from 2 July, and from 15 December 2026 no one can create new self-serve jobs. Closed-model tuning stalled because base models change faster than custom artifacts; the same logic bites wherever the weights never reach you.

Read savings claims as you would accuracy claims. Snowflake reports its service as up to 61% cheaper than Tinker and others, on its own benchmark against competitors' list prices of 22 October 2026. We found no primary source for the often-repeated rule that self-hosting breaks even after two to four projects a year. If you cannot name your annual volume, rent by the token.

Test portability before you depend on it: train a small adapter, export it, load it into vLLM on a machine you control and score it on the held-out set. An adapter is only useful if its base model is available elsewhere, so record the exact base and revision.

Our assessment

Most teams should not start with training. They should start with a baseline, a held-out set and the strongest prompt they can write, and fine-tune only when the gap is behaviour that a check can score. Buy compute by the hour or the token, not lock-in: choose the route where the weights can leave with you, and treat each fine-tune as renewable with the next base model.

Part V — Foundations every fine-tune needs

Part IV ended with what to have before training. This part builds it once, so every Build chapter can lean on the same plumbing: curated data formatted exactly as the model will see it, an evaluator the trainer cannot touch, a trainer, a store for the adapters that come out, and a way to serve them. None of it is clever, and that is the point. Fine-tuning projects that disappoint rarely fail because the optimiser was poor. They fail because the data leaked into the test, nothing compared the result with a baseline, or the artifact could not be loaded anywhere else.

The reference architecture

Reference architecture for a fine-tuning pipelineA data store feeds curation, which feeds the trainer, which logs to an experiment tracker. The tracker passes each candidate to the evaluator, an isolated process with held-out data that the trainer cannot write to. Passing adapters go to the model and adapter registry, then to serving with many adapters on one base model, then to monitoring. Monitoring sends production traces and drift signals back to the data store. Tool names inside the boxes are examples only.the trainer cannot write hereproduction traces and driftbecome the next data roundeach candidateif it passesData storeversioned snapshotsCurationfilter, dedupe, labeldatatrove · distilabelTrainerSFT, LoRA, QLoRATRL · Axolotl · UnslothExperiment trackerconfigs, curves, seedsEvaluatorisolated, held-outlm-eval-harness · InspectRegistryadapters, scores, mergesmergekitServingmany adapters, one basevLLM · SGLangMonitoringquality, drift, costTool names are examples only; none is required.

The figure shows eight parts in a ring. The data store holds versioned snapshots. Curation filters, deduplicates and labels; datatrove (Apache-2.0) does filtering and deduplication at scale, and distilabel generates synthetic data and AI feedback, though it is now held by community maintainers and has had no release since January 2025. The trainer is TRL, Axolotl or Unsloth. Unsloth's licence is split: the library is declared Apache-2.0, but the repository also carries AGPL-3.0 text for its Studio app, so check which directories you redistribute. The experiment tracker records configurations, curves and seeds.

The part to look at is the evaluator, inside the dashed boundary. It is a separate process with its own held-out data, and the trainer has no write access to it. The reason is this review's thesis in miniature: whatever can reach its grader will learn to please it. Inspect (MIT) and lm-evaluation-harness (MIT) supply the machinery; the boundary is a deployment decision no library makes for you. Candidates that pass go to the registry, which stores adapters with their scores and the base model they need, then to serving with many adapters on one base model, using vLLM or SGLang (both Apache-2.0), and to monitoring. Production traces and drift signals flow back to the data store as the next round of data. torchtune and Hugging Face's AutoTrain say in their READMEs that they are no longer maintained, so we do not recommend either.

Data: format, deduplicate, catch leakage

Treat training examples like lessons and test examples like an exam. If the model has already seen the exam, its score does not tell you whether the lesson generalised. Preserve that distinction in every split and source record.

Three jobs come before the first training step. The first is format. A chat model expects a specific template, and training text that differs from what it will see at serving time teaches a task it will never be asked. TRL's SFTTrainer accepts plain text, conversational messages, and prompt-completion pairs, in plain or conversational form; DPO and reward trainers take chosen and rejected; KTO takes prompt, completion and a boolean label. For SFT we prefer conversational prompt-completion, because by default TRL then computes the loss on the completion only, rather than on the system prompt and the user's text. In TRL 1.x the length setting is max_length, trainers take processing_class rather than tokenizer, and the old max_seq_length and PPOTrainer are gone; older tutorials will not run.

The second job is deduplication: repeats are over-weighted, and repeats across the split inflate scores. Lee et al. found that more than 4% of the validation sets of standard datasets overlap their training data. The third is leakage, the harder cousin. Hashes miss near-copies and n-grams miss paraphrases: Yang et al. showed that a 13B model could reach GPT-4-level scores on MMLU, GSM8K and HumanEval if rephrased test data was left in its training set. So treat n-gram overlap as a floor. Split by the unit that could leak, such as customer, document or vendor, not by row, and keep a second, rarer held-out set that is touched only at release.

Format, deduplicate and leak-check a dataset
Time 30 minutes (illustrative)Needs transformers; trl 1.x for training; your base model's tokenizer; two lists of {text, json} rows, one for training and one for held-out
  1. Convert each row to TRL's conversational prompt-completion format.
  2. Normalise text and drop duplicates; normalising catches case, spacing and punctuation variants that exact matching misses.
  3. Compare each held-out row's word 5-grams with every training row and stop if any overlap passes the threshold.
  4. Render the training text and the serving prompt with the base model's own template and assert that the first begins with the second.
import hashlib, re
from transformers import AutoTokenizer

tok = AutoTokenizer.from_pretrained(BASE)      # BASE: your base model id
SYSTEM = "Extract the invoice fields as JSON."

def to_example(r):                              # TRL conversational prompt-completion
    return {"prompt": [{"role": "system", "content": SYSTEM},
                       {"role": "user", "content": r["text"]}],
            "completion": [{"role": "assistant", "content": r["json"]}]}

def norm(t): return re.sub(r"\W+", " ", t.lower()).strip()
def grams(t, n=5):
    w = norm(t).split()
    return {" ".join(w[i:i + n]) for i in range(max(len(w) - n + 1, 1))}

def dedupe(rows):
    seen, out = set(), []
    for r in rows:
        h = hashlib.sha256(norm(r["text"]).encode()).hexdigest()
        if h not in seen:
            seen.add(h); out.append(r)
    return out

def leaked(train, heldout, threshold=0.5):
    index = {}                                  # n-gram -> training rows containing it
    for i, r in enumerate(train):
        for g in grams(r["text"]):
            index.setdefault(g, set()).add(i)
    out = []
    for h in heldout:
        hg = grams(h["text"])
        hits = {}
        for g in hg:
            for i in index.get(g, ()):
                hits[i] = hits.get(i, 0) + 1
        if hg and max(hits.values(), default=0) / len(hg) >= threshold:
            out.append(h)
    return out

train = dedupe(RAW_TRAIN)                       # RAW_TRAIN, RAW_HELDOUT: your rows
assert not leaked(train, RAW_HELDOUT), "held-out rows overlap training data"
ex = to_example(train[0])
served = tok.apply_chat_template(ex["prompt"], tokenize=False, add_generation_prompt=True)
trained = tok.apply_chat_template(ex["prompt"] + ex["completion"], tokenize=False)
assert trained.startswith(served), "training text does not begin with the serving prompt"
# reasoning templates (e.g. with <think> blocks) can fail this check falsely; then compare the
# token ids up to the assistant turn, or inspect which labels are masked in a collated batch
  1. Check it: on three invented invoice rows, two of them identical apart from case and punctuation, dedupe returned two rows; copying a training row into the held-out list made leaked return it. An n-gram check catches copies and near-copies only; rephrased test items get past it, so for the held-out set also compare embeddings or sample pairs by hand, and split by customer or entity, not only by template. Then pass the examples to SFTTrainer with SFTConfig(max_length=2048) and processing_class=tok.

The snippet was executed with the Qwen2.5-0.5B-Instruct tokenizer on invented rows, and the SFTConfig fields it mentions (max_length, assistant_only_loss, completion_only_loss) were checked against TRL 1.17.1; no training was run. The matching notebook is lab 02, data curation and leakage. One limit to keep in mind: this catches overlap you can see, and cannot tell whether the base model already saw your test set in pretraining. GSM1k showed some models dropping by up to 8% on a freshly written set of the same kind, so write new held-out examples where you can.

Evaluation: baseline, held-out, regression, format

A parser that produces valid JSON but assigns the wrong total has failed the business task. A parser that gets the invoice right but loses a required behaviour has also failed a release requirement. Measure the two separately, rather than hiding either in an average.

The harness has four jobs. The baseline is the untuned base model, scored by the same code on the same examples with your best prompt (lab 01, GPU, tokens and a baseline). The held-out set is scored only by the evaluator and never used to choose hyperparameters. The regression set holds behaviour that must survive: what the base already does right, general capability and safety refusals, since narrow training can cause broad drift that measuring only the target will not show. And format validity is scored on its own, because output that does not parse and output that parses but is wrong have different fixes.

Use two tools for two questions. Inspect scores your product behaviour, with your own scorer. lm-evaluation-harness checks general ability on standard benchmarks, which is a regression check and not a product evaluation. The gate then has three clauses: the tuned model beats the baseline on the held-out set by more than the standard error; it falls by no more than a stated tolerance on the regression set; and its validity rate is at least what the product needs. A few dozen examples cannot show a three-point gain, so size the set from the standard error the scorer reports. Label failures by type, as lab 18 does (regression suite and error taxonomy): the taxonomy tells you whether the next move is more data, another method or a prompt change.

Score base and tuned model on the same held-out and regression sets
Time 30 minutes (illustrative)Needs inspect-ai 0.3.x; two JSONL files with input and target fields, kept where the trainer cannot write; Inspect model strings for the base and the candidate
  1. Write a scorer that reports validity and correctness as separate numbers.
  2. Run the identical tasks against both models and print the means.
  3. Compare the numbers against the gate: gain beyond noise, regression within tolerance, validity at the required level. Both models answer the same items, so judge the gain on paired differences (the standard error of per-item score differences, or McNemar's test for pass/fail), not by comparing each model's separate error bars, which overstates the noise.
import json
from inspect_ai import Task, eval
from inspect_ai.dataset import json_dataset
from inspect_ai.scorer import Score, Target, mean, scorer, stderr
from inspect_ai.solver import TaskState, generate

@scorer(metrics={"valid_json": [mean(), stderr()], "fields_match": [mean(), stderr()]})
def invoice_scorer():
    async def score(state: TaskState, target: Target) -> Score:
        try:
            got = json.loads(state.output.completion)
        except json.JSONDecodeError:
            return Score(value={"valid_json": 0, "fields_match": 0}, answer=state.output.completion)
        ok = isinstance(got, dict) and got == json.loads(target.text)
        return Score(value={"valid_json": 1, "fields_match": int(ok)}, answer=state.output.completion)
    return score

def suite(path: str, name: str) -> Task:
    return Task(dataset=json_dataset(path), solver=generate(), scorer=invoice_scorer(), name=name)

# MODELS: Inspect model strings for the untuned base and the tuned candidate (both yours)
for label, model in MODELS.items():
    for name, path in {"heldout": "/srv/eval/heldout.jsonl", "regression": "/srv/eval/regression.jsonl"}.items():
        log = eval(suite(path, name), model=model, log_dir=f"/srv/eval/logs/{label}", display="none")[0]
        print(label, name, {s.name: round(s.metrics["mean"].value, 3) for s in log.results.scores})
  1. For general ability, run the standard benchmark with and without the adapter: lm-eval run --model hf --model_args pretrained=$BASE,peft=out/invoice-lora-v3 --tasks hellaswag --limit 200 --output_path out/lm-eval, then the same without peft=. A --limit sample is noisy; use it to catch collapses, not small changes.
  2. Check it: with Inspect's mockllm/model, a mock returning prose scored 0.0 on both numbers, and one returning valid JSON with a missing field on half the rows scored 1.0 for validity and 0.5 for correctness.

The Inspect code was run against inspect-ai 0.3.288 with the mock model, and the lm-eval flags and the peft model argument were confirmed on lm_eval 0.4.13; no real model was called. The mock proves the scorer separates the two failure types, not that your model behaves. Put safety in the regression set too: a few hundred refusal and misuse prompts, scored for base and tuned model alike, since the losses in Qi et al. arrived with benign data.

Adapters: save, merge, serve many

A LoRA fine-tune produces a small file next to a model you already have. In the LoRA paper's example the adapter checkpoint for GPT-3 175B was about 35 MB against 350 GB, so an adapter can be versioned, stored and shipped like code. Its adapter_config.json names the base model, which makes the base model part of the artifact: an adapter is meaningless without the exact base it was trained on. Record the revision, not only the name.

At serving time there are two designs. Merge the adapter into the base to get an ordinary model with no extra latency, which suits one tenant and one task. Serve many by keeping one base in memory and selecting an adapter per request, which suits many tasks or customers. S-LoRA reported up to 2,000 adapters on a single GPU, and Predibase's LoRAX served 25 Mistral-7B adapters on one A100 (vendor benchmark of its own server). In vLLM, --enable-lora turns it on, each adapter is registered by name, and the request's model field picks it. The server's documentation recommends setting --max-lora-rank to the largest rank among your adapters (64 for adapters of rank 16, 32 and 64) and calls 256 unnecessarily high in that case, and warns that loading adapters at runtime is a security risk outside a trusted environment.

Save an adapter, merge it, check the merge, serve it beside others
Time 30 minutes (illustrative)Needs peft 0.21.x; transformers; a trained PeftModel; vllm on a CUDA machine for the serving step
  1. Save the adapter on its own after training.
  2. Reload the base in 16-bit, even if you trained against a 4-bit copy, attach the adapter and call merge_and_unload. Merging into the 16-bit copy is our practice, not a documented requirement; rounding in a 4-bit copy is what we are avoiding. The adapter was trained against the dequantised 4-bit weights, so adding it to the original 16-bit weights is an approximation, which is why the next step checks the merged model against the unmerged one.
  3. Compare logits of the adapter and the merged model on a probe prompt.
import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM

BASE = "your-base-model-id"                  # the exact base the adapter was trained on
ADAPTER_DIR, MERGED_DIR = "out/invoice-lora-v3", "out/invoice-merged-v3"

trained.save_pretrained(ADAPTER_DIR)         # trained: the PeftModel; writes adapter_config.json + weights

base = AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16)
merged = PeftModel.from_pretrained(base, ADAPTER_DIR).merge_and_unload()
merged.save_pretrained(MERGED_DIR)           # a plain model; loading it needs no peft

ids = torch.tensor([PROBE_TOKEN_IDS])        # tokenised probe prompt
ref = PeftModel.from_pretrained(AutoModelForCausalLM.from_pretrained(BASE, dtype=torch.bfloat16), ADAPTER_DIR)
with torch.no_grad():
    print("max logit difference:", (ref(ids).logits - merged(ids).logits).abs().max().item())
  1. To serve several adapters on one base, start vLLM once and name each adapter:
vllm serve $BASE --enable-lora --max-lora-rank 16 \
    --lora-modules invoice=out/invoice-lora-v3 support=out/support-lora-v1
# each request picks one with "model": "invoice"; GET /v1/models lists the base and both adapters
  1. Check it: on a tiny randomly initialised Llama model with a non-trivial rank-4 adapter, the saved adapter folder held adapter_config.json and adapter_model.safetensors, the merged folder was a plain model, and the largest logit difference was 0.0022, which is bf16 rounding.

The PEFT half ran on a small random model on a CPU. The vLLM command is copied from the project's LoRA documentation (flags --enable-lora, --lora-modules, --max-lora-rank) and was not run, because it needs a GPU and a real model. The matching notebook is lab 19, adapter save, merge and portability. If you want to combine adapters or whole fine-tuned models, mergekit (LGPL-3.0, pre-1.0) and PEFT's add_weighted_adapter implement TIES and DARE, but the evidence that merged models match separately served ones is mostly leaderboard-level and abstract-level so far. Treat a merge as a candidate that must pass the same gate as any other. The same holds for post-training quantisation: serving the merged model in FP8, AWQ or GPTQ adds a second approximation on top of the merge, and the two errors compound, so run the evaluation gate on the quantised artefact you will actually serve, not on the 16-bit merge.

Where the memory goes

GPU memory anatomy for fine-tuning a 7B model (illustrative accounting)Stacked bars of GPU memory in gigabytes, from standard bytes-per-parameter accounting for a 7 billion parameter model. Full fine-tuning: weights 14, gradients 14, optimiser states 56, activations 10, about 94 gigabytes in total. LoRA: weights 14, gradients 0.1, optimiser states 0.3, activations 10, about 24 gigabytes. QLoRA: weights 3.5, gradients 0.1, optimiser states 0.3, activations 10, about 14 gigabytes. Activations vary with batch size, sequence length and checkpointing.Illustrative accounting for a 7B modelGB, bf16 weights and gradients (2 bytes per parameter), two 32-bit Adam states (8 bytes), 4-bit base 0.5 bytesWeightsGradientsOptimiser statesActivations020406080100Full fine-tuning16-bit weights, Adam14145610~94 GBLoRA16-bit frozen base1410~24 GBgradients 0.1 + optimiser 0.3 GB for about 40M adapter parametersQLoRA4-bit frozen base10~14 GB4-bit weights 3.5 + gradients 0.1 + optimiser 0.3 GB for about 40M adapter parametersIllustrative, not measured. Activations (10 GB here) depend on batch size, sequence length and checkpointing.

The figure is an accounting, not a measurement. Weights in 16-bit cost 2 bytes per parameter, so a 7B model takes 14 GB. Training adds one gradient per trainable parameter, another 14 GB if all are trainable, and the Adam optimiser keeps two 32-bit numbers per parameter, 8 bytes, or 56 GB. Add about 10 GB of activations and full fine-tuning lands near 94 GB. The same rule gives roughly 12 bytes per parameter for weights, gradients and optimiser together, which matches the QLoRA paper's figure of more than 780 GB for a 65B model in 16-bit (65 billion times 12 bytes).

LoRA freezes the base, so gradients and optimiser states exist only for the adapter: about 40M trainable parameters add well under a gigabyte, and the total falls to roughly 24 GB. QLoRA also stores the frozen base in 4 bits, 3.5 GB, which gets the total to about 14 GB. The QLoRA paper fine-tuned a 65B model on a single 48 GB GPU, and Answer.AI reported 70B on two 24 GB GPUs with FSDP and QLoRA. The lesson of the bars is that each step moves the bottleneck. Full fine-tuning is dominated by optimiser state. LoRA removes that and leaves the frozen weights. QLoRA shrinks those, and what remains, activations, depends on batch size, sequence length and gradient checkpointing, not on the method. At QLoRA's level most of the memory is activations, so sequence length is the next lever, and a 16 GB T4, the class of GPU the lab notebooks assume, has little headroom for a 7B run on this accounting. Measure your own peak with torch.cuda.max_memory_allocated() after a few steps; the figure leaves out the 32-bit master weights that some mixed-precision setups keep and the small quantisation constants, so it will read low.

Data rights and evaluation integrity
  • Provenance. Every training example has a recorded source, date and licence, and nothing is in the set because it was easy to scrape.
  • Terms on model outputs. If a teacher model wrote any of the data, its terms allow that use. Anthropic's commercial terms, in the June 2025 version we read, bar using the service to train competing models; the Llama 3.1 licence requires "Llama" at the start of the name of a model improved with its outputs; and the Stanford Alpaca repository lists a non-commercial licence. Open-weight teachers with permissive licences are the safer source.
  • Personal and client data. Anything personal or confidential is removed or lawfully covered before training, because a model can reproduce what it saw.
  • Split by unit. Train and held-out data are divided by customer, document or vendor, not by random row.
  • Overlap checked. Exact and near-duplicate overlap between train and held-out was measured and is zero or explained; paraphrase leakage is treated as unmeasured.
  • Held-out is untouched. Nothing about the held-out set, including its scores, was used to choose hyperparameters, data or checkpoints. A rarer release set exists beside it.
  • Same harness for baseline and candidate. Same prompts, decoding settings and scorer, with the base given its best prompt.
  • Regression and safety measured. Behaviour that must survive, including refusals, is scored before and after.
  • Memorisation probed. Unique canary strings planted in the training data are not reproduced by the tuned model, and sampled training records cannot be extracted verbatim from a prefix.
  • Everything versioned. Data snapshot, base revision, configuration, seed and adapter hash are recorded with each score.

Part VI — Build each method

Each chapter below builds one of the six methods from Part II and mirrors the Understand chapter with the same number. All six follow the same template: when to use the method, its architecture, the tools that implement it today, a recipe with code, how to evaluate and gate the result, what it costs in money and GPU memory, how it fails, and a checklist. Tools and their status were verified against their repositories and package indexes in November 2026, and the code matches each library's current interface; it is a starting point, not production code. Each chapter names the matching lab from the twenty teaching notebooks listed in Part VIII. Costs are illustrative unless attributed.

B1. Supervised fine-tuning

Mirrors U1 · Supervised fine-tuning and instruction data in the Understand half.

When to use it

When to use it. Use supervised fine-tuning when you can show the model what a good answer looks like, in volume, and can score an answer without asking a person. The natural fits are the ones U1 placed on the behaviour side of the line: a fixed output format, a house style, a routing label, a tool-call shape. If the failure is "the model does not know our price list", retrieval is the cheaper first move. Gekhman and colleagues found that fine-tuning on facts a model did not already know was learned slowly and raised hallucination.

If all you need is syntactically valid output, constrained decoding enforces a grammar at inference time and needs no training. Fine-tuning earns its place when the fields must also be right, when you do not control the serving stack, or when you want to retire a long prompt. That is our judgement, and the held-out test below is how you check it for your task.

There is no minimum dataset size. The reference points span three orders of magnitude: LIMA used 1,000 curated pairs and was judged by human raters on preference against other models, Llama 2 used 27,540 of its own annotations, and Tulu 3 used 939,344 examples in its SFT stage. For a narrow format task, a few hundred to a few thousand clean examples is a sensible start. Treat that as a starting estimate and plot score against 250, 500, 1,000 and 2,000 examples on your own held-out set before buying more data.

Architecture

B1 · Supervised fine-tuningB1 · Supervised fine-tuning: 1. Collect (real inputs, checked outputs); 2. Format (prompt and completion, one template); 3. Train (loss on the completion only); 4. Evaluate (held-out, strict parser); 5. Gate (thresholds frozen in advance). Then back to step 1: Failures return to collection as new training examples, never to the held-out set.B1 · Supervised fine-tuningCollectreal inputs,checked outputsFormatprompt andcompletion, onetemplateTrainloss on thecompletion onlyEvaluateheld-out, strictparserGatethresholds frozenin advance↺ Failures return to collection as new training examples, never to the held-out set
Only the evaluate step can say the model improved. The other four exist to make that step honest.

The pipeline is short; the care goes into what each step may touch. Collect inputs that look like production inputs, and take outputs from a source that has already been checked, such as records your system validated, in preference to text a model wrote. If a stronger model writes them, run them through the same validator and read B5 for the licence questions. Format with one serialisation and the chat template of the model you will serve; a template mismatch between training and serving costs quality without raising an error. Train with loss on the completion only, so the model learns to produce answers rather than to echo prompts. Evaluate on examples that share no source or template with the training set. Gate against thresholds written before the first run.

Tools

Four open-source stacks run this loop. They differ in how you drive them, not in the maths. We leave torchtune out: its README says development wound down in 2025.

TRLActive
Trainers
Hugging Face's post-training library, now on a v1 line. You pass a model id, a dataset and optionally a PEFT config. Version 1.17.1 on PyPI at 30 October 2026. Tutorials that use tokenizer= or max_seq_length= fail on a current install.
Licence: Apache-2.0Implements: SFTTrainer (no single paper)
AxolotlActive
Config-driven trainers
One YAML file describes model, data and training, and axolotl train runs it. Version 0.21.1 on 27 October 2026; the README asks for Python 3.12 or later and PyTorch 2.13 or later. The organisation was renamed from OpenAccess-AI-Collective.
Licence: Apache-2.0Implements: YAML-driven SFT, LoRA and QLoRA
LLaMA-FactoryActive
Config-driven trainers
Command line and web UI for more than 100 models. The PyPI release, 0.9.5, dates from 30 May 2026 and trails the main branch by five months; its README installs from source.
Licence: Apache-2.0Implements: arXiv 2403.13372
UnslothActive
Optimised kernels
Faster LoRA, QLoRA and full training on one GPU, usable with TRL's trainers. The vendor claims 2x speed and 70% less memory; we did not verify that. Version 2026.11.3 on 6 November 2026.
Licence: Apache-2.0 core; AGPL-3.0 Studio and Desktop (check per directory)Implements: Kernel engineering, no paper

Our choice for a first run is TRL, because the trainer sits inside your own Python and you can read it when something misbehaves. Pick Axolotl or LLaMA-Factory when you want a config file that records the run and a team that does not write training code. Pick Unsloth when one GPU is the constraint and you have read its licence. The recipe below uses TRL 1.17.1.

Recipe

Fine-tune a small model for reliable JSON output
Time an afternoon, plus about an hour of GPU timeNeeds a few thousand checked pairs of text and JSON, one GPU, trl 1.17.1, peft 0.21.2, jsonschema

The task, invented for illustration: read a one-line delivery note and return order_id, status and eta_days as JSON, with nothing else around it. The check is a schema, and a second check compares the values with the gold answer.

1. Write the checker first. Parsing alone is not enough. The scorer separates "parses", "matches the schema" and "has the right values", because a model can be perfect on the first two and wrong on the third.

import json
from jsonschema import Draft202012Validator

SCHEMA = {
    "type": "object",
    "properties": {
        "order_id": {"type": "string", "pattern": "^[A-Z]{2}-[0-9]{6}$"},
        "status": {"enum": ["delivered", "delayed", "lost", "returned"]},
        "eta_days": {"type": ["integer", "null"], "minimum": 0},
    },
    "required": ["order_id", "status", "eta_days"],
    "additionalProperties": False,
}
CHECK = Draft202012Validator(SCHEMA)

def score(output: str, gold: dict) -> dict:
    try:
        obj = json.loads(output)          # the whole output must be JSON: no fences, no chatter
    except json.JSONDecodeError:
        return {"parses": 0, "valid": 0, "exact": 0}
    valid = CHECK.is_valid(obj)
    return {"parses": 1, "valid": int(valid), "exact": int(valid and obj == gold)}

2. Format and split. Use the prompt-and-completion layout; TRL then masks the prompt out of the loss without being told. In a smoke test on 1.17.1 with eight rows, 71 of the 96 label positions in the first row were masked (prompt and padding). Split by template, not by row, and drop exact duplicates before the split. For multi-turn or tool-use data, use the conversational format with assistant_only_loss=True so that user turns and tool outputs are masked and only the assistant's turns are trained; check the masks on one collated batch.

INSTRUCTION = ("Extract the delivery facts as one JSON object with keys "
               "order_id, status, eta_days. Output JSON only.\n\nNote: ")

def to_row(ex: dict) -> dict:        # ex: {"note", "gold", "template"}
    return {
        "prompt": [{"role": "user", "content": INSTRUCTION + ex["note"]}],
        "completion": [{"role": "assistant",
                        "content": json.dumps(ex["gold"], separators=(",", ":"))}],
    }

def split_by_template(examples, held_out_templates):
    seen, train, held = set(), [], []
    for ex in examples:
        key = ex["note"].strip().lower()
        if key in seen:
            continue                  # an exact duplicate must not straddle the split
        seen.add(key)
        (held if ex["template"] in held_out_templates else train).append(ex)
    return train, held

3. Measure the baseline. Greedy decoding is deterministic, so the untuned model needs one pass. Record the failures, not only the rate. In our one-step smoke run the 0.5B instruct model wrapped its JSON in a code fence, which this strict parser rejects.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

BASE = "Qwen/Qwen2.5-0.5B-Instruct"       # an example small model: swap in yours

def load(path, dtype=torch.bfloat16):    # T4 (Turing) lacks native bf16 support: use torch.float16
    tok = AutoTokenizer.from_pretrained(BASE)
    model = AutoModelForCausalLM.from_pretrained(path, dtype=dtype, device_map="auto")
    return model.eval(), tok

@torch.no_grad()
def generate(model, tok, note: str) -> str:
    msgs = [{"role": "user", "content": INSTRUCTION + note}]
    ids = tok.apply_chat_template(msgs, add_generation_prompt=True,
                                  return_tensors="pt", return_dict=True).to(model.device)
    out = model.generate(**ids, max_new_tokens=96, do_sample=False)
    return tok.decode(out[0, ids["input_ids"].shape[1]:], skip_special_tokens=True)

def evaluate(model, tok, held):
    rows = [score(generate(model, tok, ex["note"]), ex["gold"]) for ex in held]
    return {k: sum(r[k] for r in rows) / len(rows) for k in rows[0]}

4. Train with LoRA. Passing the model as a string makes TRL load it, and TRL then defaults the dtype to float32, so set it. The learning rate is a LoRA value, ten times the full-fine-tuning default in SFTConfig; B2 explains why.

from datasets import Dataset
from peft import LoraConfig
from trl import SFTConfig, SFTTrainer

def train(train_rows, out_dir="out/json-lora", seed=0):
    cfg = SFTConfig(output_dir=out_dir, max_length=512, num_train_epochs=2,
                    learning_rate=2e-4, per_device_train_batch_size=8,
                    gradient_accumulation_steps=2, seed=seed, report_to="none",
                    model_init_kwargs={"dtype": torch.bfloat16})
    lora = LoraConfig(r=16, lora_alpha=32, lora_dropout=0.05,
                      target_modules="all-linear", task_type="CAUSAL_LM")
    trainer = SFTTrainer(model=BASE, args=cfg, peft_config=lora,
                         train_dataset=Dataset.from_list([to_row(e) for e in train_rows]))
    trainer.train()
    trainer.save_model(out_dir)       # saves the adapter, not the full model
    return out_dir

5. Evaluate and gate. Load the base, attach the adapter, score the held-out set, and apply thresholds that were written down before step 4. The numbers below are placeholders.

from peft import PeftModel

GATE = {"valid_min": 0.98, "exact_gain_min": 0.05, "regression_drop_max": 0.02}  # illustrative

def passes_gate(base, tuned, regress_base, regress_tuned) -> bool:
    return (tuned["valid"] >= GATE["valid_min"]
            and tuned["exact"] - base["exact"] >= GATE["exact_gain_min"]
            and regress_base - regress_tuned <= GATE["regression_drop_max"])

model, tok = load(BASE)
tuned = PeftModel.from_pretrained(model, "out/json-lora").eval()
print(evaluate(tuned, tok, held_out))      # compare with the step 3 baseline

We ran steps 2 to 4 for one step on CPU against the real library to confirm the interfaces. We did not train to convergence or measure any quality gain, so no result is claimed.

Evaluation and gate

Three numbers decide the run. Schema-valid rate tells you whether the format problem is solved. Exact-match rate on held-out values tells you whether the model is right, which the schema cannot. A regression set of general prompts and a handful of safety probes tells you what the narrow data cost. The last matters more than it looks: Qi and colleagues broke GPT-3.5 Turbo's guardrails with ten adversarial examples, and fine-tuning on benign Alpaca data alone raised its harmfulness rate from 5.5% to 31.8% on their GPT-4-judged measure. Lab 18 builds such a suite.

Noise comes from training, not decoding. Repeat the winning configuration with two more seeds, and report failures as counts: on 300 held-out items, one point is three examples. The gate is a file the training script cannot write, with thresholds fixed before the run. When it fails, read the failing outputs, sort them into a short error taxonomy, and add examples for the dominant class; adding more of what already works is the usual wasted effort.

Cost, GPU memory and operations

Illustrative arithmetic: 3,000 examples of about 200 tokens, two epochs, is 1.2 million training tokens. At the managed LoRA prices listed in November 2026, $0.50 per million tokens for models up to 16B on Fireworks and $0.34 for Llama 3.1 8B on Together, that is roughly $0.60 or $0.41, if the vendor bills across epochs. Self-hosted, the cost is the GPU hour and the afternoon you spend on the checker. The checker is the expensive part either way.

Memory depends on the method. Full fine-tuning keeps weights, gradients and optimiser state; LoRA keeps only the adapters' share of the last two. B2 gives the figures, and Part IV's cost and memory figure shows the comparison across methods. Operationally, store the adapter with the exact base revision, tokeniser and chat template it was trained with, plus the data version, seed and score. An adapter is meaningless without its base.

Failure drills

Valid, wrong
What happens
A schema proves shape. The model learns the shape quickly and can stay wrong on content, so a validity score near 100% can sit on top of a poor product.
Real case
Every output matches the schema; half the eta_days values are copied from the example in the prompt.
Guard
Score values against gold, not just structure; report exact-match beside validity.
Loss on the wrong tokens
What happens
The run converges and the served model behaves worse than the notebook, or learns to repeat inputs. Detect it by decoding a training batch and its labels.
Real case
Training used a different chat template from serving, or the loss included the prompt.
Guard
One template, saved with the checkpoint; check the label mask on a batch before training.
Narrow data, broad damage
What happens
Narrow fine-tuning can shift behaviour well outside the task. Detect it only by measuring outside the task.
Real case
After tuning on delivery notes, the model stops refusing an unsafe request it refused before.
Guard
Run the regression and safety probes before and after; mix in general data if they drop.
Before you train
  • The checker exists, rejects a fenced or chatty answer, and scores values as well as structure.
  • The held-out set shares no template, source or near-duplicate with training data.
  • The baseline is measured with the final prompt, and failures are saved, not only rates.
  • Prompt and completion layout is used, and a decoded batch shows the prompt masked.
  • The chat template is the one that will be served and is stored with the checkpoint.
  • Thresholds for validity, accuracy gain and regression drop are written before the run.
  • A regression set and a few safety probes run before and after, and the winner is repeated with other seeds.

Matching labs: 03 (full-parameter SFT), 04 (LoRA SFT) and 07 (reliable JSON outputs) work through this chapter, with 02 (data curation and leakage) and 18 (regression suite and error taxonomy) covering the data and the gate. The notebooks are not hosted yet.

B2. LoRA and QLoRA

Mirrors U2 · Parameter-efficient fine-tuning in the Understand half.

When to use it

When to use it. Use LoRA when a full fine-tune does not fit your GPU or your storage budget, and the job is the size of an SFT job. The memory case is large. In the LoRA paper's GPT-3 175B comparison, training memory fell from 1.2 TB to 350 GB and the checkpoint from 350 GB to 35 MB. QLoRA put a 65B model on one 48 GB GPU, against more than 780 GB for 16-bit full fine-tuning, and Answer.AI trained a 70B model on two 24 GB GPUs.

The quality case is narrower than the folklore. Thinking Machines found LoRA matched full fine-tuning on small and medium instruction and reasoning sets, and lagged once the data outgrew the adapter's capacity. Biderman and colleagues found the same split: on code instruction tuning, rank 256 reached 0.498 (at epoch 4) against 0.497 for full fine-tuning (at epoch 8), while on continued pretraining at 20B tokens LoRA reached 0.224 against 0.263 on HumanEval. Use LoRA for behaviour and skills; reach for full fine-tuning or B6 when you must absorb billions of tokens. Use QLoRA only when the 16-bit model does not fit. It buys memory with step time and one more thing to debug.

Architecture

B2 · LoRA and QLoRAB2 · LoRA and QLoRA: 1. Load 4-bit base (NF4, frozen); 2. Attach adapters (all linear layers, rank r); 3. Train (adapters only, paged optimiser); 4. Evaluate (held-out and regression); 5. Merge or serve (16-bit merge, or one adapter per request). Then back to step 1: A failed gate changes data or learning rate first and rank last.B2 · LoRA and QLoRALoad 4-bitbaseNF4, frozenAttachadaptersall linearlayers, rank rTrainadapters only,paged optimiserEvaluateheld-out andregressionMerge orserve16-bit merge, orone adapter perrequest↺ A failed gate changes data or learning rate first and rank last
Only the small adapter matrices receive gradients. The quantised base is read as needed and never changed.

U2 shows the mechanism; here is the build view. The base weight matrix W stays frozen, and training learns a low-rank update BA scaled by alpha divided by r. QLoRA stores W in 4 bits using the NormalFloat type, adds double quantisation to shrink the quantisation constants (about 0.37 bits per parameter, roughly 3 GB for 65B), and uses paged optimisers to survive memory spikes. Apply adapters to every linear layer. The QLoRA paper needed that to match full fine-tuning, and Thinking Machines measured attention-only rank 256 (0.25B parameters) behind MLP-only rank 128 (0.24B).

Merging is where QLoRA diverges. The adapters were trained against 4-bit weights, so merge them into a 16-bit copy of the base and test the result. PEFT's own notes show that merging depends on the quantisation format: AQLM adapters cannot be merged, and torchao merges correctly only for int8 weight-only.

Tools

PEFTActive
Adapters
Hugging Face's adapter library, version 0.21.2 on 1 October 2026. LoraConfig defaults to rank 8 and alpha 8; merge_and_unload() folds an adapter into its base.
Licence: Apache-2.0Implements: LoRA (arXiv 2106.09685); DoRA, rsLoRA, PiSSA options
bitsandbytesActive
Quantisation
4-bit and 8-bit quantisation and 8-bit optimisers, reached through Transformers' BitsAndBytesConfig. Version 0.50.2 on 27 August 2026. It now lives under a foundation organisation, not a personal repository.
Licence: MITImplements: LLM.int8() (arXiv 2208.07339); QLoRA NF4 (arXiv 2305.14314)
UnslothActive
Optimised kernels
Wraps loading and adapter attachment for faster QLoRA on one GPU. Its 2x-faster, 70%-less-memory claim is the vendor's own. The licence is split, so confirm the directories you redistribute.
Licence: Apache-2.0 core; AGPL-3.0 Studio and Desktop (check per directory)Implements: Kernel engineering, no paper

PEFT and bitsandbytes are the default pair, and they are what the recipe uses. bitsandbytes is not the only 4-bit route: Axolotl lists NVFP4 and MXFP4 LoRA paths that avoid it. Treat adapter variants such as DoRA, rsLoRA and PiSSA as a later experiment. Their authors report gains of a few points under their own protocols, and Thinking Machines found learning rate and layer coverage matter more. Fix those first.

Recipe

QLoRA on one GPU, then an honest rank and learning-rate sweep
Time an evening for the sweepNeeds one GPU with 16 GB or more, trl 1.17.1, peft 0.21.2, bitsandbytes 0.50.2, and the data, score and evaluate functions from B1

1. Configure the quantised run. In TRL 1.17.1 the trainer takes quantization_config and peft_config directly. We did not call prepare_model_for_kbit_training; TRL's source does not reference it, and we did not run a quantised job, so watch the first steps. TRL casts trainable adapter weights to bfloat16 when the base is quantised, and a T4 has no native bfloat16, so labs 05 and 06 may need a newer GPU or run slowly.

import torch
from datasets import Dataset
from peft import LoraConfig
from transformers import BitsAndBytesConfig
from trl import SFTConfig, SFTTrainer

BNB = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_type="nf4",
                         bnb_4bit_use_double_quant=True,
                         bnb_4bit_compute_dtype=torch.bfloat16)   # float16 on a T4

def make_cfg(out_dir, lr, seed):
    return SFTConfig(output_dir=out_dir, max_length=512, num_train_epochs=2,
                     learning_rate=lr, lr_scheduler_type="cosine", warmup_steps=0.03,
                     per_device_train_batch_size=8, gradient_accumulation_steps=2,
                     optim="paged_adamw_8bit", eval_strategy="epoch", seed=seed,
                     report_to="none", model_init_kwargs={"dtype": torch.bfloat16})

def make_lora(rank):
    # alpha = 2 * rank keeps the scale alpha/r constant, so ranks compare at the same effective
    # step size (use_rslora=True is the alternative); report the convention with every result
    return LoraConfig(r=rank, lora_alpha=2 * rank, lora_dropout=0.05,
                      target_modules="all-linear", task_type="CAUSAL_LM")

2. Sweep in stages, selecting on a dev set. SFTConfig defaults to a learning rate of 2e-5, a full-fine-tuning value. Thinking Machines found the best full-fine-tuning rate about ten times lower than the best rate for high-rank LoRA, and that the best LoRA rate moved by less than a factor of two between ranks 4 and 512. Biderman's best LoRA rates (5e-4 on code, 2e-4 on maths) were 10 and 20 times their full-fine-tuning rates (5e-5 and 1e-5). So sweep the rate first at a fixed rank, then the rank at the best rate. Select on a dev set; open the test set once, at the end.

import gc, json

def run_one(rank, lr, seed, train_ds, dev_ds, dev_ex):
    trainer = SFTTrainer(model=BASE, args=make_cfg(f"runs/r{rank}-lr{lr:g}-s{seed}", lr, seed),
                         train_dataset=train_ds, eval_dataset=dev_ds,
                         quantization_config=BNB, peft_config=make_lora(rank))
    trainer.train()
    model = trainer.model.eval()
    result = {"rank": rank, "lr": lr, "seed": seed,
              "eval_loss": trainer.evaluate()["eval_loss"],
              **evaluate(model, trainer.processing_class, dev_ex)}
    trainer.save_model(f"runs/r{rank}-lr{lr:g}-s{seed}/adapter")
    del trainer, model
    gc.collect(); torch.cuda.empty_cache()
    return result

def sweep(grid, train_ds, dev_ds, dev_ex, path="sweep.jsonl"):
    with open(path, "a") as f:
        for rank, lr, seed in grid:
            f.write(json.dumps(run_one(rank, lr, seed, train_ds, dev_ds, dev_ex)) + "\n")

LRS, RANKS, SEEDS = [5e-5, 2e-4, 1e-3], [8, 32, 128], [0, 1, 2]
stage1 = [(16, lr, 0) for lr in LRS]                  # rate first, rank fixed
# stage2 = [(r, best_lr, 0) for r in RANKS]           # then rank at the best rate
# stage3 = [(best_r, best_lr, s) for s in SEEDS]      # then seeds, to measure the spread

3. Read the sweep honestly. Rank by exact on the dev set, not by eval_loss, which can improve while outputs do not. A difference smaller than the spread across the three seeds is a tie, and in a tie take the smaller rank. If the best learning rate sits at the edge of your grid, extend the grid. Then evaluate the winner on the test set once.

4. Merge into 16-bit and check parity. Compare greedy outputs before and after the merge. Rounding can flip a rare token, so read any difference and score the merged model again before shipping it.

from peft import PeftModel

def merge_and_check(adapter_dir, out_dir, probes):
    base, tok = load(BASE, dtype=torch.bfloat16)       # a 16-bit copy, not the 4-bit base
    model = PeftModel.from_pretrained(base, adapter_dir).eval()
    before = [generate(model, tok, p) for p in probes]
    merged = model.merge_and_unload().eval()
    after = [generate(merged, tok, p) for p in probes]
    same = sum(a == b for a, b in zip(before, after))
    print(f"{same}/{len(probes)} greedy outputs identical after the merge")
    merged.save_pretrained(out_dir)
    tok.save_pretrained(out_dir)
    return same / len(probes)

We checked the constructors and options against the installed packages, and ran the adapter-save, load and merge path for one step on CPU. We did not run a quantised job (it needs a CUDA GPU) or the sweep, so no sweep result is reported. Thinking Machines' finding comes from a vendor blog, not a peer-reviewed paper, and the vendor sells a LoRA-only training service.

Evaluation and gate

Compare four rows on the same test set: the untuned base, the QLoRA adapter, the merged model, and, if you can afford it, the full fine-tune from lab 03. If the adapter trails full fine-tuning by more than the seed spread, data volume is the first suspect, since Thinking Machines saw the gap open when data outgrew capacity. Raising rank is the second thing to try, not the first.

Add two checks specific to adapters. The first is merge parity, above. The second is the regression set from B1: Shuttleworth and colleagues found LoRA adds "intruder dimensions" that full fine-tuning does not, and that forgetting concentrates in them, so a LoRA model can still lose base ability. The gate is the same shape as before, thresholds fixed in advance, with one more condition: the adapter loads on the exact base revision you will serve.

Cost, GPU memory and operations

Rank is a storage and serving cost, not a quality dial you turn freely. Illustrative arithmetic on a Llama-2-7B shape (hidden size 4,096, intermediate size 11,008, 32 layers): rank 16 on every linear layer is about 40 million trainable parameters, 0.6% of the model, roughly 80 MB in bfloat16. Rank 128 is eight times that, about 320 million parameters. Adapter size scales linearly with rank.

For serving, merged weights add no latency. Separate adapters let one base serve many tenants. vLLM selects an adapter per request through the model field, with max_loras and max_lora_rank settings; its docs use 64 for adapters of rank 16 to 64 and warn that 256 wastes memory. Runtime adapter loading needs VLLM_ALLOW_RUNTIME_LORA_UPDATING=True, and the docs flag it as a security risk outside trusted, isolated deployments. S-LoRA reported up to 2,000 adapters on one GPU in 2023, against 2023 baselines.

Training time is the quantised run's other price: expect to pay in step time for dequantisation. That is our expectation, not a measurement; lab 05 against lab 04 would give the number. At managed rates, LoRA work on a model of up to 16B parameters was $0.50 per million tokens on Fireworks in November 2026, and full-parameter training was twice that at each tier.

Failure drills

Full-fine-tuning learning rate
What happens
The run looks healthy and learns little. Detect it by comparing outputs with the base. A flat score plus a smooth loss curve is the signature.
Real case
LoRA trained at 2e-5, the SFTConfig default; the loss falls slowly and the model barely changes.
Guard
Sweep the rate first on a log grid around 2e-4; extend the grid if the best value is at an edge.
Merge into the quantised base
What happens
The adapter was trained against 4-bit weights. Merging into other numerics changes behaviour, and some formats cannot be merged at all.
Real case
Adapter outputs and merged outputs differ on a visible share of prompts.
Guard
Reload the base in 16-bit, merge, and run a parity check plus the held-out score.
Adapter on the wrong base
What happens
The adapter loads without error and quality drops quietly. Detect it with the held-out score on the exact serving stack.
Real case
An adapter trained on one base revision is loaded onto a later revision or a different chat template.
Guard
Store base id, revision and template with the adapter, and verify them at load time.
Before you trust an adapter
  • The 16-bit LoRA run was considered first; QLoRA is used because memory forces it.
  • Adapters cover all linear layers, and alpha and the scaling convention are recorded.
  • Learning rate was swept before rank, on a grid wide enough that the best value is not at an edge.
  • Choices were made on a dev set; the test set was opened once, after seeds were repeated.
  • Adapter, merged model and (where affordable) full fine-tune are scored on the same test set.
  • Merge parity and the regression set were checked on the merged weights.
  • Base id, revision, tokeniser, template, rank, alpha and seed are stored with the adapter.

Matching labs: 05 (QLoRA 4-bit), 06 (LoRA rank and learning-rate ablation) and 19 (adapter save, merge and portability). The notebooks are not hosted yet.

B3. Preference tuning (DPO, KTO)

Mirrors U3 · Preference optimisation in the Understand half.

Preference tuning is the cheapest way to teach a model taste: which of two replies a reviewer would send, how long an answer should run. DPO turns pairs into a classification loss; KTO needs only a thumbs-up or thumbs-down per answer. The hard part is not the trainer. It is getting labels that mean what you think they mean, and checking the result with labels the training never touched.

When to use it

Use it when the model already produces acceptable answers and you want to move which acceptable answer it picks. The signal must be a judgement, not a fact. If a program can check the answer, go to B4; if the model lacks the format or the skill, fix that with B1 first.

Choose the data shape by what you can collect. Pairs suit a reviewer comparing candidates sampled from your own tuned model. Thumbs suit a product that already logs approvals and rejections. KTO's authors report that it matches or exceeds pair-based methods from 1B to 30B parameters, and that no single human-aware loss wins everywhere; treat that as licence to try both, not as a ranking.

Architecture

B3 · Preference tuningB3 · Preference tuning: 1. Collect (pairs or thumbs); 2. Train (DPO or KTO, adapter); 3. Judge (independent labels, held-out prompts). Then back to step 1: Fresh pairs from the tuned model, labelled again.B3 · Preference tuningCollectpairs or thumbsTrainDPO or KTO, adapterJudgeindependent labels, held-outprompts↺ Fresh pairs from the tuned model, labelled again
The judge is the protected step. Its labels come from different people, or a different model family, than the signal used in training, and it scores prompts the trainer never saw.

Collect produces prompt / chosen / rejected rows or prompt / completion / label rows. Train is one TRL run, usually with a LoRA adapter. Judge compares the tuned model with the starting model on held-out prompts. If the judge shares the trainer's blind spot, such as a taste for long answers, it reports a gain that users never see.

Tools

Pair-based preference loss
Takes chosen / rejected rows. Default loss_type is sigmoid, default beta 0.1. Part of TRL 1.17.1 (30 October 2026).
Licence: Apache-2.0Implements: DPO (2305.18290); IPO and a length-normalised sigmoid via loss_type (SimPO is not built in)
Thumbs-based preference loss
Takes prompt / completion / label; a paired set is converted automatically. Top-level import since TRL 1.8; older code importing from trl.experimental must change.
Licence: Apache-2.0Implements: KTO (2402.01306)
Scalar reward model
Trains a scorer from chosen / rejected pairs. Use it as a judge or filter, or as the reward for online RL; DPO and KTO do not need it.
Licence: Apache-2.0Implements: Bradley–Terry reward modelling, as in InstructGPT (2203.02155)

All three share one library, one tokenizer convention (processing_class, not the old tokenizer=) and one dataset vocabulary. A reward model is an extra artefact to evaluate and keep; build one only if you want a reusable judge, and note that RewardBench found reward models over-refuse and follow instructions poorly, so it is not a neutral judge either.

Recipe

DPO from pairs, KTO from thumbs, judged on held-out prompts with length controlled
Time About 2 hours of set-up, then one GPU session per methodNeeds trl 1.17.1, peft, datasets; a few hundred reviewed pairs or logged thumbs; held-out prompts; an independent judge

The scenario is illustrative: tuning a support assistant to answer in the house style. The code is checked against TRL 1.17.1 signatures and the data helpers were run on toy rows; no model was trained here, and the model name and judge are placeholders. Labs 08 (DPO), 09 (KTO) and 10 (reward model) run the same idea at small scale.

1. Convert your labels, then audit them for length. If reviewers picked the longer reply most of the time, the pairs teach length.

import statistics as st
from datasets import Dataset

def msg(role, text): return [{"role": role, "content": text}]

def as_pair(r):    # reviewer compared two samples: {"question", "winner", "loser"}
    return {"prompt": msg("user", r["question"]),
            "chosen": msg("assistant", r["winner"]), "rejected": msg("assistant", r["loser"])}

def as_thumb(r):   # product log: {"question", "answer", "thumb": "up" | "down"}
    return {"prompt": msg("user", r["question"]), "completion": msg("assistant", r["answer"]),
            "label": r["thumb"] == "up"}

def length_audit(pairs):
    n = lambda p, k: len(p[k][0]["content"])
    return {"chosen_longer": sum(n(p, "chosen") > n(p, "rejected") for p in pairs) / len(pairs),
            "median_ratio": st.median(n(p, "chosen") / max(1, n(p, "rejected")) for p in pairs)}

pairs = [as_pair(r) for r in load_reviews()]          # placeholder loader
print(length_audit(pairs))
pair_ds, thumb_ds = Dataset.from_list(pairs), Dataset.from_list([as_thumb(r) for r in load_thumbs()])

2. Train DPO with an adapter. Passing peft_config lets TRL use the frozen base as the reference, so no second model copy is loaded.

from peft import LoraConfig
from trl import DPOConfig, DPOTrainer

lora = LoraConfig(r=16, lora_alpha=32, target_modules="all-linear", task_type="CAUSAL_LM")
cfg = DPOConfig(output_dir="dpo-out", beta=0.1, learning_rate=5e-6, max_length=1024,
                per_device_train_batch_size=4, gradient_accumulation_steps=4,
                num_train_epochs=1, loss_type="sigmoid")      # "sigmoid_norm" normalises by length
trainer = DPOTrainer(model="your-org/your-sft-model", args=cfg,
                     train_dataset=pair_ds, peft_config=lora)
trainer.train()

3. Train KTO on the thumbs. KTO estimates a reference point from other examples in the batch, so keep the per-device batch above one. Weight the rarer label up.

from trl import KTOConfig, KTOTrainer

cfg = KTOConfig(output_dir="kto-out", beta=0.1, learning_rate=5e-6, max_length=1024,
                per_device_train_batch_size=4, gradient_accumulation_steps=4,
                desirable_weight=1.0, undesirable_weight=1.5)  # set from your up/down ratio
trainer = KTOTrainer(model="your-org/your-sft-model", args=cfg,
                     train_dataset=thumb_ds, peft_config=lora)
trainer.train()

4. Judge on held-out prompts with length controlled. Generate from the starting model and each tuned model, have the independent judge pick a winner per prompt, and report the win rate twice: raw, and among replies of similar length.

def win_rate(rows, band=(0.8, 1.25)):
    # rows: {"tuned_len", "base_len", "winner": "tuned" | "base" | "tie"}
    score = lambda rs: (sum(r["winner"] == "tuned" for r in rs)
                        + 0.5 * sum(r["winner"] == "tie" for r in rs)) / max(1, len(rs))
    ratio = lambda r: r["tuned_len"] / max(1, r["base_len"])
    matched = [r for r in rows if band[0] <= ratio(r) <= band[1]]
    return {"raw": score(rows), "length_matched": score(matched), "n_matched": len(matched),
            "tuned_longer": sum(ratio(r) > band[1] for r in rows) / len(rows)}

5. Decide. Promote a model only if the length-matched win rate clears 0.5 by more than the noise of two judge runs, the raw and matched figures tell the same story, and the regression set from the Part V evaluation harness has not moved. A raw win rate far above the matched one means the model learned to be longer, not better. Treat the matched slice as a diagnostic, not the headline: filtering on output length conditions on something the model chose, and the slice may be small and unrepresentative. For the headline figure, prefer a length-controlled estimate that regresses the judge's preference on the length difference, as AlpacaEval 2's length-controlled win rate does.

Evaluation and gate

Four numbers decide promotion: the length-matched win rate against the starting model, judged by labels independent of training; the raw win rate beside it; format validity and your regression suite against baseline; and the median length ratio. Park and colleagues showed that DPO exploits length, and that a length regulariser improved the length-controlled win rate by up to 20 per cent (authors' figure). Their GPT-4 judge was itself verbose-biased, which is why the judge must be checked, not trusted.

Add a human spot-check of a few dozen disagreements between judge and training signal. TRL's documentation notes that DPO in practice mostly suppresses rejected completions rather than raising chosen ones, so falling log-probability on good answers is a warning even when the margin improves; TRL can add an sft term to the loss. Chen and colleagues found most preference-tuned models rank pairs correctly under 60 per cent of the time on common datasets, so do not read the training margin as quality.

Cost, GPU memory and operations

DPO processes both replies of every example, so a batch of four pairs is eight sequences, and sequence length drives activation memory. With an adapter the reference pass reuses the frozen base. KTO processes one completion per row but needs a batch above one for its reference estimate. Measure memory on your own card rather than assuming.

The running cost is people: reviewers compare pairs at minutes each, and the judge needs fresh labels every cycle. Version the preference data with the adapter, record beta, learning rate and loss_type, and rerun the judge on every base-model change.

Failure drills

Length drift
What happens
The model wins by writing more, not better.
Real case
Park et al. showed DPO exploits length; a length regulariser lifted length-controlled win rate by up to 20% (authors' figure).
Guard
Length audit before training; length-matched win rate at the gate; try sigmoid_norm.
Judge with the trainer's bias
What happens
The test agrees with the training signal because it is the same signal.
Real case
The summarisation study's GPT-4 judge was itself verbose-biased.
Guard
Judge labels from other people or another model family; human spot-check of disagreements.
Thumbs are not preferences
What happens
Selection bias in who rates becomes a behaviour.
Real case
Illustrative: only annoyed users click thumbs-down, so rejected rows cluster on hard questions.
Guard
Sample thumbs across question types; weight classes; have reviewers audit a slice.

Run each drill once: train on pairs where the winner is always longer and confirm the audit flags it; judge with the model that wrote the pairs and compare with the independent judge.

B3 checklist
  • The model passes the format and skill baseline before preference tuning starts.
  • Pairs or thumbs carry the prompt, both replies or the label, the labeller and a date.
  • A length audit is run on the data and its result is recorded.
  • Held-out prompts are fixed before training and never used to choose pairs.
  • The judge is independent of the training signal, and a human spot-check covers its disagreements.
  • The gate reports raw and length-matched win rates, format validity and the regression suite.
  • The adapter, data version, beta, loss_type and TRL version are stored together.
  • Fresh labels are scheduled for the next cycle and for every base-model change.

Matching labs: 08 DPO, 09 KTO and 10 reward model.

B4. RL with verifiable rewards (GRPO)

Mirrors U4 · Reinforcement learning with verifiable rewards in the Understand half.

Reinforcement learning with verifiable rewards works when a program can say whether an answer is right. The model samples a group of answers, the program scores each, and the update favours those that beat their group. There is no value model and no human in the loop, so the verifier is the whole specification: the model will find every gap in it, and it has many attempts. Most of this chapter is about the checker.

When to use it

Use GRPO when the task has an answer a program can check exactly (arithmetic, code against tests, a schema), the model already gets some answers right, and you can generate many such tasks. The second condition matters most: AWS's Bedrock documentation advises skipping reinforcement tuning above 95 per cent baseline reward and tuning supervised first near zero (vendor guidance), because a group in which every answer scores the same teaches nothing.

Do not expect new ability. Yue and colleagues found that RL-tuned models win at one attempt per problem while the base model catches up or wins at many attempts, suggesting RL mostly sharpens what the model can already do; whether longer training changes that is open (U4). Treat the gain as reliability on a checkable task.

Architecture

B4 · RL with verifiable rewardsB4 · RL with verifiable rewards: 1. Prompts (checkable tasks); 2. Rollouts (a group per prompt); 3. Verifier (a program, outside the model); 4. Reward (score minus group mean); 5. Update (adapter weights). Then back to step 1: Next batch of prompts; log reward and zero-variance groups.B4 · RL with verifiable rewardsPromptscheckable tasksRolloutsa group perpromptVerifiera program,outside the modelRewardscore minus groupmeanUpdateadapter weights↺ Next batch of prompts; log reward and zero-variance groups
The verifier runs in your code, not in the model's context. The policy can read its outputs through the reward, but it can never edit it.

The prompts carry the gold answer as a separate column, never in the text. The rollouts are a group per prompt (eight by default in TRL). The verifier returns a number per sample, and the reward step compares each with its group mean, so only differences count. Generation dominates wall-clock time.

Tools

Single-node GRPO
Reward functions are plain Python callables. TRL 1.17.1.
Licence: Apache-2.0Implements: GRPO (2402.03300)
UnslothActive
Memory-lean training kernels
Vendor-reported 2x speed and 70% less VRAM, not measured here. Licence is split by directory. PyPI 2026.11.3.
Licence: Apache-2.0 (library); AGPL-3.0 files in the repoImplements: Optimised LoRA/QLoRA/RL training on top of TRL trainers
veRLActive
Distributed RL framework
FSDP or Megatron training with vLLM, SGLang or HF rollouts; PPO, GRPO, RLOO. Moved from volcengine to verl-project in 2026. 0.9.1.
Licence: Apache-2.0Implements: HybridFlow (2409.19256)
OpenRLHFActive
Ray + vLLM + DeepSpeed RL
The README now uses dotted CLI flags (--actor.model_name_or_path); older flat-flag scripts were not tested. Its README recommends Molt, which we have not evaluated. 0.11.2.
Licence: Apache-2.0Implements: OpenRLHF (2405.11143)
SkyRLActive
Modular RL library
skyrl now unifies the older skyrl-train and skyrl-tx; skyrl-gym holds environments. 0.4.0.
Licence: Apache-2.0Implements: SkyRL-Agent (2511.16108); implements the Tinker API per its README
prime-rlActive
Asynchronous RL at scale
Not on PyPI: install from source; NVIDIA GPU required. Release v0.10.0.
Licence: Apache-2.0Implements: Async RL with FSDP2 and vLLM; Environments Hub integration

For one node and a verifier you wrote yourself, TRL is the default and what the recipe uses. The others are for when one machine is not enough, generation must run on separate hardware, or the task is a multi-turn environment. None removes the need to build the verifier; Unsloth sits beside TRL by lowering memory use.

Recipe

GRPO on an exact-answer task, with a verifier attacked before training
Time About 2 hours of set-up, then the training runNeeds trl 1.17.1, peft, datasets, vllm if use_vllm=True; one GPU; a held-out set from a different seed

The scenario is illustrative: arithmetic with the final answer inside tags, the smallest task where hacking is still easy to show. The reward functions and attack list were run on toy completions; the trainer call is checked against TRL 1.17.1 signatures, but no model was trained here.

1. Build the tasks. Keep the gold answer out of the prompt. TRL passes extra dataset columns to the reward function as keyword arguments, so answer arrives by name.

import random

def make_problems(n, seed, lo=2, hi=30):
    rng = random.Random(seed)
    rows = []
    for _ in range(n):
        a, b, c = (rng.randint(lo, hi) for _ in range(3))
        rows.append({"prompt": [{"role": "user", "content":
            f"Compute {a} + {b} * {c}. Reason briefly, then end with <answer>NUMBER</answer>."}],
            "answer": str(a + b * c)})
    return rows

train = make_problems(2000, seed=0)
seen = {r["prompt"][0]["content"] for r in train}
held_out = [r for r in make_problems(400, seed=1, hi=60)       # wider operands, new seed
            if r["prompt"][0]["content"] not in seen]

2. Write the verifier as strictly as you can. A reward function takes the batch of completions and returns a list of floats. Exactly one answer tag, at the end, holding only a number.

import re
from fractions import Fraction

TAG, NUMBER = re.compile(r"<answer>(.*?)</answer>", re.S), re.compile(r"-?\d+(?:\.\d+)?")

def text_of(c):                       # conversational completions arrive as message lists
    return c if isinstance(c, str) else c[0]["content"]

def parse_answer(text):
    tags = TAG.findall(text)
    if len(tags) != 1 or not text.rstrip().endswith("</answer>"):
        return None                   # none, several, or text after the answer: no credit
    body = tags[0].strip()
    return Fraction(body) if NUMBER.fullmatch(body) else None   # "7 or 8" earns nothing

def correctness_reward(completions, answer, **kwargs):
    return [1.0 if (g := parse_answer(text_of(c))) is not None and g == Fraction(a) else 0.0
            for c, a in zip(completions, answer)]

def format_reward(completions, **kwargs):
    return [1.0 if parse_answer(text_of(c)) is not None else 0.0 for c in completions]   # scaled by reward_weights

3. Attack it before the model does. Every string here must score zero for a gold answer of 19. Add a line each time a training log shows a new trick.

ATTACKS = ["<answer>18</answer> <answer>19</answer>",      # hedge with two tags
           "<answer>18 or 19</answer>",                    # hedge inside one tag
           "<answer>19</answer> thanks",                   # text after the answer
           "The answer is 19", "<answer>NUMBER</answer>", "<answer>20</answer>"]
assert correctness_reward(ATTACKS, ["19"] * len(ATTACKS)) == [0.0] * len(ATTACKS)
assert correctness_reward(["so 7+3*4 is <answer>19</answer>"], ["19"]) == [1.0]

4. Train with the two rewards, weighted. Correctness carries the learning; the small format reward gets the model to the tags early.

from datasets import Dataset
from peft import LoraConfig
from trl import GRPOConfig, GRPOTrainer

cfg = GRPOConfig(output_dir="grpo-out", num_generations=8, per_device_train_batch_size=8,
                 max_completion_length=256, mask_truncated_completions=True,
                 learning_rate=1e-5, reward_weights=[1.0, 0.2], max_steps=300,
                 use_vllm=True, vllm_mode="colocate", vllm_gpu_memory_utilization=0.3,
                 log_completions=True, logging_steps=5)
trainer = GRPOTrainer(model="Qwen/Qwen2.5-0.5B-Instruct",
                      reward_funcs=[correctness_reward, format_reward], args=cfg,
                      train_dataset=Dataset.from_list(train),
                      peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear",
                                             task_type="CAUSAL_LM"))
trainer.train()

5. Score the held-out set as reliability, not just a mean. Draw eight samples per problem from the base and the tuned model with your own generation helper.

def evaluate(sample, rows, k=8):          # sample(prompt, k) -> k completions; your helper
    p1 = pk = fmt = 0.0
    for r in rows:
        outs = sample(r["prompt"], k)
        ok = correctness_reward(outs, [r["answer"]] * k)
        p1 += sum(ok) / k; pk += max(ok); fmt += sum(format_reward(outs)) / (0.2 * k)
    n = len(rows)
    return {"pass@1": p1 / n, f"pass@{k}": pk / n, "format": fmt / n}

6. Decide. Promote only if held-out pass@1 beats run-to-run noise, pass@8 has not fallen, and you have read the highest-reward completions yourself.

Set vllm_mode deliberately. Since TRL 1.0 the default is "colocate", which runs vLLM inside the training process on the same GPU, governed by vllm_gpu_memory_utilization (default 0.3); use_vllm itself defaults to False. TRL 1.17.1 also defaults beta to 0.0, so no KL term is logged unless you set one, and scale_rewards to group scaling; TRL's documentation, citing the Dr. GRPO paper, notes that dividing by the standard deviation can cause a question-level difficulty bias.

Evaluation and gate

Gate on four things. First, held-out pass@1 against the untouched base, on a different seed and wider range than training. Second, pass@8 beside it: Yue et al. saw training pass@1 rise from 26.1 to 42.5 while pass@256 fell from 67.2 to 64.3 in their setting, sharpening at the cost of coverage. Third, format validity and the regression suite. Fourth, a manual read of the top-reward completions, because a number cannot show a loophole.

If you can afford one extra run, add a random-reward control. Shao and colleagues found random rewards lifted Qwen2.5-Math-7B on MATH-500 by 21.4 points against 29.1 for ground truth, and did nothing on Llama or OLMo bases; if your control moves, part of your gain is the base model.

Cost, GPU memory and operations

There is no critic network, so memory is one policy plus a reference only if beta is above zero. What costs is generation: each step produces num_generations completions per prompt, up to max_completion_length tokens each. Illustrative: doubling the group roughly doubles rollout time, so start at eight. Press coverage of DeepSeek's R1 reported a reinforcement-learning stage on the order of hundreds of thousands of dollars on 512 H800 GPUs; the arXiv paper states no cost, so treat it as unverified frontier-scale context.

In operation, watch reward, each rewards/<function>/mean, frac_reward_zero_std (groups with no spread carry no gradient), entropy and completion length. Record the verifier's source hash beside the adapter; a changed verifier makes runs incomparable.

Failure drills

Verifier loophole
What happens
The model earns reward without doing the task.
Real case
Illustrative: the model answers '18 or 19' and a loose parser gives credit. Anthropic reported reward hacking learned in real coding RL generalising to sabotage (2511.18397).
Guard
Strict parser; attack list run before training; read top-reward completions each run.
Gain from the base model
What happens
Part of the improvement was already in the weights.
Real case
Random rewards gave +21.4 points on Qwen2.5-Math-7B MATH-500 against +29.1 for correct ones (Shao et al.).
Guard
Held-out set from a new seed; optional random-reward control; a second model family.
No learning signal
What happens
Every group scores the same, so nothing moves.
Real case
AWS advises skipping RFT above 95% baseline reward and tuning supervised first near 0% (vendor guidance).
Guard
Measure baseline pass@8 first; watch frac_reward_zero_std; start with an easier slice.

Run each drill once: feed the attack list to the real reward function; train a few steps on random rewards; check the zero-variance share on the baseline before paying for the full run.

The arithmetic task is deliberately a toy, because its checker is unambiguous. Real verifiers are harder: partial credit for multi-part answers, code run in a sandbox with time and resource limits, tool calls replayed against a stub service, or SQL executed against a read-only copy. Each adds a new way to be fooled, so give every real verifier its own attack list before it scores a single training rollout.

B4 checklist
  • The task has an exact answer a program can check, and the baseline already solves some of it.
  • Gold answers live in a separate column and never appear in the prompt.
  • The verifier is strict, runs outside the model, and has an attack list that all scores zero.
  • Held-out problems come from a different seed and a wider range than training.
  • The gate reports pass@1, pass@k, format validity and the regression suite.
  • Top-reward completions are read by a person every run.
  • vllm_mode, num_generations, beta, TRL version and verifier hash are recorded with the adapter.
  • frac_reward_zero_std and completion length are watched in training.

Matching labs: 11 GRPO arithmetic verifier, 12 GRPO multiple rewards and 13 adversarially robust verifier.

B5. Distillation

Mirrors U5 · Distillation and synthetic data in the Understand half.

When to use it

Distil when a large model already does your task well enough and the price or latency of calling it is what hurts. Three things must be true before you start. You have a few thousand prompts that look like production traffic. You have a check that can tell a good teacher answer from a bad one, even a crude one such as "parses as JSON and has the required fields". And you have the right to train on the teacher's outputs. The third is the one teams skip, so the recipe below makes it the first step.

The case for distilling is in U5: DeepSeek reported that fine-tuning Qwen-32B on 800,000 teacher samples reached 72.6 on AIME 2024, against 47.0 for reinforcement learning on the same base (lab-reported). The case against over-reaching is there too. A student trained only on imitation shows little gain on tasks the imitation data did not cover, so distil the task you have prompts for, not the teacher's general ability. A student cannot pass what its teacher fails on the data it sees; that is our reading of the evidence, not a measured law.

Architecture

B5 · DistillationB5 · Distillation: 1. Terms check (may we train on this?); 2. Teacher generates (your prompts); 3. Filter (checks, dedupe, leakage); 4. Student trains (SFT or GKD); 5. Compare (cost and quality). Then back to step 1: Re-run when the teacher, the terms or the prompt mix change.B5 · DistillationTerms checkmay we train onthis?Teachergeneratesyour promptsFilterchecks, dedupe,leakageStudenttrainsSFT or GKDComparecost and quality↺ Re-run when the teacher, the terms or the prompt mix change
The filter is where most of the quality is decided: whatever passes it is what the student will believe.

The terms check is a person reading a document and writing down the answer; the code only refuses to continue without it. The teacher answers your prompts, and you record its identity, version and sampling settings beside every row. The filter drops rows that fail the task check, rows that duplicate each other, and any prompt that also sits in your held-out set. The student is then trained on what survived. Training on teacher text is off-policy: the student never sees its own mistakes. The on-policy alternative, GKD, samples from the student and scores each token against the teacher's, which needs the teacher's weights in memory. An API teacher that returns text only can feed the first route, not the second. The comparison puts teacher, prompted small model and distilled student side by side on quality and on cost per thousand requests.

Tools

TRLActive
Student training
SFTTrainer on prompt/completion pairs is sequence-level distillation. GKDTrainer lives under trl.experimental.gkd, not the top level, and may change in any release. v1.17.1.
Licence: Apache-2.0Implements: Sequence-level KD (1606.07947); GKD (2306.13649)
distilabelResearch code
Synthetic data pipelines
Community-held since the original authors left; last release 1.5.3 in January 2025, with fixes on the develop branch. Import path is distilabel.models.
Licence: Apache-2.0Implements: Pipelines for generation and AI feedback
datatroveActive
Filter, dedupe, scale
Readers, filters, dedup and writers as a pipeline of steps; used for FineWeb. 0.10.1. JSON reading needs the io extra.
Licence: Apache-2.0Implements: FineWeb-style processing pipelines

For a first distillation we would use TRL for training and datatrove for the filter, and write the generation loop ourselves against whatever serves the teacher. That loop is thirty lines, and it avoids pinning your data pipeline to a package with no release for twenty-one months. distilabel is worth reading for its task and feedback abstractions; we would not build on it without pinning the version and testing every step.

Recipe

Distil a larger teacher into a small student, with a terms check first and a cost and quality comparison
Time A half day of set-up, then generation and one training runNeeds trl 1.17.1, datatrove[io] 0.10.1, a teacher whose terms you have read, 2,000+ prompts, a held-out set (lab 14)

The scenario is illustrative: turning support tickets into a small JSON record. The code is checked against the pinned signatures (the datatrove pipeline was run on a toy file; the trainers were constructed but not trained). call_teacher, check, the model names and the prices are placeholders.

1. Write the terms down before spending anything. A function cannot read a contract, but it can refuse to run without a recorded answer.

import json, pathlib

def terms_gate(rec: dict) -> dict:
    need = ["teacher", "terms_url", "read_on", "outputs_may_train_other_models", "naming_rule"]
    missing = [k for k in need if rec.get(k) in (None, "")]
    if missing or rec["outputs_may_train_other_models"] is not True:
        raise SystemExit(f"Stop: terms not cleared ({missing or 'training on outputs not allowed'})")
    pathlib.Path("distill/terms.json").write_text(json.dumps(rec, indent=2))
    return rec

terms_gate({"teacher": "teacher-large", "terms_url": "https://example.com/terms",
            "read_on": "2026-11-07", "outputs_may_train_other_models": True,
            "naming_rule": "none"})        # e.g. Llama 3.1 requires 'Llama' at the start of the new name

2. Generate and check. Keep the prompt, the completion and the verdict in one row.

import json
from distill_helpers import call_teacher, check, load_prompts   # placeholders

with open("distill/raw/rows.jsonl", "w") as f:
    for p in load_prompts():                    # production-like prompts, held-out ones excluded
        out = call_teacher(p, temperature=0.3)  # your client for the teacher
        f.write(json.dumps({"completion": out, "prompt": p, "teacher": "teacher-large",
                            "valid": bool(check(p, out))}) + "\n")

3. Filter with datatrove. The reader puts completion in text and every other key in metadata. Dropping held-out prompts here is your leakage guard.

from datatrove.executor import LocalPipelineExecutor
from datatrove.pipeline.readers import JsonlReader
from datatrove.pipeline.filters import LambdaFilter
from datatrove.pipeline.writers import JsonlWriter

HELD = {json.loads(l)["prompt"] for l in open("heldout.jsonl")}
keep = lambda d: d.metadata["valid"] and d.metadata["prompt"] not in HELD
LocalPipelineExecutor(
    pipeline=[JsonlReader("distill/raw", text_key="completion"), LambdaFilter(keep),
              JsonlWriter("distill/clean", compression=None)],
    tasks=1, workers=1, logging_dir="distill/logs").run()

4. Train the student on teacher text. With prompt/completion rows, TRL computes loss on the completion by default.

from datasets import load_dataset
from trl import SFTConfig, SFTTrainer

raw = load_dataset("json", data_files="distill/clean/*.jsonl", split="train")
ds = raw.map(lambda r: {"prompt": [{"role": "user", "content": r["metadata"]["prompt"]}],
                        "completion": [{"role": "assistant", "content": r["text"]}]},
             remove_columns=raw.column_names)
cfg = SFTConfig(output_dir="student-sft", max_length=1024, learning_rate=2e-5,
                num_train_epochs=2, per_device_train_batch_size=8, bf16=True)
SFTTrainer(model="STUDENT_MODEL_ID", args=cfg, train_dataset=ds).train()

5. Optional on-policy pass, if you hold the teacher's weights. lmbda is the share of student-generated outputs; beta interpolates the divergence. GKD takes chat-format messages data; check the current GKD docs for the exact columns, since this trainer is experimental.

from trl.experimental.gkd import GKDConfig, GKDTrainer

cfg = GKDConfig(output_dir="student-gkd", lmbda=0.5, beta=0.5, max_new_tokens=256,
                max_length=1024, teacher_model_name_or_path="TEACHER_WEIGHTS_ID")
GKDTrainer(model="STUDENT_MODEL_ID", teacher_model="TEACHER_WEIGHTS_ID",
           args=cfg, train_dataset=messages_ds).train()

6. Compare on cost and quality together. Score all three models on the same held-out rows, then price a thousand requests.

def usd_per_1k(in_tok, out_tok, p_in, p_out):        # prices per million tokens
    return 1000 * (in_tok * p_in + out_tok * p_out) / 1e6

for name, q, price in [("teacher", teacher_score, (3.0, 15.0)),
                       ("student", student_score, (0.1, 0.4)),
                       ("student, prompted only", base_score, (0.1, 0.4))]:
    print(f"{name:24s} held-out {q:.1%}  ${usd_per_1k(600, 150, *price):.3f} per 1k requests")

Evaluation and gate

Three numbers decide. First, the student's held-out score against the teacher's, with the allowed gap fixed before training. Second, the student against the same small model prompted without training; if the prompted model is close, you bought nothing. Third, a slice of prompts unlike the training set, since imitation is weakest where the data is thin. Add cost per thousand requests at the quality you measured, and promote only if all three clear their lines. The held-out set must postdate the data you generated; Yang and colleagues showed that rephrased test items slip past n-gram filters, and found contamination even in GPT-3.5 and GPT-4 generated data.

Cost, GPU memory and operations

The bill is the teacher's output tokens. Illustrative: 5,000 prompts, two samples each, 400 tokens each is four million output tokens at the teacher's price, compare it with the monthly saving before you start. Training the student is then a one-GPU job (labs 04 and 05 cover the adapter routes). The memory difference is between methods: SFT holds only the student, while GKD holds teacher and student and generates during training. Thinking Machines reports (self-published) that on-policy distillation reached 74.4 on AIME 2024 in about 1,800 GPU-hours where a cited RL run reached 67.6 in 17,920, but its teachers were open models whose logits it could read.

Store the terms record, teacher version and sampling settings with the dataset. Re-run the terms check when the teacher or its licence changes, and mind what the licence imposes on the student: Llama 3.1, for one, requires its name at the start of any model improved with its outputs.

Failure drills

Training against the terms
What happens
Cheap generation turns into an account ban or a legal problem.
Real case
Anthropic's commercial terms (as fetched, effective June 2025) bar training competing models; in February 2026 it alleged over 16 million exchanges through some 24,000 fraudulent accounts.
Guard
Terms gate with a dated record; open-weight teachers whose licence permits it.
Teacher errors become student beliefs
What happens
The student copies wrong answers with confidence.
Real case
AlpaGasus used an LLM judge to keep 9k of 52k rows; that judge may share the generator's biases.
Guard
A task check you can run without a model; sample 50 kept rows by hand.
Imitation without capability
What happens
The student sounds like the teacher and fails like a small model.
Real case
Gudibande et al.: imitations looked competitive to raters but closed little of the gap on tasks outside the imitation data.
Guard
Out-of-distribution slice in the gate; judge by checks, not by tone.
Contaminated held-out set
What happens
The comparison flatters the student.
Real case
Yang et al.: rephrased test data inflated a 13B model to GPT-4-like scores.
Guard
Drop held-out prompts and paraphrases before training; use fresh post-dated items.

Run the first and fourth drills before generating at scale: write a terms record with the answer left blank and confirm the gate stops, then plant five held-out prompts in the raw rows and confirm the filter removes them.

B5 checklist
  • The teacher's terms were read by a person, dated and saved beside the data.
  • Any naming or attribution rule the licence places on the student is recorded.
  • Every row carries teacher id, version and sampling settings.
  • A task check that needs no model decides which rows survive.
  • Held-out prompts are removed from the training rows, and the held-out set postdates them.
  • The student is compared with the teacher and with the prompted small model.
  • The gate includes a slice unlike the training prompts and the cost per thousand requests.
  • A re-run is planned for any change of teacher, terms or prompt mix.

Lab 14 · Teacher–student distillation runs this recipe (synthetic data, T4 GPU; not yet executed).

B6. Continued pretraining

Mirrors U6 · Continued pretraining and domain adaptation in the Understand half.

When to use it

Continue pretraining when the model lacks the language of your domain: its notation, its jargon, its document shapes. Instruction data cannot supply what the model never saw as running text, and retrieval cannot help if the model misreads what it retrieves. You also need a large body of unlabelled domain text you may use, and a measurement of what the model must not forget. Try retrieval and SFT first (Part IV) and come here only when they stall.

U6 gives the shape of the evidence. Domain-adaptive pretraining moved a RoBERTa model from 63.0 to 75.4 on a citation-intent task in a distant domain, and left AGNews news classification unchanged (93.9 against 93.9), a domain the model already knew. Llama 3's annealing lifted the 8B model by 24.0% on the GSM8k and MATH validation sets and was negligible for 405B. No paper gives a minimum token count, so do not trust a threshold. A small corpus can be stretched: EntiGraph expanded 1.3 million tokens into 455 million synthetic ones and lifted closed-book QuALITY accuracy from 39.49% to 56.22% (lab-reported), while training on the raw text scored 38.15%.

Architecture

B6 · Continued pretrainingB6 · Continued pretraining: 1. Domain corpus (cleaned, deduplicated); 2. Mix (domain plus replay); 3. Train (fresh warm-up and decay); 4. Measure forgetting (general vs domain); 5. Gate (keep or retune the mix). Then back to step 1: Raise the replay share if the general score fell more than the gate allows.B6 · Continued pretrainingDomain corpuscleaned,deduplicatedMixdomain plusreplayTrainfresh warm-up anddecayMeasureforgettinggeneral vs domainGatekeep or retunethe mix↺ Raise the replay share if the general score fell more than the gate allows
Forgetting is measured against the model you started from, on data that is in neither the domain corpus nor the replay set.

The corpus is cleaned and deduplicated, including against your evaluation sets. The mix blends domain text with replayed general text so the model keeps seeing what you do not want it to lose. Ibrahim and colleagues matched full re-training with replay shares of 5% for a weak shift and 25% for English to German, plus a re-warmed and re-decayed learning rate; those are pretraining-scale numbers, and we found no measured rule for smaller runs, so treat the share as a variable and run three arms. Training is ordinary next-token loss on packed text. Measuring forgetting means the same general and domain slices, before and after.

Tools

TRLActive
Trainer
Plain-text training: set dataset_text_field, turn packing on, no chat template. v1.17.1.
Licence: Apache-2.0Implements: Next-token training via SFTTrainer on a text column
AxolotlActive
YAML-driven trainer
Raw-text rows go under datasets with type: completion; a streaming path exists for corpora too big for memory. 0.21.1.
Licence: Apache-2.0Implements: type: completion datasets for pre-training
datatroveActive
Corpus processing
Cleans and deduplicates at scale, including against evaluation sets. 0.10.1.
Licence: Apache-2.0Implements: FineWeb-style filter and dedup pipelines
DeepSpeed-based trainer
Snowflake's open framework. Main is active, but the last release (0.8.0) is from March 2026, the community is small, and its documented recipe type is sft; we did not verify a pre-training mode.
Licence: Apache-2.0Implements: Post-training recipes, YAML-driven

TRL is the shortest route and the one the recipe uses. Axolotl suits a team that wants the run to be a reviewable YAML file. Pick ArcticTraining only if you already run DeepSpeed and want its long-sequence work. We leave torchtune out because its own README says it is no longer maintained.

Recipe

Domain-adaptive pretraining with a replay mix and a before/after forgetting check
Time A day for set-up; the run scales with your token budgetNeeds trl 1.17.1, datasets, a domain corpus you may use, a general corpus, one GPU for a small model (lab 15)

The scenario is illustrative: adapting a small base model to a body of contract text. The code was checked against the pinned signatures and the interleaving was run on toy data; training and evaluate were not run. The corpora and model id are placeholders.

1. Build the mix as arms. Replay shares of 0, 10 and 25 percent are illustrative; the zero arm shows you what unmitigated forgetting costs.

from datasets import load_dataset, interleave_datasets

domain  = load_dataset("json", data_files="domain_clean/*.jsonl", split="train")   # column: text
general = load_dataset("json", data_files="general_replay/*.jsonl", split="train")

def make_mix(replay: float):
    if replay == 0:
        return domain
    return interleave_datasets([domain, general], probabilities=[1 - replay, replay],
                               seed=0, stopping_strategy="all_exhausted")   # oversample the smaller set; bound the run with max_steps

arms = {r: make_mix(r) for r in (0.0, 0.10, 0.25)}

2. Fix the measurement first. Two held-out slices that appear in no training mix: domain text and general text. Dict evaluation sets are reported as eval_<name>_loss.

evals = {"domain":  load_dataset("json", data_files="heldout_domain.jsonl",  split="train"),
         "general": load_dataset("json", data_files="heldout_general.jsonl", split="train")}

3. Train each arm from the same base, with a fresh schedule. Re-warming and re-decaying the learning rate is part of the method, not a detail. warmup_steps as a float below 1 is a share of total steps.

from trl import SFTConfig, SFTTrainer

def trainer(replay, train_ds):
    cfg = SFTConfig(output_dir=f"cpt-r{int(replay*100)}", dataset_text_field="text",
                    packing=True, max_length=2048, learning_rate=1e-5,
                    lr_scheduler_type="cosine", warmup_steps=0.05, bf16=True,
                    per_device_train_batch_size=4, gradient_accumulation_steps=8,
                    num_train_epochs=1, eval_strategy="no")
    return SFTTrainer(model="BASE_MODEL_ID", args=cfg, train_dataset=train_ds, eval_dataset=evals)

baseline = trainer(0.0, arms[0.0]).evaluate()      # the starting model, scored once

4. Train, then report forgetting as a delta from the starting model.

import math
ppl = lambda m, k: math.exp(m[f"eval_{k}_loss"])

for replay, ds in arms.items():
    t = trainer(replay, ds)
    t.train()
    after = t.evaluate()
    print(f"replay {replay:>4.0%}  domain ppl {ppl(baseline,'domain'):.1f} -> {ppl(after,'domain'):.1f}"
          f"   general ppl {ppl(baseline,'general'):.1f} -> {ppl(after,'general'):.1f}")

Repeat the comparison with a task benchmark such as lm-evaluation-harness, because perplexity can stay flat while a capability disappears. On packing=True: packing several documents into one sequence is efficient only if attention does not cross document boundaries; check that your TRL version and attention backend use position resets or variable-length attention (padding-free packing with a flash-attention kernel), or documents will attend to their neighbours.

5. Decide. Choose the smallest replay share whose general score stays inside the gate you wrote before training, and whose domain gain is real. If no arm passes, try a weight interpolation (WiSE-FT, see U6) between the starting and tuned weights at a few mixing values before buying more replay data; it needs no training.

Evaluation and gate

Compare against the starting model on four things: held-out domain loss, held-out general loss, a general benchmark, and, if you began from an instruct model, an instruction-following test. Perplexity alone is not enough. Thinking Machines reports (self-published) that mid-training a Qwen model on documents raised knowledge-question accuracy from 18% to 43% while its instruction-following score fell from 85% to 45%; mixing in chat data and adding distillation recovered it to 83%. The gate is a pair of limits set before the run: the domain gain must exceed a stated margin, and the general loss must rise by no more than a stated amount. Illustrative: domain perplexity down by 15%, general up by at most 2%.

Cost, GPU memory and operations

Full continued pretraining pays for gradients and optimiser state on every weight; with Adam in mixed precision the estimate is about 12 bytes per parameter for weights, gradients and optimiser states, or about 16 with the 32-bit master copy many setups keep (see Part V), before activations, so a 7B model needs several GPUs or sharding with DeepSpeed or FSDP. LoRA fits on one card, but Biderman and colleagues found it learns less: on code, HumanEval 0.224 for the best LoRA against 0.263 for full fine-tuning at 20 billion tokens (lab-reported). It forgets less on code, yet in maths rank-256 LoRA forgot nearly as much as full fine-tuning. Token budgets in the literature range from tens of millions (Llama 3's 405B annealing; the 8B used 40 billion) to 20 billion (Biderman's code run). Estimate yours as tokens divided by measured throughput, and measure throughput on a hundred steps first.

Operate the corpus as a versioned asset: record sources, licences, cleaning and dedup settings, and the evaluation sets it was checked against. A continued-pretrained base is not an assistant, so budget an SFT stage afterwards (B1). Re-run the whole check when the base model changes.

Failure drills

General forgetting
What happens
The model gains the domain and loses everything else.
Real case
Luo et al.: forgetting seen across 1B to 7B models and worse with scale in that range; Kalajdzievski: LoRA still forgets, on a power law.
Guard
General held-out slice and replay arms; stop on the gate, not on the loss curve.
Instruction-following collapse
What happens
Perplexity looks fine; the model stops obeying.
Real case
Thinking Machines (self-published): 85% to 45% after mid-training on documents.
Guard
Instruction test in the gate; start from the base model and run SFT afterwards.
Assuming LoRA is safe
What happens
The cheaper route does not remove the check.
Real case
Biderman et al.: rank-256 LoRA forgot nearly as much as full fine-tuning in maths.
Guard
Measure forgetting for the method you ship, not the one the paper favoured.
Duplicates and leaked tests
What happens
Memorised text and inflated scores.
Real case
Lee et al.: models emitted memorised text ten times less after deduplication; over 4% of some validation sets overlapped training data.
Guard
Deduplicate within the corpus and against every evaluation set with datatrove.

Run the second drill by evaluating instruction following before and after one arm. Run the fourth by planting twenty evaluation items in the corpus and confirming the dedup step removes them.

B6 checklist
  • Retrieval and SFT were tried first, and the gap is one of language rather than facts.
  • The corpus is cleaned, deduplicated and checked against every evaluation set.
  • The corpus is licensed for training, with sources recorded.
  • At least three replay shares are compared, including zero.
  • The learning-rate schedule is restarted with warm-up and decay.
  • General and domain held-out slices are fixed before training and appear in no mix.
  • A general benchmark, and an instruction test where relevant, run before and after.
  • The gate's two limits are written before the run.
  • An SFT stage is planned if the result must behave as an assistant.

Lab 15 · Continued pretraining vs forgetting runs this recipe (synthetic data, T4 GPU; not yet executed).

Part VII — Operate

A fine-tuned model does not finish when it ships. The model file stays still, but everything around it moves: the traffic changes, the serving stack gets upgraded, the base model it was tuned on is retired by its vendor. OpenAI's fine-tunes are the sharp example. Its deprecations page says fine-tuned versions of gpt-4o, gpt-4o-mini, gpt-4.1 and gpt-4.1-mini are removed with their base models on 14 January 2027, and a tuned model has no life of its own. Operating one is therefore a matter of watching a few numbers, knowing what to do when each moves, and having a rehearsed route for the day the base changes. This part gives the eight numbers, a playbook for an upgrade, and the lifecycle that keeps adapters from piling up.

What to watch

Eight metrics cover the failures in the Understand half and the gate in the Build half. Three tell you whether the tuning is still paying (held-out gap, regression rate, format validity). One watches what tuning can quietly damage (refusal and safety rate). One tells you whether the model, or its inputs, have moved (drift against the base). Three are about running it (cost, latency, adapter count).

Monitoring dashboard for a fine-tuned model (illustrative values)Eight tiles with illustrative values: held-out gap plus 4.1 points versus the base model, healthy; regression rate 2.8 percent and rising, watch; format validity 99.1 percent, healthy; refusal and safety rate 0.9 percent, healthy; drift versus the base model 0.21 and growing, watch; cost per 1,000 requests 38 cents, healthy; latency p95 640 milliseconds, healthy; live adapters 12 with 3 unused, healthy.Illustrative values✓ healthy ! watchHeld-out gap+4.1 ptsvs baseHealthyRegression rate2.8%risingWatchFormat validity99.1%HealthyRefusal / safety rate0.9%HealthyDrift vs base model0.21growingWatchCost per 1k requests$0.38HealthyLatency p95640 msHealthyLive adapters123 unusedHealthy

Every value on this dashboard is illustrative: it is a mock-up of a week with two warnings, not a measurement of any system. Each tile carries a glyph and a word as well as an outline, so a warning is never carried by colour alone. The shape is the point. Most tiles are flat and healthy; the two warnings, a rising regression rate and a growing drift against the base model, are slow drifts that no single day would reveal. That is why every tile shows a trend line and not only a number.

Metrics and warning signs

The table gives a working definition of each tile. The thresholds in the warning column are starting points to be tuned against your own history, not standards.

MetricWhat it measuresHow to computeWarning signFirst response
Held-out gapWhether the tuning still beats the base model on work it was never trained onScore of the tuned model minus score of the base model (with your best prompt) on a sealed held-out set, rerun on a scheduleGap shrinks by a third from release, or falls inside run-to-run noiseRefresh the held-out set from recent traffic; check whether a stronger base plus prompt now matches the tune
Regression rateHow often cases that passed at release now failShare of a fixed regression suite, plus graded samples of live traffic, that passed at release and fail nowAbove 2%, or rising three weeks in a rowRead the new failures as a slice; freeze promotions until the slice is explained
Format validityWhether outputs still parseShare of responses that validate against the output schema, counted before any repair stepBelow 99%, or any sudden stepCheck the chat template, tokenizer and serving version first, then the weights
Refusal and safety rateWhether tuning has changed what the model will and will not doRefusals on a fixed set of benign probes, and compliance on a fixed set of harmful probes, against the release baselineEither rate moves more than half a point from baselineRerun the release-gate safety suite; roll back if harmful compliance rose
Drift vs base modelHow far the tuned model's behaviour sits from the base on current trafficMean distance between tuned and base outputs on a sample of live prompts; choose a distance (embedding or edit) and keep itDistance grows steadily with no releaseCheck for a change in input mix or serving configuration before suspecting the model
Cost per 1k requestsWhat each thousand answers costs, all-in(GPU hours at your rate + hosting + managed-service fees) divided by requests, times 1,000Up 25% on the monthly baseline without a traffic changeCheck batch utilisation, adapter swapping and prompt length
Latency p95The slow tail users feel95th percentile of end-to-end latency per routeAbove your service target, or 30% over its own baselineLook for cold adapter loads; merge the busiest adapters into the base
Live adaptersHow many tuned variants you are carryingCount of adapters in the registry serving traffic, and how many saw no requests in 30 daysA fifth or more unused, or growth with no ownerRetire or archive the unused; every adapter is a thing to re-test

Two rows deserve a longer note. The safety row is there because the evidence says tuning can erode refusals even on innocent data. In one study, fine-tuning GPT-3.5 Turbo on a benign instruction dataset for one epoch raised the harmful-response rate from 5.5% to 31.8% (Qi et al., 2023), so a safe model today is not evidence of a safe model after the next tune. The held-out gap is the quiet partner of the regression rate: a gap can stay wide while a protected behaviour breaks, so you need both.

The base-model upgrade

The most predictable incident in this part is not a failure but a calendar entry. A new base model arrives, or the old one is retired. The tempting plan is to carry the adapter across. It does not work. A LoRA adapter is a pair of small matrices that adjust one specific set of base weights, and it is meaningful only against the base it was trained on; a different base has different weights, and often different dimensions. The fine-tune has to be repeated, which is why its data and recipe are the assets worth keeping, not the adapter file.

Base-model upgradeBase-model upgrade: 1. Re-baseline (new base, same held-out set); 2. Re-tune (same data, new base); 3. Compare (against the promoted adapter); 4. Swap or keep (better on every gate, or stay). Then back to step 1: if the new base alone matches your adapter, retire the adapter.Base-model upgradeRe-baselinenew base, same held-outsetRe-tunesame data, new baseCompareagainst the promotedadapterSwap or keepbetter on every gate,or stay↺ if the new base alone matches your adapter, retire the adapter

Re-baseline first, before touching any training. Score the new base on the same sealed held-out set, with the same prompt you give the old base. This answers the question that decides everything else: how much of your adapter's advantage the new base now gives you for nothing. A newer base can close part of the gap on a narrow task, and may close all of it, in which case the cheapest upgrade is to delete the adapter.

Then re-tune on the new base using the same training data snapshot and the same recipe, so any difference comes from the base and not from a changed dataset. Then compare the new adapter with the one in production on the held-out set and the regression suite, including the safety probes, because a new base has its own refusal behaviour and a new adapter can shift it. Swap only if the candidate wins by more than the noise floor and breaks nothing protected. If it does not, keep the old base running and say how long the old base remains supported. For a managed vendor that date is not yours to choose.

Registry, versions and retirement

An adapter is cheap to make, which is why they multiply. Each costs little to store; what costs something is knowing which one is serving, what it was trained on, and whether it still beats the base. The lifecycle below keeps that knowledge in one place.

Model and adapter lifecycle, with a base-model upgrade (illustrative scores)A base model version, v1, has a registry of adapter versions with held-out evaluation scores: adapter v1 retired at 71, adapter v2 promoted at 78, adapter v3 in shadow at 80. A shadow adapter is promoted only if it beats the promoted one on the held-out set with no regressions, and the old one is then retired. When the base model is upgraded to v2, the path forks: re-baseline the new base on the same held-out set, re-tune the adapters on it, compare against the old promoted adapter, then swap or keep the old base. Scores are illustrative.Illustrative versions and scoresBase model v1pinned by checksumbaseline held-out score: 62Registry: adapters on base v1held-out score, data snapshot, config, ownerAdapter v1score 71RetiredAdapter v2score 78PromotedAdapter v3score 80ShadowShadow becomes promoted only if it beats it on held-out data with no regressions.upgrade the basemodel: forkBase model v2new baseline needed1. Re-baselinebase v2, same held-out set2. Re-tunesame data, new base3. Comparevs promoted adapter v24. Swap or keeppromote only if better;else stay on base v1An adapter is tied to the base model it was trained on; it does not carry over to a new base.

Read the figure left to right. The base model is pinned by checksum and has its own baseline score. Every adapter on that base is a registry entry carrying its held-out score, the data snapshot, the config and a named owner. A new adapter enters in shadow, answering live traffic beside the promoted one without acting, and becomes promoted only if it beats the incumbent on held-out data with no regressions; the old one is then retired, not deleted, so a rollback is one change of pointer. The scores in the figure are illustrative.

Retirement is the part teams skip. Set a rule that an adapter with no traffic for 30 days is flagged, and one retired for a further period has its weights archived and its serving slot freed. Keep the data snapshot and config even after the weights go, since those are what a base-model upgrade needs. The figure's fork on the right is that upgrade: a new base starts a new column of versions, and nothing is promoted into it until the compare step has passed.

Our assessment

Watch eight numbers, and expect the first alarm to be a slow drift, not a crash. Treat the data snapshot and recipe as the lasting asset and the adapter as disposable, because a new base model will force a re-tune. Re-baseline before re-tuning, since a stronger base may make the adapter unnecessary, and keep every promoted version one pointer change from rollback.

Part VIII — Patterns, case studies, templates, directories

The earlier parts argued that fine-tuning pays when you can define and check the behaviour you want, and when you own the result. This part turns the argument into things to reuse: twelve patterns that survive contact with the evidence, six ways to get it wrong, four cases, three templates to copy, and a directory of vendors and tools as they stood on 7 November 2026. The last section maps the twenty labs onto the chapters.

Twelve patterns and six anti-patterns

Each pattern is a problem, a response and a condition for leaving it alone. Most are older than fine-tuning; the novelty is that tuning makes the old mistakes cheap to commit.

Pattern
1. Baseline first
A tune is only worth what it adds over the best prompt you could have written. Score the base model with a serious prompt and examples before any training. Skip it only when the behaviour is a format the base cannot produce at all.
Pattern
2. Sealed held-out set
Gains on data the model saw are partly memory. Build a test set before training, seal it, and look at it once per candidate. Below a few dozen cases the margin is noise.
Pattern
3. Decontaminate the split
Near-duplicates between training and test inflate every score. Deduplicate across the split, by meaning and not only by string. Unnecessary when test data is created after the training snapshot.
Pattern
4. Behaviour in weights, facts in retrieval
Tuning teaches style, format and policy; retrieval supplies facts that change. Do not train in what you will need to edit next month. Reverse this only for stable knowledge you must have offline.
Pattern
5. Fewer, cleaner examples
Quality and diversity of examples beat volume for style and format work. Curate a thousand good rows before collecting a hundred thousand ordinary ones. Large volume matters when you are teaching a new skill, not a manner.
Pattern
6. Smallest adapter that clears the gate
Start at a low rank, with a learning rate about ten times the full-fine-tuning rate as B2 explains, and raise the rank only while the held-out score rises. A larger adapter costs memory and forgets more. Full-parameter training is justified by a measured gap.
Pattern
7. Verifier before RL
Reinforcement learning needs a reward that cannot be argued with. Write and attack the checker first, then train against it. Where only a judge model exists, use preference tuning and audit the judge.
Pattern
8. Mix in the old behaviours
Narrow tuning overwrites what it does not rehearse. Include examples of safety, general chat and neighbouring tasks, and measure them. Pure continued pretraining on a domain needs this most.
Pattern
9. Teacher with a licence check
Training on a stronger model's outputs is fast, but the teacher's terms may forbid it. Read the licence, keep a record of which outputs came from which teacher, and filter by your checker. Skip distillation when the terms rule it out.
Pattern
10. Shadow, then canary, then full
An offline win can still fail on live traffic. Run the candidate beside the incumbent, then on a small slice, then everywhere. Not possible when an answer cannot be compared safely; use a small cap instead.
Pattern
11. Own the weights
Keep the data, recipe and a downloadable copy of what you trained. A vendor can retire a base model or a product. Accept lock-in only where the speed gain is worth a re-tune on their schedule.
Pattern
12. Re-baseline on every base change
A tune is a claim about one base model. When the base changes, score the new one before re-tuning. Little point where the adapter was never better than a prompt.

The anti-patterns are the same ideas from the failure side. Each is documented in the literature and each is cheap.

Anti-pattern
Tuning for knowledge
Fine-tuning to add facts underperforms retrieval, and fitting facts the model did not already know can raise hallucination. Retrieve, or tune the model to read retrieved text.
Anti-pattern
Tuning on the test set
The same cases pick the change and judge it. The score rises and the system does not. Seal the set and open it once.
Anti-pattern
A weak baseline
The comparison prompt is zero-shot and untuned, so any tune looks good. Give the baseline the same effort you gave the training run.
Anti-pattern
Skipping the safety check
Ten harmful examples were enough to break one model's guardrails, and benign data also weakened them (Part I). Test safety before and after every tune.
Anti-pattern
A judge that shares the trainer's bias
The model that produced the data also grades it, so errors agree. Use a different model or, better, an exact check, and audit against human labels.
Anti-pattern
Orphan adapters
Adapters multiply with no owner, no data snapshot and no retirement date. Each is a liability at the next base upgrade. Register, own and retire them.

Four cases

Facts here are as reported by their owners. Two cases show tuning working, one shows a service that tells you little, and one shows the cost of not checking. Business cases reads 76 documented programmes in the same way, with a source for each.

Case
A managed-service tune
Snowflake's Cortex Training, in public preview, runs supervised, preference and reinforcement-learning jobs on serverless GPUs. Its launch post claims "up to 61% lower cost" than Tinker and other serverless training APIs, from Snowflake's own LoRA benchmark priced against competitors' published rates of 22 October 2026. Named customers describe operational gains, such as OpenHands no longer spending days to weeks managing its own training cluster; the post gives no model-quality numbers for any of them. Weights stay inside Snowflake, with no download offered. Lesson: you can buy speed and give up portability, and the evidence for the purchase is operational, not about accuracy.
vendor-reported
Case
A small model beats a large one
Predibase's LoRA Land fine-tuned ten open models of 8B parameters or fewer on 31 tasks, 310 models in all, with 4-bit LoRA. It reports that 224 of the 310 beat GPT-4 and that the best tuned model per task averaged 0.756 against 0.661 for GPT-4. GPT-4 still won 6 of the 31 tasks, including coding and a broad knowledge benchmark. Lesson: narrow classification tasks favour the tune. The catch is the baseline: GPT-4 got simple zero- or one-shot prompts with no tuning, and the 0.756 picks the best model per task.
vendor-reported, baseline caveat
Case
RL on a checkable task
DeepSeek trained R1-Zero by applying GRPO directly to a base model, with rewards only from rules: whether the maths answer was right and whether the format was followed. It reports pass@1 on AIME 2024 rising from 15.6% to 77.9% in the version we read; earlier versions give a different figure, so cite the version you use. A later study found that such training lifts single-attempt accuracy while the base model can match it at many attempts. Lesson: an exact check is what makes this work, and what RL adds may be reliability more than reach.
lab-reported
Case
A fine-tune that failed
Qi and colleagues fine-tuned GPT-3.5 Turbo on the benign Alpaca dataset for one epoch and found the harmful-response rate rose from 5.5% to 31.8%, with Llama-2-7b-chat moving from 0.3% to 16.1%. Mixing in 250 safety examples brought the GPT-3.5 figure only to 21.8%. Separately, Gekhman and colleagues found that examples the model did not already know were fitted slowly, and that training to convergence on them scored 25.8% accuracy against 37.5% when stopped early. Lesson: an ordinary tune can break what you did not test.
research result

Three templates

Copy these, strip what you do not need, and keep them in the repository beside the training code. A template nobody fills in is a ritual; one that blocks a release when blank is a control. All sizes and values are illustrative.

Managed-service directory

Prices and policies change monthly, so treat this as a snapshot as of November 2026. Only rows we could check against a vendor page are included; vendors whose prices or export terms we could not verify are listed after the table.

VendorMethodsPrice basisWeight exportStatus
OpenAISupervised, vision, DPOPer 1M training tokens; last published $3 (4o-mini) to $25 (4.1)NoWind-down: no new jobs for active customers after 6 Jan 2027; 4o and 4.1 bases removed 14 Jan 2027
Together AILoRA SFT and DPO; likely full-parameter in a second tablePer 1M tokens; Llama 3.1 8B $0.34 SFT, $0.84 DPO, minimum $4Yes (merged, adapter or full)Active
FireworksLoRA SFT, DPO, full-parameter SFT; RL through a serverless training APILoRA SFT $0.50 per 1M up to 16B; DPO and full-parameter twice thatReported yes (secondary source)Active; serving a tuned model needs a dedicated deployment
Tinker (Thinking Machines)Training API for SFT and RLPer 1M tokens; Qwen3-8B $0.44 train, as of 19 Oct 2026, sampling priced separatelyYes, any saved checkpointActive; serverless inference in beta
Snowflake Cortex TrainingSFT, DPO, RL and othersAI credits per GPU-second, no minimumNo ("don't download model weights")Public preview, enablement needed
Amazon BedrockReinforcement fine-tuning on gpt-oss-20b and Qwen3 32B; classic customisationRFT $80 per training hour plus token charges; custom inference on provisioned throughputNot documented in the pages we readActive
DatabricksModel Training (replaces Foundation Model Fine-tuning, now end of life)$0.65 per DBU; 70B at 10M words about $146Checkpoints in MLflow and Unity Catalog; export steps not describedActive
Modal (DIY)Whatever you runGPU only, per second; A100-80 about $2.50 an hour, H100 about $3.95You own everythingActive

Not included because we could not verify them from vendor pages: Google Vertex and Microsoft Foundry prices (feature lists were verified, prices were placeholders or absent), Alibaba, Nebius and Predibase after its acquisition by Rubrik. The wind-down at OpenAI is a reminder of the table's main lesson: the column to read first is "Weight export", because it decides what you keep when the rest changes.

Tool directory

Tools sit at different layers, so the useful question is which layer you are working on. The panel lists every repository we checked on 7 November 2026, with licence, the date of the latest push to any branch (which can reflect documentation or CI work) and our status call. Torchtune and AutoTrain are listed so you know not to start new work on them.

The 20 labs, mapped to chapters

The companion labs run from measuring a baseline to a governed capstone. They are synthetic-data teaching notebooks, written for a T4-class GPU and syntax-checked only; they have not yet been executed on a GPU, so treat their numbers as unobserved until they are. Each card names the chapter it belongs to.

Lab 01
GPU, tokens and a baseline
Counting tokens, fitting a model in memory, and scoring the base model before you change it.
T4 GPU · Part V
Lab 02
Data curation and leakage
Cleaning examples and catching train and test overlap before it flatters a score.
T4 GPU · Part V
Lab 03
Full-parameter SFT
Supervised tuning of every weight, to see what it costs and what it changes.
T4 GPU · chapter B1
Lab 04
LoRA SFT
The same task with a small adapter, and what that saves in memory.
T4 GPU · chapter B2
Lab 05
QLoRA 4-bit
A quantised base with an adapter, and the quality cost of squeezing it.
T4 GPU · chapter B2
Lab 06
LoRA rank and learning-rate ablation
Varying rank and learning rate to find the smallest adapter that clears the gate.
T4 GPU · chapter B2
Lab 07
Reliable JSON outputs
Teaching a model to emit valid structured output and measuring how often it does.
T4 GPU · chapter B1
Lab 08
DPO
Preference tuning from chosen and rejected pairs.
T4 GPU · chapter B3
Lab 09
KTO
Preference tuning from single good-or-bad labels, with no pairs.
T4 GPU · chapter B3
Lab 10
Reward model
Training a scorer from preferences and testing what it rewards.
T4 GPU · chapter B3
Lab 11
GRPO arithmetic verifier
Reinforcement learning against an exact checker on arithmetic.
T4 GPU · chapter B4
Lab 12
GRPO multiple rewards
Combining several reward terms and watching them trade off.
T4 GPU · chapter B4
Lab 13
Adversarially robust verifier
Attacking the checker to find how a model could cheat it, then closing the hole.
T4 GPU · chapter B4
Lab 14
Teacher-student distillation
Training a small model on a stronger model's filtered outputs.
T4 GPU · chapter B5
Lab 15
Continued pretraining vs forgetting
Adding domain text and measuring what the model forgets.
T4 GPU · chapter B6
Lab 16
RAG vs fine-tuning
Comparing retrieval and tuning on the same question set.
T4 GPU · Part IV
Lab 17
Tool-call SFT
Supervised tuning on tool-call formats and the errors that follow.
T4 GPU · chapter B1
Lab 18
Regression suite and error taxonomy
Building the fixed suite and error categories the dashboard relies on.
T4 GPU · Part VII
Lab 19
Adapter save, merge and portability
Saving, merging and reloading an adapter elsewhere, and what breaks.
T4 GPU · chapter B2 and Part VII
Lab 20
Capstone: governed invoice-intake model
One tune carried through proposal, evaluation plan, release gate and monitoring.
T4 GPU · Parts IV to VII
Our assessment

Reuse the patterns, not the tools. The patterns that hold up are the ones that protect the check: a strong baseline, a sealed held-out set, a safety probe and a rollback. The directories will be stale within months, and the column to trust is weight export. Read the labs as drafts until they have been run.

Close

What it means

What it means

The $50 fine-tune

The price of a LoRA run has fallen to the cost of lunch. The price of knowing whether it worked has not moved.

Renting the compute to fine-tune a small open model now costs less than a dinner for two. As of November 2026, Together AI lists Llama 3.1 8B at $0.34 per million training tokens, Tinker lists Qwen3-8B at $0.44, and Fireworks charges $0.50 for models up to 16B parameters (all vendor-reported list prices). Take a representative job, which is ours and illustrative: 20,000 examples of 800 tokens each, trained for three epochs, or 48 million training tokens. That comes to about $16 on Together, $21 on Tinker and $24 on Fireworks. A $50 budget buys the run, a change of learning rate and a second run. OpenAI's last published price for gpt-4.1 was $25 per million tokens, which puts the same job near $1,200, on a platform that no longer admits new users.

The collapse has a plain cause. A low-rank adapter on an 8B model is cheap compute, and the hosts now compete on one table. The cheapness also reflects what a LoRA run does: a study of code and maths found that it learns less than full fine-tuning as well as forgetting less. The low price is partly a low ceiling, which is fine for narrow behaviour and a poor fit for teaching a model a new domain.

Now the part of the bill the table omits. The 20,000 examples must come from somewhere, and someone must check them. The held-out set is smaller but dearer. Suppose 500 cases, each judged by two reviewers for three minutes: that is 50 hours of expert time, or $2,000 at an illustrative $40 an hour, some eighty to 125 times the $16 to $24 training run. Human-data vendors have moved their value to expert judgement, rubrics and verifiers for the same reason. One vendor's recruiting page quotes trainer rates from $12 to over $200 an hour (vendor-reported).

Cheap runs also invite a quieter error. Run twenty variants against a test set of 500 and one will look good by chance. Contamination makes it worse: on GSM1k, a fresh set matched to a famous benchmark, some models lost up to 8%, and in Predibase's LoRA Land study 224 of 310 tuned models beat GPT-4, but the GPT-4 baseline was prompted zero- or one-shot with no tuning, while Medprompt reached state of the art with prompting alone. A fine-tune that beats a lazy baseline on a leaky test has proved nothing.

The sensible response is to move the money. Budget for the referee before the run: the data checks of Lab 02, the regression suite and error taxonomy of Lab 18, and a baseline that someone with a stake in it has tried hard to improve.

Behaviour, not knowledge

Retrieval carries the facts and tuning carries the manners. Using both is a design choice, not an upgrade.

The oldest hope for fine-tuning was that it could teach a model new facts. The measured record is unkind to it. Ovadia and colleagues tested Mistral-7B on questions about events after its training cutoff. The base model scored 0.481. With retrieved passages it scored 0.875. Unsupervised fine-tuning on the same facts reached 0.504, and 0.588 when the text was paraphrased. Soudani and colleagues, working across twelve models on rarely discussed entities, found retrieval ahead of tuning by a wide margin: on PopQA, Mistral-7B went from 21.47 to 30.70 with tuning and to 80.25 with retrieval (ideal retrieval, so an upper bound).

Gekhman and colleagues at Google explain why in terms that should worry anyone with a proprietary corpus. Examples whose facts the model did not already know were learned slowly, and fitting them made the model worse. On one set of questions, accuracy at convergence was 25.8, against 37.5 when training stopped early. The model learned to assert things it had no grounds for.

What tuning does well is change how a model behaves: the format it answers in, the tool call it emits, the register it keeps, the thing it refuses. RAFT trained a model on questions with a gold document and distractors, and its Llama 2 7B scored 73.30 on a medical set, against 59.7 for domain tuning without documents and 71.6 for GPT-3.5 with retrieval. The tuning taught the model to read what retrieval gave it, not to remember it. LoRA Land's best results were on narrow classification tasks near 90% accuracy, while GPT-4 kept its lead on coding and broad knowledge.

The combination is not automatically better, and this is the point most vendor material skips. In Soudani's work, adding tuning to retrieval helped models of 3B parameters and below (StableLM2-1.6B went from 76.14 to 82.09) and slightly hurt Mistral-7B (80.25 to 78.44). Ovadia found the gain over retrieval alone inconsistent. Whether the pair helps depends on what the tuning teaches: facts, or how to use context.

Behaviour is not harmless to change, either. Ten harmful examples took GPT-3.5 Turbo's harmfulness rate from 1.8% to 88.8% in Qi and colleagues' test, and benign Alpaca data alone moved it from 5.5% to 31.8%. Narrow tuning on insecure code produced broad misalignment in GPT-4o, in the emergent-misalignment study. A behaviour you tune in comes with behaviours you did not mean to.

The rule that follows is cheap to apply. Name the failure first. If the model states a wrong fact, fix the retrieval. If it gets the format, tone or tool call wrong, tune. If it does both, test the pair on your own data, as Lab 16 does, before assuming the sum is greater than the parts.

Own the weights

A closed-model fine-tune is a lease on a building the landlord can demolish. Open weights and a small adapter are a deed.

OpenAI has set out the schedule on its deprecations page. On 7 May 2026 it announced that new fine-tuning jobs would close to organisations that had never fine-tuned. From 2 July they closed to organisations that had not run inference on a fine-tuned model (a 60-day window, per our market review). From 15 December 2026, a date brought forward from 6 January 2027, no organisation can create new self-serve jobs. The tuned models themselves die with their bases: gpt-4o, gpt-4o-mini, gpt-4.1 and gpt-4.1-mini are removed on 14 January 2027, with gpt-6-luna named as the replacement, and a fine-tuned o4-mini was removed on 23 October 2026. The page names replacement base models but no successor fine-tuning product. Others have gone the same way: Cohere's fine-tuning was deprecated on 15 September 2025 (docs banner, secondary source), and the maintainers of Hugging Face AutoTrain say it is no longer maintained.

The lesson is about churn. Base models are replaced faster than the artefacts built on them can be amortised, and a tuned model you cannot move is a liability with a date on it. The business case for a closed fine-tune now has to cover its own funeral.

Portability is therefore the feature to compare, and vendors differ sharply. Together AI documents a download command that returns a merged model, an adapter or a full checkpoint, in Hugging Face format. Tinker offers an endpoint to download any saved checkpoint. Fireworks reportedly lets you download adapters and base models (secondary source), but its docs say a dedicated deployment is the only supported way to serve a trained model. Snowflake's documentation tells customers not to download weights. Bedrock serves custom models through provisioned throughput, and Databricks promises full control of the trained model without describing an export. Read these pages before choosing a platform, not after training.

The portable unit is the adapter on an open base. It weighs megabytes, merges into the base with one call in PEFT and loads in vLLM and SGLang. Two cautions apply. An adapter is tied to the base it was trained on, so if that base is not hosted anywhere you want to run, the export is a souvenir. And open weights carry licences: Llama's requires "Llama" at the start of the name of any model improved with its outputs, and Anthropic's commercial terms bar using the service to train competing models. We found no court ruling on the latter; enforcement so far is account bans and contract terms.

The test is empirical and takes an afternoon: train, export, serve in vLLM, and compare scores with the original. Lab 19 sets it out. Do it before you depend on the vendor, and repeat it when you change the base. Whoever holds the weights holds the choice of when to move.

What to watch

Indicator 1
Matched-baseline comparisons

What it is. Published results in which a tuned small model is compared with a prompted or retrieval-augmented model given an equal tuning effort, on the same held-out set, with the baseline prompt released.

Why it matters. Most "small tuned model beats GPT-4" results used a weak or undisclosed baseline. Medprompt showed that prompting alone can close the gap.

What would count. A stated budget of prompt-engineering hours or calls, confidence intervals, and the baseline prompt in the appendix.

Indicator 2
OpenAI's 15 December 2026 date

What it is. Whether the cut-off for creating self-serve fine-tuning jobs, already brought forward once, stands, moves again, or is paired with a successor product.

Why it matters. It decides whether the closed-model route remains open at all, and whether grader-based tuning of a frontier model survives anywhere.

What would count. An official post naming a successor, or the date passing with no job creation for active customers.

Indicator 3
A safety gate on tuning

What it is. Before-and-after safety evaluation as a standard release step for tuned models, across data types that nobody labelled harmful.

Why it matters. Benign data erodes refusals, and narrow data can shift a model's whole persona. Mixing in safety examples reduced the harm but did not restore the starting level on benign data.

What would count. A published protocol that predicts which datasets trigger emergent misalignment before training, and a defence that holds against an adaptive attacker.

Indicator 4
Matched-workload price comparisons

What it is. The same job, with the same tokens, model and quality bar, priced on several platforms, including RL jobs billed per hour.

Why it matters. Units differ: per token, per GPU-second, per training hour. Snowflake's "up to 61% lower cost" is a vendor benchmark against competitors' list prices, in preview.

What would count. An independent measurement of tokens per second per accelerator and a full bill, including storage and serving.

Indicator 5
A ruling on training from API outputs

What it is. A court decision, not a terms-of-service clause, on whether a model's outputs may be used to train a competing model.

Why it matters. Distillation from a closed teacher is the cheapest source of data, and today it rests on contract terms and account bans.

What would count. A judgment that addresses output ownership and competing use, or a change in the major providers' terms.

How is this page?

Last updated on