▚ The AI Engineer's Field Manual
Module 11 · Act III — The GenAI Core

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."

~8 hours Builds on: Modules 04 · 06 · 07 Tools: Ollama · Unsloth · TRL · vLLM Job-spec line it unlocks: "Fine-tune open-source LLMs using LoRA, RLHF, DPO, and model distillation techniques"

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.

Field report · Client memo

"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 Okafor, VP Engineering at "Juris"

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.

1 COST AT SCALE $70K / year rent the API 40M tokens/day $45K / year own the weights 1 GPU + a quarter of an engineer double the traffic and the left bar doubles; the right one barely moves 2 RESIDENCY Juris VPC client documents the weights can live here too not allowed vendor cloud API any price, any vendor the engagement letter forbids client documents leaving this box 3 SPECIALIZATION 89% flagship API 1,400 ms 93% tuned 3B 240 ms clause tagging, 300 held-out clauses
Fig. 11.0b — Dana's three problems as three measurements: $70K a year of rent against $45K of ownership, documents that may not cross the VPC line, and 4 accuracy points plus a 5.8× speed-up on the one task Juris sells. Every number here is produced later in this module; the cost pair comes from the boardroom section, the accuracy and latency pair from the eval table in section 07.
  1. 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.
  2. 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.
  3. 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.
Failure mode — the warning story first

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.

You already know this

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."

1 2 3 4 5 Does the task need facts the model lacks? (private, current, or long-tail knowledge) yes RAG — retrieval Module 08 no Do you need a guaranteed output shape? (JSON schema, enum labels, function args) yes Structured outputs Module 06 no Has prompting + few-shot plateaued — measured by your eval suite (Module 07)? not yet Keep iterating prompts — the cheapest lever there is yes, measured Need behavior, style, or domain dialect? Latency or unit cost hurting at scale? Weights required inside your VPC? none of these Re-examine the problem — fine-tuning fixes none of it at least one yes Fine-tune this module
Fig. 11.1 — The fine-tuning decision tree: knowledge exits to RAG at marker 1, format exits to structured outputs at marker 2, and you only reach the accent box at marker 5 with a measured prompting plateau plus a behavior, cost, or residency force.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Interview-ready: prompting vs RAG vs fine-tuning (memorize the rows, not the words)
Prompting + few-shotRAGFine-tuning
What it changesInstructions in contextFacts in contextThe weights themselves
Best forTask definition, tone, quick iterationCurrent/private knowledge, citationsBehavior, style, domain dialect, narrow-task skill
Upfront costHoursDays (index + retrieval + evals)Weeks (data curation dominates, not GPU time)
Marginal costHighest — every call re-pays for the long promptMedium — retrieval + bigger context per callLowest — behavior is amortized into weights
LatencyGrows with prompt length+ retrieval hop, + longer prefillShortest prompts; small model = fast tokens
MaintenanceEdit a string, redeployRe-index documents; knowledge stays freshRe-train + re-eval + re-deploy per change
Fails whenModel lacks the skill entirelyTask needs new behavior, not factsYou 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.

BE the decision framework

Your turn to play Fig. 11.1. Four teams from earlier modules bring you a request. For each one, walk the tree top to bottom with a pencil. Write the exit you reach: prompting (which includes structured outputs), RAG, or fine-tuning. Add one reason in your own words. One of the four is a trap: it uses the vocabulary of one exit while the facts point to another.

  1. TrustBank. A lending assistant must answer staff questions about the 400-page lending policy. The policy is revised every quarter, and every answer must name the section it came from.
  2. ShopStream. A product tagger must return JSON with exactly four fields. One time in twenty the model adds a fifth field, and the downstream parser crashes.
  3. ChipGuard. Twenty million defect reports a month each need one of nine defect codes. The flagship model with a thirty-example prompt scores 88% on a 500-report test set. Six measured prompt revisions have not moved it in the last three. The API bill is five figures a month, and reports may not leave the plant network.
  4. SaaSify. The support assistant writes 300-word answers; customers want two sentences. The product manager says "that is behavior, so fine-tune it". Nobody has changed the system prompt yet. One engineer added the word "concise" once, without measuring.

Write your four exits and four reasons before opening the answer. Then mark which one you think is the trap.

Check your answer
TrustBankRAG. The first question in the tree is "does the task need facts the model lacks?", and it does: a private policy that changes quarterly. A retriever re-indexes in minutes and can return the section number. A fine-tune would need a retrain every quarter and could cite nothing.
ShopStreamPrompting, through structured outputs (Module 06). The second question is "do you need a guaranteed output shape?", and this is exactly that. Declare the four-field schema on the API call and the fifth field cannot be generated. No training run can promise that; a schema can.
ChipGuardFine-tuning, and it is the only one of the four that reaches the accent box. No missing facts and no shape problem. The plateau was measured on a real test set. Then all three forces at once: a narrow behavior, unit cost at twenty million calls, and a residency rule. This is Dana's situation with the names changed.
SaaSifyPrompting. This is the trap. Answer length is behavior, so the table's right-hand column seems to apply. But the tree asks "has prompting plateaued, measured?" before it ever asks about behavior, and here nobody has measured anything. A length instruction, a max_tokens cap and two short examples usually fix this in an hour. Fine-tune only if an eval shows that ceiling.

The lesson in the gap: the comparison table tells you what each tool is good at. The tree tells you the order in which to try them. "It is behavior" is a true sentence about SaaSify and still the wrong exit, because the cheapest lever has not been pulled. Most fine-tuning requests you will meet in a career are SaaSify wearing ChipGuard's vocabulary.

Here are the four of them drawn on the tree, so you can check your pencil against the picture rather than against a paragraph.

1 Facts the model lacks? private, current or long-tail yes no 2 Guaranteed output shape? JSON schema, enum labels yes no 3 Prompting plateaued, measured? on your own eval set not yet yes, measured 4 Behaviour? Unit cost? Residency? at least one, at real volume at least one yes Fine-tune the only exit into this module TrustBank → RAG 400-page lending policy, revised every quarter; each answer must cite its section. Re-index in minutes beats retrain in weeks, and only retrieval can cite. ShopStream → structured outputs Four JSON fields; a fifth appears 1 time in 20 and the parser crashes. A schema makes the fifth field impossible; training only makes it rarer. SaaSify → prompting — THE TRAP 300-word answers; customers want two sentences. "That is behaviour, so fine-tune it" — but nobody has changed the system prompt or measured anything, so gate 3 stops it first. ChipGuard → fine-tune 20M defect reports a month, nine codes, 88% after six measured prompt revisions. Five figures a month, and reports may not leave the plant network: all three forces.
Fig. 11.1b — The four teams placed on the tree they exit at: three of the four never reach the fine-tune box, and SaaSify is the trap, stopped by the measured-plateau gate even though its problem really is behaviour.
  1. Gate 1 takes TrustBank. A 400-page policy that changes every quarter is facts the model lacks, and every answer has to name its section. Retrieval re-indexes in minutes and returns the section number. A fine-tune would need a retrain each quarter and could cite nothing.
  2. Gate 2 takes ShopStream. The complaint is a fifth JSON field appearing one time in twenty. That is a shape problem, and a declared schema makes the wrong shape impossible rather than merely unlikely. No training run can make that promise.
  3. Gate 3 takes SaaSify, and that is the trap. Answer length really is behaviour, so the comparison table points at the fine-tuning column. The tree asks a cheaper question first: has prompting been measured to its ceiling? One engineer adding the word "concise" is not a measurement, so the request goes back to the prompt.
  4. Only ChipGuard passes all four. No missing facts, no shape problem, a plateau measured over six revisions on a 500-report test set, and then all three forces at once: a narrow behaviour, twenty million calls a month, and a network the reports may not leave. It is Dana's situation with the names changed.

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.

