BOOK DEEP READ · Generative AI System Design Interview · Chapter 4
Generative AI System Design Interview · Ch 4 · Ali Aminian, Hao Sheng & Alex Xu · 2024
You type a line into a chat box and something writes back like an assistant. This chapter is about the steps between a machine that has read most of the written world and that assistant — and those steps have almost nothing to do with making it know more.
The freshly built machine already knows a great deal, but it does not answer you. Ask it "how do I soft-boil an egg" and it may well continue: "how do I soft-boil an egg? how do I fry one? how do I…" — because all it ever learned was to continue: see half a sentence, guess the rest. And on the internet, a question is very often followed by another question. It isn't unable to answer; nobody ever told it that being asked means answering.
So write rules? The trouble is that "a good answer" cannot be written down as rules: lead with the conclusion or not, how long, ask a clarifying question or not, when to refuse outright — the answer changes with every request. It is the kind of thing you recognise instantly but cannot specify.
Step one: have people demonstrate. Pay people to write good answers to a batch of questions by hand, and let the machine imitate them — like a new hire reading a folder of examples. The catch is plain: demonstrations are slow and expensive to write, and tens of thousands of them still cannot cover everything people ask.
Step two: have people judge. Let the machine write several versions of the same answer, and ask a person only which one is better. Picking is ten times faster than writing, and two people agree far more often about "which is better" than about "what score does it deserve". Feed those picks to a second machine and you get a scorer: hand it an answer, it hands back a number.
Step three: practise against the scorer. The machine writes, the scorer grades, the machine shifts a little towards higher scores, over and over. People no longer sit in the loop — their judgment already lives inside the scorer.
One more thing matters: a leash. It is not allowed to drift far from what it was. Without the leash it learns to please the scorer rather than do the job — discovering, say, that longer answers score higher, and padding every reply from then on.
It can only look at one small stack of paper at a time, so a long conversation stops fitting: either the earlier turns get boiled down into a summary, or the important things you once said get written into a notebook and looked up when needed. It also can't do big arithmetic and doesn't know today's news — so it has to learn one more habit: when the job is beyond it, ask for a tool. The system looks something up or computes it, hands the result back, and the machine carries on.
One honest cost: the same training that makes it obedient also makes it eager to agree — saying "you're right" where it should say "your premise is wrong". Flattery is the shadow of that leash. You cannot remove it, only manage it.
What it has read decides what it knows; these later steps decide how it is willing to talk to you — and since "well said" has no right answer, the only way in is people picking, again and again, between two versions.
Want the mechanisms, the notation and the diagrams? → Switch to the deep read
You think the hard part of ChatGPT is making the model smarter; in fact the knowledge is largely fixed by the end of pretraining. What this chapter actually solves is an objective mismatch — pretraining teaches "predict the next token", while the product needs "follow the instruction, answer the way people prefer, refuse when it must". The answer is three stages (pretraining → supervised fine-tuning → preference alignment), and the engineering intuition behind it fits in one line: when "good" cannot be written as a loss function, turn human pairwise comparisons into a scorer you can optimise against.
The third of the ten case studies in Part II. It follows Ch3 on translation — there at least a reference translation exists; here there is no reference answer at all, so evaluation has to be replaced wholesale. It leads into Ch5 on image captioning, pushing generation beyond plain text. In the real world it maps to ChatGPT, Claude and Gemini, and to any product backend built from multi-turn dialogue, tools and a safety boundary.
Pretraining has exactly one objective: given what came before, predict the next token — so what it learns is what internet text tends to look like next, and on the internet a question is often followed by another question, an ad, a table of contents. The characteristic failure of a base model is therefore not "can't", it is answering beside the point, or continuing the list of questions.
The second difficulty is that "good" cannot be defined. Translation has a reference; code has tests. A good resignation letter has infinitely many forms, and its quality depends on length, tone, whether to ask a clarifying question, whether it oversteps — none of which reduces to a rule or a single labelled answer.
The third is that safety becomes a system requirement for the first time: a fluent model states harmful content just as fluently. The failure mode is being wrong fluently, not throwing an error.
What happens if you skip all this? You get a knowledgeable model nobody can use: unstable formatting, instruction-following by luck, and one sentence away from saying what it shouldn't. The whole chapter is about turning "can talk" into "gets things done and stays inside the lines".
Pretraining buys knowledge and language: unlabelled text at the trillion-token scale, and the overwhelming majority of the compute. Supervised fine-tuning (SFT) buys format and intent: human-written "instruction + ideal reply" demonstrations drag the output distribution onto the "answering" side. It is cheap and fast, and its ceiling is obvious — demonstrations must be written one at a time, and they can only say "this is right", never "that one is worse".
Preference alignment buys ranking: people write nothing, they only pick the better of several replies the model produced itself. Throughput is an order of magnitude higher, and the signal is exactly the one SFT cannot give. The design in one line: write demonstrations while you can, and switch to picking when you can't.
The recipe: sample several replies per prompt (commonly 4–9), have people rank them, and train a scoring model on those pairs with a blunt objective — the chosen reply must score above the rejected one.
Why comparisons rather than scores? Because absolute scores are not comparable across people: the same reply gets a 3 from a strict annotator and a 5 from a lenient one, and the noise swamps the signal, while agreement on "is A or B better" is far higher. This is the one piece of methodology worth taking away: when no absolute standard exists, step back and ask only for relative judgments.
The cost lives in the same place: the reward model is only a finite fit to human preference, and its own biases — toward length, toward pretty formatting, toward a confident tone — are amplified faithfully by the next step.
The RL loop is: the policy model generates → the reward model scores → the weights move a small step toward higher scores. PPO's "small step" matters, but the KL penalty in the objective matters more: it measures how far the new output distribution has drifted from the frozen SFT reference, and charges for the distance.
Without it, the model attacks the reward model rather than pleasing people: if long answers score higher it pads endlessly, if boilerplate scores higher every sentence becomes boilerplate — while other capabilities quietly degrade, a loss known as the alignment tax. The KL coefficient is therefore the knob that matters most here: too small and it drifts, too large and it barely learns.
A sense of cost: in Microsoft's published DeepSpeed-Chat numbers, a 13B model finishes all three stages on 8 A100s in about 13.6 hours, of which PPO alone takes 10.8. The bulk of alignment compute is not reward-model training, it is that sample–score–update loop — which is also the heaviest to engineer: policy, reference, reward and value models all sit in GPU memory at once.
The naive approach re-assembles the whole history into the prompt every turn. The problem isn't forgetting, it is arithmetic: 500 tokens a turn and 20 turns is 10k tokens; attention cost grows with the square of length (double the length, roughly quadruple that part of the cost) while KV-cache memory grows linearly and every concurrent session holds its own copy — what you hit first is usually not the context limit but the concurrency your GPU memory allows.
So real systems split "memory" into layers: the system prompt (fixed, cacheable), recent turns verbatim (the last k, preserving tone and reference), compressed history (a rolling summary of everything earlier), plus an optional long-term memory: stable user preferences written to external storage and retrieved on demand.
Two traps that get overlooked: summarisation is lossy and irreversible — what it drops cannot be asked for later; and information sitting in the middle of a long context is more likely to be ignored, so put what matters first or last.
Three things a model is structurally bad at: events after its training cutoff, exact computation, and private data it has never seen. One answer covers all three — have it emit a structured call request, let the system execute it, feed the result back into the context, and let generation continue.
Three things to watch in production. Latency: every tool round-trip is one full forward pass plus the tool's RTT, so two or three of them take you from a few hundred milliseconds to several seconds; cap the number of rounds and fire independent calls in parallel. Reliability: models call the wrong tool and invent arguments, so validate arguments against a schema and have retries and a fallback script. Trust boundary: once tool output is in the context it sits next to the user's instructions — this is exactly where prompt injection comes in, so external content must be labelled by origin and never granted instruction authority.
Safety is three layers stacked: refusal behaviour trained in with safety preference data, an input-side classifier that blocks clearly disallowed requests, and an output-side pass on the way out. Streaming makes the third layer hard — the text is already on the screen and retracting it is expensive, so you either validate in delayed chunks or accept the "emit then withdraw" experience.
Evaluation has to be replaced too: perplexity barely correlates with user satisfaction. The workable combination is human pairwise comparison (blind A/B, ranked by win rate or Elo) + LLM-as-judge (the same pairwise verdicts at scale — cheap and repeatable, but with position bias and a length preference that has to be corrected, e.g. by swapping order) + red teaming + online signals (thumbs-up rate, regeneration rate, human-handoff rate).
And one product-level trade-off you cannot dodge: over-refusal. Raise the safety threshold and violations fall, but the share of legitimate requests that get refused rises — the most typical "hurts at both ends" curve in alignment.
Table 1 · What each of the three stages buys
| 1 · Pretraining | 2 · SFT | 3 · Preference alignment | |
|---|---|---|---|
| Data | Unlabelled text | Instruction + human-written reply | Rankings over several replies |
| Scale | Trillions of tokens | Thousands to tens of thousands of demos | Tens to hundreds of thousands of comparisons |
| Cost per item | Zero (scraped) | Highest: a person must write it | Cheap: pick one of two |
| Buys | Knowledge and language | Format, intent, basic voice | Preference, tone, refusal boundary |
| Stop here and… | It continues text, doesn't answer | It mimics demos, never learns "which is better" | — |
| Cost | Nearly all the compute; redoing it is brutal | Ceiling set by demo quality | Unstable, prone to reward hacking, alignment tax |
Table 2 · Four routes to alignment
| SFT only | RLHF · PPO | DPO | RLAIF / constitutional | |
|---|---|---|---|---|
| Reward model? | No | Yes, scoring online | None trained separately; optimise on pairs directly | Yes, but labels generated by a model from written principles |
| Engineering | Lowest | Highest: four models in GPU memory | Close to SFT | Medium; cost sits in writing and checking principles |
| Labelling cost | Every item written by hand | People only rank | Same, and public preference sets can be reused | People write principles; labelling scales |
| Risk | Unstable refusal boundary and style | Drift, alignment tax, hard to reproduce | Offline only; no exploration, and a shifted distribution can't self-correct | The model's own bias is written into the standard; vague principles, vague behaviour |
| Fits | Narrow verticals on a budget | Pushing a general assistant to the top | The default starting point for most teams | Many safety rules, auditability required |
Table 3 · Four ways to hold conversational memory
| Full concatenation | Sliding window | Rolling summary | Retrieved long-term memory | |
|---|---|---|---|---|
| Cost vs turns | Linear in tokens, quadratic in attention | Capped | Capped, plus one summarisation call per turn | Capped, plus one retrieval RTT |
| What's lost | Nothing | Everything outside the window; references break | Detail, lossily and irreversibly | Whatever retrieval misses may as well not exist |
| Fits | Short sessions, one-shot support | Casual chat, weak context coupling | Long sessions needing a consistent persona | Remembering a user across sessions |
| In practice | Picking one is the wrong question: system prompt + last k turns verbatim + a rolling summary of the rest + retrieval on demand, all four stacked. | |||
This skeleton reaches well past chatbots: every product whose quality only a human can judge looks like this — copy generation, coding assistants, support QA, AI review. Fix format with demonstrations, fix preference with pairwise comparisons, scale human judgment with a stand-in scorer, then watch like a hawk for the day the stand-in gets over-optimised.
The most valuable sentence in an interview: translate "the model answers badly" into "what went wrong with our preference signal". Saying "this bad case isn't missing knowledge, it's a reward model that prefers long answers, so I'd add a batch of 'short and correct beats long and correct' pairs" carries far more weight than naming architectures.
1.4 hours on 8 A100-80G (about $45), OPT-13B in 9 hours on 64 of them (about $290). Alignment itself isn't the expensive part; that third-stage loop is.microsoft/DeepSpeedExamples · DeepSpeed-Chat ↗SFTTrainer, RewardTrainer, DPOTrainer and GRPOTrainer side by side. The three-stage skeleton holds; the algorithm inside stage three had already turned over by the time the book shipped.huggingface/trl README ↗1. The chapter solves an objective mismatch: pretraining teaches "predict the next token"; the product needs instruction-following, preferred answers and refusal.
2. A base model's characteristic failure isn't inability, it's continuing the list of questions — it learned to continue, not to answer.
3. The three stages buy different things: knowledge, then format and intent, then "which version is better".
4. The methodology to keep: with no absolute standard, ask only for relative judgments — people agree far more on "A or B" than on "what score".
5. The reward model is a stand-in for people, and its biases get amplified faithfully by the step that follows.
6. The KL penalty is the leash on that stand-in: too loose and you get reward hacking, too tight and nothing is learned — the alignment tax lives in that tension.
7. Compute: pretraining dominates overall, but inside alignment the expensive part is PPO's sample–score–update loop.
8. Memory is not one technique but four layers: system prompt + last k turns verbatim + rolling summary + retrieval on demand.
9. Tool calling covers the training cutoff, exact computation and private data — at the price of pushing the trust boundary into the context, where prompt injection enters.
10. Sign-off means pairwise comparison + LLM judges + red teaming + online signals; the safety threshold and over-refusal are two ends of one curve.