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.
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
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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.
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.
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.
- Transfer learning: Howard and Ruder, ULMFiT (2018); Devlin et al., BERT (2018); Gururangan et al., Don't Stop Pretraining (2020).
- Multitask instruction tuning: Wei et al., FLAN (2021); Sanh et al., T0 (2021); Wang et al., Super-NaturalInstructions (2022); Chung et al., Scaling Instruction-Finetuned Language Models (2022); Longpre et al., Flan Collection (2023).
- RLHF: Ouyang et al., InstructGPT (2022); Wang et al., Self-Instruct (2022).
- PEFT democratised: Hu et al., LoRA (2021); Dettmers et al., QLoRA (2023); Taori et al., Alpaca (2023); Zhou et al., LIMA (2023); Gudibande et al., The False Promise of Imitating Proprietary LLMs (2023).
- Preference and RL post-training: Rafailov et al., DPO (2023); Shao et al., DeepSeekMath and GRPO (2024); Lambert et al., Tulu 3 (2024); DeepSeek, DeepSeek-R1 (2025).
- Serverless training utilities: Thinking Machines, LoRA Without Regret (2025) and Tinker (2025); Snowflake, Cortex Training (public preview, November 2026); OpenAI, deprecations page (2026).
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.
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.
- Zhou et al., LIMA (2023). 1,000 curated examples; the Superficial Alignment Hypothesis.
- Lin et al., The Unlocking Spell on Base LLMs (2023). Base and aligned models differ mainly in stylistic tokens.
- Raghavendra et al., Revisiting the Superficial Alignment Hypothesis (2024). Power-law gains from more fine-tuning examples.
- Lambert et al., Tulu 3 (2024). An open post-training recipe at about a million examples.
- Gekhman et al., Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? (2024).
- Ovadia et al., Fine-Tuning or Retrieval? (2023).
- Allen-Zhu and Li, Physics of Language Models 3.1 (2023).
- Biderman et al., LoRA Learns Less and Forgets Less (2024); Kalajdzievski, Scaling laws for forgetting (2024).
- Qi et al., Fine-tuning aligned language models compromises safety (2023); Betley et al., Emergent Misalignment (2025).
A framework for the whole review
Five concepts explain most of what follows, and each returns in the Build half as a gate.
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.
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.
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.
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.
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.
- Instruction collections: FLAN (2021): beats zero-shot GPT-3 175B on 20 of 25 tasks. T0 (2021): beats GPT-3 on 9 of 11 held-out datasets at about 16 times smaller. Super-NaturalInstructions (2022): 1,616 tasks. Flan-PaLM and Flan-T5 (2022): 1,836 tasks, +9.4 at 540B, 0.2% of pre-training compute. Flan Collection (2023): 3 to 17 points over earlier open sets.
- Human demonstrations: InstructGPT (2022): 13k SFT prompts, 1.3B preferred to 175B GPT-3. Llama 2 (2023): 27,540 own annotations. Tulu 3 (2024): 939,344 of 23.3M.
- Model-written data: Self-Instruct (2022): 52,445 instructions, +33 on Super-NI. Alpaca (2023): 52K examples, student-judged. False Promise (2023).
- Curation: LIMA (2023); AlpaGasus (2023): 9,229 of 52K; LESS (2024): a gradient-selected 5% often beats the full set.
- What SFT can teach: URIAL (2023); Gekhman et al. (2024); Raghavendra et al. (2024).
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.
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.
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.
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.
- Earlier adapters: Houlsby adapters (2019): within 0.4% of full tuning on GLUE with about 3.6% extra parameters. Prefix tuning (2021); Prompt tuning (2021).
- LoRA and memory: LoRA (2021): 10,000 times fewer trainable parameters, 1.2 TB to 350 GB. QLoRA (2023): 65B on 48 GB. FSDP+QLoRA (2024): 70B on two 24 GB GPUs.
- Variants (author-run): AdaLoRA (2023); VeRA (2023); rsLoRA (2023); DoRA (2024); LoRA+ (2024); PiSSA (2024).
- LoRA against full tuning: LoRA Learns Less and Forgets Less (2024); An Illusion of Equivalence (2024); LoRA Without Regret (blog, September 2025, vendor-written).
- Serving and merging: Punica (2023); S-LoRA (2023); LoraHub (2023); Model soups (2022); Task arithmetic (2022); TIES (2023); DARE (2023); MergeKit (2024).
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.
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.
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.
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.
- Origins of RLHF: Deep RL from human preferences (2017); Fine-tuning language models from human preferences (2019); InstructGPT (2022): 85 ± 3% over GPT-3, hallucination 41% → 21%, 60 vs 3,640 petaflops/s-days.
- PPO and its simplifications: Secrets of RLHF, Part I (2023); RLOO, Back to Basics (2024); Is DPO superior to PPO? (2024).
- Direct methods: DPO (2023); IPO (2023); KTO (2024); ORPO (2024); SimPO (2024): up to +6.4 AlpacaEval 2 and +7.5 Arena-Hard over DPO, author-reported.
- AI feedback: Constitutional AI (2022); RLAIF vs RLHF (2023); Online AI Feedback (2024); Tülu 3 (2024), an open SFT, DPO and RLVR recipe.
- Limits and measurement: Reward model overoptimisation (2022); RewardBench (2024); Disentangling length from quality (2024): up to 20% win-rate change when length is controlled; Preference learning algorithms do not learn preference rankings (2024): under 60% ranking accuracy.
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 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.
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.
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.
- The algorithm: DeepSeekMath / GRPO (2024); DeepSeek-R1 (2025): R1-Zero AIME 2024 pass@1 15.6% → 77.9% in the fetched version; DAPO (2025): 30 → 50 on AIME 2024 by ablation, one base model; Dr. GRPO (2025); GSPO (2025, authors' claim on MoE stability).
- Recipes: Tülu 3 (2024); Webscale-RL (2025): turns pretraining documents into verifiable questions.
- Does it add ability? Yue et al. (2025): pass@1 26.1 → 42.5, pass@256 67.2 → 64.3; ProRL (2025); SFT memorises, RL generalises (2025); RL's Razor (2025).
- Reliability of the evidence: Spurious rewards (2025): +21.4 random vs +29.1 true, Qwen only; Reasoning or memorisation? (2025), contamination argument, not settled.
- Hacking and environments: Natural emergent misalignment from reward hacking (2025); Prime Intellect Environments Hub (launched 27 August 2025).
- Managed offerings (as of November 2026): Amazon Bedrock RFT; Vertex reinforcement tuning, pre-GA; Microsoft Foundry RFT; OpenAI deprecations, o4-mini retired 2026-10-23.
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.
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.
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.
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.
- Ancestry: Distilling the Knowledge in a Neural Network (2015); Sequence-Level KD (2016): about 10× faster student, +4.2 BLEU greedy over no distillation.
- On-policy: MiniLLM (2023); GKD (2023): relative gains of 1.7–2.1× over baseline KD on T5; On-Policy Distillation (Thinking Machines, 2025, self-published).
- Imitation and instruction data: Self-Instruct (2022); Alpaca (2023, under $500 of API calls, non-commercial); Orca; Evol-Instruct; Distilling Step-by-Step; The False Promise of Imitating Proprietary LLMs; Magpie; Phi-4.
- Reasoning distillation: DeepSeek-R1 (2025): AIME 2024 72.6 (32B) against 47.0 for RL only; s1; LIMO; OpenThoughts.
- Selection and hygiene: AlpaGasus; DEITA; Deduplicating Training Data; SemDeDup; Rethinking Benchmark and Contamination; model collapse and its rebuttal; Nemotron-4 340B.
- Terms and market: Anthropic on distillation attacks (Feb 2026); Llama 3.1 licence; CoreCraft (vendor-authored); APEX-Agents (24.0% Pass@1, January 2026 snapshot); Ramp Fast Ask (company post; RL).
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.
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.
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.
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.
- Domain adaptation: Don't Stop Pretraining (2020): ACL-ARC 63.0 → 75.4, SciERC 77.3 → 80.8, no gain on news; Simple and Scalable Strategies to Continually Pre-train (2024): 5% and 25% replay.
- Mid-training: Llama 3 (2024): GSM8K +24.0% on 8B, negligible at 405B; OLMo 2 (2024): 5–10% of compute.
- Forgetting: LoRA Learns Less and Forgets Less (2024); Scaling laws for forgetting (2024); Illusion of Equivalence (2024); Forgetting in continual instruction tuning (2023).
- Facts: Synthetic continued pretraining (2024): 39.49% → 56.22%; Physics of Language Models 3.1 (2023); New knowledge and hallucination (2024); Fine-Tuning or Retrieval? (2023).
- Repair: On-Policy Distillation (Thinking Machines, self-published): knowledge QA 18% → 43%, instruction-following 85% → 45% → 83% with mixing and distillation.
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.
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.
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.
The market in 2026
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.
The model learns the wrong thing.
The check does not match production.
You do not fully own the result.
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.
- Knowledge, retrieval and prompting: Ovadia et al., Fine-Tuning or Retrieval? (2023); Soudani et al., Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge (2024); Zhang et al., RAFT (2024); Balaguer et al., RAG vs Fine-tuning (2024); Nori et al., Medprompt (2023); Agarwal et al., Many-Shot In-Context Learning (2024); Bertsch et al., In-Context Learning with Long-Context Models (2024); Mosbach et al., Few-shot Fine-tuning vs. In-context Learning (2023).
- Small tuned models: Zhao et al., LoRA Land (2024, vendor paper); Thinking Machines, Tinker customer cases (2026, vendor-reported).
- Forgetting and LoRA: Biderman et al., LoRA Learns Less and Forgets Less (2024); Kalajdzievski, Scaling laws for forgetting (2024); Luo et al., Catastrophic forgetting in continual fine-tuning (2023).
- Hallucination and overfitting: Gekhman et al., Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? (2024).
- Safety and misalignment: Qi et al., Fine-tuning Aligned Language Models Compromises Safety (2023); Qi et al., Safety Alignment Should Be Made More Than Just a Few Tokens Deep (2024); Betley et al., Emergent Misalignment (2025); Turner et al., Model Organisms for Emergent Misalignment (2025); Wang et al., Persona Features Control Emergent Misalignment (2025); MacDiarmid et al., Natural Emergent Misalignment from Reward Hacking (2025).
- Reward hacking: Gao et al., Scaling laws for reward model overoptimization (2022); Park et al., Disentangling length from quality in DPO (2024).
- Contamination and leakage: Zhang et al., A Careful Examination of LLM Performance on Grade School Arithmetic (2024); Golchin and Surdeanu, Time Travel in LLMs (2023); Yang et al., Rethinking Benchmark and Contamination (2023).
- Market, pricing and terms (vendor-reported, read 2026-11-07): OpenAI, deprecations and pricing; Together AI; Fireworks; Tinker pricing; Snowflake, Cortex Training; Anthropic, commercial terms; Cloudflare, Replicate announcement; TechCrunch, Rubrik acquires Predibase (2025).
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?
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.
- 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?
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?
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.
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
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.
- Convert each row to TRL's conversational prompt-completion format.
- Normalise text and drop duplicates; normalising catches case, spacing and punctuation variants that exact matching misses.
- Compare each held-out row's word 5-grams with every training row and stop if any overlap passes the threshold.
- 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- Check it: on three invented invoice rows, two of them identical apart from case and punctuation,
dedupereturned two rows; copying a training row into the held-out list madeleakedreturn 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 toSFTTrainerwithSFTConfig(max_length=2048)andprocessing_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.
- Write a scorer that reports validity and correctness as separate numbers.
- Run the identical tasks against both models and print the means.
- 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})- 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 withoutpeft=. A--limitsample is noisy; use it to catch collapses, not small changes. - 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 the adapter on its own after training.
- 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. - 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())- 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- Check it: on a tiny randomly initialised Llama model with a non-trivial rank-4 adapter, the saved adapter folder held
adapter_config.jsonandadapter_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
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.
- 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
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.
tokenizer= or max_seq_length= fail on a current install.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.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
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, held3. 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_dir5. 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 baselineWe 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
- 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
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
LoraConfig defaults to rank 8 and alpha 8; merge_and_unload() folds an adapter into its base.BitsAndBytesConfig. Version 0.50.2 on 27 August 2026. It now lives under a foundation organisation, not a personal repository.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
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 spread3. 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
- 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
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
chosen / rejected rows. Default loss_type is sigmoid, default beta 0.1. Part of TRL 1.17.1 (30 October 2026).prompt / completion / label; a paired set is converted automatically. Top-level import since TRL 1.8; older code importing from trl.experimental must change.chosen / rejected pairs. Use it as a judge or filter, or as the reward for online RL; DPO and KTO do not need it.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
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
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.
- 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_typeand 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
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
--actor.model_name_or_path); older flat-flag scripts were not tested. Its README recommends Molt, which we have not evaluated. 0.11.2.skyrl now unifies the older skyrl-train and skyrl-tx; skyrl-gym holds environments. 0.4.0.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
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_weights3. 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
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.
- 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_stdand 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
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
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
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 name2. 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
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.
- 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
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
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
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 once4. 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
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.
- 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).
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.
| Metric | What it measures | How to compute | Warning sign | First response |
|---|---|---|---|---|
| Held-out gap | Whether the tuning still beats the base model on work it was never trained on | Score of the tuned model minus score of the base model (with your best prompt) on a sealed held-out set, rerun on a schedule | Gap shrinks by a third from release, or falls inside run-to-run noise | Refresh the held-out set from recent traffic; check whether a stronger base plus prompt now matches the tune |
| Regression rate | How often cases that passed at release now fail | Share of a fixed regression suite, plus graded samples of live traffic, that passed at release and fail now | Above 2%, or rising three weeks in a row | Read the new failures as a slice; freeze promotions until the slice is explained |
| Format validity | Whether outputs still parse | Share of responses that validate against the output schema, counted before any repair step | Below 99%, or any sudden step | Check the chat template, tokenizer and serving version first, then the weights |
| Refusal and safety rate | Whether tuning has changed what the model will and will not do | Refusals on a fixed set of benign probes, and compliance on a fixed set of harmful probes, against the release baseline | Either rate moves more than half a point from baseline | Rerun the release-gate safety suite; roll back if harmful compliance rose |
| Drift vs base model | How far the tuned model's behaviour sits from the base on current traffic | Mean distance between tuned and base outputs on a sample of live prompts; choose a distance (embedding or edit) and keep it | Distance grows steadily with no release | Check for a change in input mix or serving configuration before suspecting the model |
| Cost per 1k requests | What each thousand answers costs, all-in | (GPU hours at your rate + hosting + managed-service fees) divided by requests, times 1,000 | Up 25% on the monthly baseline without a traffic change | Check batch utilisation, adapter swapping and prompt length |
| Latency p95 | The slow tail users feel | 95th percentile of end-to-end latency per route | Above your service target, or 30% over its own baseline | Look for cold adapter loads; merge the busiest adapters into the base |
| Live adapters | How many tuned variants you are carrying | Count of adapters in the registry serving traffic, and how many saw no requests in 30 days | A fifth or more unused, or growth with no owner | Retire 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.
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.
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.
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.
The anti-patterns are the same ideas from the failure side. Each is documented in the literature and each is cheap.
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.
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.
Write this before spending any compute. If a line cannot be filled in, you are not ready.
## Fine-tune proposal: <behaviour>
1. Behaviour to change (one sentence, observable): ___
2. Why a prompt, examples or retrieval do not suffice. Evidence: baseline
score ___ with best prompt, on held-out set of ___ cases.
3. Method: SFT / LoRA / preference / RL / distillation. Reason: ___
4. Check: exact (tests, schema, match) / model judge audited against
humans. Who wrote and attacked it: ___
5. Data: source ___, licence ___, size ___, personal data? ___
6. Base model and its vendor support end date: ___
7. Where weights live, and can we download them? ___
8. Budget: compute $___, people-days ___, GPU memory needed ___
9. Success: beats baseline by >= ___ points; zero protected regressions.
10. Decision if it fails: keep the prompt / switch method / stop.
Outcome: build / build smaller / do not buildEverything marked "sealed" is frozen for the life of the plan.
# evaluation-plan.yaml (all values illustrative)
behaviour: "invoice fields extracted as valid JSON"
base_model: "<base-model-id>" # pinned
baseline:
prompt: prompts/best_baseline.md # same effort as the tune
held_out_score: null # fill before training
splits:
train: data/train/ # model may see this
validation: data/val/ # for choosing hyperparameters
held_out: data/held_out/ # SEALED: looked at once per candidate
size: { train: 2000, val: 200, held_out: 300 }
decontamination: "near-duplicate check across all three splits"
regression_suite: eval/regression/ # SEALED: must never break
safety_probes:
benign_refusal: eval/safety/benign.jsonl
harmful_compliance: eval/safety/harmful.jsonl
metrics:
primary: held_out_exact_match
guards: [format_validity, regression_failures, safety_delta, latency_p95]
noise_floor: "rerun 5 seeds; margin must exceed the spread"
stop_when: "held-out flat for 3 candidates"A candidate is released only if every line is true. Anything unticked is a "no".
## Release gate: <adapter> v<old> -> v<new>
- [ ] Beats the best-prompt baseline on the SEALED held-out set by more
than the noise floor
- [ ] Beats the promoted version on the same set
- [ ] Regression suite: zero newly broken cases (list any: ___)
- [ ] Safety probes: refusal and compliance within ___ of baseline
- [ ] Format validity >= ___% before any repair step
- [ ] Cost per 1k requests and p95 latency within agreed bounds
- [ ] Data snapshot, config, base-model checksum and owner recorded
- [ ] Weights downloadable and load-tested in the serving stack
- [ ] Shadow run on live inputs for ___ days; disagreements reviewed
- [ ] Rollback tested today: restores v<old> in ___ minutes
Decision: release / hold / reject Reviewer: ____ Date: ____
Evidence: link to run, scores, diff of configManaged-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.
| Vendor | Methods | Price basis | Weight export | Status |
|---|---|---|---|---|
| OpenAI | Supervised, vision, DPO | Per 1M training tokens; last published $3 (4o-mini) to $25 (4.1) | No | Wind-down: no new jobs for active customers after 6 Jan 2027; 4o and 4.1 bases removed 14 Jan 2027 |
| Together AI | LoRA SFT and DPO; likely full-parameter in a second table | Per 1M tokens; Llama 3.1 8B $0.34 SFT, $0.84 DPO, minimum $4 | Yes (merged, adapter or full) | Active |
| Fireworks | LoRA SFT, DPO, full-parameter SFT; RL through a serverless training API | LoRA SFT $0.50 per 1M up to 16B; DPO and full-parameter twice that | Reported yes (secondary source) | Active; serving a tuned model needs a dedicated deployment |
| Tinker (Thinking Machines) | Training API for SFT and RL | Per 1M tokens; Qwen3-8B $0.44 train, as of 19 Oct 2026, sampling priced separately | Yes, any saved checkpoint | Active; serverless inference in beta |
| Snowflake Cortex Training | SFT, DPO, RL and others | AI credits per GPU-second, no minimum | No ("don't download model weights") | Public preview, enablement needed |
| Amazon Bedrock | Reinforcement fine-tuning on gpt-oss-20b and Qwen3 32B; classic customisation | RFT $80 per training hour plus token charges; custom inference on provisioned throughput | Not documented in the pages we read | Active |
| Databricks | Model Training (replaces Foundation Model Fine-tuning, now end of life) | $0.65 per DBU; 70B at 10M words about $146 | Checkpoints in MLflow and Unity Catalog; export steps not described | Active |
| Modal (DIY) | Whatever you run | GPU only, per second; A100-80 about $2.50 an hour, H100 about $3.95 | You own everything | Active |
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.
Training frameworks
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| TRL | Apache-2.0 | 2026-11-07 | active; v1 line with breaking changes |
| Axolotl | Apache-2.0 | 2026-11-06 | active; organisation renamed |
| LLaMA-Factory | Apache-2.0 | 2026-11-06 | active; install from source, since the package release is months behind |
| Unsloth | Apache-2.0 in the package; some root files and the Studio folder are AGPL-3.0 | 2026-11-07 | active; read both licences before use |
| ArcticTraining | Apache-2.0 | 2026-11-05 | active on main; latest release March 2026 |
| torchtune | BSD-3-Clause | 2026-09-09 | not maintained (README banner); do not start new work |
| AutoTrain Advanced | Apache-2.0 | 2026-10-29 (CI commits only) | no longer maintained (README); do not start new work |
Adapters, quantisation and kernels
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| PEFT | Apache-2.0 | 2026-11-05 | active |
| bitsandbytes | MIT | 2026-11-02 | active |
| Liger Kernel | BSD-2-Clause | 2026-11-06 | active |
Reinforcement learning
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| verl | Apache-2.0 | 2026-11-06 | active; moved organisation in January 2026 |
| OpenRLHF | Apache-2.0 | 2026-11-03 | active; command-line flags are now dotted |
| SkyRL | Apache-2.0 | 2026-11-07 | active; restructured into several packages |
| prime-rl | Apache-2.0 | 2026-11-07 | active; install from source, not on PyPI |
| Tinker SDK | Apache-2.0 (the service itself is hosted and proprietary) | 2026-11-07 | active; pre-1.0 |
Data
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| datatrove | Apache-2.0 | 2026-11-04 | active |
| distilabel | Apache-2.0 | 2026-11-02 (develop branch) | community-maintained; no release since January 2025 |
Evaluation
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| lm-evaluation-harness | MIT | 2026-11-04 | active; command line refactored December 2025 |
| Inspect | MIT | 2026-11-07 | active; very frequent releases |
| lighteval | MIT | 2026-10-29 | active on main; last release November 2025 |
Serving, merging and distributed training
| Tool | Licence | Last activity | Status |
|---|---|---|---|
| vLLM | Apache-2.0 | 2026-11-07 | active |
| SGLang | Apache-2.0 | 2026-11-07 | active |
| mergekit | LGPL-3.0 | 2026-10-31 | active |
| DeepSpeed | Apache-2.0 | 2026-11-07 | active; organisation moved |
| Accelerate | Apache-2.0 | 2026-11-02 | active |
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.
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
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.
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.
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.
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.
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.
- Equal-effort baselines. Do tuned-model wins survive an equally tuned prompting and retrieval baseline? None of the vendor case studies publishes its baseline prompt.
- Tuning plus retrieval. For which model sizes, retrieval qualities and kinds of tuning does the pair beat retrieval alone? Soudani's result flips sign between 3B and 7B models, and ideal retrieval is an upper bound.
- New facts in modern models. Does Gekhman's finding, that fitted unknown facts raise hallucination, hold for models of 70B and above, and for question-answer tuning with paraphrases at scale?
- LoRA variants. Do DoRA, PiSSA, LoRA+ and rsLoRA keep any advantage over plain LoRA when learning rate, alpha and layer coverage are tuned equally? No independent equal-budget study has been found.
- The capacity limit. At what ratio of data to adapter capacity does LoRA stop matching full fine-tuning on current, larger and mixture-of-experts models? The main comparison used Llama 2 7B.
- Emergent misalignment. Which datasets trigger it, can it be predicted before training, and is a post-tuning check on a few hundred prompts enough?
- New ability or sharpening. Does reinforcement learning with verifiable rewards ever create reasoning the base model lacked at any number of samples, on tasks free of leakage and on bases other than Qwen?
- Grader integrity. Which reward-hacking defences hold for model-judged or rubric graders in agentic environments, and how can a buyer audit a grader before paying for RL hours?
- Distillation without logits. On-policy distillation needs teacher probabilities or a scorer. How does it fare when the teacher is an API that returns text only?
- Held-out sets that stay clean. How should a tuned product build an evaluation set that resists contamination and drift, and is there a published standard for regression suites beyond academic benchmarks?
- Mixture-of-experts bases. Adapters on mixture-of-experts models touch routers and experts that dense-model results say nothing about; how routing and load balancing behave under LoRA or full tuning is little studied, so check your tool's support and measure per-expert load before and after.
- Low-precision training. Most results here use 16-bit training or a 4-bit base. Native 8-bit and 4-bit floating-point training on newer GPUs changes the memory and cost arithmetic, and its effect on fine-tuning quality is not yet well measured.
- Long-context tuning. Extending context by fine-tuning (RoPE scaling, sequence parallelism across GPUs) is common practice, but how much long-context data a tune needs, and what it costs in short-context quality, is reported mostly by the labs that sell long-context models.
- Adapter. A small set of extra trained weights, such as a LoRA, that modifies a frozen base model; megabytes in size.
- Base model. The pretrained model that tuning starts from; an adapter works only with the base it was trained on.
- Catastrophic forgetting. Loss of earlier abilities after training on new data.
- Chat template. The fixed text format that wraps system, user and assistant turns; a mismatch between training and serving breaks tuned models.
- Continued pretraining. Further next-token training on domain text, before or instead of instruction tuning.
- Contamination. Test material that has leaked into training data, so that recall can pass for ability.
- Distillation. Training a smaller student model on the outputs, or the probabilities, of a stronger teacher.
- DPO. Direct preference optimisation: tuning on pairs of preferred and rejected answers without a separate reward model.
- Emergent misalignment. Broad harmful behaviour that appears after tuning on a narrow set of examples, such as insecure code.
- Epoch. One full pass over the training set.
- Few-shot / zero-shot. Prompting with a handful of worked examples, or with none.
- Full fine-tuning. Updating every weight of the model, as opposed to training an adapter.
- GRPO. A reinforcement-learning method that scores a group of sampled answers against one another, without a value model.
- Held-out set. Cases the training never sees, used only to decide whether a change is real.
- Hallucination. A fluent statement with no support in the model's knowledge or its sources.
- In-context learning. Teaching a model a task through examples in the prompt, with no weight change.
- Instruction tuning. Supervised training on instruction and response pairs so that a model follows requests.
- KTO. A preference method that learns from single answers labelled good or bad, not from pairs.
- LoRA. Low-rank adaptation: training two small matrices whose product is added to a frozen weight matrix.
- Merge. Folding an adapter into the base weights, or combining several tuned models, to produce one set of weights.
- Model collapse. Rare cases vanishing from a model trained on its own outputs; bounded when real data is kept alongside.
- Preference optimisation. Tuning a model towards answers people or graders prefer.
- QLoRA. LoRA trained over a frozen base held in 4-bit precision, to cut GPU memory.
- RAG. Retrieval-augmented generation: fetching documents at query time and placing them in the prompt.
- Rank. The width of the low-rank matrices in a LoRA; it caps how much the adapter can change.
- Regression suite. A fixed set of cases run before every release to catch behaviour that used to work and no longer does.
- Reward hacking. Exploiting a flaw in how a system is scored instead of doing the intended task.
- Reward model. A model trained to score answers, used as the signal for preference or RL tuning.
- RFT. Reinforcement fine-tuning: tuning with a grader that scores the model's own attempts.
- RLVR. Reinforcement learning with verifiable rewards, where a program, such as a test or an answer key, computes the score.
- SFT. Supervised fine-tuning: training on input and desired-output pairs.
- Student / teacher. The smaller model being trained, and the stronger model it learns from.
- Training token. A unit of text processed in training; vendor prices are quoted per million.
- Verifier. The check that scores an attempt; its quality sets the ceiling for any RL loop.
- Weight export. The right and the means to download the trained weights, or an adapter, and run them elsewhere.
Grouped by the part of the page that uses them. A work appears once, under the first group that cites it. Years and attributions follow the sources as read; vendor figures are vendor-reported. Market and price pages are as of November 2026.
Opening, Part I and the foundations
- Howard and Ruder, ULMFiT (2018).
- Devlin et al., BERT (2018).
- Wei et al., FLAN (2021).
- Sanh et al., T0 / Multitask Prompted Training (2021).
- Wang et al., Super-NaturalInstructions (2022).
- Ouyang et al., InstructGPT (2022).
- Chung et al., Scaling Instruction-Finetuned LMs (Flan-PaLM / Flan-T5) (2022).
- Longpre et al., Flan Collection (2023).
- Touvron et al., Llama 2 (2023).
- Lambert et al., Tulu 3 (2024).
- Dubey et al., Llama 3 herd (2024).
- OLMo Team, 2 OLMo 2 Furious (2024).
- Qwen team, Qwen3 Technical Report (2025).
U1. Supervised fine-tuning and data selection
- Lee et al., Deduplicating Training Data Makes LMs Better (2021).
- Wang et al., Self-Instruct (2022).
- Taori et al., Alpaca (2023).
- Zhou et al., LIMA (2023).
- Chen et al., AlpaGasus (2023).
- Gudibande et al., The False Promise of Imitating Proprietary LLMs (2023).
- Lin et al., The Unlocking Spell on Base LLMs (URIAL) (2023).
- Abbas et al., SemDeDup (2023).
- Liu et al., What Makes Good Data for Alignment? (DEITA) (2023).
- Raghavendra et al., Revisiting the Superficial Alignment Hypothesis (2024).
- Xia et al., LESS (2024).
- Zhang et al., When Scaling Meets LLM Finetuning (2024).
- Xu et al., Magpie (2024).
U2. Parameter-efficient fine-tuning
- Houlsby et al., Parameter-Efficient Transfer Learning for NLP (Houlsby adapters) (2019).
- Li and Liang, Prefix-Tuning (2021).
- Lester, Al-Rfou and Constant, Prompt Tuning (2021).
- Hu et al., LoRA (2021).
- Wortsman et al., Model soups (2022).
- Ilharco et al., Task arithmetic (2022).
- Zhang et al., AdaLoRA (2023).
- Yadav et al., TIES-Merging (2023).
- Dettmers et al., QLoRA (2023).
- Kopiczko et al., VeRA (2023).
- Chen et al., Punica (2023).
- Sheng et al., S-LoRA (2023).
- Huang et al., LoraHub (2023).
- Yu et al., DARE / Super Mario (2023).
- Kalajdzievski, rsLoRA (2023).
- Liu et al., DoRA (2024).
- Hayou et al., LoRA+ (2024).
- Meng et al., PiSSA (2024).
- Goddard et al., Arcee MergeKit (2024).
- Shuttleworth et al., LoRA vs Full Fine-tuning: An Illusion of Equivalence (2024).
- Answer.AI and Hugging Face, Efficient fine-tuning of large models with FSDP and QLoRA (2024).
- Thinking Machines, LoRA Without Regret (2025).
- vLLM, LoRA adapters (documentation) (2026).
- SGLang, LoRA serving (documentation) (2026).
- Hugging Face, PEFT: LoraConfig and merging guide (documentation) (2026).
U3. Preference optimisation
- Christiano et al., Deep RL from human preferences (2017).
- Ziegler et al., Fine-Tuning LMs from Human Preferences (2019).
- Bai et al., Constitutional AI (2022).
- Gao et al., Scaling laws for reward model overoptimization (2022).
- Zheng et al., Secrets of RLHF, Part I: PPO (2023).
- Rafailov et al., DPO (2023).
- Azar et al., Psi-PO / IPO (2023).
- Lee et al., RLAIF vs RLHF (2023).
- Guo et al., OAIF: online AI feedback (2024).
- Ethayarajh et al., KTO (2024).
- Hong et al., ORPO (2024).
- Meng et al., SimPO (2024).
- Park et al., Disentangling length from quality in DPO (2024).
- Xu et al., Is DPO superior to PPO? (2024).
- Ahmadian et al., RLOO: Back to Basics (2024).
- Lambert et al., RewardBench (2024).
- Chen et al., Preference Learning Algorithms Do Not Learn Preference Rankings (2024).
U4. Reinforcement learning with verifiable rewards
- Shao et al., DeepSeekMath / GRPO (2024).
- DeepSeek, DeepSeek-R1 (2025).
- Chu et al., SFT Memorizes, RL Generalizes (2025).
- Yu et al., DAPO (2025).
- Liu et al., Understanding R1-Zero-Like Training (Dr. GRPO) (2025).
- Yue et al., Does Reinforcement Learning Really Incentivize Reasoning Capacity in LLMs Beyond the Base Model? (2025).
- NVIDIA, ProRL (2025).
- Shao et al., Spurious Rewards (2025).
- Wu et al., Reasoning or Memorization? Unreliable Results of Reinforcement Learning Due to Data Contamination (2025).
- Shenfeld et al., RL's Razor (2025).
- Qwen team, GSPO (2025).
- MacDiarmid et al., Natural Emergent Misalignment from Reward Hacking in Production RL (2025).
- Cen et al., Webscale-RL (2025).
- Prime Intellect, Environments Hub (2025).
- AWS, Amazon Bedrock: reinforcement fine-tuning (documentation) (2026).
- Google, Vertex AI: reinforcement tuning (documentation) (2026).
- Microsoft, Foundry: reinforcement fine-tuning (documentation) (2026).
U5. Distillation, synthetic data and human data
- Hinton, Vinyals and Dean, Distilling the Knowledge in a Neural Network (2015).
- Kim and Rush, Sequence-Level KD (2016).
- Hsieh et al., Distilling Step-by-Step (2023).
- Mukherjee et al., Orca (2023).
- Xu et al., WizardLM / Evol-Instruct (2023).
- Gu, Dong, Wei, Huang, MiniLLM (2023).
- Agarwal et al., GKD: On-Policy Distillation (2023).
- Gunasekar et al., Textbooks Are All You Need (phi-1) (2023).
- Li et al., phi-1.5 (2023).
- Yang, Chiang, Zheng, Gonzalez, Stoica, Rethinking Benchmark and Contamination (2023).
- Shumailov et al., The Curse of Recursion: Training on Generated Data Makes Models Forget (2023).
- Gerstgrasser et al., Is Model Collapse Inevitable? (2024).
- NVIDIA, Nemotron-4 340B (2024).
- Penedo et al., FineWeb / FineWeb-Edu (2024).
- Microsoft, Phi-4 Technical Report (2024).
- Muennighoff et al., s1 (2025).
- Ye et al., LIMO (2025).
- Guha et al., OpenThoughts (2025).
- Thinking Machines, On-Policy Distillation (2025).
- Mercor, Mercor to acquire Deeptune (2026).
- Vidgen et al., APEX-Agents (2026).
- Surge AI, EnterpriseBench CoreCraft (2026).
- Anthropic, Detecting and preventing distillation attacks (2026).
- Ramp, with Prime Intellect, Fast Ask post-training (2026; reinforcement learning, not distillation; company post via search summary).
U6. Continued pretraining and forgetting
- Gururangan et al., Don't Stop Pretraining (DAPT/TAPT) (2020).
- Luo et al., An Empirical Study of Catastrophic Forgetting in Large Language Models During Continual Fine-tuning (2023).
- Allen-Zhu and Li, Physics of Language Models: Part 3.1, Knowledge Storage and Extraction (2023).
- Biderman et al., LoRA Learns Less and Forgets Less (2024).
- Kalajdzievski, Scaling laws for forgetting (2024).
- Ibrahim et al., Simple and Scalable Strategies to Continually Pre-train Large Language Models (2024).
- Yang et al., Synthetic continued pretraining (EntiGraph) (2024).
Part III. When tuning beats prompting and retrieval, and what it breaks
- Ovadia et al., Fine-Tuning or Retrieval? (2023).
- Qi et al., Fine-tuning Aligned Language Models Compromises Safety, Even When Users Do Not Intend To! (2023).
- Lin et al., RA-DIT (2023).
- Mosbach et al., Few-shot Fine-tuning vs ICL: A Fair Comparison (2023).
- Nori et al., Medprompt: Can Generalist Models Outcompete Special-Purpose Tuning? (2023).
- Golchin and Surdeanu, Time Travel in LLMs: Tracing Data Contamination (2023).
- EleutherAI, Language Model Evaluation Harness (2023).
- Gekhman et al., Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations? (2024).
- Balaguer et al., RAG vs Fine-tuning: Pipelines, Tradeoffs, and a Case Study on Agriculture (2024).
- Soudani, Kanoulas and Hasibi, Fine Tuning vs. Retrieval Augmented Generation for Less Popular Knowledge (2024).
- Zhang et al., RAFT: Adapting LM to Domain-Specific RAG (2024).
- Zhao et al., LoRA Land: 310 Fine-tuned LLMs that Rival GPT-4 (2024).
- Agarwal et al., Many-Shot In-Context Learning (2024).
- Bertsch et al., ICL with Long-Context Models: An In-Depth Exploration (2024).
- Qi et al., Safety Alignment Should Be Made More Than Just a Few Tokens Deep (2024).
- Zhang et al., A Careful Examination of LLM Performance on Grade School Arithmetic (GSM1k) (2024).
- Zhang et al., xLAM (2024).
- Checkr and Predibase, How Checkr streamlines background checks with fine-tuned small language models (2024).
- Harvey and OpenAI, Customer story: Harvey custom case-law model (2024).
- Betley et al., Emergent misalignment (2025).
- Turner et al., Model Organisms for Emergent Misalignment (2025).
- Wang et al., Persona Features Control Emergent Misalignment (2025).
- Thinking Machines, Tinker: customer results (Bridgewater, Lightning Rod Labs) (2026).
Market, pricing and portability (as of November 2026)
- Rubrik, Rubrik-Predibase (2025).
- Cloudflare, Cloudflare-Replicate (2025).
- Fireworks, Fireworks pricing (2026).
- OpenAI, OpenAI deprecations page (2026).
- OpenAI, OpenAI pricing (2026).
- OpenAI, OpenAI model-optimization guide (2026).
- Together AI, Together fine-tuning pricing (2026).
- Fireworks, Fireworks fine-tuning docs (2026).
- Thinking Machines, Tinker pricing (2026).
- Thinking Machines, Tinker product page (2026).
- Snowflake, Snowflake Cortex Training blog (2026).
- Snowflake, Snowflake docs (2026).
- Databricks, Databricks docs (2026).
- Databricks, Databricks pricing (2026).
- AWS, Bedrock pricing (2026).
- Microsoft, Foundry fine-tuning overview (2026).
- Google, Vertex Gemini tuning doc (2026).
- Modal, Modal pricing (2026).
- Nscale, Nscale-Anyscale (2026).
How is this page?
Last updated on