🧠 Brain power

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:

Open-weight model families, August 2026 — names rotate quarterly, the columns to check don't
FamilySizesLicenseKnown 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 + MoEApache 2.0Strongest small models per GB; multilingual; the permissive-license workhorse
Gemma 3 (Google)1B–27BGemma Terms of UseExcellent quality at laptop-friendly sizes; 128k context
Mistral Small / Magistral~24BApache 2.0 (Small line)Efficient dense models, strong function calling; the European-sovereignty pick
DeepSeek-R1 + distills671B MoE; distills 1.5B–70BMITOpen reasoning — visible chains of thought, GRPO-trained; distills bring reasoning to small models
MORE OF IT IS YOURS LESS OF IT IS YOURS fully open weights + data + code rare, mostly research open-weight, permissive Apache 2.0 · MIT Qwen 3 (0.6B–235B) Mistral Small ~24B · DeepSeek-R1 open-weight, conditional vendor licence with terms Llama 3.x (free under 700M MAU) Gemma 3 (Gemma Terms) API only no weights at all claude-sonnet-5 $3 / $15 per 1M tokens 1 download, fine-tune, serve inside the Juris VPC — the residency clause is satisfied here 2 call it, and that is all 3 Juris trains Llama-3.2-3B here
Fig. 11.1c — The open-model spectrum with real families on it: everything left of the API-only stop can be downloaded and run inside your own network, which is the property Dana's engagement letter actually requires.
  1. 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.
  2. 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.
  3. 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
  1. 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.
  2. ollama pull llama3.2:3b downloads 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.
  3. ollama run llama3.2:3b opens a chat prompt in your terminal against that model. Nothing leaves your machine.
  4. The curl call 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": false asks for the whole reply at once instead of token by token.
  5. There is no API key and no per-token bill anywhere in this block. That absence is the point of the section.
terminal — Ollama quickstartruns offline
# 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.

Sharpen your pencil

Below are ten lines lifted from local_baseline.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Some of these you met in Module 06; the interesting ones are the lines that changed.

