Your data and AI
You want to build your own model. Chances are extremely high that you do not.
Read the prose straight through for the argument. Open “Go deeper” under any section for the boards, diagrams and sources behind it, or switch them all on from the chapter bar.
Five rabbit holes, one question underneath them all
Use a chatbot for a month and you end up asking the same question: how do we get it to know our stuff? Part I covered it briefly and said: prompt, then retrieve, then adapt, and almost nobody should train a model. That was right. This chapter is the long version. It starts with the three knobs, because “what it knows”, “how it acts” and “building a brain” are not synonyms, and the order you try them in matters.
Then retrieval, at length, because that is what most organisations will actually build or buy: chunks, embeddings, the window, why it can cite, why it goes wrong, and when you can just paste it all. Then adaptation, kept short because most readers should not do it: fine-tuning for form rather than facts, LoRA, QLoRA, distillation, and pretraining, which is someone else’s job.
The fourth section is the one everyone skips and the one where projects live or die: a test set, a scorecard, and what goes in the index, with three stories about organisations that skipped it. The chapter ends with the practical choice, switch on, assemble or build, and the thirty questions to write before any of it. One rule runs underneath all five sections: manners go in the weights, truth goes in the retrieval, and nothing changes until you can score it.
The three knobs
“How do I get it to know our stuff?” is three different questions wearing one coat. Pull them apart first.
Knows · acts · isThis section pulls them apart, restates Part I’s sequence with the real time and money attached, and ends with the zero-engineering version most people should try first.
“Get it to know our stuff” is three different requests.
Every organisation that has used a chatbot for a month asks the same question: how do we get it to know our stuff? The answer starts with noticing that “our stuff” hides three different requests. The first is knowledge: facts that live in documents and that change. The refund policy, the current price list, the contract signed last Tuesday, the ticket a customer opened this morning.
The model did not read these in training and cannot have, and Part II’s rule applies: if a fact is not in the window, the answer is a guess. The fix is to look the facts up at question time and put them in front of the model. That is retrieval, and it is what the word RAG means. The second request is behaviour: the model knows enough but will not act the way you want.
It is too chatty, it will not stick to the format, it does not sound like you. That is adaptation: a thin layer of training that changes how the frozen model responds, without giving it a memory. The third request is to change what the model fundamentally is, by retraining most of its weights or starting again. Part I said that if you need that you already have a machine-learning organisation, and nothing has changed.
Part I’s mnemonic still holds: RAG is what it knows, LoRA is how it acts, pretraining is building a new brain. The rest of this chapter is the first two in detail, in that order, because that is the order you should try them.
In my experience nearly every such ticket is the first kind, most of the rest are the second, and almost nobody asking is the third.
Go deeper3 panels
What it knows → Retrieval
Facts that live in documents and change: policies, prices, tickets, the wiki, last week’s contract. The model looks them up at question time and reads them in the window. Part I: “RAG = what it knows.” Part II: if it is not in the window, it is a guess.
How it acts → Adaptation
Tone, format, a narrow skill: “always answer in our house style”, “always emit this JSON”. A thin adapter nudges the frozen model’s behaviour. Part I: “LoRA = how it acts.” It does not add a knowledge base.
What it is → Pretraining
Change most of the weights, or start from scratch, so the model itself is different. Lab money, months, an ML organisation. Part I: “if you need this, you already have an ML org.” This chapter says no and moves on.
The 2026 sequence: prompt, retrieve, adapt, distil. Stop at the first yes.
Part I drew this as a list. It is really a ladder, and the rule is to stop at the first rung that works. Rung one is prompting: a system prompt that states the job, the rules and the tone, plus a handful of good examples. Part I said this fixes, in my experience, about half the tickets that arrive labelled “we need a custom model”, and that is still true; the examples do most of the work. It costs an afternoon and can be undone in a minute.
Rung two is retrieval: if the right answer lives in documents that change, index them and look them up at question time. Days to weeks, and the index can be updated tomorrow. Rung three is adaptation: if the model knows the facts but will not behave, train a thin adapter on examples of the behaviour. Weeks, plus the evaluation work in section four, because without a test set you cannot tell whether the adapter helped.
Rung four is distillation: if you need the behaviour cheaper or running locally, teach a small model from a large one’s answers. Rung five is pretraining, which Part II priced: thousands of GPUs for months. OpenAI’s own guide for developers says the same thing in different words. Prompt engineering is “typically the best place to start”, retrieval is for when the model lacks the context, and fine-tuning is for when its behaviour is inconsistent.
The guide is careful to say these are not strictly sequential; you pick the lever that matches the failure you see. But you only know which failure you see once you have measured it, which is section four.
Go deeperladder · 1 source
Prompt it
System prompt, rules, three good examples. Fixes half the “custom model” tickets.
Retrieve
The answer lives in documents that change? Index them and look them up at question time. Days to weeks.
Adapt
It knows the facts but will not behave? Format, voice, a narrow skill: add a thin adapter (LoRA / QLoRA).
Distil, maybe
Need the behaviour cheaper or local? Teach a small model from a big one’s answers. Still not training GPT.
Pretrain
Change the brain. Thousands of GPUs, months, an ML team. Part II showed the bill. Not you.
Prompt it first. The zero-engineering version already exists.
Before anyone writes code, there is a version of all this that needs none. A system prompt is a block of standing instructions sent with every message: who the assistant is, what the job is, the rules, the tone, what to do when it is not sure. It is where most behaviour complaints are fixed, usually by adding one sentence that nobody had written down. Examples do the rest.
Show the model a real input and the answer you wanted, three or four times, and format, length and voice follow. This is sometimes called few-shot prompting. It is the cheapest “training” there is, and it is not training at all, because nothing in the model changes. The consumer products package this.
ChatGPT Projects keep instructions and files together and apply the instructions only inside the project; the help page lists file limits of 5 on the free plan, 25 on Plus and 40 on business tiers, as of October 2026. Claude Projects do the same, and on paid plans switch to retrieval automatically when the uploaded knowledge gets close to the window limit; the help page describes this as expanding capacity by up to ten times.
So the zero-engineering version turns into section two when the documents get big. Week one is: put the policy in a project, write one paragraph of instructions, add three worked examples, and try to break it with real questions. You will learn more from that afternoon than from a quarter of vendor meetings. And you will have the beginnings of a test set.
Put the policy in a Project with three worked examples and a one-paragraph instruction. Then try to break it. That is week one.
Go deeper4 panels · 2 sources
The system prompt
Standing instructions sent with every message: who it is, what the job is, the rules, the tone, what to do when unsure. Most “it won’t behave” complaints are a missing sentence here.
Three good examples
Show it a real input and the answer you wanted, three times. Format, length and voice follow. This is the cheapest “training” there is and it is not training at all.
Projects / custom instructions
ChatGPT Projects and Claude Projects: upload files, write project instructions, chat inside it. Free tiers allow a handful of files per project; check each product’s current limit. Paid Claude plans switch to retrieval when the files outgrow the window.
When this is not enough
The documents change weekly or run to thousands of pages (retrieve). The format still breaks after good examples (adapt). You do not know, because nobody scored it (evals, section four).
Which knob are you actually asking for?
Four questions. The last one is the whole of section four in a sentence.
- Take the last “train it on our data” request you heard. Was it about facts, about behaviour, or about being able to say you trained a model?
- Which of your documents change monthly? Those can never live in weights.
- Has anyone put the policy and three examples in a Project and tried to break it? What broke?
- Who, by name, would say whether the custom version was better? How would they know?
Retrieval (RAG)
Look the facts up at question time and put them in front of the model. The mechanism, why it can cite, why it fails, and when to skip it.
What it knowsRetrieval is what most organisations build or buy, so this is the longest section.
RAG in plain words. Index once, look up every time.
RAG stands for retrieval-augmented generation, a phrase from a 2020 paper by Patrick Lewis and colleagues at Facebook AI Research that combined a language model with a searchable index of documents. The working version is simpler than the paper. There are two phases, shown in the figure below. The first happens before anyone asks a question, and again whenever documents change. Take the documents you want the system to know.
Cut them into chunks, pieces of a few hundred words each; Amazon’s managed service defaults to about 300 tokens, Anthropic’s guidance says “usually no more than a few hundred tokens”. Turn each chunk into an embedding, which is a list of numbers that captures what the chunk is about; the next section explains that idea. In an index, store the chunk, its numbers, its source and who is allowed to see it. That last one matters most. The second phase happens on every question.
Turn the question into the same kind of numbers, find the chunks whose numbers are closest, and take the top few. Paste those chunks, with their sources, into the context window next to the question. Now the model does what Part II said it is good at: reading what is in front of it and answering from it, naming which chunk said what. A person can then open the source. Notice what the model does and does not do. Everything except one step is ordinary code: cutting, counting, searching.
The model does that one step. It reads and writes. It never “learns” the documents. It is handed the relevant pages each time, like a new temp with a very good filing clerk.
RAG means search first, then generate. The model never “learns” your documents; it reads them.
Go deeper2 step diagrams · 3 sources
Documents
Policies, PDFs, wiki pages, tickets. Whatever you want it to know.
Chunk
Cut into pieces of a few hundred words. A chunk is one piece. Boundaries matter.
Embed
Turn each chunk into an embedding: a list of numbers that captures its meaning. Next section.
Store
Keep chunk + numbers + source + who may see it in an index (a “vector database”).
Question
“Can a contractor claim travel?”
Retrieve
Embed the question. Find the chunks with the closest numbers. Keep the top few.
Fill the window
Paste those chunks, with their sources, into the prompt next to the question.
Answer, cite
The model reads the chunks and answers from them, naming which chunk said what.
Check
A person can open the source. That is the whole point.
BEFORE ANYONE ASKS · DONE ONCE, REPEATED WHEN DOCUMENTS CHANGE
Embeddings: turning meaning into a position on a map.
The word that stops most non-specialists is “embedding”, so here it is without the maths. An embedding is a list of numbers, a vector, that a small model produces from a piece of text. OpenAI’s current embedding models produce 1,536 or 3,072 numbers per text. The numbers are arranged so that texts with similar meaning get similar numbers; in OpenAI’s own words, “small distances suggest high relatedness and large distances suggest low relatedness”. The useful picture is a map.
Every chunk of your documents is a pin, and pins about the same thing cluster together. A question is a pin too. Retrieval means dropping the question’s pin on the map and picking up the nearest few chunks. That is why it works without keywords: “can a contractor claim travel” lands near the expense policy and the contractor terms whether or not they use the word “claim”; the match is on meaning, not on the word. The analogy breaks in three places, and they matter.
First, the map has thousands of dimensions, not two, and nobody can tell you what any one of them means; the figure above draws two because a screen is flat. Second, “near” means “about the same topic”, not “true” or “current”: the 2024 policy sits right beside the 2026 one, and the embedding does not know which is in force. Neither, usually, does the new starter. Third, meaning-search is poor at exact strings. A part number, a surname, an invoice ID, a legal citation: these need old-fashioned keyword matching, which comes next.
So it is a filing system that files by meaning. Useful and mechanical, and it understands nothing.
An embedding is a filing system that files by meaning instead of by keyword. That is all. It is not understanding.
Go deeper4 panels · 1 source
What it is
Embedding: a list of numbers (OpenAI’s current models: 1,536 or 3,072 of them) made by a model so that texts with similar meaning get nearby numbers. “Small distances suggest high relatedness.”
The analogy
A map where every chunk is a pin and “near” means “about the same thing”. A question is a pin too. Retrieval: find the closest pins. No keywords needed: “travel claim” lands near “expense policy”.
Where the analogy breaks
A map has two dimensions; this has thousands, and nobody can say what each means. “Near” is about topic, not truth: the wrong policy sits beside the right one. And exact strings (part numbers, names) are not its strength: next section.
ILLUSTRATIVE · TWO OF 1,536 DIMENSIONS · POSITIONS INVENTED
Contractor T&Cs
Travel expense policy
“Can a contractor claim travel?”
Per-diem rates 2026
nearest chunks → retrieved
Christmas party photos
Office Wi-Fi password
Kitchen rota
It can cite. It updates tomorrow. And you want both searches.
Three properties make retrieval the default answer for knowledge, and they all follow from the mechanism. First, it can cite. Every chunk that goes into the window carries its source: file, section, date. If the prompt tells the model to answer only from those passages and to mark which passage each claim came from, then a citation is a pointer to something that exists, which a person can open. Part II’s Mata v. Avianca lawyers were caught by citations the model predicted. Here the passage is retrieved, not predicted. The model still decides which claim to pin it to, so check the pin.
The rule has to be enforced, in the prompt and in the eval in section four: no supporting chunk, no claim. Second, it updates tomorrow. When the policy changes, re-index the file and the next question gets the new answer. Nothing about the model changed. The knowledge cutoff from Part II stops mattering for anything in the index. Compare that with baking the policy into weights, which section three will show goes stale the day you sign it off.
Third, it can run both kinds of search. Meaning-search is good at “about the same thing” and poor at exact strings. Keyword search, usually an algorithm called BM25, is the reverse: it finds the exact part number, surname or clause reference and misses the paraphrase. Production systems run both and merge the rankings; Azure AI Search does it as a single hybrid query merged by a simple rule that adds up reciprocal ranks (reciprocal rank fusion), and Postgres with pgvector can do the same with its built-in full-text search.
Anthropic’s September 2024 measurements give a sense of the gain: on their test sets the rate at which the right chunk was missing from the top twenty fell from 5.7% with plain embeddings to 2.9% with contextual embeddings plus keywords, and to 1.9% with a reranking step added. Those are their corpora and their numbers; the direction holds generally.
Illustrative prompt. The citation rule is written by you, enforced by the prompt, and checked by the eval.
Go deeper3 panels · code · 3 sources
It can cite
Every chunk in the window carries its source. Ask the model to answer only from the chunks and name them, and a citation is a pointer you can open, not a prediction of what a citation looks like (Part II, Mata v. Avianca). Enforce it: no chunk, no claim.
It updates tomorrow
Change the policy, re-index the file, done. Nothing about the model changes. The model’s knowledge cutoff (Part II) stops mattering for anything in the index. This is the single biggest reason to retrieve rather than train.
Hybrid: meaning + keywords
Vector search finds “about the same thing”. Keyword search (BM25) finds the exact part number, name or clause. Run both, merge the rankings. Anthropic measured retrieval failures falling from 5.7% to 2.9% with contextual embeddings plus keyword search, and to 1.9% with a reranker (a second model that re-scores the candidates) added.
SYSTEM: Answer only from the passages below. After each claim write [n] for the passage it came from. If the passages do not contain the answer, say "Not in the documents I have" and stop. PASSAGES: [1] Travel policy v6, §4.2 (2026-03-01) … [2] Contractor T&Cs, cl. 9 (2025-11-12) …
When RAG fails, it is usually the retrieval. Not the model.
When retrieval systems fail, the model is rarely the culprit: it answered from what it was given, and the failure is in what it was given. Two numbers set the scene. In May 2024 Stanford’s RegLab and HAI tested commercial legal research tools built on retrieval and marketed as hallucination-free. Lexis+ AI and Thomson Reuters’ Ask Practical Law AI produced incorrect or misgrounded answers more than 17% of the time; Westlaw’s AI-Assisted Research more than 34%. Misgrounded means the answer cited a source that did not support it.
The authors blamed retrieval difficulty, documents inapplicable by jurisdiction or date, and the model agreeing with false premises in the question. Anthropic’s own figure is the other side of the coin: with ordinary embeddings, 5.7% of test questions did not have the right chunk anywhere in the top twenty results. In those cases the model never saw the answer, and in most systems it answers anyway.
Chunks cut mid-sentence separate a number from its unit. Chunk on structure instead, and give each chunk a line of context about the document it came from, which is what Anthropic’s contextual retrieval does. Wrong documents in the index means the 2023 draft is in there with the 2026 policy, and the embedding cannot tell them apart. Curate, date, and filter by status before ranking. A stale index means the policy changed and nobody re-indexed. Re-index on change, and print the index date on every answer.
If the model ignores the chunks, the prompt must say answer only from the passages, cite each claim, and admit when the passages do not contain the answer, and section four must test for it. And the one that gets you in the newspaper: a retrieval system is a search engine over everything you gave it, and if you gave it HR’s folder, everyone now has HR’s folder.
Go deeper2 panels · what goes wrong · 2 sources
17% to 34% · wrong or misgrounded
Share of answers from Lexis+ AI, Ask Practical Law AI (over 17%) and Westlaw AI-Assisted Research (over 34%) in Stanford’s 2024 test of legal RAG tools sold as “hallucination-free”. Stanford RegLab / HAI, May 2024.
5.7% · right chunk never retrieved
Share of questions where the correct chunk was missing from the top twenty results with ordinary embeddings, on Anthropic’s own test corpora. The model never saw the answer. It answered anyway. Anthropic, Sep 2024.
Or just paste it all? When long context wins, and when it doesn’t.
Context windows grew faster than retrieval advice did, so the question deserves a straight answer: can you skip all of this and just paste the documents into the prompt? Often, yes. Anthropic’s own guidance says that if the knowledge base is under about 200,000 tokens, roughly 500 pages, you should simply include it in the prompt and use prompt caching, which cuts repeated-prompt cost by up to 90% and latency by more than half.
As of October 2026 the major models take about a million tokens: Anthropic made 1M context standard for Opus and Sonnet 4.6 in March 2026 with no long-context surcharge, and OpenAI’s GPT-5.5 lists 1,050,000 with a surcharge above 272K input tokens. So the handbook fits. But four things still favour retrieval. The first is cost: every pasted token is billed on every question, so 500 pages is roughly 200,000 tokens, about a dollar of input per question at GPT-5.5’s $5 per million before caching. Retrieval sends a few thousand tokens.
The second is freshness: re-pasting a changed corpus is fine for a stable handbook and absurd for a ticket queue. The third is permissions: whatever is pasted is visible to whoever can ask, which is fine for one audience and a breach for several, and retrieval can filter chunks by who is asking. The fourth is accuracy at length: Part II covered “lost in the middle”, where facts in the middle of a long input get missed, and “context rot”, where reliability falls as input grows.
Pasting needs no engineering. Retrieval is a system you have to run. Pick the smallest thing that passes your test set.
Under 500 pages and one audience: paste it, cache it, stop. Above that, or if different people may see different things: retrieve.
Go deepertable · 4 sources
| Paste it all (long context) | Retrieve (RAG) | |
|---|---|---|
| Fits when | Whole corpus under ~200K tokens (≈500 pages). Windows are now 1M tokens. | Any size. Thousands of documents, millions of pages. |
| Freshness | You re-paste. Fine for a stable handbook. | Re-index the changed file. Fine for things that change daily. |
| Cost per question | Every token every time. 500 pages ≈ 200K tokens ≈ $1 in on GPT-5.5 before caching. | A few chunks: thousands of tokens. Cents or less. |
| Permissions | Everyone who can ask sees everything pasted. | Filter chunks by who is asking. Per-document access survives. |
| Accuracy | Good, but “lost in the middle”: facts mid-window get missed (Part II). | Good if retrieval is good. Fails silently if it is not (previous section). |
| Engineering | None. A prompt and a file. | Chunking, embeddings, index, permissions, re-indexing. A system to run. |
What is in your index, and who can search it?
The first of these deflates a lot of projects. The last is the diagnostic habit that separates teams who improve their retrieval from teams who swap models.
- How many pages are the documents you actually want it to know? Under 500? Then why are you buying a vector database?
- Which of those documents have a date on them, and which have three versions nobody has retired?
- If a chunk from the HR folder came back for a junior analyst’s question, who would notice, and when?
- When the answer is wrong, how will you tell whether the right chunk was never retrieved or the model ignored it?
Adaptation
Fine-tuning changes how the model behaves. It is a poor way to change what it knows, and it goes stale the day you ship it.
How it actsFine-tuning is real, useful and overprescribed, so this section is deliberately short: what a thin adapter is, the evidence that facts do not belong in weights, and distillation and pretraining in one breath.
Fine-tuning for form: a thin adapter on a frozen model.
Fine-tuning means continuing to train a model on your own examples so that its behaviour shifts. Done to the whole model, that is expensive and fragile: you need the memory to hold every weight and its gradients, and you can damage what the model already knew. The 2021 LoRA paper from Microsoft, “Low-Rank Adaptation”, found a cheaper route. Leave the base model frozen. Add small extra matrices beside the big ones and train only those. Think of a clip-on lens for a camera you already own.
Compared with fully fine-tuning GPT-3, the authors report ten thousand times fewer trainable weights and about a third of the GPU memory, with no added latency at inference, and quality on par with full fine-tuning. The adapter is a small file you can swap in and out; one base model, many adapters. QLoRA, from Tim Dettmers and colleagues in 2023, squashes the frozen base to 4-bit precision so that the whole thing fits on much less hardware; they fine-tuned a 65-billion-parameter model on a single 48 GB GPU.
That is why Part I said a serious laptop can do small ones. What is it for? Form. Tone and house style, consistently. A rigid output format. A narrow skill that is awkward to describe in a prompt, such as sorting tickets into forty categories the way your team does. Moving a long list of examples out of the prompt and into the adapter, which saves tokens on every call.
And making a small, cheap model behave like a large one on a single job, which is distillation, covered below. What it is not for is facts. An adapter has no sources to cite, it is frozen on the day you train it, and, as the next section shows, teaching it facts is both inefficient and risky.
Fine-tuning just means more training on your examples. LoRA does it through a small add-on instead of the whole model. Manners in the weights.
Go deeper4 panels · 2 sources
LORA ADAPTER · TRAINABLE · A FEW MILLION WEIGHTS · YOURS
Small extra matrices added beside the frozen ones. Trained on your examples. Swappable: one base model, many adapters. The 2021 paper: 10,000× fewer trainable weights than full fine-tuning of GPT-3, about 3× less GPU memory, no extra latency, quality on par.
Good for (form)
Tone and house style, consistently
A rigid format: “always this JSON, never prose”
A narrow skill the prompt can’t hold: our 40 ticket types
Shorter prompts: the examples move into the adapter
A small, cheap model that acts like a big one on one job
Bad for (facts)
Teaching it your policies, prices, products
Anything that changes: frozen at training day
Citations: an adapter has no sources to point at
Fixing a problem you have not measured
Replacing retrieval. It adds no memory.
THE BASE MODEL · FROZEN · BILLIONS OF WEIGHTS · UNTOUCHED
Everything it learned in pretraining and post-training (Part II). You cannot afford to change this, and you do not need to.
QLoRA (2023): the same trick with the base model squashed to 4-bit so it fits. A 65B model fine-tuned on one 48 GB GPU. A serious laptop can do small ones (Part XII will show one).
Manners in the weights. Truth in the retrieval.
Part I gave you the rule as a slogan: fine-tuning is for form, not facts. Here is the evidence behind it. Two studies tried to do the thing the ticket asks for, which is to teach a model new facts by training on them. Ovadia and colleagues, in a paper revised in January 2024, compared unsupervised fine-tuning (training on raw text rather than question-and-answer pairs) against retrieval for injecting knowledge, both facts the model had seen in training and entirely new ones. Fine-tuning helped a little.
Retrieval won consistently in both cases, and the authors note that models struggle to learn new facts this way unless shown many paraphrases of each one. Gekhman and colleagues, in work revised in October 2024, found something worse than inefficiency. Training examples that introduce new facts are learned more slowly than examples the model already agrees with, and once the new facts are learned they linearly increase the model’s tendency to hallucinate, which the authors suggest is because fitting new facts teaches the model to produce assertions it cannot ground in what it learned in pretraining.
Their summary is the one to remember: models acquire factual knowledge in pretraining, and fine-tuning mostly teaches them to use it. Then there is the mechanical point that needs no study. Whatever you bake in is right on training day. The price list changes on Thursday. The adapter does not know. It will quote last quarter’s prices with total confidence. With retrieval you re-index one file; with an adapter you retrain, re-run the evals, and redeploy. So the division of labour is simple. Behaviour, format and voice can live in weights, because they change slowly.
Facts live in the index, because they do not.
Part I’s rule, now with footnotes: fine-tuning is for form, not facts. Bake in manners. Retrieve the truth.
Go deeper3 panels · 2 sources
Retrieval beats fine-tuning for facts
Ovadia et al. compared fine-tuning against retrieval for injecting knowledge into models. “RAG consistently outperforms it, both for existing knowledge encountered during training and entirely new knowledge.” Models “struggle to learn new factual information through unsupervised fine-tuning”. arXiv 2312.05934, revised Jan 2024
New facts in weights raise hallucination
Gekhman et al.: training examples that introduce new facts are learned slowly, and once learned they “linearly increase the model’s tendency to hallucinate”. Their conclusion: models acquire facts in pretraining; fine-tuning teaches them to use what they already have. arXiv 2405.05904, revised Oct 2024
And it is stale on day one
Whatever you bake in is correct on training day and drifts from then on. The price list changes on Thursday; the adapter does not know. There is no re-index. There is a retrain, a new eval run and a redeploy, every time. Mechanism, not a study
Distil to make a cheap specialist. Pretrain only if you are a lab.
Two more knobs, briefly, because they exist and vendors will mention them. Distillation is an old idea with a 2015 paper by Hinton, Vinyals and Dean behind it: transfer what a large model does into a smaller one that is cheaper to deploy. The modern recipe is plain. Run the big model on thousands of your real inputs. Keep the answers. Fine-tune a small model on those input-answer pairs. Compare both on your evaluation set and keep the small one if it passes.
OpenAI packaged this as a product in October 2024: stored completions capture the big model’s answers, fine-tuning trains the small model, and an evals tool compares them. The result is a narrow specialist: faster, cheaper, and often small enough to run on your own hardware, which is what Part XII’s local models are for. It is only as good as the large model was on that job, and only on that job.
Pretraining is the other extreme. Part II priced it: Llama 3.1’s largest model was trained on more than fifteen trillion tokens using over sixteen thousand GPUs, and Epoch AI projected the largest frontier runs passing a billion dollars. That will not go through on the company card. There is a middle ground called continued pretraining, where an existing model is trained further on a very large specialised corpus, such as decades of a particular kind of technical document. It is real, but rare. It still needs retrieval for anything that changes, and it needs a machine-learning team.
Part I’s line stands: if you need this, you already have that team.
Rungs four and five of the ladder. Most teams never climb past three, and that is not a failure.
Go deeper2 panels · side by side · 2 sources
Teach a small model from a big one.
- Idea (Hinton, Vinyals, Dean, 2015): transfer what a large model does into a smaller one that is cheaper to run.
- Recipe today: run the big model on thousands of your real inputs, keep the answers, fine-tune a small model on them, compare both on your eval set. OpenAI ships this as a workflow: stored completions → fine-tune → evals.
- Result: a narrow specialist. Cheaper, faster, can run locally (Part XII). Only as good as the big model was on that job, and only on that job.
- Still not “training GPT”. Still needs the eval set first.
Build a brain. No.
- Change most or all of the weights, or start from scratch, on trillions of tokens.
- Part II’s numbers: 15 trillion tokens, 16,000 GPUs for Llama 3.1 405B; frontier runs heading past $1 billion.
- Continued pretraining on your corpus is a real technique for very large, very specialised bodies of text. It still needs retrieval for anything that changes, and an ML team to run it.
- If you need this, you already have that team. If you are asking, you do not.
Is there a format the base model keeps botching?
Ask these four before anyone trains anything. The second is lifted from Part I because it is still the best one: almost everyone has a RAG war story, and almost nobody checked whether the right chunk was retrieved.
- What has the model refused to do consistently even after three good examples in the prompt? That is an adaptation candidate. Anything else is not.
- Where has RAG already failed you, and was it retrieval or the model? Did anyone check which?
- If you fine-tuned on this quarter’s facts, who would retrain it next quarter? Is that a job anyone has?
- Which job is big enough, and boring enough, that a cheap distilled specialist would pay for itself?
Evals and hygiene
If you cannot score the job, you cannot tell whether the change helped. And what you put in the index, everyone with access can now find.
Score it · scrub itThis is the part everyone skips and the part that decides whether anything above worked.
An eval is an exam: real questions, known answers, a score.
An eval, short for evaluation, is an exam for the system. It has three parts: a set of real questions, the right answer to each, and a way to score an attempt. Everything else in this chapter is a change you might make; the eval is how you find out whether the change helped. Start with real questions. Pull them from the inbox, the helpdesk, the search logs, the things people actually typed, including the badly phrased ones and the ones with wrong assumptions in them.
Part IV asked for a hundred past cases; thirty is enough to begin, and the list at the end of this chapter starts there. For each question, a person who knows writes the correct answer and names the document and section that supports it. This is the expensive step, and the one that gets skipped. It is also the only step you cannot automate, because it is the definition of correct. Then run the system over the questions and score.
Some scoring is code: the answer contains the right number, the JSON parses, the cited chunk is the one the expert named. Some scoring is a second model acting as judge: “is every claim in this answer supported by the passages, yes or no”; standard practice, to avoid a model preferring its own answers, is to use a different model from the one being tested. And some scoring is a human reading a sample every week, because the automated judges drift.
The guidance from both Anthropic and OpenAI points the same way: make the eval task-specific, automate what you can, and prefer many cheap checks to a few careful ones. OpenAI’s guide suggests at least twenty questions with ground-truth answers as the output of the prompting stage. Then comes the discipline: change one thing, run it again.
Two disciplines from Part II’s learning section carry over. Keep some cases out of the loop: the ones you tune the prompt on are development cases, and a second set you never look at while tuning is the only real score, because fixing case three while watching case three tells you nothing about cases seven and nine. And run the variable ones more than once: a case that passes three times in five is a sixty per cent case, not a pass. Then read the consequential failures one by one, because an average hides the one that costs money.
Part I: evals before adapters. Part IV: 100 real past cases. Same test set, same reason. Build it first.
Go deeper1 panel · numbered list · 2 sources
Collect real questions
From the inbox, the helpdesk, the search logs. Not the ones you would like people to ask. Part IV asked for 100 past cases; 30 is a start.
Write the right answer, and where it lives
A person who knows writes the answer and names the document and section that supports it. This is the expensive part. Do it anyway.
Run the system. Score it.
Correct? Grounded in the cited chunk? Refused when it should? How long, how much? Code checks what it can; a model grades the rest; humans sample.
Change one thing. Run it again.
New chunking, new prompt, new model, an adapter. The score moved or it did not. If you cannot run this, you cannot tell.
Grading, cheaply
Code: exact match, “does the answer cite chunk 4”, numbers equal, JSON valid.
Model as judge: “Is every claim supported by the passages? Yes / no.” Use a different model from the one being tested.
Humans: a sample of 20 a week, read properly. Sparingly, because it is slow; always, because the judges drift.
Anthropic’s guidance: task-specific, automated where possible, “volume over quality”.
What to measure: six numbers, and what each one catches.
Six numbers cover almost every retrieval or adaptation project, and the point of having six rather than one is diagnosis. Correctness is the blunt instrument: did the answer match what the expert wrote. Score it with code where the answer is a number, a date or a fact, and with a judge model where it is prose. Groundedness asks a sharper question: is every claim in the answer supported by the passages that were retrieved.
The open-source Ragas library calls this faithfulness and scores it mechanically: split the answer into claims, check each against the context, divide supported by total, so two claims with one supported scores 0.5. A low groundedness score with high retrieval hit means the model is ignoring the chunks or decorating them. Retrieval hit asks whether the right chunk was in the retrieved set at all; it is pure code, comparing the expert’s cited section against what came back.
A low hit rate means the failure is upstream of the model: chunking, a stale index, the wrong documents. This is the number that the previous section said nobody checks, and it is the cheapest to compute. Refusal rate needs questions the corpus cannot answer, deliberately included, so that you can count the times the system correctly said “not in my documents” and the times it wrongly did. Latency should be reported at the slow tail, because that is what the person waiting experiences.
Cost is tokens in and out times the price, plus the retrieval service. Read together, these tell you which part of the pipeline to fix.
Groundedness and retrieval hit tell you where the failure is. Correctness only tells you that there was one.
Go deepertable · 2 sources
| Measure | The question it answers | How it is scored | What it catches |
|---|---|---|---|
| Correctness | Did it give the right answer? | Match against the expert answer: code for numbers and facts, a judge model for prose | Everything, bluntly. Start here. |
| Groundedness | Is every claim supported by the retrieved passages? | Split the answer into claims; count the supported ones. Ragas calls this “faithfulness”: 2 claims, 1 supported = 0.5 | The model ignoring the chunks. Confident filler. |
| Retrieval hit | Was the right chunk among the top few (k) retrieved at all? | Code: is the expert’s cited section among the retrieved chunks? | Chunking, stale index, wrong documents. Most failures. |
| Refusal rate | Did it say “not in my documents” when it should, and only then? | Include questions with no answer in the corpus. Count correct refusals and wrong ones | Over-confidence one way; uselessness the other. |
| Latency | How long did the person wait? | Clock. Report the slowest 5%, not the average | Reranking and long contexts that cost seconds. |
| Cost | What did each answer cost? | Tokens in and out × price, plus retrieval | The “paste it all” design, at scale. |
A scorecard: what “did it help?” looks like on paper.
Here is what the previous two sections produce when someone actually does the work. The numbers are invented; the shape is what you see in practice. Version A is the model with a prompt and no documents: it gets eleven of thirty right from general knowledge, and refuses none of the five unanswerable questions, because it does not know it does not know.
Version B pastes the whole handbook, 180,000 tokens, into every call: much better, twenty-four right and mostly grounded, but ten seconds and nearly a dollar per answer. Version C is the first retrieval attempt, with fixed-size chunks and vector search only, and it is worse than pasting: nineteen right, because the retrieval-hit column shows that nine times the right chunk was never found. The model never saw the answer.
Version D fixes retrieval, not the model: chunk on headings, add keyword search, and a prompt that must cite or refuse. Twenty-six right, twenty-nine grounded, all five refusals correct, four seconds, three cents. Version E is a LoRA adapter trained on four hundred past answers, a fortnight of work, and it moves the numbers you care about not at all and the groundedness slightly down. That is the normal result for an adapter aimed at facts. The decision writes itself. Ship D.
Keep B as the ceiling to compare against. Bin E and write down why. Then take the four D got wrong and look at them one at a time, because the next improvement is in those four, not in a new model. Notice that no step of this needed anyone to argue about which vendor’s model is smartest.
Go deeper2 panels · table
| Version | Correct | Grounded | Retrieval hit | Right refusals | p95 latency (slowest 5%) | Cost / answer |
|---|---|---|---|---|---|---|
| A · Prompt only, no documents | 11 / 30 | n/a | n/a | 0 / 5 | 2.1 s | $0.004 |
| B · Paste the whole handbook (180K tokens) | 24 / 30 | 26 / 30 | n/a | 3 / 5 | 9.8 s | $0.92 |
| C · RAG, fixed 500-token chunks, vectors only | 19 / 30 | 22 / 30 | 21 / 30 | 2 / 5 | 3.4 s | $0.02 |
| D · RAG, heading chunks + keywords + “cite or refuse” prompt | 26 / 30 | 29 / 30 | 28 / 30 | 5 / 5 | 3.9 s | $0.03 |
| E · D plus a LoRA adapter trained on 400 past answers | 26 / 30 | 27 / 30 | 28 / 30 | 4 / 5 | 3.8 s | $0.03 |
Read it like a skeptic
B to C: adding retrieval made it worse than pasting, because 9 of 30 right chunks were never retrieved. C to D fixed the retrieval, not the model. E, the adapter, cost a fortnight and moved nothing you care about.
What you would decide
Ship D. Keep B as the benchmark. Bin E, and write down why, so the next person doesn’t repeat it. Add the four D got wrong to the test set and look at them one at a time.
ILLUSTRATIVE SCORECARD · 30 REAL QUESTIONS, 5 WITH NO ANSWER IN THE CORPUS · ALL NUMBERS INVENTED
The index searches whatever you fed it. Feed it carefully.
A retrieval index is a search engine over everything you put in it, and it is usually a better search engine than the one your file shares had. That is the point, and it is the risk. What goes in is current, approved documents, one version each, and the things people actually ask about. Every chunk carries a source, a date, an owner and an intended audience, because those are what the filters and the citations use.
Structured data, the customer table, the stock levels, the ledger, should not be chunked into prose at all. Leave it in the database and give the model a tool to query it, which was Part IV’s whole argument; the index is for documents.
Four things must not go in. Drafts and superseded versions, because the embedding cannot distinguish them from the current one. Personal data the questions do not need, which includes payroll, health, HR case files and customer identifiers. Anything whose access list you cannot state, because if you do not know who may read it the only safe answer is nobody. And secrets, because wiki pages full of passwords exist in every organisation and retrieval will find them.
Three rules follow. Permissions mirror the source system: a chunk inherits the access list of the file it came from, and retrieval filters by who is asking before it ranks, not after. Retention follows the source, so a deleted document means deleted chunks on the same clock. Log what was retrieved, for whom, and when. That log is the audit trail when something goes wrong and the raw material for the next hundred eval questions. And Part II’s line, once more: the model is not a database.
Facts of record live in systems of record. The index points at them.
If a person could not have found it by searching the source system, the index must not find it for them either.
Go deeper3 panels
What goes in
- Current, approved versions. One per document.
- Things people actually ask about: policies, procedures, product facts, FAQs.
- A source, a date, an owner and an audience on every chunk.
- Structured data? Leave it in the database and give the model a tool (Part IV). The index is for prose.
What must not
- Drafts, superseded versions, “final_v3_OLD”.
- Personal data that the question does not need: payroll, health, HR cases, customer PII.
- Anything whose access list you cannot state. If you don’t know who may read it, nobody may.
- Secrets: keys, passwords, credentials in wiki pages. They will be retrieved.
The rules
- Permissions mirror the source system. The chunk inherits the file’s access list, and retrieval filters by who is asking, before ranking.
- Retention: when the source is deleted, the chunk is deleted. Same clock.
- Log what was retrieved for whom. That is your audit trail and your eval data.
- The model is not a database (Part II). Facts of record live in systems of record; the index points at them.
Oversharing: the search is only as good as the permissions.
The clearest large-scale lesson about data hygiene came from one of the largest enterprise retrieval rollouts to date. Microsoft 365 Copilot, launched to enterprises in November 2023, is a retrieval system over everything in a company’s Microsoft tenant: mail, chats, files, meetings. Microsoft’s documentation is precise that it answers only from data the user already has permission to access. That turned out to be the problem. In June 2024 Gartner surveyed 132 IT leaders, about half at organisations with more than ten thousand employees.
Sixty per cent had started Copilot pilots; one per cent had deployed it to everyone eligible. Forty per cent had delayed rollout by three months or more over oversharing concerns, sixty-four per cent said governance and security risks had taken significant time and resources, and fifty-seven per cent had restricted the rollout to low-risk or trusted users. What they had found, in the words of Gartner’s Max Goss, was that they were “putting Copilot into an environment where permissions haven’t really been taken care of for years”.
Documents shared with “everyone” in 2017, open team sites, inherited access on folders nobody remembered. People had always had those rights. Before, exercising them required knowing where to look. Retrieval removed that. Microsoft responded with what it calls a blueprint for oversharing: find high-risk sites and files, restrict access first and fix it after, label sensitive content, govern sharing, and only then switch on, with SharePoint Advanced Management bundled into the licence to do it.
Goss’s summary is the rule for every retrieval project in this chapter: the better the retrieval tool, the better your information governance has to be.
Nobody’s permissions were broken by AI. They were already broken. Retrieval is the first thing that made it matter.
Go deeper5 panels · 2 sources
40%
of IT leaders piloting Microsoft 365 Copilot had delayed rollout by three months or more because of oversharing concerns. Gartner survey of 132 IT leaders, Jun 2024
64%
said information governance and security risks took significant time and resources to address before Copilot could be used. Gartner, Jun 2024
57%
limited the rollout to low-risk or trusted users while they cleaned up who could see what. Gartner, Jun 2024
What “oversharing” means
Copilot answers only from “the data users already have permission to access” (Microsoft). The problem is that permission. Years of “share with everyone”, open SharePoint sites and inherited access meant people had rights they never used. Search made them usable.
What the fix looks like
Microsoft’s own blueprint: find high-risk sites and files, restrict first and fix after, label sensitive content, govern sharing, then switch on. “The better the information retrieval tool, the better your information governance has to be.” (Gartner’s Max Goss.)
Three stories worth knowing.
Three stories, two from the evals half of this section and one from the hygiene half. The first is New York City’s MyCity business chatbot, announced by the mayor in October 2023 as a centrepiece of the city’s use of AI and built on Microsoft’s Azure AI services over material from the Department of Small Business Services. In March 2024 The Markup tested it. It said landlords did not have to accept housing vouchers; New York bans that discrimination.
It said employers could take workers’ tips, that restaurants could go cashless, and that funeral homes could hide prices; all wrong. It gave one reporter the right answer on vouchers and ten colleagues the wrong one, and often answered without links despite a disclaimer asking users to check them. The city called it a pilot and left it up. Everything about that is a retrieval-and-eval story: the right documents existed, the answers were not grounded in them, and it behaved as if nobody had run thirty known questions through it before launch.
The second is the Stanford study from earlier in this chapter. Legal publishers sold retrieval tools as hallucination-free. A 200-question evaluation found 17% to 34% of answers wrong or misgrounded, and neither vendor had published a benchmark or even a definition. The lesson is that “our RAG doesn’t hallucinate” is a claim about an eval the vendor should be able to show you. The third is the Copilot oversharing story from the section above: the search worked exactly as designed, over permissions that had not.
Three organisations with budgets, and in two cases famous names. None of them was stupid. Each skipped the boring step.
Go deeper3 panels · 3 sources
The city’s bot said: break the law.
A Microsoft Azure-based chatbot on New York City’s business portal told users landlords could refuse housing vouchers, employers could take workers’ tips, and restaurants could refuse cash. All illegal in New York. It gave different answers to the same question. Often no links. The city called it a pilot and kept it running.
“Hallucination-free” was never measured.
Two legal publishers sold retrieval-based research tools as avoiding hallucination. Stanford built a 200-question eval and found 17% to 34% of answers wrong or citing sources that did not support them. Neither vendor had published a benchmark or a definition.
Search found what the permissions allowed.
Enterprises piloting Microsoft 365 Copilot found it surfacing files staff technically had access to but had never seen. 40% of surveyed IT leaders delayed rollout by three months or more. Microsoft published a remediation blueprint.
Sources (3)
- https://themarkup.org/news/2024/03/29/nycs-ai-chatbot-tells-businesses-to-break-the-law
- https://hai.stanford.edu/news/ai-trial-legal-models-hallucinate-1-out-6-or-more-benchmarking-queries
- https://www.computerworld.com/article/3542000/microsoft-365-copilot-rollouts-slowed-by-data-security-roi-concerns.html
Who owns the test set?
These four are about ownership. The first is the one that stalls projects, and should: if nobody can write the right answers, nobody can say the system is right.
- Name the person who would write the thirty right answers. Do they have the time? Do they know they have been volunteered?
- Of the shared folders you know, which would you least like to be searchable by everyone who technically has access?
- If the chatbot gave a customer a wrong policy answer tomorrow, how would you find out, and how would you find the chunk?
- What does your vendor show when you ask for their eval results? A slide, or a spreadsheet of questions?
Use it Monday
Switch on what you already pay for, assemble if you must, build if you really must. And write the thirty questions before any of it.
Questions firstSwitch on, assemble, or build. Examples, not endorsements.
This is the one section with product names and prices, checked in October 2026 against vendor pages, and it will be wrong within months, so treat it as a map of the columns rather than a price list. The first column is switch on: retrieval already exists inside the suites most organisations pay for. Microsoft 365 Copilot is sold as an add-on; the list price is $30 per user per month, and in October 2026 the small-business page offered a promotional tier at $18 per user per month on annual billing, or $25.20 monthly, grounded in the tenant’s mail, files and chats.
Google’s Gemini Enterprise is a per-seat subscription with connectors to Drive, Gmail, OneDrive, SharePoint, ServiceNow, Jira and Confluence; list prices were $21 to $30 per seat per month at launch, so check the current page. ChatGPT Projects and Claude Projects give you files plus instructions on free tiers, with Claude switching to retrieval on paid plans when files outgrow the window. The connected ones inherit your existing permissions, and a file you upload by hand carries whatever you give it, which is the point of the oversharing section above. The second column is assemble: a managed retrieval service plus a model, wired up by your team.
OpenAI’s vector stores chunk, embed and index uploaded files, with a gigabyte free and $0.10 per gigabyte per day after that. Amazon Bedrock Knowledge Bases offer fixed, hierarchical and semantic chunking with a default of about 300 tokens. Azure AI Search has hybrid keyword-plus-vector queries built in. pgvector adds vector search to Postgres you may already run. Your team owns chunking, permission filtering and re-indexing.
The third column is build: your own pipeline and your own adapters, with LoRA and QLoRA tooling, the API vendors’ distillation workflows, or the local models Part XII will cover. Do this only with an eval set, a named owner, and evidence on paper that the first two columns failed.
Whatever column you pick, the test set, the permissions and the person who owns the index are not in the box. They never are.
Go deeper3 panels · 8 sources
Switch on
Retrieval inside suites you already pay for. Microsoft 365 Copilot: $30 per user per month list; an $18–25.20 small-business promotional tier. Google Gemini Enterprise: per seat, connectors to Drive, SharePoint, Jira, Confluence. ChatGPT and Claude Projects: files + instructions, free tiers included. Fastest. Inherits your permissions for connected sources, for better and worse; a file you upload by hand carries whatever you give it.
Assemble
A managed retrieval service plus a model, wired by your team. OpenAI vector stores (1 GB free, then $0.10/GB/day), Amazon Bedrock Knowledge Bases (default ~300-token chunks), Azure AI Search (hybrid built in), pgvector if you already run Postgres. You own chunking, permissions and re-indexing. Weeks.
Build
Your own pipeline, your own adapters. LoRA / QLoRA via open tooling; distillation workflows from the API vendors; local models, which Part XII covers. Only with an eval set, a named owner, and a job the first two columns failed on paper. Months, and it is yours to maintain.
Sources (8)
- https://www.microsoft.com/en-us/copilot/pricing/business
- https://cloud.google.com/gemini-enterprise/faq
- https://help.openai.com/en/articles/10169521-projects-in-chatgpt
- https://support.claude.com/en/articles/9517075-what-are-projects
- https://developers.openai.com/api/docs/guides/retrieval
- https://docs.aws.amazon.com/bedrock/latest/userguide/kb-chunking.html
- https://learn.microsoft.com/en-us/azure/search/hybrid-search-overview
- https://github.com/pgvector/pgvector
What to do on Monday, in this order.
Write 30 real questions. With answers.
From the helpdesk and the inbox. Five with no answer in your documents. A named person writes the right answer and the section it lives in. This is the whole job; everything else is a change you can now measure.
Try the zero-engineering version.
A Project: the current policy documents, one paragraph of instructions, three worked examples. Run the 30. Write the score down. That is your baseline, and for many teams it is also the finished product.
Measure before you buy.
Correct, grounded, retrieved, refused, seconds, cents. When a vendor says “our RAG doesn’t hallucinate”, hand them the 30 questions and wait.
Then decide if you need retrieval.
Over ~500 pages, changing weekly, or different audiences? Retrieve. Before switching anything on: who can see what, in the source system, today?
Never fine-tune before evals.
If the only evidence is a demo, it is not evidence. Adapters are for form the prompt could not fix, proven on the scorecard. Facts stay in the index. Nobody pretrains.
Manners in the weights. Truth in the retrieval. And a score, before and after, or you are guessing in a nicer font.
The five, in fullprose version
Write thirty real questions with answers: pull them from the helpdesk and the inbox, include five that your documents cannot answer, and have a named person write the correct answer and where it lives. That is the test set, and it is most of the work. Try the zero-engineering version: a Project with the current documents, a paragraph of instructions and three worked examples; run the thirty and write the score down.
That is your baseline, and for a surprising number of teams it is also the product. Measure before you buy: the six numbers from section four, and when a vendor says their retrieval does not hallucinate, hand them the thirty questions.
Then, and only then, decide whether you need retrieval at all. The signs are more than about five hundred pages, changing weekly, or different people who should see different things. Before switching anything on, find out who can see what in the source system today, because the search will. Finally, never fine-tune before evals. An adapter is for a behaviour the prompt could not fix, proven on the scorecard, and facts stay in the index. Part I said almost nobody should pretrain.
Nothing since has changed that.
Put the facts where it can find them, with a name and a date. Teach it manners only if the prompt could not. Score the job before and after. Clean up who can see what, first.
Build the exam before the student.
Retrieval knobs: the six settings that move the hit rate.
Open the appendixfor the nerds · optional
For the people who will actually build the pipeline, these are the settings that move the retrieval-hit number, roughly in the order to try them. Chunk size and boundaries first: a few hundred tokens is the common default, Amazon’s managed service uses about 300 aligned to sentences, and cutting on headings and paragraphs beats any fixed number. Hierarchical chunking matches small child chunks and returns the larger parent; semantic chunking uses a model to find topic breaks.
Contextual chunks next: before embedding, prepend a sentence or two saying where the chunk sits in its document. Anthropic reported top-20 retrieval failures falling from 5.7% to 3.7% from this alone. The cost is one cheap model call per chunk at index time. Hybrid search with rank fusion: run keyword search and vector search in parallel and merge by reciprocal rank fusion; Azure AI Search does this in a single query, and Anthropic’s figure with contextual BM25 added is 2.9%.
Then reranking: retrieve generously, say 150 chunks, and let a reranker model score each against the question, keeping 20; Anthropic’s figure with reranking is 1.9%, and the cost is latency, so watch the slow tail. Metadata filters are where access control, dates and status live, and they should be applied before ranking, not after. Finally the embedding model itself: OpenAI’s current models produce 1,536 or 3,072 numbers per chunk and can be shortened; changing models means re-embedding everything, so pin the version and record it alongside the index.
The discipline is the same as the rest of the chapter: change one knob, re-run the thirty, read the retrieval-hit column.
Change one knob, re-run the 30. The retrieval-hit column tells you if it worked before the model ever answers.
Chunk size and boundaries
A few hundred tokens is typical (Bedrock defaults to ~300, sentence-aligned). Fixed-size with overlap is the crude baseline; hierarchical (child chunks matched, parent returned) and semantic chunking exist. Cut on headings and paragraphs before you tune numbers.
Contextual chunks
Prepend a one- or two-sentence summary of where the chunk sits in its document before embedding it. Anthropic: top-20 retrieval failures 5.7% → 3.7% with contextual embeddings alone. Costs one cheap model call per chunk at index time.
Hybrid + rank fusion
Run BM25 keyword search and vector search in parallel; merge with reciprocal rank fusion. Azure AI Search does it in one query. Anthropic: 5.7% → 2.9% with contextual BM25 added.
Top-k and reranking
Retrieve more than you need (e.g. 150), then a reranker model scores each against the question and keeps the top 20. Anthropic: 5.7% → 1.9%. Adds latency; measure p95.
Metadata filters
Filter before ranking on date, status (“current”), audience and permissions. OpenAI’s vector stores and most services expose attribute filters. This is where access control lives.
Embedding model and dimensions
OpenAI’s text-embedding-3-small is 1,536-dimensional, -large 3,072, both shortenable. Changing the embedding model means re-embedding everything; pin the version and record it with the index.
Sources (5)
- https://docs.aws.amazon.com/bedrock/latest/userguide/kb-chunking.html
- https://www.anthropic.com/news/contextual-retrieval
- https://learn.microsoft.com/en-us/azure/search/hybrid-search-overview
- https://developers.openai.com/api/docs/guides/retrieval
- https://developers.openai.com/api/docs/guides/embeddings
Adapter arithmetic: why LoRA is small and QLoRA fits.
Open the appendixfor the nerds · optional
For the curious, the reason a thin adapter is thin. Inside a model are many weight matrices, and a typical one in a mid-sized model might be 4,096 by 4,096, which is about seventeen million numbers. Fully fine-tuning means updating all of them, in every matrix, and holding gradients and optimiser state for each, which is why the memory bill is several times the size of the model.
LoRA leaves that matrix frozen and adds two thin ones: B, which is 4,096 by r, and A, which is r by 4,096, where r is a small number called the rank, typically between 4 and 64. The model uses the frozen matrix plus the product of the two thin ones. With r equal to 8 that is about 65,000 trainable numbers in place of seventeen million, under half a per cent, and the same saving applies in every matrix you adapt.
The paper reports ten thousand times fewer trainable parameters than full fine-tuning of GPT-3 175B, roughly a third of the GPU memory, no added latency, and quality on par; the adapter can be merged back into the weights for serving. QLoRA attacks the other term: holding the frozen base at all.
Part II’s rule of thumb is parameters times bits divided by eight, so a 65-billion-parameter model at 16-bit precision is 130 GB just for the weights; stored at 4-bit it is about 33 GB, which fits a single 48 GB GPU with room for the adapter and its optimiser state. Dettmers and colleagues add a 4-bit number format tuned to how weights are distributed, a second round of quantisation on the quantisation constants, and paged optimisers to survive memory spikes, and report matching 16-bit results on their benchmarks.
Small adapter, frozen base, your examples. The arithmetic is why a serious laptop can do it. The evals are why most of them shouldn’t.
# One weight matrix inside the model, say 4096 x 4096 full = 4096 * 4096 # 16.8M numbers per matrix if you train it all # LoRA: freeze W; train thin B (4096 x r) and A (r x 4096); use W + B@A (4096 x 4096 again) r = 8 # the "rank"; 4-64 is typical lora = 4096 * r + r * 4096 # 65,536 numbers: about 0.4% of full, per matrix # QLoRA: same adapter, but W is stored in 4-bit instead of 16-bit w16_GB = 65e9 * 16 / 8 / 1e9 # 65B at 16-bit: 130 GB just for the weights w4_GB = 65e9 * 4 / 8 / 1e9 # at 4-bit: ~33 GB. Fits one 48 GB GPU + adapter
Building software? Part VIII follows straight on from this one; come back to VII for media and robots.
All parts