Open Models & Fine-Tuning — When You Need Your Own Weights
"Most teams that fine-tune shouldn't have. The teams that should, win on cost, privacy, or a narrow task the flagship model will never care enough about."
01 · The hookThree Forces That Justify Owning Weights
When to stop calling someone else's API and run your own weights. The decision framework comes first, because most problems people bring to fine-tuning are not fine-tuning problems.
"We're Juris — contract review for mid-market law firms. Three problems landed on my desk in the same week. One: our API bill. We push about 40 million tokens a day through a flagship model, and finance has started attending my standups.
Two: our biggest client's new engagement letter has a data-residency clause — client documents may not leave our VPC, which as written forbids every external model API we use.
Three: the one task our whole product hangs on — tagging contract clauses by type — is exactly the task the flagship model is mediocre at. It's brilliant at everything, which apparently includes being 89%-good at the only thing we sell.
And a warning from our own history: last quarter a team fine-tuned a model to 'teach it our product docs.' It answered faster, sounded more confident, and hallucinated worse. I need someone who knows which of these three problems fine-tuning actually solves."
Dana's memo is the whole module in miniature. Until now, every system you've built in this course rents its intelligence: you send tokens to someone else's model and pay by the drink. That's the right default — and it stays the right default. But three forces, alone or together, push serious teams toward open-weight models they run and adapt themselves:
Cost at scale. API pricing is linear in tokens forever; a GPU you own is a step function. At 40M tokens/day, the lines cross — we'll do the actual math in the boardroom section.
Privacy and residency. A contract clause that says "documents never leave our infrastructure" is not a negotiation; it's an architecture requirement. Weights you host in your own VPC satisfy it; an external API at any price does not.
Specialization. A 3-billion-parameter model fine-tuned on 1,500 curated examples of your task routinely beats a frontier model prompted at it — on that one task, and at a fortieth of the latency.
Those three forces are not slogans. They are Dana's three problems, and each one arrives with a number that the rest of this module keeps using. Here they are as one picture; every later section puts a value into one of these three panels.
- The rent line and the ownership line. Renting a flagship model costs about $192 a day at Juris's 40 million tokens, which is roughly $70,000 a year, and that bar grows in a straight line with traffic. Owning the weights costs about $7,000 of GPU plus a quarter of an engineer, roughly $45,000 a year, and that bar hardly moves when traffic doubles. At today's volume the saving is real but modest; the shape of the two bars is the argument, not the gap.
- The line documents may not cross. The outer box is Juris's own network. The client's engagement letter says contract text stays inside it. An external model API, at any price, means the text crosses that line, so the dashed arrow is struck out. Weights you host sit inside the box with the documents, which is the only way to satisfy the clause.
- Four points and 5.8 times faster. On the same 300 held-out clauses, the flagship with a careful few-shot prompt gets 89% right at 1,400 milliseconds a call. The fine-tuned 3-billion-parameter model gets 93% right at 240 milliseconds. Neither bar is dramatic on its own; the pair is, because the smaller model wins on the one task the product is sold for.
Notice what's not on that list: knowledge. The Juris team that fine-tuned on product docs made the classic mistake. Fine-tuning changes a model's behavior — its style, format, dialect, and skill at a narrow task. It is a terrible way to install facts.
A model fine-tuned on your docs doesn't gain a searchable memory; it gains a stronger tendency to produce doc-shaped sentences — including confidently doc-shaped sentences about things that were never in the docs, with no citations and no way to update when the docs change.
Knowledge belongs in retrieval (Module 08). Behavior belongs in weights. Every fine-tuning disaster you'll ever see starts with confusing the two.
Fine-tuning an LLM is transfer learning from Module 04 with the labels changed.
Back then you took a pretrained vision backbone, froze it, and trained a small new head for your task — because the backbone's features (edges, textures, shapes) transfer, and only the last-mile mapping is yours.
Same move here: the language backbone (grammar, reasoning, world-shape) transfers; you nudge a tiny set of weights toward your task. LoRA, the technique at the center of this module, is the trick that makes "tiny" mean 0.5% of the parameters.
And the tooling maps too: Ollama is Docker-for-models on your laptop; vLLM is your production app server; a merged fine-tune is a build artifact you version and deploy like any other.
02 · The decisionFine-Tune, RAG, or Just Prompt Harder?
Dana's three problems are on the table: 40 million tokens a day, a client contract that forbids documents leaving the VPC, and a clause tagger stuck at 89% on the one task Juris sells. Nobody at Juris has touched a GPU yet, and that is deliberate. The team's own history is the warning: last quarter's product-docs fine-tune answered faster and was wrong more often, so a wrong yes here costs weeks. What Juris needs first is a test it can run on any request, in a fixed order, that says whether the request belongs to prompting, to retrieval, or to training.
We're teaching the decision framework before any mechanics, deliberately. The market research behind this course is blunt: fine-tuning is a "top-tier 2026 hiring signal… widely claimed and rarely proven." Running a training script is a commodity — Colab notebook, twenty minutes. What interviewers and employers actually screen for is the judgment call: knowing when not to. Here is the whole decision as one picture. Walk it top to bottom; you exit at the first "yes."
- Gate 1, the facts gate. Ask whether the task needs information the model does not have: private, current, or long-tail. If yes, you leave here for retrieval and you never reach the training branch. Juris's product-docs disaster exited here and kept walking, which is the whole reason this gate is first.
- Gate 2, the shape gate. Ask whether you need a guaranteed output shape, such as exactly four JSON fields or one label from a fixed list. A schema on the API call makes the wrong shape impossible to generate. Training can only make it rarer, so a format problem exits here.
- Gate 3, the plateau gate. Ask whether prompting and few-shot examples have stopped improving, measured on your own eval set rather than felt. "We tried a few prompts" is not a plateau. This is the gate almost every premature fine-tune walks straight past.
- Gate 4, the three forces. Only here do you ask about behaviour and dialect, about unit cost and latency at volume, and about weights being required inside your own network. These are Dana's three problems: clause tagging, 40 million tokens a day, and the residency clause.
- The exit nobody reaches by accident. The accent box is the only way into the rest of this module, and it needs a measured plateau plus at least one of the three forces. Juris arrives here with all three. A team that arrives with none should re-examine the problem, because fine-tuning fixes none of it.
Two details in that tree carry most of the weight. First, the plateau gate, marker 3 in Fig. 11.1, is measured — by the eval suite you built in Module 07, not by vibes. "We tried a few prompts" is not a plateau. Second, the three lines inside the box at marker 4 are exactly Dana's three problems: specialization (clause tagging, 89% today), cost (40M tokens/day), residency (the VPC clause). Juris passes all three and reaches the accent box at marker 5. The product-docs team from the warning story never gets past the facts gate at marker 1.
| Prompting + few-shot | RAG | Fine-tuning | |
|---|---|---|---|
| What it changes | Instructions in context | Facts in context | The weights themselves |
| Best for | Task definition, tone, quick iteration | Current/private knowledge, citations | Behavior, style, domain dialect, narrow-task skill |
| Upfront cost | Hours | Days (index + retrieval + evals) | Weeks (data curation dominates, not GPU time) |
| Marginal cost | Highest — every call re-pays for the long prompt | Medium — retrieval + bigger context per call | Lowest — behavior is amortized into weights |
| Latency | Grows with prompt length | + retrieval hop, + longer prefill | Shortest prompts; small model = fast tokens |
| Maintenance | Edit a string, redeploy | Re-index documents; knowledge stays fresh | Re-train + re-eval + re-deploy per change |
| Fails when | Model lacks the skill entirely | Task needs new behavior, not facts | You needed facts, or data is thin/noisy |
"Why not just fine-tune on all our documents so it knows everything? Then there is no retriever to break."
— a backend lead who has just read the RAG module and counted its moving parts
The tree answers it before the mechanics do. Marker 1 in Fig. 11.1 is the facts gate, and "all our documents" is that gate in four words, so the request leaves for retrieval at the first question. It is a fair instinct, and the answer starts with what training actually stores. Gradient descent does not file documents away. It nudges billions of weights so that document-shaped text becomes a little more likely. The model ends up with the habits of your documents, not a copy of them. A specific number on page 212 is one faint pattern among trillions.
That is why the Juris product-docs team got a model that sounded more confident and was wrong more often. Three practical problems follow. You cannot update one fact without a retrain. You cannot cite the page an answer came from. And you cannot revoke access: once a confidential clause is in the weights, every user who can reach the model can reach it.
The honest downside of the alternative: retrieval is another system to run. It can miss the right chunk, it adds a hop of latency, and the index needs care every time the documents change. Module 08 spends most of its length on those failures. The two compose well in practice: retrieval supplies the facts, and a small fine-tune can teach the model how to use them.
Prompt first.
Retrieve for facts.
Tune for behavior.
Measure before and after.
Prompt first: gate 3, marker 3 in Fig. 11.1 — nothing passes it until an eval shows the prompt has stopped improving. Retrieve for facts: gate 1, marker 1, where TrustBank's quarterly policy leaves the tree in Fig. 11.1b. Tune for behaviour: gate 4, marker 4, the only place where style, unit cost and residency are asked about. Measure before and after: the three bar groups of Fig. 11.2f, where the tuned 3B and the flagship are scored on the same 300 clauses.
Before reading on: PolicyPal (from Module 08) wants their assistant to "know" the 2026 policy handbook, which changes monthly. A teammate proposes fine-tuning on the handbook — "then we don't need the vector database at all." Predict three distinct ways this goes wrong in production.
Reveal the answer
(1) Staleness: next month's handbook edit requires a full retrain-and-redeploy cycle instead of a re-index; the model confidently serves last month's policy forever.
(2) No citations: fine-tuned "knowledge" has no provenance — you can't show a customer which clause the answer came from, which the compliance team requires.
(3) Hallucination amplification: the model learns the handbook's style far better than its facts, so wrong answers now sound exactly like right ones — precisely the Juris product-docs failure.
The correct design: RAG for the handbook; fine-tune only if the assistant's behavior (tone, refusal policy, output format) needs work the prompt can't deliver.
03 · The landscapeOpen Models Worth Knowing, August 2026
Juris has walked the tree and reached the accent box at marker 5 of Fig. 11.1. The next question is not "how do we train" but "train what": the weights have to be ones Juris is allowed to download, run inside the VPC, and adapt. That rules out every flagship API, and it makes the licence text as load-bearing as the benchmark score. So before any code, here is the field of open models, and where a 3-billion-parameter Llama sits in it.
"Open model" spans a spectrum: open-weight (you can download and run the weights — most of the list below) is not the same as open-source (training data and code too — rare). Licenses matter commercially: Apache 2.0 and MIT are do-what-you-want; Meta's community license and Google's Gemma terms carry conditions your legal team will actually read. Here's the field as of August 2026:
| Family | Sizes | License | Known for |
|---|---|---|---|
| Llama 3.x (Meta) | 1B–405B (3.2: 1B/3B edge; 3.1: 8B/70B/405B; 3.3: 70B) | Llama Community License (free below 700M MAU; not OSI-open) | The default ecosystem — most tooling, most fine-tunes, most tutorials assume it |
| Qwen 3 (Alibaba) | 0.6B–235B, dense + MoE | Apache 2.0 | Strongest small models per GB; multilingual; the permissive-license workhorse |
| Gemma 3 (Google) | 1B–27B | Gemma Terms of Use | Excellent quality at laptop-friendly sizes; 128k context |
| Mistral Small / Magistral | ~24B | Apache 2.0 (Small line) | Efficient dense models, strong function calling; the European-sovereignty pick |
| DeepSeek-R1 + distills | 671B MoE; distills 1.5B–70B | MIT | Open reasoning — visible chains of thought, GRPO-trained; distills bring reasoning to small models |
- The band that satisfies residency. Any stop left of API-only gives you a file you can host, so client documents never leave the VPC. That, not the benchmark score, is what makes this half of the line usable for Juris.
- The stop with no weights. An API model can be excellent and still fail the clause, because the document has to travel to it. Hosted fine-tuning sits here too, which is why it solves specialization and not residency.
- Where Juris lands. Llama 3.x is open-weight with conditions: free below 700 million monthly users, but not an OSI-open licence, so legal reads it. This module trains Llama-3.2-3B; Qwen 3 under Apache 2.0 is the swap if the terms bite.
Hold this table loosely. Model names rotate faster than course materials — by the time you read this there will be a Llama 4.x point release or a Qwen 4 making headlines.
Read leaderboards skeptically too: public benchmarks leak into training data (contamination), and arena-style rankings reward pleasing voters, not doing your task. The durable skill is the one from Module 07: a held-out eval set for your task, run against every candidate.
A model's rank on someone else's benchmark is a rumor; its score on your test set is a fact.
04 · Build it yourselfRun a Model on Your Laptop in Five Minutes
Juris has picked a family and a size: a 3-billion-parameter Llama, at the accent stop in Fig. 11.1c. Nothing is trained yet, and that is the right order — before spending a GPU hour, the team needs to see how far a stock open model already gets on clause tagging. That number becomes the floor everything later is measured against. So we run the model on a laptop, point Module 06's client at it, and tag one clause.
Before any training, get an open model running locally — it makes everything downstream concrete. Ollama is the dev-loop tool: it pulls quantized models from a registry and serves them over HTTP, Docker-style.
Step-by-step: what the Ollama quickstart does, in plain English
- Install Ollama once. On Linux that is one shell script; on macOS and Windows it is a normal download. It installs a background service that manages model files for you.
ollama pull llama3.2:3bdownloads a 3-billion-parameter Llama model from Ollama's registry, already rounded to 4-bit weights. That is why it is about 2 GB rather than 6.ollama run llama3.2:3bopens a chat prompt in your terminal against that model. Nothing leaves your machine.- The
curlcall shows the same model behind a local HTTP server on port 11434. You send a JSON body with a model name and a list of chat messages."stream": falseasks for the whole reply at once instead of token by token. - There is no API key and no per-token bill anywhere in this block. That absence is the point of the section.
# Install once (Linux): curl -fsSL https://ollama.com/install.sh | sh
# macOS/Windows: download from ollama.com
ollama pull llama3.2:3b # ~2.0 GB — int4-quantized weights
ollama run llama3.2:3b # REPL: chat with it right in the terminal
# It's also a local HTTP server on :11434 — no key, no network, no per-token bill
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2:3b",
"messages": [
{"role": "user", "content": "Classify this clause: Either party may terminate with 30 days notice."}
],
"stream": false
}'
Better still, Ollama exposes an OpenAI-compatible endpoint at /v1. In the open-model world, "OpenAI-compatible" means the chat.completions surface — it's the lingua franca that Ollama, vLLM, and nearly every serving tool speak (OpenAI's own newer Responses API from Module 06 is OpenAI-proper). Practical consequence: the client wrapper you built in Module 06 works against a local model by changing one environment variable. Let's use it to establish the baseline Dana complained about — how good is an untuned small model at clause tagging?
The file below reuses the client you wrote in Module 06, plus a handful of lines you have not met. You are not expected to know the new ones yet. Guess first, then check. The step-by-step list under the exercise walks every line, and the rest of this section explains the parts that are new.
Step-by-step: what local_baseline.py does, in plain English
- Bring in
osto read environment variables andOpenAI, the same client class from Module 06. - Build the client with two overrides.
base_urlpoints at Ollama's OpenAI-compatible endpoint on port 11434.api_keyis a placeholder, because the library insists on one and Ollama ignores it. - Define
LABELS, the twelve clause types, andSYSTEM, an instruction that names the task and pastes the twelve labels in. The model may answer with one of them and nothing else. - Define
tag(clause): send one chat request with the system instruction and the clause as the user turn.max_tokens=8cuts the reply off after a few tokens, since a label needs no more. - Take the first choice's message text out of the response and strip whitespace, so
"auto_renewal\n"compares equal to"auto_renewal". - Call it once on an auto-renewal clause and print the answer. The comment records what the untuned 3B usually says instead, which is the gap the rest of the module closes.
# pip install "openai>=1.60"
# Module 06's client, unchanged — only base_url moves. That's the point.
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.environ.get("LLM_API_KEY", "ollama"), # any string; Ollama ignores it
)
LABELS = [
"indemnification", "limitation_of_liability", "confidentiality",
"auto_renewal", "termination", "governing_law", "assignment",
"non_compete", "payment_terms", "warranty", "ip_ownership", "audit_rights",
]
SYSTEM = (
"You tag contract clauses. Reply with exactly one label from this list, "
"nothing else: " + ", ".join(LABELS)
)
def tag(clause: str) -> str:
resp = client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": clause},
],
max_tokens=8, # a label is one short token run — cap it
)
return resp.choices[0].message.content.strip()
print(tag(
"This Agreement shall automatically renew for successive one-year terms "
"unless either party gives written notice 60 days prior to expiration."
))
# expected: auto_renewal (the base model often says "termination" — that's our gap)
Why does a 2 GB file contain a 3-billion-parameter model? Quantization: storing weights at lower precision. Training happens in 16-bit floats; for inference you can round each weight to 8 or even 4 bits with surprisingly little quality loss, because what matters is the pattern across billions of weights, not the sixth decimal of any one of them. The trade is a small, task-dependent accuracy haircut (rule of thumb: int8 ≈ free, int4 ≈ noticeable on hard reasoning, fine for narrow tasks) in exchange for 4× less memory — which is the difference between "needs an A100" and "runs on your laptop."
- What is lost. A 16-bit weight keeps 0.4213; a 4-bit weight must pick the nearest of sixteen levels and picks 0.375, an error of 0.0463. That error is real, and it is why int4 shows up on hard reasoning.
- Why it is survivable. The model's behaviour comes from the pattern across three billion weights, not from the sixth decimal of any one of them, and the rounding errors point in random directions. On one narrow task the haircut is small enough to ignore.
- What is bought. Four times less memory: 6 GB becomes 1.5 GB, plus about half a gigabyte of metadata, which is the 2.0 GB file Ollama pulls. The same trick is what lets QLoRA keep a frozen base on a 16 GB card.
"Can a 3B model on my laptop really replace an API call? I asked it something last week and it made up a Python library."
— a senior engineer who tried Ollama once and closed the terminal
As a general assistant, no, and this page will not pretend otherwise. A 3-billion-parameter model rounded to 4-bit weights knows less, reasons worse, and invents more than a frontier model. Marker 1 in Fig. 11.1d is part of the reason: every weight has been snapped to one of sixteen levels, and 0.4213 is stored as 0.375. The failure block below measures it: on clause tagging, untuned, it lands near 60% where the flagship reaches the high 80s.
As a specialist on one narrow, repetitive task, yes, and that is the only claim this module makes. After fine-tuning on about 1,500 reviewed examples, the same 3B model beats the flagship on that task, several times faster, on hardware you control. It replaces one API call, the one you make tens of thousands of times a day. It does not replace the API.
The honest downsides: your laptop is a development box, not a server. It serves one user at a time, has no autoscaling, and the 4-bit rounding costs a little accuracy on hard reasoning. Production means a real GPU and vLLM, which is section 09.
The memory math: params × bytes — optional depth
Model memory for inference is, to first order, params × bytes-per-param. fp16 (16-bit float) = 2 bytes; int8 = 1 byte; int4 = 0.5 bytes.
| Model | fp16 | int4 |
|---|---|---|
| 3B | 3B × 2 = 6 GB | 3B × 0.5 = 1.5 GB — plus ~0.5 GB of metadata and buffers, hence the 2 GB download. |
| 8B | 16 GB | ~4.5 GB |
| 70B | 140 GB — multi-GPU territory. | ~40 GB — one 48 GB card, barely. |
On top of weights sits the KV cache — the attention keys and values for every token in every active context (Module 05). It grows linearly with context length × concurrent requests, which is why serving many users needs far more memory than "the model fits." Keep this formula loaded; it reappears in the interview radar.
Run the baseline over a few hundred labeled clauses (you'll build that set properly in section 06) and the untuned 3B lands around 60% accuracy — it confuses auto_renewal with termination, and indemnification with warranty, because generic pretraining never forced it to care about the difference.
The flagship API model with few-shot prompting reaches high-80s. Both are below what Juris ships on.
So: fine-tune the 3B. But the naive version of that — full fine-tuning, updating all weights — needs the weights (6 GB fp16) plus gradients for every weight (6 GB) plus Adam's two optimizer moments in fp32 (24 GB): ~36 GB before a single activation, for the small model.
For a 7B: ~84 GB. Your laptop is out; even a rented A100 is sweating. This wall — not accuracy — is why LoRA exists.
- The three blocks that make 36 GB. Weights at 6 GB, one gradient per weight at another 6 GB, and Adam's two running averages kept in 32-bit at 24 GB. Optimizer state, not the model, is the biggest block.
- The line the bar crosses. 16 GB is the free Colab T4. The full fine-tune runs out of memory before the first step, and a 7B needs about 84 GB, so this is a wall and not a slow run.
- What freezing removes. No gradient and no moment is ever stored for a frozen weight, so only the adapters carry that cost. That is why the second bar is short, and why the run in the next section finishes on a free GPU.
05 · The intuitionLoRA: Fine-Tuning Without the Memory Bill
Two walls are now in front of Juris. The untuned 3B scores about 60% on clause tagging, far below the 89% the flagship already gives, and the obvious fix — retrain all the weights — needs the 36 GB drawn at marker 1 of Fig. 11.1e on a card that has 16. The team has one free Colab T4 and no budget for a rented cluster. What we need is a way to change the model's behaviour while touching almost none of its weights, and that is exactly what LoRA is.
Here's the insight, and it's genuinely elegant. Fine-tuning a weight matrix W means finding an update ΔW so the new behavior is W + ΔW. Full fine-tuning learns ΔW at full size — 4096 × 4096 numbers per matrix.
But empirically, the update needed to adapt a pretrained model to one narrow task is low-rank: it doesn't need 4096 independent directions of change, it needs about sixteen.
LoRA (Low-Rank Adaptation) bakes that in: keep W frozen, and learn ΔW as the product of two thin matrices, B (4096 × 16) and A (16 × 4096). All gradient flow, all optimizer state, all learning lives in the thin pair.
- The frozen block. W is one attention matrix, 4096 × 4096 = 16,777,216 numbers. It receives no gradient and no optimizer state, which is what removed 34 of the 36 gigabytes at marker 1 of Fig. 11.1e.
- The two thin matrices. B is 4096 × 16 and A is 16 × 4096, so together they hold 131,072 numbers. Their product has the same shape as W, but it can only point in sixteen independent directions.
- The update that is added. At every forward pass the model computes W·x and B·(A·x) and adds them. Learning happens only in B and A; W is read, never written.
- The whole-model count. Repeat the sum for the seven adapted matrices in each of the 3B model's 28 layers and you get about 24.3 million trainable parameters, 0.76% of 3.21 billion — an adapter folder of 50 to 100 MB instead of a 6 GB model.
Two refinements complete the picture.
First, at inference you can merge: compute W + B·A once and serve a plain model with zero added latency — or keep adapters separate and hot-swap many tasks over one shared base (one base model, one ~100 MB adapter per customer).
Second, QLoRA: since the base is frozen anyway, store it 4-bit quantized and train LoRA adapters on top in 16-bit.
The 36 GB full-fine-tune budget for our 3B collapses to under 8 GB — which is why the training run in the next section finishes on a free Colab T4.
- The dial positions. Trainable parameters are r × (4096 + 4096), so r = 8 gives 65,536, r = 16 gives 131,072 and r = 32 gives 262,144, against 16,777,216 frozen. As percentages: 0.3906%, 0.7813% and 1.5625%.
- The cost is linear. Double r and you double the adapter, the optimizer state and the file you ship. Nothing about that curve bends in your favour.
- The benefit is not. Quality climbs steeply to about r = 16 and then runs flat, which is why the community default is r = 16 with lora_alpha = 16. When accuracy is short, more data beats more rank.
The parameter count for a 7B model at r=16 — optional depth
LoRA on a matrix of shape d × k adds r·(d + k) parameters (matrix B is d × r, matrix A is r × k). For a Llama-style 7–8B model — hidden size 4096, 32 layers, MLP width 14336, grouped-query KV width 1024 — at rank r = 16, per layer:
· attention q, o (4096×4096 each): 2 × 16·(4096+4096) = 262,144
· attention k, v (4096×1024 each): 2 × 16·(4096+1024) = 163,840
· MLP gate, up, down (4096×14336-ish each): 3 × 16·(4096+14336) = 884,736
≈ 1.31M per layer × 32 layers ≈ 42M trainable parameters — about 0.6% of 7B. Target only the attention matrices and it's ~13.6M, about 0.2%. That's the honest range to quote: 0.2–0.6% trainable, depending on which matrices you target. The adapter file is tiny too: 42M × 2 bytes ≈ 84 MB — an email attachment, not a model.
Why rank 16 and not 4 or 256? Empirically the quality curve flattens fast: r=8–32 captures nearly everything for single-task adaptation, and community defaults have converged on r=16 with lora_alpha (a scaling factor on B·A) set equal to r. Doubling r doubles adapter cost for a sliver of quality; it is not where your next point of accuracy lives — better data is.
Before reading on: the rank-16 bottleneck means the fine-tune can only push the model's behavior along 16 directions per matrix. Why on earth is that enough to teach clause tagging — and what does that tell you about what fine-tuning is actually doing?
Reveal the answer
Because the pretrained model already has the features that matter — representations of legal language, obligation, renewal, liability — learned from trillions of tokens. Adapting to clause tagging isn't learning new concepts; it's re-weighting and routing existing ones toward a specific output behavior.
Steering a rich representation is a low-dimensional operation, so a low-rank update suffices.
This is also the honest limit of LoRA: if the base model genuinely lacks the underlying capability (say, a language it never saw), no 16-dimensional nudge will conjure it — you'd need a different base model, not a bigger rank.
Same lesson as Module 04's transfer learning: the backbone's features decide what the head can do.
Questions you might be asking now
This section asks you to picture a 4096 × 4096 matrix, a rank of 16 and a 4-bit base at once. The questions below shrink all three until a pencil can do the work: one frozen layer four numbers wide, with a rank-1 adapter. Every number comes from rerunning lora_tiny_layer.py or qlora_memory.py.
| Part | Shape | Values | Its job |
|---|---|---|---|
| W, frozen | 4 × 4 | row 1 (0.42, −0.19, 0.10, −0.33) row 2 (0.07, 0.25, −0.40, 0.18) row 3 (−0.21, 0.36, 0.05, −0.12) row 4 (0.30, −0.08, 0.22, 0.14) | The pretrained weights. Read on every token, never written. |
| x, the input | 4 numbers | (1.0, 0.5, −1.0, 2.0) | One token of a clause, as this layer receives it. |
| A, trainable | 1 × 4 | (0.5, −0.5, 0.25, 0.5) | Starts random. |
| B, trainable | 4 × 1 | (0, 0, 0, 0) at the start; (0.15, −0.10, 0.05, 0.20) after one training step | Starts at zero, so the adapter begins by adding nothing. |
| The wanted change | 4 numbers | (0.30, −0.20, 0.10, 0.40) | Made up for the arithmetic: how far the task wants this layer's output to move for this token. |
What does "rank 16" actually mean? How can two thin matrices stand in for a full-size update?
Rank is the number of independent patterns an update is made of. A rank-r update is built from r column patterns and r row patterns, so it needs r × (rows + columns) numbers instead of rows × columns. On the tiny layer, rank 1 stores 8 numbers for a 16-cell update; on a 4096 × 4096 matrix, rank 16 stores 131,072 numbers for 16,777,216 cells.
Start with the product itself. B is a column of 4 numbers and A is a row of 4 numbers. Multiplying a column by a row gives a grid. Each cell is one number from B times one number from A.
Use B after one training step, (0.15, −0.10, 0.05, 0.20). The next question shows where those four numbers came from.
- Row 1 of B·A. B's first number times every number in A: 0.15 × (0.5, −0.5, 0.25, 0.5) = (0.075, −0.075, 0.0375, 0.075).
- Row 2. −0.10 × A = (−0.05, 0.05, −0.025, −0.05).
- Row 3. 0.05 × A = (0.025, −0.025, 0.0125, 0.025).
- Row 4. 0.20 × A = (0.10, −0.10, 0.05, 0.10).
- Count what was stored. 4 numbers in B plus 4 in A: 8 numbers for a grid of 16 cells.
Now look at the four rows you just wrote. Every one of them is A multiplied by a single number. Row 4 is row 2 times −2, and row 1 is row 3 times 3. The product has 16 cells but only one pattern in it.
That is what rank 1 means: one independent pattern. The script's rank check prints 1 for this grid. Rank 2 would need B with 2 columns and A with 2 rows, which is 16 numbers for a 16-cell grid. So on a 4-wide layer, rank 2 saves nothing. Rank only pays when r is far smaller than the matrix.
| Full update ΔW (delta W) | LoRA update B·A | |
|---|---|---|
| Numbers stored, tiny layer | 4 × 4 = 16 | 1 × (4 + 4) = 8 |
| Independent patterns it can hold, tiny layer | up to 4 | 1 |
| Numbers stored, one 4096 × 4096 matrix | 16,777,216 | 16 × (4096 + 4096) = 131,072 |
| Independent patterns it can hold | up to 4,096 | 16 |
- The grid. Each cell is B's number for its row times A's number for its column. Sixteen cells come from eight stored numbers, and all four rows share A's shape. That one shared shape is what makes the rank 1.
- The count at full size. The count is r × (rows + columns). That is 8 of 16 on the tiny layer, but 131,072 of 16,777,216 on one 4096 × 4096 matrix at r = 16: 0.7813%. The wider the matrix, the bigger the saving.
- What gets lost. Both made-up updates have two independent patterns, and size is the sum of the squared cells. With strengths 1.0 and 0.2, the stronger pattern holds 1 ÷ (1 + 0.04) = 96.2% of it. With two equal patterns it holds 50.0%, and a rank-1 adapter cannot learn the other half.
Marker 3 is the honest limit. A rank-16 adapter can only learn an update made of 16 patterns. LoRA bets that the change a narrow task needs looks like the top bar: a few strong patterns and a faint rest. The LoRA paper measured that bet on real models and found it mostly holds. This toy cannot prove it; it only shows what happens when the bet fails.
That is the brain-power answer above in numbers: clause tagging re-routes features the model already has, a change with few patterns. A language the model never saw would need thousands.
Rank counts the independent patterns in an update. LoRA stores r column patterns and r row patterns, r × (rows + columns) numbers, and bets that a narrow task needs only a few.
Walk one input through h = W·x + B·(A·x). What happens before training, after one step, and after merging?
Before training B is zero, so the adapter adds exactly nothing and the layer answers like the base model: h = (−0.435, 0.955, −0.32, 0.32). One training step moves only B, to (0.15, −0.10, 0.05, 0.20), and cuts the loss from 0.15 to 0.0375. Merging W + B·A gives the same four outputs with one multiply instead of two paths.
The formula under Fig. 11.2 says every token takes two paths through the layer and the results are added. Here is the token x = (1.0, 0.5, −1.0, 2.0) taking both, station by station.
Station 1: the frozen path, W·x
- Row 1 of W times x. 0.42 × 1.0 + (−0.19) × 0.5 + 0.10 × (−1.0) + (−0.33) × 2.0 = 0.42 − 0.095 − 0.10 − 0.66 = −0.435.
- Rows 2 to 4, the same way. 0.955, −0.32 and 0.32. So W·x = (−0.435, 0.955, −0.32, 0.32). That took 16 multiplications, one per weight.
Station 2: the side path, A·x and then B
- Squeeze with A. A·x = 0.5 × 1.0 + (−0.5) × 0.5 + 0.25 × (−1.0) + 0.5 × 2.0 = 0.5 − 0.25 − 0.25 + 1.0 = 1.0. Four numbers become one. That single number is the bottleneck; at rank 16 it would be sixteen numbers.
- Widen with B. Multiply each of B's four numbers by 1.0. At the start B is (0, 0, 0, 0), so the side path adds (0, 0, 0, 0).
- Add the paths. h = W·x + (0, 0, 0, 0) = (−0.435, 0.955, −0.32, 0.32). The adapted layer starts exactly equal to the frozen one.
That zero start is deliberate, and it is why the anatomy of the adapter call says the adapted model begins exactly equal to the base. The scale lora_alpha ÷ r is 1 here, as on the page, so it changes nothing.
Station 3: one training step
Suppose the task wants this output moved by (0.30, −0.20, 0.10, 0.40). The gap between where h is and where it should be is (−0.30, 0.20, −0.10, −0.40). The loss here is half the sum of the squared gaps: ½ × (0.09 + 0.04 + 0.01 + 0.16) = 0.15.
- Slope for B. Each gap times A·x, which is 1.0: (−0.30, 0.20, −0.10, −0.40).
- Slope for A. B's numbers times the gaps, times x. B is all zeros, so every slope for A is 0. A cannot move on the first step.
- Take the step. With a learning rate η (eta) of 0.5: B ← 0 − 0.5 × (−0.30, 0.20, −0.10, −0.40) = (0.15, −0.10, 0.05, 0.20).
- Run the token again. The side path is now (0.15, −0.10, 0.05, 0.20) × 1.0, so h = (−0.285, 0.855, −0.27, 0.52). Every gap is halved, and the loss drops from 0.15 to 0.0375.
On step 2 the slope for A is no longer zero: (−0.075, −0.0375, 0.075, −0.15). From then on both thin matrices learn together. The frozen W never receives a slope at all, which is exactly why it needs no gradient and no optimizer memory.
Station 4: merging
- Fold the update into W once. Add the B·A grid from the previous question to W. Row 1 becomes (0.42 + 0.075, −0.19 − 0.075, 0.10 + 0.0375, −0.33 + 0.075) = (0.495, −0.265, 0.1375, −0.255).
- Multiply once. 0.495 × 1.0 − 0.265 × 0.5 + 0.1375 × (−1.0) − 0.255 × 2.0 = 0.495 − 0.1325 − 0.1375 − 0.51 = −0.285. That is station 3's first output.
- Check all four. The script's largest difference between the two ways is 5.6 × 10⁻¹⁷: rounding dust, not a real gap.
- Two paths. W does its 16 multiplications as always. The side path does 4 through A, down to the single number 1.0, and 4 through B, and the results are added.
- Step 0. B is all zeros, so the side path adds nothing and h is exactly W·x: the fine-tune starts from the base model's behaviour.
- After one step. B took the whole move because A's slope contains B, which was zero. The four gaps to the wanted output halved, and the loss went from 0.15 to 0.0375. A starts moving from step 2.
- Merged. W + B·A is stored as an ordinary matrix, and one multiply gives the same h as the two paths. Nothing downstream can tell an adapter was there.
| Merged: (W + B·A)·x | Kept separate: W·x + B·(A·x) | |
|---|---|---|
| Output for this token | (−0.285, 0.855, −0.27, 0.52) | (−0.285, 0.855, −0.27, 0.52) |
| Multiplies per token, tiny layer | 16 | 16 + 8 = 24, which is 50% more |
| Multiplies per token, 4096 × 4096 at rank 16 | 16,777,216 | 16,777,216 + 131,072, which is 0.78% more |
| Switching to another task | Load another merged model, about 6 GB | Name another adapter, about 50 MB |
The honest limit of merging is the last row: once B·A is folded in, one set of weights serves one task. The 0.78% extra work of keeping adapters separate is the price of hot-swapping, and it is small only because the rank is small next to the width.
The adapter is a side path that starts at zero, learns in B first, and can be added into W at the end with no change to a single output.
In QLoRA the frozen W is stored in 4 bits, but x and the adapters are 16-bit. How can a 4-bit W still be multiplied?
It is rebuilt just before each multiply. Every block of weights is stored as 4-bit codes plus one scale. At multiply time each code is looked up in a table of 16 levels and multiplied by the scale. On the tiny layer the rebuilt weights are off by at most 0.0376, and the adapter trains against the rebuilt W, never the original.
Fig. 11.1d drew one weight snapping to the nearest of sixteen evenly spaced levels. QLoRA stores the frozen base with two refinements. Each block of weights gets its own scale, so small weights do not waste levels meant for large ones. And the sixteen levels are spaced like a bell curve, crowded near zero where most weights sit. The format is called NF4, short for 4-bit NormalFloat.
Four words carry the whole mechanism:
- Block. A run of weights that share one scale. QLoRA uses 64; here a block is one row of 4.
- Scale. The largest weight in the block, ignoring its sign.
- Level. One of 16 fixed numbers between −1 and 1, the same table for every block.
- Code. Which level a weight was snapped to: a whole number from 0 to 15, which fits in 4 bits.
Here is row 1 of W, (0.42, −0.19, 0.10, −0.33), treated as one block.
- Find the scale. The largest weight by size is 0.42.
- Divide by it. (0.42, −0.19, 0.10, −0.33) ÷ 0.42 = (1.0, −0.4524, 0.2381, −0.7857). Every block now lies between −1 and 1, so one table of levels fits them all.
- Snap to the nearest level. 1.0 is a level (code 15). −0.4524 is 0.0575 from −0.3949 and 0.0727 from −0.5251, so it becomes −0.3949 (code 3). 0.2381 becomes 0.2461 (code 10). −0.7857 becomes −0.6962 (code 1).
- Store. Four 4-bit codes, 15, 3, 10 and 1, plus the one scale, 0.42. The original weights are thrown away.
- Rebuild at multiply time. Level × scale: 1.0 × 0.42 = 0.42, −0.3949 × 0.42 = −0.1659, 0.2461 × 0.42 = 0.1034, −0.6962 × 0.42 = −0.2924.
- Measure the damage. Against the originals the errors are 0, 0.0241, 0.0034 and 0.0376.
The other three rows go the same way; their largest errors are 0.025, 0.021 and 0.0078. Now the multiply. The rebuilt W times x is (−0.3511, 0.9295, −0.2718, 0.3049), against (−0.435, 0.955, −0.32, 0.32) for the original. The first output moved by 0.0839, more than any single weight's error.
The reason is x. Each error is multiplied by its input: 0.0241 × 0.5 + 0.0034 × (−1.0) + 0.0376 × 2.0 = 0.0839. The last input, 2.0, doubles the largest error. Rounding errors are small per weight, but they add up across a row.
- The snap. Dividing by the scale puts every weight between −1 and 1, and each moves to the nearest tick. The ticks bunch up around 0 because most trained weights are small, so that is where precision is spent.
- What is kept. Four 4-bit codes and one scale. The original weights no longer exist anywhere in memory.
- The multiply. The rebuilt row times x gives −0.3511 instead of −0.435, because each error is multiplied by its input. The adapter's slopes are computed through this rebuilt row, so it learns to correct the rounding as well as the task.
- The storage bill. A shared 32-bit scale adds 8 bits per weight in a block of 4, making 12. In a block of 64 it adds half a bit, making 4.5: about 3.6 times smaller than 16.
| Fig. 11.1d's rounding | NF4 in QLoRA | |
|---|---|---|
| The 16 levels | Evenly spaced, 0.125 apart | Spaced like a bell curve, crowded near 0 |
| Scale | One fixed ruler for every weight | One scale per block of 64 weights |
| Bits per weight | 4 | 4 + 32 ÷ 64 = 4.5; 4.127 with double quantisation |
| When the real number is used | Not shown | Rebuilt to 16-bit just before each multiply, then discarded |
| Does it train? | Not shown | No. Slopes flow through it to B and A, and it never changes |
The QLoRA paper reported that a 4-bit NF4 base with adapters matched 16-bit LoRA on its benchmarks. One step on a 4-wide layer cannot show that, and the script does not try.
Two costs remain. The rebuild runs on every forward and backward pass, which is part of why a QLoRA step is slower than a plain LoRA step. And the scales take space; QLoRA's double quantisation stores them in 8 bits, taking 4.5 bits down to 4.127.
A 4-bit weight is a code plus a shared scale. The GPU rebuilds a 16-bit number from them for every multiply, and the adapter trains against that rebuilt copy.
How do 36 GB become "under 8 GB"? Add up full fine-tuning, LoRA and QLoRA for Juris's 3B, line by line.
Count bytes by job. Full fine-tuning pays 12 bytes for each of 3.21 billion weights: 38.6 GB before activations (the page's round 3B gives 36). LoRA pays 2 bytes per frozen weight and 12 only for the 24.3 million adapter numbers: 6.7 GB. QLoRA stores most frozen weights in about half a byte: 2.7 GB, or about 5.7 GB with the page's 3 GB of activations.
Every number on the GPU during training has a job, and each job has a size in bytes. The table lists the four jobs. The middle column holds the key fact: three of the four jobs exist only for weights that train.
| Job | Needed for | Bytes per number |
|---|---|---|
| The weight itself | Every weight, trained or frozen | 2 at 16-bit; 0.5625 in NF4 (4.5 bits) |
| Its gradient: the slope that says which way to nudge it | Trained weights only | 2 |
| Adam's running average of that slope, called m | Trained weights only | 4 |
| Adam's running average of the squared slope, called v | Trained weights only | 4 |
So a trained weight costs 2 + 2 + 4 + 4 = 12 bytes, and a frozen weight costs only its own storage. Freezing removes 10 of the 12.
First, the tiny layer
- Full fine-tune. All 16 weights train: 16 × 12 = 192 bytes.
- LoRA. 16 frozen weights × 2 bytes = 32, plus 8 adapter numbers × 12 bytes = 96. Total 128 bytes.
- QLoRA. 16 weights × 0.5 byte = 8 bytes of codes, plus 4 scales × 4 bytes = 16, plus the same 96. Total 120 bytes.
The tiny layer saves little, 192 bytes down to 120, because its adapter is half the size of W. Both tricks pay off only at scale.
Then Juris's 3B, one matrix at a time
The 3B model is 3072 wide, not the 4096 of Fig. 11.2. The count works the same way: a matrix of rows × columns gets r × (rows + columns) adapter numbers, with r = 16.
| Matrix | Rows × columns | Weights | LoRA numbers, 16 × (rows + columns) |
|---|---|---|---|
| q_proj, o_proj (each) | 3072 × 3072 | 9,437,184 | 98,304 |
| k_proj, v_proj (each) | 1024 × 3072 | 3,145,728 | 65,536 |
| gate_proj, up_proj, down_proj (each) | 8192 × 3072, or 3072 × 8192 | 25,165,824 | 180,224 |
| One layer, all seven | 100,663,296 | 868,352 | |
| × 28 layers | 2,818,572,288 | 24,313,856 | |
| Embedding table, shared with the output layer | 128,256 × 3072 | 394,002,432 | not adapted |
| Norm vectors | 57 × 3072 | 175,104 | not adapted |
| Whole model | 3,212,749,824 | 24,313,856 = 0.757% |
This is where the page's "about 24.3 million, 0.76%" comes from: 868,352 per layer, times 28, divided by 3,212,749,824. At 2 bytes each the adapter is 48.6 MB, the "about 50 MB" folder in Fig. 11.2e.
The bill, side by side
| Job | Full fine-tune | LoRA | QLoRA |
|---|---|---|---|
| Weights | 3.21B × 2 = 6.43 (trained) | 3.21B × 2 = 6.43 (frozen) | 2.82B linear × 4.5 bits = 1.59, plus embeddings and norms at 16-bit = 0.79 (frozen) |
| Adapter numbers | none | 24.3M × 2 = 0.05 | 0.05 |
| Gradients | 3.21B × 2 = 6.43 | 24.3M × 2 = 0.05 | 0.05 |
| Adam m and v | 3.21B × 8 = 25.70 | 24.3M × 8 = 0.19 | 0.19 |
| Total | 38.6 GB | 6.7 GB | 2.7 GB |
| With about 3 GB of activations, on a 16 GB T4 | Does not fit | About 9.7 GB: fits | About 5.7 GB: fits with room |
- Full fine-tune. All 3.21 billion weights carry all four jobs. Adam's two averages are two thirds of the bar, and 38.6 GB is past the T4 line before any activation.
- LoRA. The frozen weights still take 2 bytes each, 6.4 GB. Only the 24.3 million adapter numbers pay 12 bytes: the 0.29 GB sliver.
- QLoRA. The 2.82 billion linear weights drop to 4.5 bits, 1.59 GB. The embedding table, drawn dashed, stays at 16-bit, 0.79 GB, because loaders round linear layers only.
- The line. A free Colab T4 has 16 GB. With about 3 GB of activations LoRA needs about 9.7 GB and QLoRA about 5.7 GB. Both fit, but only QLoRA leaves room for longer clauses or a bigger batch.
Three honest adjustments, all computed by qlora_memory.py:
- The page's round number. 3B × 12 bytes = 36 GB. The exact 3.21 billion gives 38.6 GB. It is the same wall, slightly higher.
- A copy the page leaves out. Mixed-precision training usually also keeps a 32-bit master copy of every trained weight, 4 more bytes each. That takes the full fine-tune to 51.4 GB, so the wall in Fig. 11.1e is if anything higher than drawn.
- A base that is not all 4-bit. The embedding table stays at 16-bit and the scales add half a bit per weight. So the frozen base is about 2.4 GB rather than the 1.5 GB in Fig. 11.1e. Double quantisation brings the whole QLoRA total to 2.53 GB.
None of this changes the conclusion. The 3 GB of activations is the page's rough figure; it grows with batch size and clause length, and is not computed here.
Memory is bytes per number times how many numbers do each job. Freezing strips 10 of the 12 bytes from almost every weight, and 4-bit storage then shrinks most of the 2 that remain.
06 · The industry recipeA Complete QLoRA Run with Unsloth
Juris now knows the trick that makes the run affordable: about 24.3 million trainable parameters, 0.76% of the model, drawn at marker 4 of Fig. 11.2. What the team does not have is a single training example. The 89% flagship and the 60% base model are both still guesses about clause tagging until somebody writes down what a correct answer looks like, 1,500 times. This section is that work, in the order it actually happens: data first, twenty minutes of GPU second.
Now the production-grade version, on Juris's clause-tagging task. The 2026 tool split, as of August: Unsloth for single-GPU fine-tuning (roughly 2× faster and leaner than stock, wraps Hugging Face TRL), Axolotl when you graduate to multi-GPU, TRL v1.0 underneath both. But before any of them: the part that actually determines whether this works.
Before the recipe, here is every tool this module leans on, and what you would pick instead.
The stack, and why
Which open-weight model, trained with which tool, on what hardware, and served how, for a narrow task that has to run inside your own cloud account?
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Tuning library | Unsloth (wraps TRL) | Axolotl, TRL directly, LLaMA-Factory | Fastest and leanest on one GPU, and the shortest script. Weakness: its speed-ups shrink at long context, and multi-GPU is not its strength. | More than one GPU or a node: Axolotl (YAML, DeepSpeed/FSDP). You need a custom training loop: plain TRL. |
| Method | QLoRA: 4-bit frozen base plus rank-16 adapters | Full fine-tuning; LoRA on a 16-bit base | Fits a 3B model on a 16 GB T4. Weakness: 4-bit rounding costs a little quality. | The task still misses its bar after data fixes and you have an 80 GB GPU: try LoRA on a 16-bit base, then full. |
| Base model | Llama 3.2 3B Instruct | Qwen3-4B, Gemma 3, Mistral Small | Small enough to serve cheaply, with a chat template the tools support. Weakness: its licence has conditions. | Licence must be Apache-2.0: Qwen3. Eval gap of more than 5 points against another model on your test set. |
| Training hardware | Free Colab T4 (16 GB) | Rented A100/H100, a local 24 GB card | Free, and 20 minutes for 1,500 rows. Weakness: sessions disconnect, and it is not for private data. | Data cannot leave your network, or runs take over an hour: rent a GPU in your own account. |
| Label drafting | A flagship model drafts, a human reviews | Hand labelling only, open-weight teacher | Review is much faster than writing. Weakness: the teacher's mistakes leak in if review is lazy. | Terms forbid training on API output, or contracts are too sensitive to send: label by hand or use an open teacher. |
| Serving | Ollama to try, vLLM to serve | llama.cpp server, SGLang, TGI (maintenance mode) | vLLM batches requests continuously, about 2× the throughput at 8 users on this page. Weakness: it needs a GPU server. | Under ~1 request a second, or CPU only: Ollama or llama.cpp is enough. |
Use Unsloth with QLoRA on a 3B model until data or scale says otherwise; the dataset is the part you cannot swap out.
Step 0 — dataset engineering (where fine-tunes are won)
Dana can pay for a GPU hour. What she cannot buy in an afternoon is 1,500 clauses that paralegals agree on. Juris has one advantage here: years of contracts that humans have already tagged in the normal course of work, plus a flagship model that can draft the rest for review. This step turns that raw material into three files — train, validation, and a test set frozen before anything else happens.
The uncomfortable truth of this whole module: the dataset is the product. The training script is twenty lines of configuration; the difference between a fine-tune that ships and one that embarrasses you is 500–2,000 curated, reviewed, deduplicated examples.
For Juris, examples come from three sources, in order of value: (1) historical human labels — clauses paralegals have already tagged in the normal course of work; (2) distillation — draft labels from the flagship model, every one reviewed by a human before it trains anything (draft-then-review is 10× cheaper than labeling from scratch, and the review step is non-negotiable: training on unreviewed model output launders its mistakes into your weights); (3) targeted authoring for rare classes, so no label has fewer than ~30 examples.
One more rule from Module 02 that still applies: carve out a test set — 300 clauses here — that never touches training, ever.
build_train_files.py's rule of max(50, 10%) for validation.- The test set leaves first. 300 clauses are put in the dashed box before a single label is drafted. Freeze it later and every number in section 07 is contaminated, because the model will have trained on rows it is then graded on.
- The review step is the product. The flagship drafts a label and a one-sentence rationale; a paralegal corrects 5 to 15% of them. Those corrections are the hard cases, and training on unreviewed drafts would copy the flagship's mistakes into the weights.
- The split feeds the run. 150 rows become the validation set the trainer scores itself on every 50 steps, and 1,350 become training rows — which, at an effective batch of 16, is the 85 steps per epoch you will see on the loss curve.
Step-by-step: what make_dataset.py does, in plain English
- Bring in
jsonandpathlibfor file work,BaseModelfrom Pydantic to describe the shape of an answer, and the Anthropic client. - Define
LABELS, the same twelve clause types as the baseline, so the draft labels and the later fine-tune share one vocabulary. - Define
ClauseTag, a two-field schema: the label, and a one-sentence rationale. The rationale exists for the human reviewer and is never trained on. - Create the client; it reads
ANTHROPIC_API_KEYfrom the environment on its own. - Define
draft(clause): callmessages.parsewith the schema asoutput_format, so the reply comes back as aClauseTagobject rather than free text. This is the Module 06 structured-outputs pattern. - Read the raw clauses from
clauses_raw.jsonl, one JSON object per line, keeping only the text field. - Loop over every clause and ask the flagship for a draft. Collect a row holding the clause, the drafted label, the rationale and
reviewed: False. - Write the rows to
for_review.jsonl. A paralegal now corrects each row and flipsreviewedto true; only those rows go forward. The 5–15% they correct are the hard cases the fine-tune needs most.
# pip install "anthropic>=0.75" "pydantic>=2.8"
# Distillation with review: the flagship DRAFTS labels; a human approves each one.
import json, pathlib
from pydantic import BaseModel
from anthropic import Anthropic
LABELS = [
"indemnification", "limitation_of_liability", "confidentiality",
"auto_renewal", "termination", "governing_law", "assignment",
"non_compete", "payment_terms", "warranty", "ip_ownership", "audit_rights",
]
class ClauseTag(BaseModel):
clause_type: str
rationale: str # one sentence for the human reviewer — never trained on
client = Anthropic() # reads ANTHROPIC_API_KEY from the environment
def draft(clause: str) -> ClauseTag:
resp = client.messages.parse( # structured outputs, Module 06 style
model="claude-sonnet-5",
max_tokens=300,
system="You tag contract clauses. clause_type must be one of: " + ", ".join(LABELS),
messages=[{"role": "user", "content": clause}],
output_format=ClauseTag,
)
return resp.parsed_output
clauses = [json.loads(line)["text"] for line in open("clauses_raw.jsonl")]
rows = []
for c in clauses:
t = draft(c)
rows.append({"clause": c, "clause_type": t.clause_type,
"rationale": t.rationale, "reviewed": False})
pathlib.Path("for_review.jsonl").write_text(
"\n".join(json.dumps(r) for r in rows) + "\n")
# → a paralegal reviews/corrects every row (a spreadsheet afternoon, not a research project);
# only rows flipped to reviewed=true move on. Expect to correct 5–15% — those corrections
# are EXACTLY the hard cases your fine-tune needs most.
Reviewed rows then get converted to chat format — the same messages structure the model was instruction-tuned on. Consistency matters more than cleverness here: one fixed system prompt, one answer style (the bare label), across every example. You are teaching a reflex, and reflexes are taught by repetition of an identical form.
Step-by-step: what build_train_files.py does, in plain English
- Bring in
jsonandrandom, and fix the random seed so the shuffle is the same on every run. - Define the one system prompt the model will be trained on. It must be identical in every example, and identical again at serving time.
- Read
reviewed.jsonl, keep only rows a human has approved, and shuffle them. - Define
to_chat(r): turn one row into the three-turn chat the model was instruction-tuned on: system, user (the clause), assistant (the bare label). - Reserve about 10% of the rows, and never fewer than 50, as a validation set. The trainer scores itself on these during the run to detect overfitting.
- Write
train.jsonlandval.jsonl, one chat object per line. The 300-clause test set was set aside before any of this and is not touched here.
import json, random
random.seed(42)
SYSTEM = "You are Juris ClauseTagger. Reply with exactly one clause_type label."
rows = [r for r in map(json.loads, open("reviewed.jsonl")) if r["reviewed"]]
random.shuffle(rows)
def to_chat(r):
return {"messages": [
{"role": "system", "content": SYSTEM},
{"role": "user", "content": r["clause"]},
{"role": "assistant", "content": r["clause_type"]},
]}
n_val = max(50, int(0.1 * len(rows))) # ~10% for validation during training
splits = {"val": rows[:n_val], "train": rows[n_val:]}
for name, part in splits.items():
with open(f"{name}.jsonl", "w") as f:
for r in part:
f.write(json.dumps(to_chat(r)) + "\n")
# test.jsonl (300 clauses) was set aside BEFORE any of this and stays untouched.
Step 1 — the training run
The three files exist: 1,350 training rows, 150 validation rows, and 300 test clauses nobody may look at. Now the twenty minutes that people mistake for the whole job. Everything Juris decided so far — rank 16, a frozen 4-bit base, one fixed system prompt — becomes about forty lines of configuration, and the only output that matters while it runs is the validation loss.
This needs an NVIDIA GPU — a free Colab T4 (16 GB) finishes ~1,500 examples in about twenty minutes. No GPU? Read the script anyway; every line is a decision you'll be asked to defend, and the eval and serving sections after it run on anything.
You have not been taught Unsloth, TRL, or any of the arguments below, and you are not expected to know them yet. Read the file once as a story, using the step-by-step list. The anatomy after the code takes the one call that matters apart token by token, and section 07 then measures what this run produced.
Build it in chunks
We build train_qlora.py in five chunks. Chunks 1–2 run offline and grow into each other; chunks 3 and 4 are small offline experiments on the two ideas that surprise beginners; chunk 5 is the GPU part and is not run here.
-
Chunk 1 — write two tiny chat files and load them as a dataset
Everything later in
train_qlora.pystarts from atrain.jsonland aval.jsonlof chats, so we make a four-row pair by hand and prove the loader reads them. Nothing is trained yet.Step-by-step: what this chunk does, in plain English
- Define
chat(clause, label): one training row is three messages, system, user, assistant. - Write three rows to
train.jsonland one toval.jsonl, one JSON object per line. - Call
load_dataset("json", ...)with both files; print what it found and the answer message of row 0.
chunk1_load.pyruns offline# chunk 1: write a tiny train/val pair and load it the way train_qlora.py does import json, pathlib from datasets import load_dataset def chat(clause, label): return {"messages": [ {"role": "system", "content": "You are Juris ClauseTagger. Reply with exactly one clause_type label."}, {"role": "user", "content": clause}, {"role": "assistant", "content": label}]} pathlib.Path("train.jsonl").write_text("\n".join(json.dumps(chat(c, l)) for c, l in [ ("Either party may terminate with 30 days notice.", "termination"), ("This Agreement renews each year unless cancelled 60 days before.", "auto_renewal"), ("Supplier shall indemnify Customer against third-party claims.", "indemnification")]) + "\n") pathlib.Path("val.jsonl").write_text(json.dumps(chat("Fees are due net 30.", "payment_terms")) + "\n") ds = load_dataset("json", data_files={"train": "train.jsonl", "val": "val.jsonl"}) print(ds) print(ds["train"][0]["messages"][2])load_dataset("json", data_files={...})— turns JSON-lines files into a named-split dataset, the same call the trainer script makes.python chunk1_load.pyprintsDatasetDictwithtrain: num_rows: 3andval: num_rows: 1, then{'role': 'assistant', 'content': 'termination'}. Measured. - Define
-
Chunk 2 — turn each chat into the one text string the model reads
A model reads one long string, not a list of messages. This chunk renders the chat with Llama's special tokens. The real script asks the tokenizer to do it; here a six-line stand-in does, so you can see the string.
Step-by-step: what this chunk does, in plain English
- Define
apply_chat_template: start with<|begin_of_text|>, then for each message add a header naming the role, a blank line, the content, and<|eot_id|>. - Define
to_textto do that for a whole batch of rows at once. - Map it over both splits and drop the old
messagescolumn.
chunk2_template.py (added lines; chunk 1 stays above them)runs offline# --- NEW: stand-in for tokenizer.apply_chat_template (real one needs a model download) --- def apply_chat_template(messages, tokenize=False): out = "<|begin_of_text|>" for m in messages: out += f"<|start_header_id|>{m['role']}<|end_header_id|>\n\n{m['content']}<|eot_id|>" return out def to_text(batch): return {"text": [apply_chat_template(m, tokenize=False) for m in batch["messages"]]} ds = ds.map(to_text, batched=True, remove_columns=["messages"]) print(ds["train"].column_names) print(ds["train"][0]["text"])ds.map(fn, batched=True, remove_columns=[...])— runs a function over every row and swaps the columns.python chunk2_template.pyprints['text'], then one string that starts<|begin_of_text|><|start_header_id|>system<|end_header_id|>and endstermination<|eot_id|>. Measured. - Define
-
Chunk 3 — count the numbers LoRA will add
Before we load a 3-billion-parameter model, check the arithmetic that makes the run affordable. This chunk is a standalone side-experiment: it does not need the data from chunks 1–2.
Step-by-step: what this chunk does, in plain English
- Write down rank 16, 28 layers, and the shape of each of the seven target matrices.
- LoRA stores r × (rows + columns) numbers per matrix. Add that up for one layer.
- Multiply by 28 layers and divide by the 3.21 billion base parameters.
chunk3_lora_config.pyruns offline# chunk 3: what get_peft_model will add. Count LoRA numbers for Llama-3.2-3B by hand. r, layers, hidden, ffn, kv = 16, 28, 3072, 8192, 1024 targets = {"q_proj": (hidden, hidden), "k_proj": (hidden, kv), "v_proj": (hidden, kv), "o_proj": (hidden, hidden), "gate_proj": (hidden, ffn), "up_proj": (hidden, ffn), "down_proj": (ffn, hidden)} per_layer = sum(r * (i + o) for i, o in targets.values()) # B is (o x r), A is (r x i) total = per_layer * layers print(f"per layer : {per_layer:,}") print(f"all layers: {total:,}") print(f"share of a 3.21B model: {total / 3.21e9:.2%}")A dict of
(rows, columns)pairs, andsum()over a generator.python chunk3_lora_config.pyprintsper layer : 868,352,all layers: 24,313,856andshare of a 3.21B model: 0.76%. Measured; it matches the 24.3 million on Fig. 11.2. -
Chunk 4 — the loss mask: score the answer, ignore the prompt
The trainer scores every token unless told otherwise, and the label is 2 tokens out of 32. This chunk builds the mask by hand on one row, with words standing in for tokens (also standalone).
Step-by-step: what this chunk does, in plain English
- Render one row to a string and cut it at the assistant header.
- Count the pieces before the cut; give each the label −100, which means ignore.
- Keep the real pieces after the cut as labels and count how many are scored.
chunk4_mask.pyruns offline# chunk 4: the loss mask. Everything before the assistant header gets label -100 (ignored). # Offline stand-in: one "token" per whitespace-separated word, special tokens count as one. RESPONSE_PART = "<|start_header_id|>assistant<|end_header_id|>\n\n" def apply_chat_template(messages): out = "<|begin_of_text|>" for m in messages: out += f"<|start_header_id|>{m['role']}<|end_header_id|>\n\n{m['content']}<|eot_id|>" return out import re def fake_tokens(s): # each <|special|> token is one piece; ordinary text is split on spaces return re.findall(r"<\|[^|]+\|>|[^\s<]+", s) messages = [ {"role": "system", "content": "You are Juris ClauseTagger. Reply with exactly one clause_type label."}, {"role": "user", "content": "Either party may terminate with 30 days notice."}, {"role": "assistant", "content": "termination"}] text = apply_chat_template(messages) head, answer = text.split(RESPONSE_PART) n_head = len(fake_tokens(head + RESPONSE_PART)) toks = fake_tokens(text) labels = [-100] * n_head + toks[n_head:] # ignore the prompt, score the answer print("tokens in row :", len(toks)) print("scored (not -100):", sum(l != -100 for l in labels)) print("scored pieces :", [l for l in labels if l != -100])re.findallwith a pattern that keeps each<|special|>token as one piece; the label value-100.python chunk4_mask.pyprintstokens in row : 32,scored (not -100): 2,scored pieces : ['termination', '<|eot_id|>']. Measured. Real tokens differ a little; the idea does not. -
Chunk 5 — load the 4-bit model, add the adapters, and run the trainer
Now every piece is familiar: the data files (chunk 1), the text column (chunk 2), the adapter call whose size you counted (chunk 3) and the mask (chunk 4). What is left is the model and the loop, which is the real file below.
Step-by-step: what this chunk does, in plain English
- Load the base model already stored in 4-bit.
- Add rank-16 adapters to the seven matrices.
- Build
SFTTrainerwith batch 4 × 4 accumulation, two epochs, learning rate 2e-4, evaluating every 50 steps. - Wrap it in
train_on_responses_only(chunk 4's mask) and calltrain().
train_qlora.py (shortened excerpt)not run here — needs a GPUmodel, tokenizer = FastLanguageModel.from_pretrained( model_name="unsloth/Llama-3.2-3B-Instruct-bnb-4bit", max_seq_length=2048, load_in_4bit=True, ) model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=16, target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]) trainer = SFTTrainer(model=model, processing_class=tokenizer, train_dataset=ds["train"], eval_dataset=ds["val"], args=SFTConfig(output_dir="clausetag-lora", dataset_text_field="text", per_device_train_batch_size=4, gradient_accumulation_steps=4, num_train_epochs=2, learning_rate=2e-4, eval_strategy="steps", eval_steps=50)) trainer = train_on_responses_only(trainer, instruction_part=..., response_part=...) trainer.train()FastLanguageModel,SFTTrainerandtrain_on_responses_only— three library calls; the arguments are explained in the step-by-step list and the anatomy below.Not run here: it needs an NVIDIA GPU, and this course machine does not train models. On a free Colab T4 it prints a training loss and a validation loss every 50 steps; the sections after it show what such a run produced.
Step-by-step: what train_qlora.py does, in plain English
- Install
unsloth; it pulls in PyTorch, Transformers, TRL, PEFT and bitsandbytes. Import the fast model loader, the answer-only mask helper, the dataset loader, and TRL's supervised fine-tuning trainer with its config class. - Load the base model and its tokenizer from a checkpoint that is already stored in 4-bit.
max_seq_length=2048caps the tokens per example;load_in_4bit=Truekeeps the base rounded in memory. A frozen 4-bit base with trainable adapters on top is what QLoRA means. - Wrap the model with
get_peft_model: add a rank-16 pair of thin matrices to each of the seven named weight matrices in every layer. Freeze everything else. From here on, only those adapters receive gradients. - Turn on Unsloth's gradient checkpointing, which recomputes activations during the backward pass instead of storing them all. It trades some compute for the memory that makes a 16 GB T4 enough.
- Load
train.jsonlandval.jsonlas one dataset with two splits. - Define
to_text: render each chat (system, user, assistant) into one string with the model's own chat template. That way the special tokens match what the model saw in its own instruction tuning. Apply it to every row and drop the original messages column. - Build the trainer. It gets the model, the tokenizer as
processing_class, the two splits, and a config. The config says where to save and which column holds the text. Batch size 4 with 4 accumulation steps gives an effective batch of 16. Two epochs, and a learning rate of 2e-4 with cosine decay and a short warm-up. Evaluate every 50 steps, with a fixed seed. - Wrap the trainer in
train_on_responses_only. It finds the assistant header in every row and sets every label before it to −100, which Hugging Face reads as "ignore". This one call decides what the run is graded on: without it all 70 predictions in a row are scored, and only 4 are the answer. trainer.train()runs the loop: forward pass, loss on the scored tokens, backward pass through the adapters only, optimizer step. Watch the validation loss it prints. Falling then flat is healthy; rising while training loss keeps falling is overfitting.- Save the adapter and the tokenizer. The folder holds only the trained B and A matrices, 50–100 MB, not the base model.
The whole program
Lines 1–6 are imports. Lines 7–14 are rung 5 (load the model), 15–25 rung 3 (adapters), 26–28 rung 1 (load the data), 29–35 rung 2 (chat to text), 36–57 rung 5 (the trainer) and 58–76 rung 4 (the loss mask, then train and save). Each begins with a # ── rung n ── comment.
# pip install unsloth # pulls torch, transformers, trl, peft, bitsandbytes (checked Sep 2026)
from unsloth import FastLanguageModel
from unsloth.chat_templates import train_on_responses_only
from datasets import load_dataset
from trl import SFTConfig, SFTTrainer
# ── rung 5: load the 4-bit base ──
# Base already stored 4-bit → this is QLoRA: frozen int4 base + fp16 LoRA adapters.
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Llama-3.2-3B-Instruct-bnb-4bit", # or unsloth/Qwen3-4B
max_seq_length=2048,
load_in_4bit=True,
)
# ── rung 3: the adapters (24.3 M numbers) ──
model = FastLanguageModel.get_peft_model(
model,
r=16, lora_alpha=16, # community default: alpha = r
lora_dropout=0.0, bias="none",
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"], # all linear layers
use_gradient_checkpointing="unsloth", # trade compute for memory — fits the T4
random_state=42,
)
# ── rung 1: load the chat files ──
ds = load_dataset("json", data_files={"train": "train.jsonl", "val": "val.jsonl"})
# ── rung 2: chat to text ──
def to_text(batch): # render chat messages with the model's own template
return {"text": [tokenizer.apply_chat_template(m, tokenize=False)
for m in batch["messages"]]}
ds = ds.map(to_text, batched=True, remove_columns=["messages"])
# ── rung 5: the trainer ──
trainer = SFTTrainer(
model=model,
processing_class=tokenizer, # TRL renamed the old `tokenizer=` argument
train_dataset=ds["train"],
eval_dataset=ds["val"],
args=SFTConfig(
output_dir="clausetag-lora",
dataset_text_field="text",
per_device_train_batch_size=4,
gradient_accumulation_steps=4, # effective batch 16
num_train_epochs=2, # more epochs on 1.5k examples = overfitting
learning_rate=2e-4, # LoRA tolerates high LR; full FT would not
lr_scheduler_type="cosine",
warmup_ratio=0.03,
logging_steps=10,
eval_strategy="steps", eval_steps=50,
seed=42,
report_to="none",
),
)
# ── rung 4: the loss mask ──
# Grade the answer only. A plain `text` column is scored on every token, so the loss
# would mostly measure how well the model predicts clause wording and a system prompt
# it sees in all 1,350 rows — the label is 4 tokens out of 70. This sets every label
# before each assistant header to -100 so it is ignored. TRL's own assistant_only_loss
# needs a chat template carrying {% generation %}, which Llama 3.2's does not, so for
# this model Unsloth's wrapper is the documented route.
trainer = train_on_responses_only(
trainer,
instruction_part="<|start_header_id|>user<|end_header_id|>\n\n",
response_part="<|start_header_id|>assistant<|end_header_id|>\n\n",
)
trainer.train()
# Watch val loss: fall-then-flatten is healthy. Rising while train loss falls =
# overfitting — stop, reduce epochs, or go get more data (it's always the data).
model.save_pretrained("clausetag-lora") # adapter only: ~50–100 MB
tokenizer.save_pretrained("clausetag-lora")
model = FastLanguageModel.get_peft_model(1
model,
r=16,2 lora_alpha=16,3
lora_dropout=0.0, bias="none",4
target_modules=["q_proj", "k_proj", "v_proj", "o_proj",
"gate_proj", "up_proj", "down_proj"],5
use_gradient_checkpointing="unsloth",6
random_state=42,7
)
- The wrapper. PEFT stands for parameter-efficient fine-tuning. This call freezes every existing weight and attaches a B·A pair to the matrices you name. The object it returns is what you train and save; the base checkpoint on disk never changes. The common mistake is expecting a full model at the end. You get an adapter folder, and you merge it in step 2.
- The rank.
ris the width of the bottleneck: the number of independent directions the update may use. It is the count you worked out by hand in section 05. Raising it doubles the adapter for a sliver of quality. When accuracy is short, the fix is almost always more or cleaner data, not a biggerr. - The scale. The update B·A is multiplied by
lora_alpha / rbefore it is added to the frozen weight. With alpha equal to r the scale is 1. The mistake: changingrand leaving alpha alone. That silently shrinks or inflates every update, so the run behaves as if you had changed the learning rate. - The fast-path settings. No dropout on the adapter inputs, and no trainable bias terms. Unsloth supports other values but is only optimised for these two, and warns when you change them. Copying
lora_dropout=0.1from a stock PEFT tutorial is the usual way to lose the speedup. - The targets. The list names which weight matrices get an adapter. Here it is the four attention projections and the three feed-forward projections in every layer. That is every linear layer in a Llama block. The original LoRA paper adapted only q and v; the QLoRA paper found that covering all linear layers matters more than rank. Targeting fewer is a common reason a fine-tune underperforms.
- Memory for time. Gradient checkpointing discards the activations after the forward pass and recomputes them during the backward pass. Unsloth's version also parks them in system memory, cutting GPU memory by roughly a third at the cost of a slower step. Turning it off to speed up a run is how you meet an out-of-memory error on a T4.
- The seed. LoRA starts with B all zeros and A random, so the adapted model begins exactly equal to the base. The seed fixes that random A. Compare two runs with different seeds and you cannot tell whether the gap came from the change you made or from the dice.
What the run prints while it works is two numbers, and the second one is the one that matters. Here is the shape to look for, and the shape that means stop.
num_train_epochs=2 is 170 steps and eval_steps=50 gives exactly three validation points. The loss values come from an earlier run, made before the answer-only mask, so they average over every token in a row. Read them as illustrative of the shape, not as measurements of the script as it now stands: with the mask the numbers land differently. Yours will differ either way.- The solid line. Training loss, printed every 10 steps. It falls from 1.82 to 0.21 because the model is getting better at the rows it is being shown. On its own it proves nothing.
- The three dots. Validation loss on 150 rows the model never trains on, scored at steps 50, 100 and 150. Falling to 0.34 and then flattening at 0.31 is the healthy shape: it learned the task, then ran out of task to learn. Those three values are from the pre-mask run; read the direction, not the digits.
- The separation. Left running to six epochs, training loss keeps falling to 0.08 while validation turns up to 0.45. The gap between the lines is memorisation. The fix is fewer epochs or more data, never a bigger rank.
Questions you might be asking now
The loss curve above is the only thing the run shows you while it works. The questions below slow down for what that number is, which tokens it is computed on, and how to read two curves against each other. They use the same three training rows, all clauses this page already quotes, and every count comes from rerunning one_row_to_loss.py or overfit_toy_tagger.py.
| Row | User turn: the clause | Assistant turn: the label | Clause characters | Tokens in the whole row |
|---|---|---|---|---|
| A | This Agreement shall automatically renew for successive one-year terms unless either party gives written notice 60 days prior to expiration. | auto_renewal | 140 | 71 |
| B | Supplier shall defend, indemnify and hold harmless Customer against all third-party claims arising from Supplier's negligence. | indemnification | 126 | 69 |
| C | Either party may terminate with 30 days notice. | termination | 47 | 48 |
What does one training row actually look like by the time it reaches the model? Walk row A through the chat template, the tokens and the loss.
It becomes one string with role markers, then about 71 tokens, and the model is asked to predict each token from the ones before it. Only 4 of those 70 predictions are the answer, and train_qlora.py scores exactly those 4. Delete its train_on_responses_only call and all 70 get scored instead.
Station 1: the chat template
On disk, row A is three messages: system, user and assistant. to_text in train_qlora.py calls apply_chat_template with tokenize=False, which joins them into one string in the layout Llama 3 was instruction-tuned on. The markers in angle brackets are special tokens that mark where each turn starts and ends:
<|begin_of_text|><|start_header_id|>system<|end_header_id|>
You are Juris ClauseTagger. Reply with exactly one clause_type label.<|eot_id|><|start_header_id|>user<|end_header_id|>
This Agreement shall automatically renew for successive one-year terms unless either party gives written notice 60 days prior to expiration.<|eot_id|><|start_header_id|>assistant<|end_header_id|>
auto_renewal<|eot_id|>
This is the format Meta documents for Llama 3.2. The template shipped with a checkpoint can add a short header of its own, such as a date line in the system turn. Print yours with tokenize=False before trusting any count.
Station 2: tokens
- Count the markers. <|begin_of_text|> once. Then, for each of the three turns, a start marker, the role name, an end marker, the blank line and <|eot_id|>. That is 1 + 3 × 5 = 16 tokens.
- The system prompt. 69 characters ÷ 4 ≈ 17 tokens.
- The clause. 140 characters ÷ 4 = 35 tokens.
- The label.
auto_renewalis 12 characters ÷ 4 = 3 tokens. - Add them. 16 + 17 + 35 + 3 = 71 tokens for row A. Rows B and C come to 69 and 48.
Station 3: predictions, and which ones are scored
A language model learns by predicting each token from all the tokens before it. A row of 71 tokens therefore holds 70 predictions: token 2 from token 1, token 3 from tokens 1 and 2, and so on. The first token has nothing before it, so nothing predicts it.
Each prediction is compared with the token that really came next. The trainer can mark any position "ignore", with the value −100 in Hugging Face's code, and that position then adds nothing to the loss. That marking is called the loss mask.
| If you forget the mask | As train_qlora.py is written | |
|---|---|---|
| Scored predictions in row A | 70 | 4 |
| What they are | Every marker after the first, the 17 system-prompt tokens, the 35 clause tokens, the label and its end marker | The 3 label tokens and the <|eot_id|> that ends the answer |
| Answer's share of the scored predictions, row A | 4 of 70 = 5.7% | 4 of 4 |
| Answer's share, rows A, B and C together | 13 of 185 = 7.0% | 13 of 13 |
| What the printed loss mostly describes | How well the model predicts contract text, and a system prompt it sees 1,350 times | How sure the model is of the label |
Why does the mask have to be asked for at all? to_text produces one plain text column. TRL's documentation for completion_only_loss says a dataset in that shape is scored on the full sequence; only prompt-completion datasets are scored on the completion by default.
So the mask is opt-in, and forgetting it is silent: the run still finishes and prints a falling loss, just of the wrong thing.
That is why train_qlora.py wraps the trainer in train_on_responses_only from unsloth.chat_templates before trainer.train(). The user header goes in as instruction_part and the assistant header as response_part, each with its blank line.
TRL has its own switch, assistant_only_loss=True. It needs a chat template carrying the {% generation %} marker, which Llama 3.2's does not (checked September 2026), so Unsloth's wrapper is the route that works here.
- The row. 16 markers, 17 system-prompt tokens, 35 clause tokens and 3 label tokens. The label, the only thing Juris wants produced, is the thin box at the right end.
- If you forget the mask. Every position after the first is graded, so the model is also taught to predict contract text and a prompt that never changes. The answer is 4 of 70, 5.7%.
- Scored as the script is written. Every position before the answer is set to −100 and ignored. The model still reads all 71 tokens; only the grading changes.
- Serving.
add_generation_prompt=Truehands the model everything up to the assistant header, 67 tokens, and it writes the rest. The masked version trains exactly the 4 tokens it will be asked to write.
Two honest limits. First, scoring the whole row is not wrong in every setting; some recipes keep it on purpose, because practising the domain's language can help. It is wrong here: Juris is paying for one label, so the loss should grade it. What changes with the mask is what the loss curve means, which is the next question.
Second, the counts use the 4-characters rule, and a real tokenizer may split auto_renewal differently. The shape does not change: the label is a handful of tokens in a row of dozens.
The model reads the whole row, but the loss grades only the positions the mask leaves open; as written that is the 4 answer tokens, not all 70 predictions.
What is the "loss" the trainer prints? What does a validation loss of 0.31 actually mean?
For each scored position the loss is −ln p: minus the natural logarithm of p, the probability the model gave to the token that really came next. The printed number is the average over all scored positions. Undo the logarithm and 0.31 means a typical probability of e^−0.31 = 0.733 on the right token.
At every position the model does not pick one token. It hands out probabilities to all 128,256 tokens in its vocabulary, and they add up to 1. The loss looks at only one of them: the probability p it gave to the token that really came next.
Here is the arithmetic for three answer positions. The three probabilities are made up to show the steps; a real run computes them for every scored position in every row.
- Read off p for the right token. Say the model gave 0.9, 0.6 and 0.4 to the three tokens that really came next.
- Take minus the natural log of each. −ln 0.9 = 0.105, −ln 0.6 = 0.511, −ln 0.4 = 0.916. The natural log, ln, is the log to base e (about 2.718).
- Average them. (0.105 + 0.511 + 0.916) ÷ 3 = 0.511. This is the kind of number the trainer prints, averaged over thousands of positions instead of three.
- Undo the log. e^−0.511 (e raised to the power −0.511) = 0.600. That is the typical probability on the right token.
- Compare with a plain average. (0.9 + 0.6 + 0.4) ÷ 3 = 0.633. The log version is lower because it listens hardest to the weakest position.
Why a logarithm, and why the minus sign? Three properties make it the right score for this job:
- Certain and right costs nothing. −ln 1 = 0, so a perfect prediction adds nothing.
- Confident and wrong costs a lot. p = 0.01 costs 4.6, and the cost has no ceiling as p approaches 0.
- Whole answers add up. The probability of a three-token label is the three probabilities multiplied. Logs turn multiplying into adding, so the trainer can simply average.
Now the values in Fig. 11.2d, turned back into typical probabilities. Those losses are from the run before the answer-only mask, so read the conversions as a way to read any curve, not as measurements.
| Point on the curve | Loss | Typical p on the right token |
|---|---|---|
| Training loss at the start | 1.82 | 0.162 |
| Validation, step 50 | 0.62 | 0.538 |
| Validation, step 100 | 0.34 | 0.712 |
| Validation, step 150 | 0.31 | 0.733 |
| Training loss, step 170 | 0.21 | 0.811 |
| Training loss after six epochs | 0.08 | 0.923 |
| Validation after six epochs | 0.45 | 0.638 |
- The curve. Near p = 1 it is almost flat: going from 0.9 to 1.0 saves only 0.105. Near p = 0 it climbs without limit, so confident mistakes are punished hard.
- The start of training. 1.82 means a typical probability of 0.162 on the right next token before any training. A blind guess across 128,256 tokens would cost 11.76; the base model already knows English and contracts.
- The average. 0.105, 0.511 and 0.916 average to 0.511, a typical probability of 0.600. Most of it came from the one weak position at 0.4.
- Accuracy is a different question. It only asks whether the right token had the highest probability. 0.4 can win when the other 128,255 tokens share the remaining 0.6, and it still costs 0.916 in loss.
Marker 4 in Fig. 11.2m is why section 07 grades the fine-tune with accuracy on 300 test clauses, and the loss only steers training. Loss measures confidence; accuracy measures the top pick. TRL logs both: loss, and mean_token_accuracy over the same scored positions.
Which positions those are matters too. As train_qlora.py is written the mask is on, so a validation loss is about the label alone.
The 0.31 in this question comes from the earlier run, before the mask, where the number was mostly about clause text and a system prompt seen 1,350 times. The arithmetic above is the same either way; what you can say about the result is not.
A loss is the average of −ln p over the scored positions; e^−loss turns it back into the typical probability on the right token.
How do I read training loss against validation loss? Show me overfitting in real numbers, not an illustrative curve.
Watch validation loss, and read its direction after its lowest point. Training loss falls almost no matter what, because it grades rows the model studies. A toy clause tagger was trained on 600 rows with 52 wrong labels. Its validation loss bottomed out at 0.399 on step 80 and climbed to 0.615, while training loss fell to 0.015. Accuracy on new clauses fell from 88.3% to 79.7%.
Module 02's test-set question used a teacher who hands out practice questions with the answer key. Training loss is the score on those practice questions. Validation loss is the score on a sealed set of new ones: here, the 150 rows of val.jsonl.
Now suppose some answers in the key are wrong. Nothing but memory can reproduce a wrong answer. That makes wrong labels the cleanest way to watch overfitting, and they are Juris's real risk: the 5 to 15% of draft labels a paralegal corrects in Fig. 11.2c.
Fig. 11.2d is illustrative, so here is a curve you can rerun. overfit_toy_tagger.py trains a bag-of-words tagger for three of Juris's labels with gradient descent on the same kind of loss. It is not an LLM, which is why three versions train on the same clauses in about four seconds.
| Run | Lowest validation loss | Validation accuracy there | At step 2,000: training loss, validation loss, validation accuracy | What it says |
|---|---|---|---|---|
| 1. 600 reviewed rows | 0.277 at step 230 | 88.7% | 0.006, 0.321, 88.3% | Healthy: fell, flattened, then crept up by 0.044 while accuracy held |
| 2. The same 600 rows, 52 labels wrong (8.7%) | 0.399 at step 80 | 88.3% | 0.015, 0.615, 79.7% | Overfitting: turned up early and kept climbing; 8.6 points of accuracy lost |
| 3. The first 60 reviewed rows | 0.493 at step 1,250 | 79.0% | 0.001, 0.494, 79.0% | Too little data: memorised every row, flat but high |
Reading run 2, step by step
- Look at training loss, then stop trusting it. It fell from 0.988 to 0.015. That only says the model can now recite its 600 rows, the 52 wrong ones included.
- Find the lowest validation loss. 0.399, at step 80. Validation accuracy there was 88.3%.
- Read the direction after it. Step 200: 0.420. Step 500: 0.478. Step 2,000: 0.615. Validation rising while training keeps falling is the overfitting signature.
- Read the gap. Validation minus training was 0.399 − 0.266 = 0.133 at step 80, and 0.615 − 0.015 = 0.600 at the end. A widening gap is memorisation growing.
- Turn the loss into a probability. e^−0.399 = 0.671 at the lowest point and e^−0.615 = 0.541 at the end. On clauses it never saw, the model grew less sure of the right label.
Why wrong labels do this: to fit a clause whose label is wrong, the model cannot use the words that really mark that label. It leans on words that happen to sit in that one clause, such as a party name or a date. Those words turn up in new clauses by chance, and there they push toward the wrong label.
Run 1's small creep after step 230, 0.044 while accuracy held at 88%, is the previous question's point that loss is not accuracy. The model grows overconfident on the few clauses it gets wrong.
- Reviewed rows. Training loss falls to 0.006. Validation loss falls to 0.277 at step 230 and barely moves after, ending at 0.321 with accuracy still 88%: the fall-then-flatten shape.
- Wrong labels. The same clauses with 52 labels changed. Validation loss bottoms out early, 0.399 at step 80, and climbs to 0.615 while training loss keeps falling; accuracy drops from 88.3% to 79.7%. The step-80 checkpoint is the one to keep.
- Too few rows. Sixty rows are memorised, and training loss reaches 0.001. Validation loss flattens at 0.494 and never turns up, so no earlier checkpoint is better. The gap of 0.49 closes only with more rows.
| Training loss | Validation loss | What it means | What to do |
|---|---|---|---|
| Falling | Falling | Still learning | Keep going |
| Falling | Flat | Learned what these rows can teach (run 1 after step 230) | Stop; more steps buy nothing |
| Falling | Rising | Memorising (run 2 after step 80) | Keep the checkpoint from the lowest point, train fewer epochs, and look for bad rows |
| Near zero | Flat and high, with a wide gap | Too few rows to generalise (run 3) | Add reviewed rows |
| Flat and high | Flat and high | Not learning at all | Check the learning rate, the chat template and the loss mask |
Two trainer settings turn the table into behaviour. load_best_model_at_end=True with metric_for_best_model="eval_loss" hands back the checkpoint with the lowest validation loss, provided checkpoints are saved on the same schedule as evaluations. EarlyStoppingCallback from transformers ends the run once validation loss has stopped improving for a set number of evaluations.
One caution about spacing. eval_steps=50 gives the page's run only three validation points. Checked at the same steps, run 2 would have shown 0.407 at step 50 and 0.400 at step 100, and the first rise only at step 150, as 0.409. The fewer the points, the later you see the turn.
The honest limit is scale. The toy took 2,000 passes to overfit badly, while a 3-billion-parameter model has far more room to memorise 1,350 rows, which is why the page's configuration warns against more epochs. The step counts do not transfer; the shapes and the reading do.
Training loss says how well the model recites its rows; validation loss says how well that carries to new ones. Keep the checkpoint where validation loss was lowest, and when it turns up early, check the data before the settings.
Step 2 — merge, export, smoke-test
The run has finished and left a folder of about 50 MB on disk: the trained B and A matrices, nothing else. That folder cannot serve traffic on its own, and Juris needs two different shapes of it — one for the vLLM server inside the VPC, one small enough for a laptop. This step produces both, then asks the model a single clause before anyone celebrates.
Step-by-step: what the merge, export and smoke test do, in plain English
save_pretrained_mergedcomputes W + B·A for every adapted matrix once and writes a plain 16-bit model toclausetag-merged. This is what vLLM serves in section 09; nothing at inference time knows LoRA was involved.save_pretrained_ggufwrites the same merged model in GGUF, the file format Ollama and llama.cpp read, rounded to 4-bit with theq4_k_mscheme. That lets a laptop run the fine-tune too.- Switch the in-memory model to inference mode, which turns off the training-only machinery and speeds up generation.
- Build one prompt through the chat template: the exact system prompt used in training, plus an indemnification clause.
add_generation_prompt=Truemakes the template end where the assistant's turn begins. - Tokenize it, move the tensors to the GPU, and generate at most 8 new tokens.
- Decode only the tokens after the prompt (the slice starting at the prompt's length) and print them. The expected answer is the bare label; anything wordier means the training format did not take.
# Merge adapter into base weights for serving; export a GGUF so Ollama can run it too.
model.save_pretrained_merged("clausetag-merged", tokenizer, save_method="merged_16bit")
model.save_pretrained_gguf("clausetag-gguf", tokenizer, quantization_method="q4_k_m")
# Smoke test BEFORE celebrating — same system prompt as training, always.
FastLanguageModel.for_inference(model)
SYSTEM = "You are Juris ClauseTagger. Reply with exactly one clause_type label."
prompt = tokenizer.apply_chat_template(
[{"role": "system", "content": SYSTEM},
{"role": "user", "content":
"Supplier shall defend, indemnify and hold harmless Customer against "
"all third-party claims arising from Supplier's negligence."}],
tokenize=False, add_generation_prompt=True)
inputs = tokenizer(prompt, return_tensors="pt").to("cuda")
out = model.generate(**inputs, max_new_tokens=8)
print(tokenizer.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True))
# → indemnification
- Merging. W + B·A is computed once and written out as ordinary weights, so serving code, latency and memory look exactly as if you had trained the whole model. The adapter stops existing at that point.
- Hot-swapping. Keep the base loaded and the adapters as files, and one GPU serves many tasks or many customers. Each request names its adapter, and each adapter is about 50 MB instead of 6 GB.
- The trade. Merging costs disk and gives the fastest token; keeping them separate costs a small per-token multiply and gives you one machine for every task. Juris merges for the clause tagger and keeps the option open for per-client dialects.
07 · Prove it with evalsThe Fine-Tune vs the Flagship, Measured
Juris has a merged model and one correct answer on one clause. That is worth nothing to Dana, who has to tell a client that clause tagging got better. The 300 test clauses put aside in the dashed box at marker 1 of Fig. 11.2c have not been opened yet, and this is what they were saved for. One harness, three contenders, the same clauses on the same afternoon: the untuned 3B, the flagship with the best prompt the team could write, and the fine-tune.
A smoke test is not evidence. Module 07's rule — the eval suite gates every project — applies to your own model with extra force, because you are now emotionally invested in the thing you're grading. The harness is the same one you'd use for any system: held-out test set, one metric, identical conditions for every contender.
Step-by-step: what eval_vs_baseline.py does, in plain English
- Bring in
json,osandtime, plus both clients:OpenAIfor the local server andAnthropicfor the flagship. - Load the 300 held-out clauses from
test.jsonl. These were frozen before dataset work began and have never been seen by the fine-tune. - Define the same system prompt the model was trained on, and two clients.
localpoints at vLLM on port 8000 (or Ollama on 11434);apiis for claude-sonnet-5. - Define
call_local: one chat request to the fine-tune, namedclausetag, capped at 8 tokens. - Define
call_api: one request to the flagship using the best few-shot prompt the team found, read fromfewshot_system.txt. A weak baseline would make the fine-tune look better than it is, so this is the strongest prompt available. - Define
run(name, call): for every test clause, time one call and normalise the reply to lowercase. Count it correct only if it exactly matches the label. - Sort the timings and print accuracy as a percentage with the median (p50) latency in milliseconds. Median rather than mean, so one slow outlier does not distort the number.
- Run the same function over both contenders. One harness, identical conditions, one line of output each: that is what makes the comparison fair.
# pip install "openai>=1.60" "anthropic>=0.75"
# One harness, every contender. Module 07's discipline, pointed at your own model.
import json, os, time
from openai import OpenAI
from anthropic import Anthropic
test = [json.loads(l) for l in open("test.jsonl")] # 300 clauses, never trained on
SYSTEM = "You are Juris ClauseTagger. Reply with exactly one clause_type label."
local = OpenAI(base_url=os.environ.get("LOCAL_BASE_URL", "http://localhost:8000/v1"),
api_key="none") # vLLM (next section) — or :11434/v1 for Ollama
api = Anthropic()
def call_local(clause):
r = local.chat.completions.create(
model="clausetag", max_tokens=8,
messages=[{"role": "system", "content": SYSTEM},
{"role": "user", "content": clause}])
return r.choices[0].message.content
def call_api(clause): # the honest baseline: flagship + few-shot, best prompt we found
r = api.messages.create(
model="claude-sonnet-5", max_tokens=8,
system=open("fewshot_system.txt").read(), # instructions + 12 worked examples
messages=[{"role": "user", "content": clause}])
return r.content[0].text
def run(name, call):
correct, times = 0, []
for row in test:
t0 = time.perf_counter()
pred = call(row["clause"]).strip().lower()
times.append(time.perf_counter() - t0)
correct += int(pred == row["clause_type"])
times.sort()
print(f"{name:22s} acc={correct/len(test):.1%} p50={times[len(times)//2]*1000:.0f}ms")
run("fine-tuned 3B (local)", call_local)
run("claude-sonnet-5 (API)", call_api)
One representative run of this exact recipe (illustrative numbers — yours will differ, which is why the harness exists and the notebook ships with the project):
| System | Accuracy | p50 latency | $ / 1k requests | Where it runs |
|---|---|---|---|---|
| llama3.2:3b, few-shot (untuned) | 61% | 380 ms | ~$0.05 | your GPU |
| claude-sonnet-5, few-shot | 89% | 1,400 ms | ~$3.20 | vendor cloud |
| fine-tuned 3B (QLoRA) | 93% | 240 ms | ~$0.05 | your VPC |
Assumptions behind the cost column: API — ~1,000 input tokens/request (clause + few-shot system prompt) at $3 per 1M input tokens for claude-sonnet-5, output negligible. Local — one L4 GPU at ~$0.80/hr sustaining ~15k requests/hr at this size. Order-of-magnitude, not procurement-grade.
- The accuracy group. The left bar is the same 3B model before training: 61%. Training on 1,350 reviewed rows moved it to 93%, past the flagship's 89%. The 32-point jump is what the dataset bought; the 4-point lead over the flagship is what makes the case.
- The latency group. Median, not mean, so one slow call cannot flatter the result. A small model on your own GPU answers in 240 ms against the flagship's 1,400 ms, because the prompt is one line instead of twelve worked examples.
- The cost group. The flagship re-reads about 1,000 prompt tokens on every call, which is $3.20 per thousand requests. The local model's bill is GPU time: about $0.05 for the same thousand. The base and tuned bars are equal here, which is the point — the fine-tune costs no more to run than the model it replaces.
Now the part that separates a portfolio from a pile of notebooks. The market research line bears repeating: fine-tuning is widely claimed and rarely proven. Anyone can paste a training script into a README. Almost nobody ships the table above — quality and latency and unit cost against a serious API baseline — and almost nobody writes the section that makes reviewers trust everything else:
"When I would NOT fine-tune" — written into the README of this very project: (1) if the knowledge changes weekly — that's RAG's job, and no retrain cadence saves you; (2) with fewer than ~500 reviewed examples — the model memorizes instead of generalizing; (3) while the task definition is still moving — every product pivot invalidates the dataset, prompt iteration is the right tool mid-discovery; (4) if the flagship already hits the quality bar and volume is low — $50/month of API calls doesn't justify owning a training pipeline; (5) if no one owns the eval harness — an unmeasured fine-tune is a liability with a version number. An engineer who writes this list has the judgment the JDs are actually screening for; the training script is just the receipt.
Before the two of them argue, look at what each one actually does. Every line in the chat below points at a row of this picture, and no turn uses a number that is not on it.
- Row 1, what changes. Retrieval edits the prompt; fine-tuning edits the weights. That single difference produces every other row.
- Row 2, updating. A fact that changed is a re-index for retrieval and a retrain for a fine-tune, so freshness is not a preference, it is a property of where the information lives.
- Row 3, the bill and the score. The flagship re-reads about a thousand prompt tokens every call: $3.20 per thousand requests at 1,400 ms. The tuned 3B answers from a one-line prompt: $0.05 at 240 ms, and 93% against the flagship's 89%.
- Row 4, access. Chunks can be filtered per user before the model sees them. Weights cannot: whatever was trained in reaches everyone who can reach the model, which is why confidential text does not belong in a training set.
Tonight's talk: RAG and Fine-Tuning argue over the question, "Who's more important?"
Row 1 of Fig. 11.2g, and I will start with the memo everyone in this module has read. A team fine-tuned a model on its product docs. It answered faster, sounded more confident, and was wrong more often. That is you at your best: a model that memorised the shape of the documents and none of the content. I change the prompt. I hand over the actual page, fetched now, with the section number attached.
retrieval puts the source text into the prompt, so the answer can be traced to a page. Training only makes document-shaped sentences more likely, which is not the same as knowing what they say.
Fetched now, if your retriever found it. Module 08, failure two: the adjuster asked whether she could approve a claim herself, and you returned three copies of the same flood exclusion and dropped the dual-approval rule. Look at my half of row 1. There is no retriever in my path. The behaviour is in the weights on every request, whether or not the top five chunks cooperate.
a fine-tune has no retrieval step to go wrong, because the behaviour is baked into the model. Retrieval adds a component that can fail on its own.
Behaviour, yes. Facts, no — the failure block at the top of this page says so in one line. And look at row 2. A fact changes, I re-index one document, and it takes minutes. You need a retrain, an eval run and a redeploy, which is days, and until then you serve last quarter's policy with a straight face.
row 2 of the picture is the update cost. Where the information lives decides how fast it can be corrected: an index in minutes, weights in days.
And what do you serve when the fact is not in any document? Juris needs a model that knows an auto-renewal clause from a termination clause. There is no page to retrieve for that. It is a reflex, and reflexes are trained. Row 3, my side: 1,350 reviewed examples, and the 3B beats the flagship, 93% against 89%.
some tasks have no document to look up, because the knowledge is a judgment the model has to make. Those are the tasks training is for.
At 240 milliseconds. I will give you that one, it is a good number and it is on the same row. Mine carries a retrieval hop and a longer prompt. But look one row down. Row 4: I filter chunks per user before the model reads a word. A confidential clause you trained on is in the weights for every user who can reach the model, and you cannot take it out.
access control is possible before the model sees the text, and impossible afterwards. Anything in the weights is visible to anyone who can call the model.
Access control is a real point and I will not pretend otherwise. Now yours, still row 3: you cost tokens forever. About a thousand prompt tokens every call, $3.20 per thousand requests, at 40 million tokens a day. I paid once, in a twenty-minute Colab session, and the prompt shrank to one line at $0.05. Finance is attending standups because of your column, not mine.
retrieval re-pays for a long prompt on every single call. A fine-tune pays once, during training, and then runs on a short prompt.
Finance is attending standups because of the flagship API. Put me in front of a fine-tuned 3B inside the VPC and my column is cheap too. Which is the part of this argument neither of us likes to say out loud, and the picture says it in its last line: the best system in this module uses both of us.
the cost in row 3 belongs to the flagship model, not to retrieval itself. Retrieval in front of a small local model is cheap.
I was going to get there. You supply the facts in row 1; I supply the behaviour that uses them well: the format, the dialect, the refusal when the context is thin. The reader's own decision tree sends knowledge to you at gate 1 and only reaches me at gate 4. I have made my peace with that order.
the two are complementary. Retrieval decides what the model reads; the fine-tune decides how it answers.
Peace, from the one who hallucinated worse?
a jab at the product-docs fine-tune in the hook, which sounded more confident and was wrong more often.
Peace, from the one who returned three copies of the same paragraph. We will revisit who is more important when the eval harness grades us both.
neither wins the argument. Both have measured failure modes, and only an eval decides which one hurts your product more.
It already does. Fig. 11.2f grades you on accuracy against a frozen set of 300 clauses. Module 08 grades me on context recall. Different scores, different pagers.
each one is measured by its own metric: task accuracy for a fine-tune, retrieval quality for RAG. They are graded separately because they fail separately.
08 · Preference tuningSFT, DPO, RLHF — What Comes After Imitation
Juris has what it came for: 93% on clause tagging, inside the VPC, at $0.05 per thousand requests. The next request is already on Dana's desk, and it does not fit the same mould — the summaries the assistant writes for client emails are correct and far too long, and nobody can write down the one perfect summary. What the team can do is put two answers side by side and say which is better. That is a different training signal, and this section names the three that exist.
Everything you just did is SFT — supervised fine-tuning: show the model demonstrations, train it to imitate them token by token. SFT is the workhorse and, for a narrow task like clause tagging, the whole story. But imitation has a ceiling: it can only teach what a demonstration can show. "Be less verbose," "prefer the safer refusal," "pick the better of two proofs" are comparative judgments — easy to express as a preference between two outputs, awkward to express as a single golden answer.
DPO (Direct Preference Optimization) trains on exactly that data shape: pairs of responses to the same prompt, one chosen, one rejected.
The loss pushes the model to raise the probability of chosen-style outputs and lower rejected-style ones, relative to a frozen reference copy that keeps it from drifting off into gibberish that games the objective.
It's a plain supervised loss — no reinforcement learning loop — which is why it has become the default second stage. RLHF is the older, heavier route to the same goal: train a separate reward model on human preferences, then run reinforcement learning (PPO) against it.
More moving parts, more failure modes, still used at frontier labs with big alignment teams; DPO gets most of the benefit for a fraction of the plumbing.
The 2026 twist is GRPO, the RL variant behind DeepSeek-R1: when answers are checkable (math, code, your unit tests), the reward can be computed instead of learned, and RL teaches genuine reasoning behavior rather than taste.
- SFT. The stage this module ran: demonstrations in, imitation out. It turns a next-token model into one that follows orders, and it is where Juris's 1,350 clause rows were used.
- DPO. The optional second stage. It consumes pairs rather than answers, and it is the cheap way to teach a preference such as "two sentences, not three hundred words".
- RLHF. The older route to the same place: train a reward model on the same pairs, then optimise against it with reinforcement learning. More parts, more ways to fail, still used where alignment teams are large.
Awareness level is the goal here, and it's deliberate — the curriculum research files "PPO plumbing from scratch" under skip. What you should know: TRL v1.0 ships a DPOTrainer that consumes {"prompt", "chosen", "rejected"} rows exactly the way SFTTrainer consumed your chat rows, plus a GRPOTrainer for the checkable-reward pattern. When an interviewer asks "SFT vs DPO?", the crisp answer is: SFT teaches what to do from demonstrations; DPO teaches what to prefer from comparisons; RLHF is DPO's goal with a learned reward model and an RL loop; you run them in that order, and for most product work you stop after SFT.
build_train_files.py on this page; the summary pair is written here as a plausible Juris example.- The SFT row. System, user, assistant, where the assistant turn is the bare label. Training raises the probability of exactly that answer, which is all a classification task needs.
- The DPO pair. Same prompt, two answers, a human says which is better. "Shorter", "safer", "better-judged" are easy to pick between and hard to write down once, which is why the pair exists.
- The frozen reference. DPO keeps an untouched copy of the model and penalises drifting far from it. Without that anchor, a model can raise the chosen style by wandering into text that is no longer sensible.
Now Fig. 11.3 a second time, with this module's actual files in the boxes and the steps around it that the figure leaves out. If a stage feels abstract, find its row here: every stage is a script you have already read or a command you can run.
| Stage | In the naive version (section 04) | In the production build (sections 06–09) | What flows out |
|---|---|---|---|
| Base model | ollama pull llama3.2:3b, a 4-bit file from the registry | FastLanguageModel.from_pretrained("unsloth/Llama-3.2-3B-Instruct-bnb-4bit", load_in_4bit=True) | A frozen 4-bit model in GPU memory, about 2 GB |
| Demonstrations | Twelve label names pasted into SYSTEM | make_dataset.py drafts, a paralegal reviews; build_train_files.py writes train.jsonl and val.jsonl | About 1,500 chat rows with one fixed system prompt; 300 test clauses frozen first |
| Adapters | None: the weights are untouched | get_peft_model(r=16, lora_alpha=16, target_modules=[...]) in train_qlora.py | About 24M trainable parameters, under 1% of the model |
| SFT | None: the prompt does all the work | SFTTrainer with SFTConfig: 2 epochs, learning rate 2e-4, effective batch 16 | The clausetag-lora folder, 50–100 MB, plus a loss curve to read |
| Instruct model | The stock instruct checkpoint | save_pretrained_merged folds B·A into W; save_pretrained_gguf exports a 4-bit copy | clausetag-merged for vLLM and a GGUF for Ollama |
| DPO | None | Skipped for clause tagging; TRL's DPOTrainer on {"prompt", "chosen", "rejected"} rows when taste matters | An aligned model, only when a single golden answer cannot express the goal |
| Measure | One printed example and a hunch | eval_vs_baseline.py: 300 held-out clauses, one harness for the fine-tune and claude-sonnet-5 | Accuracy, p50 latency, and $ per 1k requests, side by side |
| Serve | Ollama on port 11434 | vllm serve ./clausetag-merged on port 8000, or --enable-lora to hot-swap adapters | An OpenAI-compatible endpoint the Module 06 client hits unchanged |
09 · Serving in productionvLLM: From "It Runs" to "It Serves"
Juris has a model worth deploying: 93% at 240 ms, merged into a plain checkpoint by marker 1 of Fig. 11.2e. What it does not have is a service. Everything so far ran one request at a time on a laptop, and Juris has hundreds of paralegals tagging clauses at once inside the VPC. This last build step turns the file into an endpoint that the Module 06 client can call, without changing a line of application code.
Ollama got you a dev loop. Production is a different animal: many concurrent users, throughput per GPU-dollar, streaming under load.
The naive approach — model.generate() behind FastAPI — collapses at the second concurrent user, because each request hogs the GPU for its full generation while others queue. The production default in August 2026 is vLLM, and its two core ideas are worth one sentence each.
Continuous batching: new requests join the running batch at the next token step instead of waiting for the batch to finish — the GPU never idles between requests.
PagedAttention: each request's KV cache is stored in small non-contiguous pages (yes, exactly like OS virtual memory), so memory doesn't fragment and far more concurrent streams fit.
Net effect, per the benchmarks in this course's research: at 8 concurrent users, vLLM sustains roughly 2.3× Ollama's throughput on the same hardware.
- Continuous batching. A new request joins the batch at the next token step instead of waiting for the current batch to finish, so the GPU never idles between calls. This is most of the 2.3× throughput gap at 8 concurrent users.
- PagedAttention. Each request's attention cache is stored in small non-contiguous pages, exactly like operating-system virtual memory, so memory does not fragment and more streams fit on one card.
- One fused batch. What reaches the GPU is a single batch per token step covering every live request, which is why eight paralegals see 240 ms each rather than one at 240 ms and seven waiting.
Step-by-step: what the vLLM serve commands do, in plain English
- Install vLLM; as of August 2026 it needs Linux and an NVIDIA GPU.
vllm serve ./clausetag-mergedloads the merged 16-bit model from step 2 and starts an OpenAI-compatible HTTP server on port 8000.--served-model-name clausetagis the name clients put in themodelfield. It decouples your API from the folder path on disk.--max-model-len 4096caps prompt plus reply at 4,096 tokens, which bounds how much KV cache one request can claim. Clause tagging needs far less, and a smaller cap means more concurrent requests fit.--gpu-memory-utilization 0.90lets vLLM pre-allocate 90% of the card for weights and KV pages. The rest is left for the CUDA runtime and anything else on the box.- The alternative block serves the untouched base model with
--enable-loraand registers the adapter folder under the nameclausetag. A request naming that model applies the adapter on the fly, and more adapters can share the same base.
# pip install vllm # Linux + NVIDIA (Aug 2026)
vllm serve ./clausetag-merged \
--served-model-name clausetag \
--max-model-len 4096 \
--gpu-memory-utilization 0.90
# OpenAI-compatible on :8000 — Module 06's client works unchanged:
# OpenAI(base_url="http://localhost:8000/v1", api_key="none")
# client.chat.completions.create(model="clausetag", ...)
# Alternative: share one base model, hot-swap LoRA adapters per task or customer
vllm serve unsloth/Llama-3.2-3B-Instruct \
--enable-lora --max-lora-rank 16 \
--lora-modules clausetag=./clausetag-lora
# then request model="clausetag" — the adapter is applied on the fly
- The top row is a development loop. Ollama answers one request at a time from a 2 GB 4-bit file, at 380 ms each. That is perfect for trying a prompt and useless for hundreds of paralegals, because the second caller waits for the first.
- The bottom row is a service. vLLM lets new requests join the running batch at the next token step and stores each request's KV cache in small pages, so eight streams share one GPU and the median falls to 240 ms.
- The application code does not change. Both expose the OpenAI-compatible surface, so Module 06's client moves between them by changing one environment variable — which is why the eval harness could grade the fine-tune without knowing where it ran.
Worth one line each: SGLang is vLLM's main rival, and it wins specifically on shared-prefix workloads — thousands of requests reusing the same giant system prompt (its RadixAttention caches the shared prefix's KV once). If your traffic is one big prompt with a small varying tail, benchmark it. And note the pattern you've now seen three times: Ollama, vLLM, and SGLang all speak the same OpenAI-compatible dialect, so your application code is a base_url away from any of them — vendor-agnostic by construction.
Hugging Face TGI (Text Generation Inference) has been in maintenance mode since December 2025 — fine in existing deployments, wrong choice for new ones; tutorials recommending it are dated. LM Studio is a desktop app for personal use — lovely for exploring models, not a production server; it appearing in an architecture diagram is an interview red flag. New serving builds: vLLM by default, SGLang for shared-prefix-heavy traffic.
There are no dumb questions
- Why not just put 50 examples in the system prompt instead of fine-tuning?
- You can, and you should try it first — that's the plateau gate, marker 3 in Fig. 11.1. But you pay for those examples in tokens and latency on every single call, forever, and past a few dozen examples the quality gains flatten while the bill doesn't. Fine-tuning amortizes the examples into the weights once; the per-call prompt shrinks to one line. At 40M tokens/day, "prompt rent" vs "weight ownership" is a real budget line.
- So fine-tuning can never add knowledge?
- It can — models do memorize training data — but unreliably, without citations, and frozen at training time. What it adds well is the dialect and structure of a domain: after tuning on legal text, the model uses legal vocabulary correctly. Treat any specific retrievable fact as RAG's job, and the best systems do both: RAG supplies the facts, a fine-tune supplies the behavior that uses them well.
- Should I fine-tune the biggest open model I can afford?
- Usually the opposite. The economic sweet spot is the smallest model that reaches your quality bar after tuning — that's what maximizes the latency and cost win, which was the reason you're here. Start at 3–8B; escalate only when the eval says the small model's ceiling is genuinely below your bar.
- What about the hosted fine-tuning the API vendors offer?
- OpenAI, Google, and others offer hosted fine-tuning for some models; it removes the GPU-ops burden and is a reasonable middle path for pure specialization. But you don't get the weights, per-token pricing continues, and Dana's residency clause still fails — the documents still leave the VPC. It solves force #3 (specialization) while leaving #1 and #2 (cost, privacy) on the table. Know it exists; know what it doesn't solve.
- Is distilling from a flagship model even allowed?
- Read the provider's terms, not a forum thread. Most providers restrict using outputs to build competing general-purpose models; using drafts (with human review) to automate your own narrow internal task is the widely-accepted intended territory. For a legal-tech company especially: this is a question for counsel, and "we reviewed the ToS" belongs in the project doc.
The build-vs-rent math, with every assumption visible. Juris pushes 40M tokens/day — say 34M in, 6M out. On claude-sonnet-5 ($3/$15 per 1M in/out, Aug 2026): 34×$3 + 6×$15 ≈ $192/day ≈ $70K/year, scaling linearly with growth forever.
Self-hosting the fine-tuned model: this volume fits one L4-class GPU with headroom (~$0.80/hr ≈ $7K/year) — but the honest line item is people: call it 0.25 of an engineer for serving, monitoring, and retrains, ~$35–40K loaded.
So at today's volume it's roughly $70K rent vs ~$45K own — real but not dramatic.
The pitch has three legs, and cost is the weakest: (1) at 2× volume the API bill doubles while the GPU just gets busier — owning is a step function, renting is a straight line; (2) the fine-tuned model is better and 5× faster at the one task we sell — 93% vs 89%, 240ms vs 1.4s; (3) the residency clause: weights and documents never leave our VPC, which converts our biggest client's compliance requirement from a blocker into a signed renewal.
Elevator version: "For the cost of a quarter of an engineer we make our core feature better, faster, and compliant with the client contract that was about to break it — and our unit costs stop scaling with our success."
- The straight line through the origin. API pricing is per token, so the bill is proportional to traffic for ever. Double the traffic and this line doubles: $70K at 40M tokens a day, $140K at 80M.
- The nearly flat line. Most of the cost of owning is a person, about $38K of loaded engineer time, which does not change when traffic grows. The GPU part grows, but slowly: $7K a year at today's volume.
- The crossing, and why cost is the weakest leg. Below about 24M tokens a day, renting wins outright. Juris is above it, but only by $25K a year — which is why the case is really made by the 4 accuracy points, the 5.8× speed-up and the residency clause.
10 · The labBuild the Real Thing
Dana's three problems are answered on paper: 93% at 240 ms and $0.05 per thousand requests, inside the VPC, from a 50 MB adapter. Your own version has to answer them for a task of your choosing, and the artifact that matters is not the training script. It is the measured case — the table in Fig. 11.2f with your numbers in it, and the paragraph saying when you would not do this at all.
Mission: fine-tune a small open model (≤4B) for one narrow behavior — a classification dialect like clause tagging, a structured-extraction style, or a house-style rewriter — and ship the portfolio artifact the market research says almost nobody ships: the measured cost-benefit case against a flagship API baseline. Training needs a GPU (free Colab T4 suffices); the dataset, eval, and writeup work runs anywhere.
- Decision memo first: which branch of Fig. 11.1 does your task exit at, and why is it the fine-tune branch? (If it honestly isn't — pick a different task. That judgment is the lab.)
- 500+ reviewed examples in chat format (distill-then-review or hand-label), deduplicated, every label ≥30 examples; a ≥200-example test set frozen before training
- QLoRA run at r=16 via Unsloth; training + validation loss curves in the README, with one sentence reading them
- Eval table vs two baselines (untuned base model, flagship API few-shot): task metric, p50 latency, $/1k requests, with all cost assumptions stated
- README section "When I would NOT fine-tune this" — 3+ honest bullets in your own words
- README documents 3 failure modes found in error analysis (Module 07 style) and what you changed — data fixes count double
Stretch goal: merge and serve with vLLM, load-test with 8 concurrent users (e.g. hey or Locust), and report tokens/sec and p95 latency vs Ollama on the same box — you should reproduce the ~2× continuous-batching gap yourself.
11 · Interview radarHow This Shows Up in Interviews
"When would you fine-tune vs use RAG?"
The real test The classic, asked at every level — the grade is on routing each need to the right technique, not on praising either one.
Strong answer Route by what you're trying to change:
- Knowledge goes to RAG — it stays fresh, citable, and updateable without touching the model
- Behavior, style, and narrow-task skill go to fine-tuning — that's what training into the weights is actually good at
- Format goes to structured outputs — no training required
And before any of it, prompting must hit a measured plateau — gate 3 in Fig. 11.1: until you've shown the prompt's ceiling, you haven't earned the fine-tune.
Land it Bonus points for "they compose — RAG for facts, a fine-tune for how to use them," and for a war story about someone who fine-tuned knowledge in and amplified hallucinations instead.
"Explain LoRA to a PM."
The real test Whether you understand it or memorized it — an analogy in your own words only survives if you do.
Strong answer One version that works: "The model is a mixing desk with 7 billion knobs, already well set. We don't re-tune every knob — we add sixteen master sliders wired across them and learn just the slider positions. That gets us the same behavior change with 0.5% of the moving parts."
Land it The payoff line: the sliders fit in a 100 MB file, so one base model can swap in a different slider file per task.
"Your fine-tuned model got worse at general tasks. What happened?"
The real test A failure-mode probe — the point goes to naming the pathology precisely and prescribing fixes for it.
Strong answer Name it: catastrophic forgetting. The update dragged shared representations toward one task, usually driven by over-narrow data, too many epochs, or a too-high learning rate. Then prescribe:
- Fewer epochs and a lower rank, so the update pulls less hard
- Mix 5–10% general instruction data back in, so training rehearses what the model must not forget
- Target fewer modules, confining the adapters to a smaller slice of the network
Land it The real lesson: your eval suite must include a general-capability slice, not just the task metric — otherwise you ship the regression blind.
"Estimate the GPU memory for a 7B QLoRA run."
The real test The interviewer wants the arithmetic narrated component by component, not a memorized total.
Strong answer Walk it out loud, adding as you go:
- Base weights in 4-bit — about 3.5 GB
- LoRA adapters — roughly 42M parameters in fp16, about 0.08 GB
- Adapter gradients — another 0.08 GB
- Adam moments in fp32 — about 0.34 GB
- Activations with gradient checkpointing — 2–4 GB depending on batch size × sequence length
That totals ~8–10 GB, which fits a 16 GB T4 — the free Colab GPU.
Land it Contrast with full fine-tuning — roughly 84 GB+ for the same model — to show you know why QLoRA exists.
"Serve a fine-tuned model to 100 concurrent users."
The real test A system-design prompt with vendor-agnostic judgment on display — every piece needs a reason, not a brand.
Strong answer Serve merged weights with vLLM, then justify each choice:
- vLLM because continuous batching and PagedAttention are what make 100 concurrent streams affordable
- An OpenAI-compatible endpoint so application code stays portable across serving stacks
- Quantization to fit headroom, with KV-cache memory budgeted per concurrent stream
- Autoscaling on queue depth, against p95 latency and tokens/sec SLOs
- An eval-gated deploy for every retrain, so a new adapter can't silently regress quality
Land it Mention when you would not self-host: low volume, no ops ownership, and no residency constraint mean renting wins.
Quick reference — Open models and fine-tuning
- Decide before you tune
- Missing knowledge → RAG. Wrong format → structured outputs. Wrong behaviour or style → fine-tuning. Most requests are one of the first two.
- The four real reasons
- Cost at scale · privacy and data residency · specialisation on a narrow task · latency control.
- The cost shape
- Fine-tuning has a high upfront cost and a low marginal cost. An API has none of the first and all of the second. The crossover is a volume calculation, not an opinion: at Juris's prices the two lines meet near 24M tokens a day.
- LoRA / QLoRA
- Train a small number of added weights instead of all of them. Rank ~16 is the usual starting point, and it runs on one GPU.
- Rank, counted
- The number of independent patterns an update can hold. LoRA stores r × (rows + columns) numbers per matrix: 24.3 million, 0.757%, for the 3B at r = 16.
- Loss and the loss mask
- Loss is the average of −ln p over the scored tokens, so e−loss is the typical probability on the right token. The mask decides which tokens are scored.
train_qlora.pymasks everything before the assistant header; forget that and a plain text column scores every token. - Reading two loss curves
- Validation falls, then flattens: stop. Validation rises while training falls: memorising, so keep the lowest checkpoint and check the labels.
- What it will not fix
- Staleness, missing citations, and hallucination — fine-tuning on facts tends to make the model more confidently wrong, not more correct.
- Serving
- Ollama for development, vLLM for production. Not HF TGI — in maintenance since Dec 2025.
- The stack rule
- Unsloth + QLoRA + a 3B model on one GPU; move to Axolotl at more than one GPU, and to vLLM once you serve more than about one request a second.
- Open-weight options (Aug 2026)
- Llama 3.x · Qwen 3 · Gemma 3 · Mistral Small / Magistral · DeepSeek-R1.
12 · RecapWhat You Can Do Now
- You can walk a stakeholder through the fine-tune / RAG / prompt decision tree and defend the exit — including refusing to fine-tune for knowledge
- You can run open models locally with Ollama and estimate memory for any model from params × bytes, quantization included
- You can explain LoRA and QLoRA from the matrix picture up — and compute the trainable-parameter count for a given rank
- You can engineer a fine-tuning dataset: distill-then-review, one consistent chat format, balanced labels, a frozen test set
- You can run a complete QLoRA recipe with Unsloth on a free GPU, read the loss curves, and merge/export the result
- You can trace one training row through the chat template and the loss mask, turn a loss back into a probability, and tell overfitting from too little data on a pair of loss curves
- You can prove a fine-tune's worth with the three-column case — quality, latency, $/1k — against a flagship baseline, and say when you wouldn't
- You can place SFT, DPO, and RLHF in one pipeline and say which data shape each consumes
- You can choose and defend a serving stack — vLLM by default, SGLang for shared prefixes — and explain continuous batching and PagedAttention in one sentence each
From this module: close the page and sketch Fig. 11.1 from memory — all four questions, all five exits. Then write the three forces that justify open weights and match each to Dana's three problems.
Reaching back to Module 04: transfer learning froze a vision backbone and trained a new head; LoRA freezes the backbone and trains thin adapters inside every layer.
Write two sentences: what assumption about pretrained features do both techniques share, and why does the LLM version inject adapters throughout instead of replacing the final layer?