base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),point the OpenAI client at the local Ollama server instead of OpenAI, unless an environment variable says otherwise
api_key=os.environ.get("LLM_API_KEY", "ollama"),
LABELS = ["indemnification", "limitation_of_liability", ...]
SYSTEM = ("You tag contract clauses. Reply with exactly one label from this list, nothing else: " + ", ".join(LABELS))the instruction the model sees on every call: the task, and the twelve allowed answers pasted in as a comma-separated string
def tag(clause: str) -> str:
resp = client.chat.completions.create(
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),
{"role": "system", "content": SYSTEM}, {"role": "user", "content": clause},
max_tokens=8,stop the model after eight tokens: a label is a few tokens long, and anything longer is the model rambling
return resp.choices[0].message.content.strip()
Check your answers
base_url=os.environ.get("LLM_BASE_URL", "http://localhost:11434/v1"),point the OpenAI client at the local Ollama server instead of OpenAI, unless an environment variable says otherwise
api_key=os.environ.get("LLM_API_KEY", "ollama"),the OpenAI library refuses to start without some key string, so hand it a placeholder; Ollama never reads it. The same variable holds a real key later, when you point at a paid service
LABELS = ["indemnification", "limitation_of_liability", ...]the twelve clause types Juris sells, as a Python list, so the same names can be pasted into the prompt and compared against later
SYSTEM = ("You tag contract clauses. Reply with exactly one label from this list, nothing else: " + ", ".join(LABELS))the instruction the model sees on every call: the task, and the twelve allowed answers pasted in as a comma-separated string
def tag(clause: str) -> str:declare a function that takes one clause as a string and returns one label as a string. The type hints are documentation, not enforcement
resp = client.chat.completions.create(make one chat request through the OpenAI-compatible surface. Ollama, vLLM and nearly every open-model server speak this shape, which is why the client did not change
model=os.environ.get("LLM_MODEL", "llama3.2:3b"),name the model to run, defaulting to the 3B Llama you just pulled. The same variable later switches to the fine-tuned model without touching code
{"role": "system", "content": SYSTEM}, {"role": "user", "content": clause},the two-message conversation the model sees: the fixed instruction as the system turn, the clause as the user turn
max_tokens=8,stop the model after eight tokens: a label is a few tokens long, and anything longer is the model rambling
return resp.choices[0].message.content.strip()dig the reply text out of the response object (first choice, its message, its content) and trim stray whitespace so the label compares cleanly

If you got the Module 06 lines, good: that was retrieval practice. The three lines that matter for this module are base_url, api_key and model, and all three read from the environment. That is what lets the eval harness in section 07 reuse this exact code. It points at Ollama, at vLLM, or at the fine-tuned model with no edits.

Step-by-step: what local_baseline.py does, in plain English
  1. Bring in os to read environment variables and OpenAI, the same client class from Module 06.
  2. Build the client with two overrides. base_url points at Ollama's OpenAI-compatible endpoint on port 11434. api_key is a placeholder, because the library insists on one and Ollama ignores it.
  3. Define LABELS, the twelve clause types, and SYSTEM, an instruction that names the task and pastes the twelve labels in. The model may answer with one of them and nothing else.
  4. Define tag(clause): send one chat request with the system instruction and the clause as the user turn. max_tokens=8 cuts the reply off after a few tokens, since a label needs no more.
  5. Take the first choice's message text out of the response and strip whitespace, so "auto_renewal\n" compares equal to "auto_renewal".
  6. 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.
local_baseline.pyruns offline
# 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."

1 ONE WEIGHT, TWO PRECISIONS 16 bits (2 bytes): 65,536 possible values stores 0.4213 exactly as written 4 bits (0.5 bytes): 16 levels, 0.125 apart 0.4213 snaps to 0.375 error 0.0463 across 3 billion weights the errors mostly cancel: int8 costs about nothing, int4 shows on hard reasoning and is fine on one narrow task such as clause tagging 2 THE SAME 3B MODEL ON DISK fp16 3B × 2 bytes = 6 GB int8 3 GB int4 1.5 GB + 0.5 GB metadata and buffers 3 WHAT THAT BUYS 6 GB ÷ 1.5 GB = 4× less memory, and the download is the 2.0 GB that ollama pull llama3.2:3b reports. That is the difference between "needs a data-centre card" and "runs on the laptop you are reading this on".
Fig. 11.1d — Quantization drawn twice: one weight losing 0.0463 when it snaps to the nearer of sixteen 4-bit levels, and the whole 3B model shrinking from 6 GB to the 2.0 GB Ollama downloads. The sixteen levels are spaced 0.125 apart to keep the arithmetic small; real 4-bit schemes rescale the levels per block of weights.
  1. 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.
  2. 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.
  3. 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.

Memory needed to hold the weights, by model size and precision.
Modelfp16int4
3B3B × 2 = 6 GB3B × 0.5 = 1.5 GB — plus ~0.5 GB of metadata and buffers, hence the 2 GB download.
8B16 GB~4.5 GB
70B140 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.

Failure mode ×2 — mediocre baseline, impossible full fine-tune

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.

GPU memory needed before a single activation is stored — 18 pixels per gigabyte 1 FULL FINE-TUNE 6 GB 6 GB Adam's two moments, fp32 — 24 GB weights gradients = 36 GB 16 GB — a free Colab T4 stops here 2 QLoRA frozen 4-bit base 1.5 GB · adapters and their gradients 0.1 GB · moments 0.2 GB · activations with checkpointing about 3 GB under 8 GB — it fits, with room to spare 3 THE WALL BETWEEN THEM freeze the weights and 34 of those 36 gigabytes stop existing
Fig. 11.1e — Why LoRA exists, drawn to scale: full fine-tuning of the same 3B model needs 36 GB before any activations, three times past the 16 GB a free Colab T4 has, while QLoRA's frozen 4-bit base and thin adapters stay under 8 GB.
  1. 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.
  2. 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.
  3. 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.

1 2 3 4 one matrix is 131,072 ÷ 16,777,216 = 0.7813% trainable. Seven matrices in each of 28 layers of the 3B model: about 24.3M trainable = 0.76% of 3.21 billion. W 4096 × 4096 frozen 16.8M params — no gradients + B 4096 × 16 × A 16 × 4096 ΔW = B·A rank-16 bottleneck 131,072 trainable vs 16,777,216 frozen = 0.7813% of the matrix forward pass: h = W·x + B·(A·x) — W never changes; gradients flow only through A and B
Fig. 11.2 — LoRA replaces the full-size update with a rank-16 product: per matrix, 131,072 trainable parameters stand in for 16,777,216 frozen ones, and across the whole 3B model about 24.3 million parameters, 0.76%, are the only ones that move.
  1. 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.
  2. 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.
  3. 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.
  4. 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.

Sharpen your pencil

Count the LoRA parameters once by hand and Fig. 11.2 stops being a picture and becomes arithmetic you own. Take one attention matrix from a Llama-style layer: d = 4096 rows and 4096 columns, and the rank the page uses, r = 16. Matrix B is d × r; matrix A is r × d. Fill in the blanks.

Parameters in B = d × r = 4096 × 1665,536
Parameters in A = r × d = 16 × 4096
Trainable per matrix = B + A
Parameters in the full matrix W = d × d = 4096 × 409616,777,216
Trainable ÷ full, as a percentage
Same again for k_proj, which is 4096 × 1024: trainable, full, percentage
Double the rank to r = 32 on the 4096 × 4096 matrix: trainable, percentage
Adapter file size for one 4096 × 4096 matrix at 2 bytes per parameter131,072 × 2 = 262,144 bytes, about 256 KB

Work to four decimal places on the percentages. Then answer: which changes the count faster, doubling the rank or doubling the matrix width?

Check your answers
Parameters in A16 × 4096 = 65,536, the same as B, because the matrix is square
Trainable per matrix65,536 + 65,536 = 131,072, the number printed in Fig. 11.2
Trainable ÷ full131,072 ÷ 16,777,216 = 0.0078 = 0.7813%. Every gradient and every optimizer moment lives in that 0.78%.
k_proj, 4096 × 1024trainable 16 × (4096 + 1024) = 81,920; full 4096 × 1024 = 4,194,304; 81,920 ÷ 4,194,304 = 0.0195 = 1.9531%. Thinner matrices give a larger fraction, because r × (d + k) shrinks more slowly than d × k.
r = 3232 × (4096 + 4096) = 262,144, exactly double, so 1.5625%. The count is linear in r.

What the numbers mean. Doubling the rank doubles the adapter, every time. Doubling the width of a square matrix quadruples the frozen part but only doubles the adapter, so the fraction halves. That is why LoRA gets relatively cheaper as models grow. It is also why raising r is a poor place to look for your next point of accuracy. It costs linearly and, past about 16, buys almost nothing.

To get from one matrix to the whole model, repeat the sum for each of the seven target matrices in train_qlora.py. Then multiply by the layer count. The 3B model the page trains has hidden width 3072, 28 layers, MLP width 8192, and key and value width 1024. That sum comes to about 24.3 million trainable parameters, roughly 0.76% of 3.21 billion. The optional note below does the same sum for a 7B.

1 THE DIAL — ONE 4096 × 4096 MATRIX r r = 8 r = 16 what this module uses r = 32 8 × (4096 + 4096) 65,536 trainable 0.3906% adapter 128 KB 16 × (4096 + 4096) 131,072 trainable 0.7813% adapter 256 KB 32 × (4096 + 4096) 262,144 trainable 1.5625% adapter 512 KB every doubling of r doubles all three numbers — the cost is a straight line in r 2 WHAT THE EXTRA RANK BUYS rank r → task quality r = 16 nearly flat from here: more rank, almost no gain the next accuracy point lives in the data, not in r
Fig. 11.2b — The rank dial: turning r from 8 to 16 to 32 doubles the trainable count, the percentage and the adapter file every time, while the quality it buys flattens after about 16. The three counts are exact arithmetic on a 4096 × 4096 matrix; the quality curve is the shape reported by the LoRA and QLoRA papers, drawn without numbers because this page measures none.
  1. 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%.
  2. 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.
  3. 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.

🧠 Brain power

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.

The tiny layer every answer below uses. W stands in for one 4096 × 4096 attention matrix, and the rank is 1 instead of 16. The values are easy numbers; the arithmetic is the real adapter's.
PartShapeValuesIts job
W, frozen4 × 4row 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 input4 numbers(1.0, 0.5, −1.0, 2.0)One token of a clause, as this layer receives it.
A, trainable1 × 4(0.5, −0.5, 0.25, 0.5)Starts random.
B, trainable4 × 1(0, 0, 0, 0) at the start; (0.15, −0.10, 0.05, 0.20) after one training stepStarts at zero, so the adapter begins by adding nothing.
The wanted change4 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.

  1. 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).
  2. Row 2. −0.10 × A = (−0.05, 0.05, −0.025, −0.05).
  3. Row 3. 0.05 × A = (0.025, −0.025, 0.0125, 0.025).
  4. Row 4. 0.20 × A = (0.10, −0.10, 0.05, 0.10).
  5. 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.

A full-size update and a LoRA update, side by side. Counts from rerunning lora_tiny_layer.py.
Full update ΔW (delta W)LoRA update B·A
Numbers stored, tiny layer4 × 4 = 161 × (4 + 4) = 8
Independent patterns it can hold, tiny layerup to 41
Numbers stored, one 4096 × 4096 matrix16,777,21616 × (4096 + 4096) = 131,072
Independent patterns it can holdup to 4,09616
1 B · A BY HAND: A COLUMN TIMES A ROW A (1 × 4) 0.5 −0.5 0.25 0.5 +0.15 −0.10 +0.05 +0.20 B (4 × 1) 0.075 −0.075 0.0375 0.075 −0.05 0.05 −0.025 −0.05 0.025 −0.025 0.0125 0.025 0.10 −0.10 0.05 0.10 = +0.15 × A = −0.10 × A = +0.05 × A = +0.20 × A 16 cells from 8 stored numbers. Every row is A times one number: one pattern, so the rank is 1. 2 THE SAME COUNT AT FULL SIZE the tiny layer, rank 1 full update: 4 × 4 = 16 numbers LoRA: 1 × (4 + 4) = 8 numbers, 50% one 4096 × 4096 matrix, rank 16 full update: 16,777,216 numbers LoRA: 16 × (4096 + 4096) = 131,072 = 0.7813% of the full update the smaller r is next to the width, the bigger the saving 3 WHAT RANK 1 CANNOT HOLD: TWO MADE-UP UPDATES AND THEIR BEST RANK-1 FIT mostly one pattern (strengths 1.0 and 0.2) keeps 96.2% two equal patterns (1.0 and 1.0) keeps 50.0%
Fig. 11.2h — Rank on a layer small enough to multiply. Top left: B after one training step times A fills a 4 × 4 grid in which every row is A scaled by one number. Top right: the same count on the tiny layer and on one 4096 × 4096 matrix. Bottom: how much of two made-up updates the best rank-1 update can keep. Values from rerunning lora_tiny_layer.py.
  1. 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.
  2. 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.
  3. 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

  1. 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.
  2. 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

  1. 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.
  2. 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).
  3. 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.

  1. Slope for B. Each gap times A·x, which is 1.0: (−0.30, 0.20, −0.10, −0.40).
  2. 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.
  3. 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).
  4. 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

  1. 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).
  2. 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.
  3. Check all four. The script's largest difference between the two ways is 5.6 × 10⁻¹⁷: rounding dust, not a real gap.
1 ONE TOKEN, TWO PATHS, ADDED x (1.0, 0.5, −1.0, 2.0) W, frozen 16 multiplies W·x = (−0.435, 0.955, −0.32, 0.32) A, 1 × 4 4 multiplies A·x = 1.0 the bottleneck B, 4 × 1 4 multiplies B·(A·x) + h layer output THE SAME TOKEN AT THREE MOMENTS moment B side path B·(A·x) h = W·x + B·(A·x) 2 step 0 (0, 0, 0, 0) (0, 0, 0, 0) (−0.435, 0.955, −0.32, 0.32) 3 after one step (0.15, −0.10, 0.05, 0.20) (0.15, −0.10, 0.05, 0.20) (−0.285, 0.855, −0.27, 0.52) 4 merged folded into W none: one multiply (−0.285, 0.855, −0.27, 0.52) Step 1 moved B only, because A's slope is zero while B is zero. The loss fell from 0.15 to 0.0375.
Fig. 11.2i — One token through a LoRA layer. Top: the frozen path and the side path, which squeezes four numbers into one and widens them again before the two are added. Bottom: the same token before training, after one step, and after merging. Values from rerunning lora_tiny_layer.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
Serving the trained adapter two ways. Multiply counts from rerunning lora_tiny_layer.py; file sizes from Fig. 11.2e.
Merged: (W + B·A)·xKept 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 layer1616 + 8 = 24, which is 50% more
Multiplies per token, 4096 × 4096 at rank 1616,777,21616,777,216 + 131,072, which is 0.78% more
Switching to another taskLoad another merged model, about 6 GBName 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.

  1. Find the scale. The largest weight by size is 0.42.
  2. 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.
  3. 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).
  4. Store. Four 4-bit codes, 15, 3, 10 and 1, plus the one scale, 0.42. The original weights are thrown away.
  5. 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.
  6. 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.

1 ROW 1 OF W ÷ ITS SCALE 0.42, SNAPPED TO THE NEAREST OF 16 NF4 LEVELS −0.33 → −0.7857 −0.19 → −0.4524 0.10 → 0.2381 0.42 → 1.0 −1 0 −0.6962 −0.3949 0.2461 1.0 code 1 3 10 15 × 0.42 −0.2924 −0.1659 0.1034 0.42 error 0.0376 0.0241 0.0034 0 levels crowd near 0, where most weights sit 2 WHAT THE GPU KEEPS, AND WHAT IT DOES AT MULTIPLY TIME stored for row 1 codes 15, 3, 10, 1 + scale 0.42 rebuilt: level × scale (0.42, −0.1659, 0.1034, −0.2924) 3 times x = (1.0, 0.5, −1.0, 2.0) row 1 · x = −0.3511 the unrounded W gives −0.435 4 storage: 4 bits + a 32-bit scale shared by 4 weights = 12 bits each here; shared by 64 = 4.5 bits in QLoRA
Fig. 11.2j — One block of the frozen W in NF4. Top: row 1 divided by its scale, snapped to the nearest of the sixteen levels, then multiplied back. Bottom: what is kept in memory, what is rebuilt for the multiply, and what that does to the output. Values from rerunning lora_tiny_layer.py; a real block holds 64 weights, not 4.
  1. 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.
  2. What is kept. Four 4-bit codes and one scale. The original weights no longer exist anywhere in memory.
  3. 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.
  4. 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.
Section 04's picture of 4-bit rounding and the NF4 format QLoRA uses, side by side
Fig. 11.1d's roundingNF4 in QLoRA
The 16 levelsEvenly spaced, 0.125 apartSpaced like a bell curve, crowded near 0
ScaleOne fixed ruler for every weightOne scale per block of 64 weights
Bits per weight44 + 32 ÷ 64 = 4.5; 4.127 with double quantisation
When the real number is usedNot shownRebuilt to 16-bit just before each multiply, then discarded
Does it train?Not shownNo. 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.

What one number costs, by job
JobNeeded forBytes per number
The weight itselfEvery weight, trained or frozen2 at 16-bit; 0.5625 in NF4 (4.5 bits)
Its gradient: the slope that says which way to nudge itTrained weights only2
Adam's running average of that slope, called mTrained weights only4
Adam's running average of the squared slope, called vTrained weights only4

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

  1. Full fine-tune. All 16 weights train: 16 × 12 = 192 bytes.
  2. LoRA. 16 frozen weights × 2 bytes = 32, plus 8 adapter numbers × 12 bytes = 96. Total 128 bytes.
  3. 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.

Counting the 3B model and its adapters, from rerunning qlora_memory.py. Shapes are the ones this page gives: width 3072, MLP width 8192, key and value width 1024, 28 layers, plus a 128,256-token vocabulary.
MatrixRows × columnsWeightsLoRA numbers, 16 × (rows + columns)
q_proj, o_proj (each)3072 × 30729,437,18498,304
k_proj, v_proj (each)1024 × 30723,145,72865,536
gate_proj, up_proj, down_proj (each)8192 × 3072, or 3072 × 819225,165,824180,224
One layer, all seven100,663,296868,352
× 28 layers2,818,572,28824,313,856
Embedding table, shared with the output layer128,256 × 3072394,002,432not adapted
Norm vectors57 × 3072175,104not adapted
Whole model3,212,749,82424,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

The same 3B model trained three ways, in decimal gigabytes before activations. From rerunning qlora_memory.py.
JobFull fine-tuneLoRAQLoRA
Weights3.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 numbersnone24.3M × 2 = 0.050.05
Gradients3.21B × 2 = 6.4324.3M × 2 = 0.050.05
Adam m and v3.21B × 8 = 25.7024.3M × 8 = 0.190.19
Total38.6 GB6.7 GB2.7 GB
With about 3 GB of activations, on a 16 GB T4Does not fitAbout 9.7 GB: fitsAbout 5.7 GB: fits with room
1 FULL FINE-TUNE 38.6 GB weights 6.4 gradients 6.4 Adam m and v, 32-bit: 25.7 2 LoRA, FROZEN 16-BIT BASE 6.7 GB frozen 6.4 + adapter jobs 0.29 3 QLoRA, FROZEN 4-BIT BASE 2.7 GB NF4 1.59 + embeddings 0.79 + adapter jobs 0.29 0 4 16 GB: the free Colab T4 stops here decimal gigabytes before activations, drawn to scale at 18 px per GB
Fig. 11.2k — The memory bill of Fig. 11.1e recounted with the exact 3B model. Full fine-tuning pays 12 bytes for every weight; LoRA pays 12 only for 24.3 million adapter numbers; QLoRA also shrinks the frozen linear weights to 4.5 bits. Values from rerunning qlora_memory.py.
  1. 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.
  2. 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.
  3. 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.
  4. 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?

What this module uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Tuning libraryUnsloth (wraps TRL)Axolotl, TRL directly, LLaMA-FactoryFastest 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.
MethodQLoRA: 4-bit frozen base plus rank-16 adaptersFull fine-tuning; LoRA on a 16-bit baseFits 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 modelLlama 3.2 3B InstructQwen3-4B, Gemma 3, Mistral SmallSmall 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 hardwareFree Colab T4 (16 GB)Rented A100/H100, a local 24 GB cardFree, 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 draftingA flagship model drafts, a human reviewsHand labelling only, open-weight teacherReview 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.
ServingOllama to try, vLLM to servellama.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.

1,800 clauses clauses_raw.jsonl 1 300 test clauses frozen before anything else 1,500 drafted labels make_dataset.py · flagship 2 a human reviews each row 75–225 corrected (5–15%) 3 val.jsonl — 150 max(50, 10%) train.jsonl — 1,350 the 90% that is left Twelve labels, none with fewer than 30 examples, one identical system prompt on every row. 1,350 training rows ÷ an effective batch of 16 = 85 optimizer steps per epoch, 170 for the two-epoch run. The 300 in the dashed box are never trained on, never tuned against, and only opened in section 07.
Fig. 11.2c — Where the 1,500 training examples come from, and what is taken out before they are made. The totals follow this page's own figures: about 1,500 curated examples and a 300-clause test set, split by build_train_files.py's rule of max(50, 10%) for validation.
  1. 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.
  2. 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.
  3. 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
  1. Bring in json and pathlib for file work, BaseModel from Pydantic to describe the shape of an answer, and the Anthropic client.
  2. Define LABELS, the same twelve clause types as the baseline, so the draft labels and the later fine-tune share one vocabulary.
  3. 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.
  4. Create the client; it reads ANTHROPIC_API_KEY from the environment on its own.
  5. Define draft(clause): call messages.parse with the schema as output_format, so the reply comes back as a ClauseTag object rather than free text. This is the Module 06 structured-outputs pattern.
  6. Read the raw clauses from clauses_raw.jsonl, one JSON object per line, keeping only the text field.
  7. 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.
  8. Write the rows to for_review.jsonl. A paralegal now corrects each row and flips reviewed to true; only those rows go forward. The 5–15% they correct are the hard cases the fine-tune needs most.
make_dataset.pyneeds API key
# 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
  1. Bring in json and random, and fix the random seed so the shuffle is the same on every run.
  2. Define the one system prompt the model will be trained on. It must be identical in every example, and identical again at serving time.
  3. Read reviewed.jsonl, keep only rows a human has approved, and shuffle them.
  4. 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).
  5. 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.
  6. Write train.jsonl and val.jsonl, one chat object per line. The 300-clause test set was set aside before any of this and is not touched here.
build_train_files.pyruns offline
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.

  1. Chunk 1 — write two tiny chat files and load them as a dataset

    Everything later in train_qlora.py starts from a train.jsonl and a val.jsonl of 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
    1. Define chat(clause, label): one training row is three messages, system, user, assistant.
    2. Write three rows to train.jsonl and one to val.jsonl, one JSON object per line.
    3. 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.py prints DatasetDict with train: num_rows: 3 and val: num_rows: 1, then {'role': 'assistant', 'content': 'termination'}. Measured.

  2. 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
    1. 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|>.
    2. Define to_text to do that for a whole batch of rows at once.
    3. Map it over both splits and drop the old messages column.
    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.py prints ['text'], then one string that starts <|begin_of_text|><|start_header_id|>system<|end_header_id|> and ends termination<|eot_id|>. Measured.

  3. 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
    1. Write down rank 16, 28 layers, and the shape of each of the seven target matrices.
    2. LoRA stores r × (rows + columns) numbers per matrix. Add that up for one layer.
    3. 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, and sum() over a generator.

    python chunk3_lora_config.py prints per layer : 868,352, all layers: 24,313,856 and share of a 3.21B model: 0.76%. Measured; it matches the 24.3 million on Fig. 11.2.

  4. 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
    1. Render one row to a string and cut it at the assistant header.
    2. Count the pieces before the cut; give each the label −100, which means ignore.
    3. 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.findall with a pattern that keeps each <|special|> token as one piece; the label value -100.

    python chunk4_mask.py prints tokens in row : 32, scored (not -100): 2, scored pieces : ['termination', '<|eot_id|>']. Measured. Real tokens differ a little; the idea does not.

  5. 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
    1. Load the base model already stored in 4-bit.
    2. Add rank-16 adapters to the seven matrices.
    3. Build SFTTrainer with batch 4 × 4 accumulation, two epochs, learning rate 2e-4, evaluating every 50 steps.
    4. Wrap it in train_on_responses_only (chunk 4's mask) and call train().
    train_qlora.py (shortened excerpt)not run here — needs a GPU
    model, 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, SFTTrainer and train_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
  1. 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.
  2. Load the base model and its tokenizer from a checkpoint that is already stored in 4-bit. max_seq_length=2048 caps the tokens per example; load_in_4bit=True keeps the base rounded in memory. A frozen 4-bit base with trainable adapters on top is what QLoRA means.
  3. 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.
  4. 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.
  5. Load train.jsonl and val.jsonl as one dataset with two splits.
  6. 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.
  7. 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.
  8. 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.
  9. 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.
  10. 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.

train_qlora.pyneeds GPU (free Colab T4 works)
# 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")
Anatomy of the adapter call — the one line to know by heart
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
)
  1. 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.
  2. The rank. r is 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 bigger r.
  3. The scale. The update B·A is multiplied by lora_alpha / r before it is added to the frozen weight. With alpha equal to r the scale is 1. The mistake: changing r and leaving alpha alone. That silently shrinks or inflates every update, so the run behaves as if you had changed the learning rate.
  4. 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.1 from a stock PEFT tutorial is the usual way to lose the speedup.
  5. 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.
  6. 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.
  7. 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.

1 HEALTHY: FALL, THEN FLATTEN 2.0 1.0 0 0 85 170 optimizer steps — 1,350 rows ÷ batch 16, two epochs training loss, 1.82 → 0.21 validation, every 50 steps 0.62 → 0.34 → 0.31 epoch 1 epoch 2 2 OVERFITTING: THE TWO LINES SEPARATE 0 150 510 the same run left to six epochs validation turns up after step 150, while training loss keeps falling to 0.08 the model is memorising 1,350 rows, not learning the task
Fig. 11.2d — The loss curve you are watching for, and the one that means stop. The step counts are computed from this page's own configuration: 1,350 training rows at an effective batch of 16 is 85 steps per epoch, so 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.
  1. 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.
  2. 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.
  3. 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.

The three training rows every answer below uses, all with the same 69-character system prompt. Token counts take each special marker as one token and ordinary text at the course's rule of about 4 characters per token; a real tokenizer will differ by a few.
RowUser turn: the clauseAssistant turn: the labelClause charactersTokens in the whole row
AThis Agreement shall automatically renew for successive one-year terms unless either party gives written notice 60 days prior to expiration.auto_renewal14071
BSupplier shall defend, indemnify and hold harmless Customer against all third-party claims arising from Supplier's negligence.indemnification12669
CEither party may terminate with 30 days notice.termination4748
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

  1. 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.
  2. The system prompt. 69 characters ÷ 4 ≈ 17 tokens.
  3. The clause. 140 characters ÷ 4 = 35 tokens.
  4. The label. auto_renewal is 12 characters ÷ 4 = 3 tokens.
  5. 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.

Which predictions count, two ways. Counts from rerunning one_row_to_loss.py.
If you forget the maskAs train_qlora.py is written
Scored predictions in row A704
What they areEvery marker after the first, the 17 system-prompt tokens, the 35 clause tokens, the label and its end markerThe 3 label tokens and the <|eot_id|> that ends the answer
Answer's share of the scored predictions, row A4 of 70 = 5.7%4 of 4
Answer's share, rows A, B and C together13 of 185 = 7.0%13 of 13
What the printed loss mostly describesHow well the model predicts contract text, and a system prompt it sees 1,350 timesHow 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.

1 ROW A AFTER THE CHAT TEMPLATE: 71 TOKENS, 11 PX EACH system prompt, 17 clause, 35 label, 3 narrow boxes are markers: the begin marker, three 4-token headers and three end markers 2 IF YOU FORGET THE MASK: 70 PREDICTIONS SCORED every position after the first; the answer is 4 of the 70 3 AS train_qlora.py IS WRITTEN: 4 PREDICTIONS SCORED ignored: each label set to −100 4 AT SERVING TIME THE MODEL IS HANDED 67 TOKENS AND WRITES 4 given in the prompt, ending with the assistant header generated: auto_renewal, then the end marker
Fig. 11.2l — Row A from string to score. Top: the row after the chat template, one box per piece, drawn to scale by token count. Middle: the positions scored if the mask were forgotten, and the four scored as train_qlora.py is written. Bottom: what the model is given and what it writes when it serves. Counts from rerunning one_row_to_loss.py, using 4 characters per token for ordinary text.
  1. 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.
  2. 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%.
  3. 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.
  4. Serving. add_generation_prompt=True hands 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.

  1. 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.
  2. 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).
  3. 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.
  4. Undo the log. e^−0.511 (e raised to the power −0.511) = 0.600. That is the typical probability on the right token.
  5. 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.

The loss values of Fig. 11.2d as typical probabilities, e^−loss. Illustrative values, from before the mask.
Point on the curveLossTypical p on the right token
Training loss at the start1.820.162
Validation, step 500.620.538
Validation, step 1000.340.712
Validation, step 1500.310.733
Training loss, step 1700.210.811
Training loss after six epochs0.080.923
Validation after six epochs0.450.638
1 ONE POSITION: LOSS = −ln p 0 1 2 3 0 0.5 1 p, the probability given to the right token 2 start of training: 1.82, p = 0.162 validation at step 150: 0.31, p = 0.733 3 THREE POSITIONS, AVERAGED p = 0.9 0.105 p = 0.6 0.511 p = 0.4 0.916 average 0.511 e^−0.511 = 0.600, the typical probability a plain average of p would say 0.633: the log average listens hardest to the weakest position 4 LOSS IS NOT ACCURACY p = 0.4 can still be the highest of 128,256, so the token counts as right for accuracy and still costs 0.916 in loss
Fig. 11.2m — What one loss number is made of. Left: the cost of one position against the probability the model gave the right token, with the start of training and the step-150 validation value from Fig. 11.2d marked. Right: three made-up positions averaged, turned back into a typical probability, and the reason a loss is not an accuracy. Values from rerunning one_row_to_loss.py.
  1. 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.
  2. 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.
  3. 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.
  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.

Three training sets, the same 300 correctly labelled validation clauses, 2,000 steps each. From rerunning overfit_toy_tagger.py.
RunLowest validation lossValidation accuracy thereAt step 2,000: training loss, validation loss, validation accuracyWhat it says
1. 600 reviewed rows0.277 at step 23088.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 8088.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 rows0.493 at step 1,25079.0%0.001, 0.494, 79.0%Too little data: memorised every row, flat but high

Reading run 2, step by step

  1. 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.
  2. Find the lowest validation loss. 0.399, at step 80. Validation accuracy there was 88.3%.
  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.
  4. 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.
  5. 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.

1 600 REVIEWED ROWS 0 0.5 1.0 1 10 100 1,000 lowest 0.277, step 230 ends at 0.321 val accuracy 88.7% → 88.3% 2 600 ROWS, 52 LABELS WRONG 0 0.5 1.0 1 10 100 1,000 lowest 0.399, step 80 ends at 0.615 val accuracy 88.3% → 79.7% 3 60 REVIEWED ROWS 0 0.5 1.0 1 10 100 1,000 flat at 0.494 gap 0.49 val accuracy stuck at 79.0% steps on a log scale: each tick is 10 times the last solid line: training loss · dashed line: validation loss on 300 clauses never trained on
Fig. 11.2n — The two shapes of Fig. 11.2d, measured on a toy tagger, plus a third. Each panel trains on a different set of rows and is scored on the same 300 correctly labelled validation clauses. Values from rerunning overfit_toy_tagger.py; it is a bag-of-words model, not an LLM, so the step counts do not transfer and the shapes do.
  1. 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.
  2. 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.
  3. 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.
Reading any pair of loss curves, with the toy run that shows each case
Training lossValidation lossWhat it meansWhat to do
FallingFallingStill learningKeep going
FallingFlatLearned what these rows can teach (run 1 after step 230)Stop; more steps buy nothing
FallingRisingMemorising (run 2 after step 80)Keep the checkpoint from the lowest point, train fewer epochs, and look for bad rows
Near zeroFlat and high, with a wide gapToo few rows to generalise (run 3)Add reviewed rows
Flat and highFlat and highNot learning at allCheck 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
  1. save_pretrained_merged computes W + B·A for every adapted matrix once and writes a plain 16-bit model to clausetag-merged. This is what vLLM serves in section 09; nothing at inference time knows LoRA was involved.
  2. save_pretrained_gguf writes the same merged model in GGUF, the file format Ollama and llama.cpp read, rounded to 4-bit with the q4_k_m scheme. That lets a laptop run the fine-tune too.
  3. Switch the in-memory model to inference mode, which turns off the training-only machinery and speeds up generation.
  4. Build one prompt through the chat template: the exact system prompt used in training, plus an indemnification clause. add_generation_prompt=True makes the template end where the assistant's turn begins.
  5. Tokenize it, move the tensors to the GPU, and generate at most 8 new tokens.
  6. 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.
train_qlora.py (continued)needs GPU
# 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
1 MERGE: ADD THE UPDATE IN, ONCE W frozen 16-bit base + B · A 24.3M trained clausetag-merged one plain model, ~6 GB Nothing at inference time knows LoRA was involved, so there is no extra matrix multiply and no added latency. This is what vLLM serves. GGUF export, 4-bit ~2 GB — Ollama on a laptop 2 KEEP SEPARATE: ONE BASE, MANY ADAPTERS frozen base in GPU loaded once, 1.5 GB at 4-bit clausetag — 50 MB redline-style — 50 MB client-A dialect — 50 MB The request names the adapter: model="clausetag". One GPU then serves every task, at the cost of one small extra multiply per token. Three merged models would be 18 GB; three adapters are 150 MB. 3 Same trained numbers, two deployments: merge when one task owns the GPU, keep separate when many do.
Fig. 11.2e — What the 50 MB adapter folder becomes: folded into the weights as one plain model for vLLM and exported at 4-bit for Ollama, or kept beside a shared base and named per request. The 50 MB is 24.3 million parameters at 2 bytes each; the 6 GB and 2 GB come from the memory table in section 04.
  1. 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.
  2. 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.
  3. 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
  1. Bring in json, os and time, plus both clients: OpenAI for the local server and Anthropic for the flagship.
  2. 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.
  3. Define the same system prompt the model was trained on, and two clients. local points at vLLM on port 8000 (or Ollama on 11434); api is for claude-sonnet-5.
  4. Define call_local: one chat request to the fine-tune, named clausetag, capped at 8 tokens.
  5. Define call_api: one request to the flagship using the best few-shot prompt the team found, read from fewshot_system.txt. A weak baseline would make the fine-tune look better than it is, so this is the strongest prompt available.
  6. 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.
  7. 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.
  8. Run the same function over both contenders. One harness, identical conditions, one line of output each: that is what makes the comparison fair.
eval_vs_baseline.pyneeds API key (for the baseline)
# 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):

Clause tagging, 300 held-out clauses — quality, latency, unit cost (illustrative run, Aug 2026)
SystemAccuracyp50 latency$ / 1k requestsWhere it runs
llama3.2:3b, few-shot (untuned)61%380 ms~$0.05your GPU
claude-sonnet-5, few-shot89%1,400 ms~$3.20vendor cloud
fine-tuned 3B (QLoRA)93%240 ms~$0.05your 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.

1 ACCURACY 61% 89% 93% base 3B flagship tuned 3B 2 MEDIAN LATENCY 380 ms 1,400 ms 240 ms base 3B flagship tuned 3B 3 COST PER 1,000 REQUESTS $0.05 $3.20 $0.05 base 3B flagship tuned 3B One harness, the same 300 held-out clauses, the same afternoon — eval_vs_baseline.py runs all three through identical code.
Fig. 11.2f — The three-column case, drawn: the fine-tuned 3B is 4 points better than the flagship, 5.8 times faster, and 64 times cheaper per thousand requests, while the untuned model of the same size is 32 points worse than the fine-tune. Every number is the row it sits above in the table on this page.
  1. 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.
  2. 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.
  3. 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.

RAG — facts into the prompt Fine-tuning — behaviour into the weights 1 what it changes the prompt: the actual page, fetched now, with the section number attached the weights: a reflex present on every request, with no retriever in the path 2 update one fact re-index one document minutes, no model change retrain, re-eval, redeploy days, and the old answer serves until then 3 per 1,000 requests ~1,000 prompt tokens every call $3.20 and 1,400 ms on the flagship a one-line prompt, 93% against 89% $0.05 and 240 ms on your own GPU 4 who can see it chunks filtered per user before the model reads a word a trained clause is in the weights for everyone who can reach the model Each fails in its own way: the retriever can miss the chunk; the fine-tune can only be corrected by training again. The system Juris ships uses both — retrieval for the facts, the fine-tune for the behaviour that uses them.
Fig. 11.2g — The two roles side by side, with this page's own numbers in the cells: what each one changes, how each is updated, what each costs per thousand requests, and who can see what.
  1. Row 1, what changes. Retrieval edits the prompt; fine-tuning edits the weights. That single difference produces every other row.
  2. 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.
  3. 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%.
  4. 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.
Fireside chat

Tonight's talk: RAG and Fine-Tuning argue over the question, "Who's more important?"

RAG
Fine-Tuning

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.

prompt → ideal answer chosen ▸ rejected pairs Base model next-token only SFT imitate demos 1 2 3 Instruct model follows orders DPO prefer chosen Aligned model your taste alternative RLHF: reward model + RL loop (PPO) same goal, more moving parts
Fig. 11.3 — The post-training pipeline: SFT teaches by imitation at marker 1, then DPO tunes taste from chosen/rejected pairs at marker 2 — reaching what RLHF, at marker 3, reaches without the reinforcement-learning machinery.
  1. 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.
  2. 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".
  3. 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.

1 SFT — ONE GOLDEN ANSWER system You are Juris ClauseTagger. Reply with exactly one clause_type label. user This Agreement shall automatically renew for successive one-year terms… assistant auto_renewal 1,350 rows of this shape trained the clause tagger. The loss asks one question: make this exact answer more likely. It can only teach what a demonstration can show, which for a label is everything — so clause tagging stops here. 2 DPO — TWO ANSWERS, ONE PREFERRED prompt Summarise this indemnity clause for a client email. chosen Supplier pays for third-party claims caused by its own negligence. rejected A 300-word recital that restates the clause and adds caveats. The loss asks: raise the chosen one, lower the rejected one. 3 a frozen copy of the model before DPO the loss is penalised for drifting far from it RLHF reaches the same goal the heavy way: train a reward model on these pairs, then run an RL loop against it.
Fig. 11.3b — The two data shapes, drawn: SFT consumes one golden answer per prompt, DPO consumes a chosen and a rejected answer for the same prompt plus a frozen reference copy. The clause-tagging row is the one built by build_train_files.py on this page; the summary pair is written here as a plausible Juris example.
  1. 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.
  2. 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.
  3. 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.

Fig. 11.3 again, concretely: each stage as it exists in this module's code
StageIn the naive version (section 04)In the production build (sections 06–09)What flows out
Base modelollama pull llama3.2:3b, a 4-bit file from the registryFastLanguageModel.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
DemonstrationsTwelve label names pasted into SYSTEMmake_dataset.py drafts, a paralegal reviews; build_train_files.py writes train.jsonl and val.jsonlAbout 1,500 chat rows with one fixed system prompt; 300 test clauses frozen first
AdaptersNone: the weights are untouchedget_peft_model(r=16, lora_alpha=16, target_modules=[...]) in train_qlora.pyAbout 24M trainable parameters, under 1% of the model
SFTNone: the prompt does all the workSFTTrainer with SFTConfig: 2 epochs, learning rate 2e-4, effective batch 16The clausetag-lora folder, 50–100 MB, plus a loss curve to read
Instruct modelThe stock instruct checkpointsave_pretrained_merged folds B·A into W; save_pretrained_gguf exports a 4-bit copyclausetag-merged for vLLM and a GGUF for Ollama
DPONoneSkipped for clause tagging; TRL's DPOTrainer on {"prompt", "chosen", "rejected"} rows when taste mattersAn aligned model, only when a single golden answer cannot express the goal
MeasureOne printed example and a huncheval_vs_baseline.py: 300 held-out clauses, one harness for the fine-tune and claude-sonnet-5Accuracy, p50 latency, and $ per 1k requests, side by side
ServeOllama on port 11434vllm serve ./clausetag-merged on port 8000, or --enable-lora to hot-swap adaptersAn 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.

client 1 client 2 client 3 …8 concurrent /v1/chat/completions vLLM server :8000 1 continuous batching requests join mid-flight 2 PagedAttention KV cache in small pages fused batch 3 GPU weights + KV pages
Fig. 11.4 — The serving path: concurrent OpenAI-compatible requests are fused by the continuous-batching scheduler at marker 1 into one GPU batch per token step; tokens stream back to each client as they're produced.
  1. 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.
  2. 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.
  3. 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
  1. Install vLLM; as of August 2026 it needs Linux and an NVIDIA GPU.
  2. vllm serve ./clausetag-merged loads the merged 16-bit model from step 2 and starts an OpenAI-compatible HTTP server on port 8000.
  3. --served-model-name clausetag is the name clients put in the model field. It decouples your API from the folder path on disk.
  4. --max-model-len 4096 caps 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.
  5. --gpu-memory-utilization 0.90 lets 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.
  6. The alternative block serves the untouched base model with --enable-lora and registers the adapter folder under the name clausetag. A request naming that model applies the adapter on the fly, and more adapters can share the same base.
terminal — serve the fine-tune with vLLMneeds GPU
# 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
1 THE DEV LOOP — OLLAMA ON A LAPTOP you one request Ollama :11434 2 GB GGUF, 4-bit one at a time the next call queues p50 380 ms · about 2.6 requests/s ≈ 46 tokens/s in total hardware bill: none 2 PRODUCTION — vLLM ON ONE L4 IN THE VPC 8 paralegals at the same moment vLLM :8000 continuous batching PagedAttention merged 16-bit model one L4 GPU $0.80 per hour inside the Juris VPC p50 240 ms at 8 concurrent 2.3× the throughput of the top row ≈ 106 tokens/s in total ≈ 15,000 requests/hour = $0.05 per 1,000 requests 3 Both speak the same OpenAI-compatible dialect, so the only difference in your code is one base_url: http://localhost:11434/v1 on the laptop, http://localhost:8000/v1 in the VPC.
Fig. 11.4b — The same merged model served two ways, with the cost of each. The latencies are this page's own eval numbers and the 2.3× throughput gap is this course's benchmark at 8 concurrent users; the token rates and the requests-per-hour figure are computed from those and stated as an illustration on one L4-class GPU.
  1. 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.
  2. 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.
  3. 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.

Deprecation radar — serving edition (Aug 2026)

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.
Boardroom translation

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."

$0 $50K $100K $150K 0 20M 40M 60M 80M tokens per day → (annual cost, up) 1 rent: $1.75K a year for every million tokens a day 2 own: $38K of engineer, plus GPU that grows with traffic 3 they cross at about 24M tokens a day Juris today: $70K rent, $45K owned a $25K gap — real, and not the argument
Fig. 11.4c — Build versus rent, drawn from the boardroom numbers: renting is a straight line through the origin, owning starts at about $39K of loaded engineer time and rises gently with hardware. They cross near 24M tokens a day; Juris is at 40M. The GPU cost is scaled linearly from the $7K a year quoted at today's volume.
  1. 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.
  2. 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.
  3. 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.

LAB 11 — A fine-tuned specialist with a cost-benefit case

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

Interview radar

"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.py masks 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
🧠 Flex your memory

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?