▚ The AI Engineer's Field Manual
Module 05 · Act II — ML Foundations

NLP & Transformers — How Machines Read

"Language is structured ambiguity. Attention is the mechanism that resolves it — and everything in Act III is built on top of it."

~6 hours Builds on: Module 04 Tools: tiktoken · Hugging Face · PyTorch · Anthropic API Job-spec line it unlocks: "Strong understanding of Transformer architectures"

01 · The hook8,000 Tickets a Day and the Queue Is on Fire

How a machine reads: text becomes numbers, numbers become vectors that carry meaning, and attention lets every word look at every other word to work out what it means here.

Field report · Client memo

"Our support team receives 8,000 tickets a day across email, chat, and the web portal. 45% of agent time goes to manually tagging and routing — clicking category dropdowns instead of solving problems.

Median time-to-first-touch is 4.2 hours, which means a 'production database is down' ticket can sit behind forty password resets. I need a system that reads every ticket and assigns intent and urgency in under 100 milliseconds.

And I need to know whether we build it with our own model or rent one by the token."

— Maya Lin, Chief Customer Officer at "HelpDeskAI"

Your first instinct after nine years of engineering is probably a keyword rule engine: if "refund" in text → Billing. That instinct fails within a week, because language doesn't behave like log lines. "I don't hate the new UI, but the payment gateway is broken" is a payment outage wearing a compliment. "Can you fix my password?" contains "fix" — the classic incident word — but it's a routine account request. Negation, sarcasm, synonyms, and domain jargon shred any rule set you can maintain.

This module is the bridge module of the whole course. Everything in Act III — prompting, RAG, agents, fine-tuning — assumes you know how machines turn text into numbers and how self-attention lets every word borrow meaning from every other word. You'll build that machinery from scratch, watch the pre-transformer approach fail on a paraphrase, then solve Maya's problem twice: once by fine-tuning a small transformer that runs on a CPU, and once by prompting a frontier LLM over an API — and you'll produce the cost/latency/quality report that tells her which to ship.

You already know this

Every piece of this module maps onto something you've shipped before. A tokenizer is a lexer: it turns a character stream into a token stream before any real processing happens.

An embedding is a locality-preserving index for meaning — like a geohash, where nearby keys mean nearby things, except "nearby" means "semantically similar".

And self-attention is a soft hash-map lookup: every token issues a query, every token exposes a key, and instead of returning the single best match, the lookup returns a weighted blend of all the values.

Q/K/V is a key-value store where the match score is a dot product and the result is a mixture.

The bridge above names query, key and value before they have been explained. That is deliberate. Section 02 builds the intuition for them with a spotlight picture, and section 04 has you compute them by hand on three tokens. Nothing here needs to be memorized yet.

02 · The intuitionWords → Vectors → Attention

Maya's memo left one job and three numbers: 8,000 tickets a day, 45% of agent time lost to tagging, and under 100 milliseconds to read each ticket. Nothing you have built so far reads text at all. Before a single ticket can be routed, you need to know how a machine turns "prod Postgres cluster throwing 500s" into numbers it can multiply. This section walks the three ways the industry has done that, oldest first, because the oldest one is still the baseline the new thing has to beat.

NLP went through three eras, and each one fixed the previous one's blind spot. You need all three, because era one is still the right production baseline for plenty of problems — and knowing when it's enough is a senior-engineer skill.

Era 1 — Counting: bag-of-words and TF-IDF

Start where Maya's team would start, and where you should start on any text problem: count the words. It trains in about two seconds and predicts far faster than her queue fills. We build it here so every later model has a number to beat, and so you can see exactly which of her 8,000 daily tickets it gets wrong.

The oldest trick: forget order, count words. A document becomes a sparse vector of word counts.

TF-IDF sharpens the counts: term frequency (how often a word appears in this document) multiplied by inverse document frequency (a penalty for words that appear in every document).

"The" appears everywhere, so its IDF collapses to zero; "refund" and "postgres" are rare and informative, so they dominate the vector.

Feed those vectors to the logistic regression you met in Module 02 and you have a text classifier that trains in seconds and predicts at 10,000+ tickets per second.

You have not been taught scikit-learn's text tools yet, and you are not expected to know them. Guess first, then check. Every line in the table below is explained in the step-by-step list above the code. The ideas behind TF-IDF are in the paragraphs you just read, and again in section 09.

Sharpen your pencil

Below are eleven lines lifted from tfidf_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. A wrong guess costs nothing and tells you exactly which line to slow down on.

from sklearn.feature_extraction.text import TfidfVectorizerbring in the tool that turns each ticket into a list of word counts, with common words weighted down
random.seed(42)fix the random number generator so every run builds the same 1,200 tickets
texts.append(random.choice(TEMPLATES[cat]).format(id=random.randint(1000, 9999)))
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.2, random_state=42, stratify=labels)
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True)
LogisticRegression(max_iter=1000)
clf = Pipeline([("tfidf", ...), ("logreg", ...)])
clf.fit(X_tr, y_tr)learn from the training tickets which weighted word counts go with which category
print(classification_report(y_te, clf.predict(X_te)))
clf.predict([ticket])[0]
clf.predict_proba([ticket])[0].max()
Check your answers
from sklearn.feature_extraction.text import TfidfVectorizerbring in the tool that turns each ticket into a list of word counts, with common words weighted down
random.seed(42)fix the random number generator so every run builds the same 1,200 tickets
texts.append(random.choice(TEMPLATES[cat]).format(id=random.randint(1000, 9999)))pick one of the category's four template sentences, fill its {id} slot with a random four-digit number, and add the result to the list of tickets
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.2, random_state=42, stratify=labels)hold back 20% of the tickets as a test set the model never trains on; stratify keeps the three categories in the same proportions in both halves
TfidfVectorizer(ngram_range=(1, 2), sublinear_tf=True)count single words and adjacent word pairs, and replace each raw count with 1 + log(count), so a word repeated twenty times does not weigh twenty times as much
LogisticRegression(max_iter=1000)the classifier from Module 02, allowed up to 1,000 rounds of fitting so the solver has room to settle
clf = Pipeline([("tfidf", ...), ("logreg", ...)])chain the two steps into one object, so that fitting or predicting on raw text runs the vectorizer first and the classifier second
clf.fit(X_tr, y_tr)learn from the training tickets which weighted word counts go with which category
print(classification_report(y_te, clf.predict(X_te)))predict a category for every test ticket and print precision, recall and F1 for each of the three categories
clf.predict([ticket])[0]classify one new ticket; the input list has one element, so take the first (and only) prediction out of the result
clf.predict_proba([ticket])[0].max()the probability the classifier assigns to its chosen category, so you can see how confident a wrong answer is

If you guessed that the vectorizer counts words and that fit learns from the training half, you already have the shape of the file. The two lines that matter most are the last two. They ask the classifier about a ticket written in words it has never counted, and that is where this era of NLP breaks.

Step-by-step: what tfidf_baseline.py does, in plain English
  1. Bring in random for building the toy dataset, and five pieces of scikit-learn: the TF-IDF vectorizer, logistic regression, a scoring report, a train/test splitter, and Pipeline, which chains steps into one object.
  2. Define TEMPLATES: three categories, four ticket sentences each. The {id} slot will be filled with a random number so the tickets are not exact copies of each other.
  3. Fix the random seed at 42 so every run builds the same 1,200 tickets. Then loop 1,200 times: pick a category, pick one of its templates, fill the slot, and store the text with its label.
  4. Split the tickets 80/20 into training and test sets. stratify=labels keeps the three categories in the same proportions in both halves.
  5. Build a two-step pipeline. Step one turns text into TF-IDF vectors: ngram_range=(1, 2) counts adjacent word pairs as well as single words, and sublinear_tf=True replaces a raw count with 1 + log(count), so repeating a word does not multiply its weight.
  6. Step two is the logistic regression from Module 02, with max_iter=1000 so the solver has room to converge.
  7. clf.fit runs both steps in order: learn the vocabulary and word weights from the training texts, then fit the classifier on the resulting vectors.
  8. Predict a category for every test ticket and print precision, recall and F1 per category.
  9. Write one new ticket in words the templates never used, predict its category, and print the probability of the chosen class. This last line is the one whose output carries the lesson.
tfidf_baseline.pyruns offline
# pip install "scikit-learn>=1.5,<2"
"""HelpDeskAI baseline: TF-IDF + logistic regression. Trains in ~2 s on a laptop."""
import random
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

TEMPLATES = {
    "Billing": [
        "I was double charged on invoice {id}, need this reversed",
        "Payment failed but my card still shows an active charge",
        "Where do I download the VAT receipt for order {id}?",
        "Requesting a refund for the annual license renewal",
    ],
    "Technical": [
        "Database connection pool exhausted, error {id}",
        "API endpoint /v1/users returning 500 internal server error",
        "Production CPU pinned at 99 percent since the deploy",
        "Container keeps restarting, OOM-killed after {id} seconds",
    ],
    "Account": [
        "Password reset email never arrives",
        "How do I add a teammate with admin permissions?",
        "Please update our SSO domain and billing address",
        "Requesting GDPR data export and account deletion",
    ],
}

random.seed(42)
texts, labels = [], []
for _ in range(1200):
    cat = random.choice(list(TEMPLATES))
    texts.append(random.choice(TEMPLATES[cat]).format(id=random.randint(1000, 9999)))
    labels.append(cat)

X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.2,
                                          random_state=42, stratify=labels)

clf = Pipeline([
    ("tfidf", TfidfVectorizer(ngram_range=(1, 2),   # bigrams catch "double charged"
                              sublinear_tf=True)),  # 1+log(tf): 20× "error" ≠ 20× the signal
    ("logreg", LogisticRegression(max_iter=1000)),
])
clf.fit(X_tr, y_tr)
print(classification_report(y_te, clf.predict(X_te)))

ticket = "URGENT: prod Postgres cluster throwing 500s and timing out"
print(clf.predict([ticket])[0], f"{clf.predict_proba([ticket])[0].max():.2%}")
# → perfect 1.00 on the held-out test set… then "Account" at 67% on this
#   OBVIOUS outage ticket. "Postgres", "throwing", "timing" never appear in
#   the training vocabulary — counting has nothing to count. Section 05
#   dissects exactly this failure.

Read that output twice. The classifier is flawless on its test set — template tickets share exact vocabulary with their category, which is precisely the world where counting wins — and then confidently misroutes a production outage written in words it hasn't seen. That gap between benchmark and reality is the defining failure of the counting era. Hold that thought.

The picture below is that whole failure in one frame, with the numbers the script printed. Marker 1 is the vocabulary it learned and the perfect score it earned on its own test set. Marker 2 checks the real ticket word by word against that vocabulary. Marker 3 is the answer it returns anyway.

1 WHAT COUNTING LEARNED 1,200 template tickets 904 words in its vocabulary held-out test: 240 tickets precision 1.00 · recall 1.00 F1 1.00 in all three classes flawless — inside its own vocabulary 2 MONDAY'S TICKET, WORD BY WORD "URGENT: prod Postgres cluster throwing 500s and timing out" urgent not in vocabulary prod not in vocabulary postgres not in vocabulary cluster not in vocabulary throwing not in vocabulary 500s not in vocabulary and known — and worthless timing not in vocabulary out not in vocabulary 8 of the 9 words are unknown 1 non-zero feature out of 904 3 THE ANSWER IT GIVES ANYWAY what predict_proba returns: Account 0.6727 Technical 0.1822 Billing 0.1452 bar length = probability (1.00 would be 260 px) the outage now waits behind the password resets, 4.2 hours deep
Fig. 5.0b — Why the baseline's perfect score is a lie. Every number here is printed by tfidf_baseline.py: 1.00 on the 240 held-out tickets, then "Account" at 67.27% for a database outage, because exactly one of that ticket's nine words — "and" — exists in the 904-word vocabulary it learned.
  1. The vocabulary is the whole model. Fitting the vectorizer on 1,200 template tickets produced a list of 904 words. That list is the model's entire idea of language. A word that is not on the list cannot be counted, cannot be weighted, and therefore cannot contribute one thing to the answer.
  2. The real ticket lands almost entirely outside it. The outage ticket has nine words. Eight of them — urgent, prod, postgres, cluster, throwing, 500s, timing, out — never appeared in a template, so they score zero. The one survivor is "and", and in the training tickets it appears only in Account tickets, so to this model it is an Account word, not a neutral one.
  3. A nearly empty vector still gets a confident label. Logistic regression has to return a probability for all three classes, and they have to add up to 1. Its one surviving feature, "and", was learned only from Account tickets, so it prints Account 0.6727 as if it had read the ticket. Confidence is not evidence; it is just the largest of three numbers that were forced to sum to one.

Era 2 — Meaning: word embeddings

Counting just sent a production outage to the Account queue with 67% confidence, because eight of the nine words in that ticket were missing from its vocabulary. Maya cannot ship that. What her classifier needs is for "Postgres" and "database" to already sit near each other before any classifier looks at them. That nearness is what an embedding buys, and this is the era that invented it.

Counting treats "refund" and "reimbursement" as unrelated dimensions — orthogonal axes in a 50,000-dimensional space. Word embeddings (word2vec, GloVe, ~2013) fixed that by learning a dense vector per word such that words appearing in similar contexts end up close together. The space develops real geometry: the famous party trick is vector("king") − vector("man") + vector("woman") ≈ vector("queen") — the "royalty" direction and the "gender" direction are actual, reusable directions in the space.

But static embeddings have a ceiling: one vector per word, forever. Consider "bank". In "we fished off the river bank" and "the bank declined my card", word2vec hands you the same vector both times — a smeared average of the geology sense and the finance sense, correct for neither. Meaning depends on context, and a lookup table has no context.

Both halves of that story are drawn below: what the space gives you on the left, and where it runs out on the right.

1 MEANING BECOMES A PLACE billing words refund reimbursement cash back account words password login infrastructure words database server postgres near = used in the same company of words, learned from raw text 2 ONE STEP, REUSED woman queen man king the same "+ royalty" step king − man + woman ≈ queen 3 THE CEILING: ONE VECTOR PER WORD we fished off the river bank the bank declined my card bank one row, always both senses collapse into one smeared average
Fig. 5.0c — What a word embedding buys, and where it stops. Words used in similar company end up in similar places (marker 1), and the offsets between places are reusable directions (marker 2) — but every word still owns exactly one vector, so "bank" gets a single smeared answer in both sentences (marker 3). Positions in the left map are drawn by hand to show the geometry; only the grouping is the claim.
  1. The neighbourhood. An embedding is a list of numbers per word, learned so that words appearing in similar company end up close together. "Refund", "reimbursement" and "cash back" land in one region without anyone declaring them synonyms. That closeness is exactly what the counting baseline lacked when eight of nine ticket words scored zero in Fig. 5.0b.
  2. The direction. Because positions are learned from context, the step from "man" to "king" turns out to be roughly the same step as from "woman" to "queen". Directions in the space carry meaning of their own, which is why the arithmetic king − man + woman lands near queen. It is a party trick, but it is evidence that the geometry is real and not decoration.
  3. The ceiling. Both sentences on the right contain "bank", and word2vec answers both with the same row of the same table. The vector it returns is an average of the river sense and the finance sense, which describes neither. No amount of extra training fixes this, because the lookup never sees the sentence. Removing this ceiling is the entire job of the next era.

Era 3 — Context: self-attention

Embeddings put "refund" and "reimbursement" near each other, but they still hand back one fixed vector per word, forever. Plenty of Maya's tickets use "charge", "down" or "bank" in a sense only the sentence settles. To route them inside her 100-millisecond budget, the model has to read each word in its context. Attention is the mechanism that does that, and every module after this one sits on top of it.

The transformer's answer (2017, "Attention Is All You Need"): stop reading left-to-right like the RNNs and LSTMs before it — which forgot word 1 by word 50 thanks to the vanishing gradients you met in Module 04 — and instead let every word look at every other word simultaneously.

Picture a theater stage: when the model processes "crashed", a spotlight sweeps across the whole sentence and brightens on the words that matter for this word's meaning. "Crashed" lights up "database" and "server"; the filler word "the" barely glows.

The spotlight's brightness settings are the attention weights, and the model learns them from data.

The server crashed because the database timed out .03 .22 .08 .05 .03 .41 .18 crashed · query asks every token: "how relevant are you to my meaning here?" 1 2 weights sum to 1 3 small weight
Fig. 5.1 — One attention head, one query: "crashed" scores every token in the sentence; softmax turns the scores into weights that sum to 1, and "database" wins the spotlight. Line thickness = weight.
  1. The asking token (marker 1). Only one word is asking here: "crashed". It sends a question to every token in the sentence, including itself, and the question is always the same one — how much does your content belong in my meaning right now. Every other token asks its own version of this at the same time; the picture draws one of the seven for legibility.
  2. The weights (marker 2). The seven small numbers under the tokens are what comes back: .03, .22, .08, .05, .03, .41, .18. They are all positive and they add up to 1, because softmax makes them do that. "Database" takes .41 of the spotlight and the filler "the" gets .03. Nothing is ever zero, which is why the model can still be nudged by a word it currently ignores.
  3. The thickness (marker 3). Each arrow is drawn as thick as its weight, so the shape of the answer is visible before you read a single number. A thin arrow means that token contributes almost nothing to this word's new vector. The output is not the arrows; it is the blend they describe, which is computed by hand in Fig. 5.2c.

The output of attention for "crashed" is a new vector: a weighted blend of every token's value vector, dominated by "database" and "server". That blend is a contextual embedding — the same word, re-mixed by its sentence. Run "bank" through a transformer and it gets a river-flavored vector in the fishing sentence and a finance-flavored vector in the card sentence. Era 2's ceiling, gone.

Split the text into tokens.

Look up a vector for each one.

Let every token attend to the ones that matter.

Blend what it found into a new vector.

Predict the next token.

Split the text: the pieces in Fig. 5.2b, where "the team rethinks refunds" becomes six tokens. Look up a vector: the row lookup at marker 4 of Fig. 5.2. Let every token attend: the arrows in Fig. 5.1, where "crashed" sends a thick arrow to "database" and a thin one to "the". Blend: the weighted sum at marker 5 of Fig. 5.2c, which turns [0.5, 2] into [0.3616, 1.8964]. Predict the next token: the dashed "next?" box on the right of Fig. 5.4.

🧠 Brain power

Before reading on: take the tickets "the app is not working after the update" and "the app is working, not after the update it wasn't". Which of the three eras can tell these apart, and why?

Reveal the answer

Only era 3. TF-IDF sees nearly identical bags of words — same tokens, same counts — so the vectors are nearly identical (bigrams like "not working" help a little, which is why we used ngram_range=(1,2), but this doesn't scale to arbitrary reorderings).

Static embeddings average the same word vectors regardless of position, so they collapse too.

Self-attention, combined with positional information, produces a different contextual vector for "working" depending on whether "not" attends to it — word order and negation finally become signal instead of noise.

03 · Tokenizers, properlyWhat a "Word" Actually Is

You have the three eras and a picture of attention. Before you can compute one, you have to know what a "word" is to a model, because it is not a word. This matters to Maya twice over. The pieces decide what her classifier can generalise to, and the same pieces are the unit every vendor bills her for, 8,000 tickets a day, every day.

Everything above says "word", and that was a lie. Models don't see words — they see tokens, and the difference explains half of the weird LLM behavior you'll debug in Act III, plus your entire API bill.

"Why can't the model just read the words? I have written parsers. A string is a string. Why the whole tokens-and-numbers ceremony?"

— a backend engineer who has shipped three parsers, right about now

Because a neural network is arithmetic and nothing else. Every layer you met in Module 04 multiplies numbers by learned weights and adds them up. A letter has no arithmetic: you cannot multiply "r" by 0.3. So before anything happens, text must become numbers, and the only open question is how.

The tokenizer is the "how", and the four boxes of Fig. 5.2 are the whole of it. It cuts the text into pieces it has seen before (marker 2) and gives each piece an integer id (marker 3). That id selects one row from a table of numbers, the embedding table (marker 4), which the network learned during training. Your parser produces a syntax tree that the program then walks. The tokenizer produces a list of ids that the network then multiplies. Same job, different consumer.

The honest downside is marker 3 again. Once a piece has become the number 101, nothing downstream can look inside it. That is why counting the letters in "strawberry" fails, drawn as three sealed boxes at marker 2 of Fig. 5.2b, and why a typo quietly makes the input rarer and worse. It is also why the same sentence costs a different number of tokens on every vendor's model. The next paragraphs explain why the pieces are subwords rather than whole words or single characters.

Why not whole words? A word-level vocabulary either explodes (every typo, plural, and database_timeout_err_500 needs its own entry) or hits unknowns constantly. Why not characters? Sequences get 5× longer and attention cost grows with the square of sequence length.

The industry answer is Byte-Pair Encoding (BPE), and the intuition is compression: start with raw bytes as your vocabulary, scan a giant corpus, and repeatedly merge the most frequent adjacent pair into a new vocabulary entry.

t+h→th, th+e→the… run ~100,000 merges and you get a vocabulary where common words are single tokens, rare words split into reusable chunks ("unbelievable" → un·belie·vable — statistical pieces, not tidy morphemes), and nothing is ever out-of-vocabulary — the worst case is falling back to bytes.

A typo like "unbeleivable" doesn't crash anything; it just becomes a rarer, uglier token sequence, which is one reason typos quietly degrade model quality.

raw text what you write BPE merges subword tokens learned from corpus stats vocab lookup token ids integers, ~100k vocab row lookup embeddings what the net sees "Where's my refund?!" Where |'s | my | refund |?! [9241, 596, 856, …] 5 rows × 768 floats the network never sees letters — only rows of the embedding table, one per token id 1 2 3 4
Fig. 5.2 — The tokenization pipeline. Text becomes subword pieces, pieces become integer ids, ids select rows of a learned embedding matrix. Everything downstream — attention included — operates on those rows.
  1. Raw text (marker 1). The string as the customer typed it, punctuation and typos included. This is the last point at which letters exist.
  2. Subword pieces (marker 2). The merge rules cut the string into pieces the vocabulary already contains. The cuts are decided by corpus statistics, not by grammar, which is why they often fall in the middle of a word.
  3. Token ids (marker 3). Each piece is looked up in a table of about 100,000 entries and replaced by its integer position. From here on the model is handling row numbers, and a row number carries no information about the letters that produced it.
  4. Embedding rows (marker 4). Each id selects one row of a learned matrix — 768 numbers per row in the DistilBERT you will fine-tune later. Those rows are the first thing in this whole course that a neural network can actually multiply.
BE the tokenizer

Your turn to play the machine. A BPE tokenizer owns nothing but a list of merges, learned in order from a corpus. To split a word, start from single letters and apply the merges in list order: rule 1 everywhere it fits, then rule 2, and so on. A rule only fires where its two pieces sit next to each other as whole pieces. Once th exists, the t inside it can no longer pair with anything else. Here is a toy merge list, ten rules long.

  1. t + h → th
  2. th + e → the
  3. r + e → re
  4. f + u → fu
  5. n + d → nd
  6. fu + nd → fund
  7. re + fund → refund
  8. i + n → in
  9. th + in → thin
  10. k + s → ks

The sentence: the team rethinks refunds. With a pencil, split the, rethinks and refunds into tokens using only those ten rules, and write down how many tokens each word becomes. Then guess: does the real tokenizer that tokens_up_close.py loads cut rethinks into re and thinks?

Check your answer

the is t h e. Rule 1 joins t and h into th. Rule 2 joins th and e into the. One token.

refunds is r e f u n d s. Rule 3 makes re, rule 4 makes fu, rule 5 makes nd, rule 6 joins fu and nd into fund, and rule 7 joins re and fund into refund. No rule touches the final s. Two tokens: refund and s.

rethinks is r e t h i n k s. Rule 1 makes th. Rule 2 cannot fire, because no e follows that th. Rule 3 makes re, rule 8 makes in, rule 9 joins th and in into thin, and rule 10 makes ks. Three tokens: re, thin, ks.

Look at that last one. The tidy split a person would make is re + think + s. The tokenizer made re + thin + ks, because in its toy corpus "thin" earned a merge and "think" did not. It has no idea what a word is. It only knows which letter pairs it saw most often.

Now the real thing. cl100k_base, the GPT-4-era vocabulary that tokens_up_close.py loads, turns "the team rethinks refunds" into six tokens: the, ␣team, ␣re, th, inks, ␣refunds (␣ marks a leading space). It made the same cut after "re" that your toy did, then produced "th" and "inks", which are not word parts in any dictionary. "refunds" survived whole because it is common on the web.

Two details are worth keeping. The space is glued to the front of the token after it, so "␣refunds" and "refunds" are different ids. And capitals change the cut: "Refunds" becomes Ref + unds. Tokens are statistics about a corpus, not units of meaning, and rare spellings pay for that on every API bill.

Step-by-step: what tokens_up_close.py does, in plain English
  1. Import tiktoken, OpenAI's tokenizer library. It ships the exact merge tables the GPT models use, so what it prints is what those models see.
  2. Load the cl100k_base vocabulary, about 100,000 tokens. Newer OpenAI models use o200k_base; the mechanism is the same, the cuts differ.
  3. Define show(text): encode the text into a list of integer ids, then decode each id back to its bytes so you can see the pieces.
  4. Print the text, how many tokens it became, and the pieces, lined up in columns.
  5. Call show five times: an ordinary sentence, a long word, the same word with a typo, "strawberry", and a Japanese word. Each one demonstrates a different consequence listed under the code.
  6. Count the tokens in one realistic ticket, multiply by 8,000 tickets a day, and price the result at $1 per million input tokens. The point is that the ticket text is cheap; the prompt wrapped around it is what costs.
tokens_up_close.pyruns offline
# pip install "tiktoken>=0.8"
"""What the model actually sees. First run downloads the BPE vocab file (~2 MB)."""
import tiktoken

enc = tiktoken.get_encoding("cl100k_base")   # GPT-4-era vocab; newer models use o200k_base

def show(text):
    ids = enc.encode(text)
    pieces = [enc.decode_single_token_bytes(i) for i in ids]
    print(f"{text!r:24} → {len(ids):>2} tokens  {pieces}")

show("Where's my refund?!")
show("unbelievable")             # → [b'un', b'belie', b'vable'] — meaningful chunks
show("unbeleivable")             # typo → different, rarer pieces; nothing crashes
show("strawberry")               # → [b'str', b'aw', b'berry'] (splits vary per vocab)
show("ラズベリー")                # non-Latin text → raw bytes → MORE tokens per character

# Tokens are also the billing unit. English averages ~4 characters per token:
ticket = "My payment gateway is returning intermittent 502 errors since Tuesday."
n = len(enc.encode(ticket))
daily = n * 8_000
print(f"\n{n} tokens/ticket → {daily:,} tokens/day for HelpDeskAI's queue")
print(f"at $1 per 1M input tokens (claude-haiku-4-5, Aug 2026): ${daily / 1e6:.2f}/day raw")
# The ticket text is nearly free. The few-shot prompt you wrap around EVERY
# ticket is what costs money — we'll count that in the lab.

Here is that output drawn on the three sentences the script prints. Marker 1 is an ordinary English sentence, marker 2 is "strawberry", marker 3 is the Japanese word. Every cut shown is the one cl100k_base actually makes.

1 CHARACTERS IN, PIECES OUT t h e ␣ t e a m ␣ r e t h i n k s ␣ r e f u n d s 25 chars the ␣team ␣re th inks ␣refunds 6 tokens "rethinks" is cut re · th · inks — not re · think · s. The space is glued to the front of the piece after it. 2 THREE SEALED BOXES s t r a w b e r r y 10 chars, 3 of them r str aw berry 3 ids 3 ids in — the r's are sealed inside them "Refunds" is cut Ref · unds — different ids again 3 NON-LATIN TEXT COSTS MORE ラ ズ ベ リ ー 5 characters 6 tokens more tokens than characters: the merges were learned from mostly English text, so this falls back to raw bytes
Fig. 5.2b — The tokenizer drawn on real input, using the cl100k_base cuts tokens_up_close.py prints. Twenty-five characters become six tokens, and the cut inside "rethinks" lands in a place no dictionary would choose (marker 1). "Strawberry" becomes three ids (marker 2). Five Japanese characters become six tokens (marker 3).
  1. The cuts are statistics, not grammar (marker 1). "␣team" and "␣refunds" survive whole because they are common on the web, while "rethinks" shatters into ␣re · th · inks. The space belongs to the piece that follows it, so "␣refunds" and "refunds" are two different ids with two different rows.
  2. Sealed boxes (marker 2). The three r's of "strawberry" sit inside the ids for "str" and "berry", and no layer downstream can open them. Asking the model to count letters asks it to read something it was never given.
  3. The bill in another language (marker 3). Five characters producing six tokens is worse than one token per character, and English prose averages about four characters per token. The same ticket text can therefore cost two to three times more to send in Japanese than in English, with no change to its meaning.

Three consequences worth tattooing somewhere:

🧠 Brain power

Before reading on: BPE merges are learned from corpus frequency. What happens to tokenization efficiency — and therefore cost — when your domain text (medical notes, Solidity code, log files) looks nothing like the web text the vocabulary was trained on?

Reveal the answer

Domain terms that never appeared in the training corpus never earned merges, so they shatter into many small tokens. hydrochlorothiazide might be 6–8 tokens; a stack-trace line can be dozens. Sequences get longer, costs rise, and effective context shrinks. This is why some domain-specific models train their own tokenizers — and why, in Module 11, "tokenizer mismatch" appears on the fine-tuning checklist.

04 · Build it yourselfSelf-Attention in 40 Lines of NumPy

Maya's tickets are now token ids, and you can price them. What is still only a story is attention itself: "every word looks at every other word" is a sentence, not a mechanism. So you compute one attention head by hand on three tokens, then run the same arithmetic in 40 lines of NumPy on "the server crashed the database". After this section the thing that will route her queue is no longer a black box.

The spotlight analogy becomes real when you compute it. Here's a single attention head on a 5-token sentence, with hand-crafted 4-dimensional embeddings so you can read the weight matrix like a story. No frameworks — just matrix multiplies and a softmax, the same two operations you trained in Module 04.

Sharpen your pencil

Compute one row of attention by hand, once, and the code below becomes obvious. Three tokens, two numbers each. The two positions are invented: the first means "filler word", the second means "infrastructure noun". The asking token is crashed.

Use the recipe the code uses. Score every token by a dot product with the asker and divide by √2, since d is 2 here. Then turn the scores into weights with softmax: e to the power of each score, divided by the sum of the three.

the = [2, 0] · database = [0, 2] · crashed = [0.5, 2]the three embeddings; the query is "crashed"
score(crashed → the) = (0.5×2 + 2×0) ÷ √21 ÷ 1.4142 = 0.7071
score(crashed → database) = (0.5×0 + 2×2) ÷ √2
score(crashed → crashed) = (0.5×0.5 + 2×2) ÷ √2
e^score for each of the threee^0.7071 = 2.0281 for "the"; now the other two
weights = each e^score ÷ the sum of all three
new vector for crashed = Σ weight × embedding

Work to four decimal places. Then answer: which token does "crashed" pull most of its new meaning from, and how far does its own vector move?

Check your answers
score(crashed → the)1 ÷ 1.4142 = 0.7071
score(crashed → database)4 ÷ 1.4142 = 2.8284
score(crashed → crashed)4.25 ÷ 1.4142 = 3.0052
e^score2.0281, 16.9188, 20.1903; they sum to 39.1373
weightsthe 0.0518 · database 0.4323 · crashed 0.5159 (they sum to 1.0000)
new vector for crashed0.0518×[2, 0] + 0.4323×[0, 2] + 0.5159×[0.5, 2] = [0.1036 + 0 + 0.2579, 0 + 0.8646 + 1.0318] = [0.3616, 1.8964]

Read the weights as a spotlight. "crashed" keeps about half of itself (0.516), takes 43% of its new meaning from "database", and gives "the" 5%. The filler word got a small but non-zero share, which is normal: softmax never sends a weight to exactly zero. The new vector moved from [0.5, 2] to [0.36, 1.90], a little less filler-like and a little more like "database".

Two things to carry into the code. First, the division by √2 mattered. Without it the scores would be 1, 4 and 4.25, and the weights would be 0.021, 0.429 and 0.550, more extreme. At d = 64, the size real models use per head, skipping it pushes softmax to almost all-or-nothing and the gradients die.

Second, the weights are a by-product. The output of attention is the blended vector, and that vector is the contextual embedding from section 02.

Here is that same arithmetic drawn end to end, left to right, with your four-decimal answers on it. Read it as one journey: three tokens go in on the left, and one new vector for "crashed" comes out on the right.

1 THE THREE TOKENS 2 SCORE = DOT ÷ √2 3 e TO THE SCORE 4 WEIGHTS 5 OUTPUT the [2, 0] database [0, 2] crashed [0.5, 2] "crashed" is the one asking dim 1 = filler, dim 2 = infra 0.5×2 + 2×0 = 1 ÷ 1.4142 = 0.7071 0.5×0 + 2×2 = 4 ÷ 1.4142 = 2.8284 0.5×0.5 + 2×2 = 4.25 ÷ 1.4142 = 3.0052 √2 because d = 2 here 2.0281 16.9188 20.1903 sum 39.1373 exponent first, then share the 0.0518 database 0.4323 crashed 0.5159 they add up to 1.0000 [0.3616, 1.8964] the new "crashed" it went in as [0.5, 2] 0.0518 × [2, 0] + 0.4323 × [0, 2] + 0.5159 × [0.5, 2] = [0.3616, 1.8964] "crashed" keeps about half of itself, takes 43% of its new meaning from "database", and hands the filler word 5%. Softmax never returns exactly zero, so even "the" moves the answer a little.
Fig. 5.2c — One attention head, computed. Every number on this path is the arithmetic you just did by hand: scores 0.7071, 2.8284 and 3.0052; weights 0.0518, 0.4323 and 0.5159; output [0.3616, 1.8964]. Only the two embedding dimensions are invented, to keep the multiplication small enough to read.
  1. Dot, then divide (marker 2). The dot product is the whole similarity test: multiply the matching positions and add. Dividing by √2 shrinks the spread of the scores, and at the d = 64 that real models use per head, skipping it pushes softmax to an almost all-or-nothing answer with no slope left to learn from.
  2. Exponentiate, then share (markers 3 and 4). Raising e to each score makes every number positive and pulls the big ones further ahead. Dividing each by the total of 39.1373 turns them into shares of one spotlight, which is what "weights sum to 1" means.
  3. The output is the blend, not the weights (marker 5). The three weights multiply the three token vectors and the results are added, giving [0.3616, 1.8964]. That vector is the contextual embedding for "crashed" in this sentence: slightly less filler-like and noticeably more database-like than the [0.5, 2] that went in.
Step-by-step: what attention_from_scratch.py does, in plain English
  1. Import NumPy. No framework, on purpose: the whole mechanism is two matrix multiplies and a softmax.
  2. Name the five tokens of the sentence.
  3. Type in E, one 4-number embedding per token. The four positions are invented: filler, infrastructure noun, failure verb, data noun. Both "the" rows are identical, because a lookup table gives the same token the same vector every time.
  4. Set W_q, W_k and W_v to the identity matrix, so Q, K and V simply equal E. A trained model learns these three matrices with gradient descent; identity is the simplest choice that still lets you watch the mechanism move.
  5. Compute scores = Q @ K.T / np.sqrt(d): every token's query dotted with every token's key, a 5 × 5 table, divided by √4 = 2 to keep the numbers modest.
  6. Turn each row into weights with softmax: exponentiate every score, then divide each row by its own sum, so every row adds up to 1. axis=1 means "per row"; per column would be wrong.
  7. Print the table with token names on both axes. A row is the token asking; a column is the token being looked at.
  8. Compute context = weights @ V: each token's new vector is its row of weights times the value vectors, a weighted blend of everyone's content.
  9. Print "crashed" before and after. The after vector has moved toward "database" and "server". That moved vector is the contextual embedding.
attention_from_scratch.pyruns offline
# pip install "numpy>=2.0"
"""One self-attention head, from scratch, on a 5-token sentence."""
import numpy as np

tokens = ["the", "server", "crashed", "the", "database"]

# Hand-crafted 4-d embeddings. Invented dims: [filler, infra-noun, failure-verb, data-noun]
E = np.array([
    [2.0, 0.0, 0.0, 0.0],   # the
    [0.0, 2.0, 0.4, 0.2],   # server
    [0.0, 0.8, 2.0, 0.8],   # crashed
    [2.0, 0.0, 0.0, 0.0],   # the
    [0.0, 1.8, 0.6, 1.2],   # database
])
d = E.shape[1]

# Real models LEARN these three projections — that's what the gradient descent
# from Module 04 optimizes. Identity means "look for tokens similar to me",
# which is enough to watch the mechanism move.
W_q = W_k = W_v = np.eye(d)
Q, K, V = E @ W_q, E @ W_k, E @ W_v

scores = Q @ K.T / np.sqrt(d)                     # every token scores every token: n×n
weights = np.exp(scores)
weights /= weights.sum(axis=1, keepdims=True)     # softmax rows → each row sums to 1

print("attention weights (row = who is asking, cols = who they attend to)\n")
print("          " + "".join(f"{t:>10}" for t in tokens))
for t, row in zip(tokens, weights):
    print(f"{t:>10}" + "".join(f"{w:10.2f}" for w in row))

context = weights @ V     # each token's NEW vector: a weighted blend of all values
print("\n'crashed' before:", E[2].round(2))
print("'crashed' after: ", context[2].round(2))

# The 'crashed' row ≈ [0.04, 0.14, 0.55, 0.04, 0.24]: it keeps half of itself
# and pulls a quarter of its meaning from 'database'. The 'the' row attends
# to the OTHER 'the' (≈ .42 each) — filler finds filler, content finds content.
# That blended output vector IS a contextual embedding.

Run it and stare at the matrix. Two things to internalize. First, attention is learned similarity search: with identity projections it degenerates to raw cosine-style similarity, and the whole point of the trained WQ, WK, WV matrices is to let the model learn what kind of similarity to look for — one head learns syntax, another coreference, another "which entity does this verb act on". Second, the score matrix is n×n: every token against every token. Double your context length, quadruple the attention work. That quadratic is why context windows are expensive, why long-context pricing exists, and why the KV cache (Module 12) was invented.

The second point is the one that shows up on every bill, so here it is drawn. On the left is the score table the script prints for five tokens; on the right is what that table costs as the text gets longer.

1 EVERY TOKEN SCORES EVERY TOKEN the server crashed the database the server crashed the database 0.42 0.06 0.06 0.42 0.06 0.05 0.38 0.17 0.05 0.36 0.04 0.14 0.55 0.04 0.24 0.42 0.06 0.06 0.42 0.06 0.04 0.27 0.21 0.04 0.44 25 cells for 5 tokens — one per pair every row adds up to 1 2 DOUBLE THE TEXT, QUADRUPLE THE WORK tokens in the window score cells (n × n) 5 25 10 100 128 — the cap in finetune_distilbert.py 16,384 1,000 1,000,000 n = 5 n = 10 the area is the work: twice the tokens costs four times as much this square is why long context is priced the way it is
Fig. 5.2d — The attention bill. The table on the left is exactly what attention_from_scratch.py prints for "the server crashed the database"; the list on the right is the same table's size as the sequence grows, and the cell counts are just n × n.
  1. Rows ask, columns answer (marker 1). Row three is "crashed" asking, and it is the row you computed by hand. Row one and row four are identical because both are the word "the", which is the giveaway that this toy has no position information yet.
  2. The table is the cost (marker 2). The model fills in one number for every ordered pair of tokens, so 5 tokens need 25 and 128 tokens need 16,384. Nothing here depends on how long the model is, only on how long the text is.
  3. Why it is charged the way it is. Doubling the input quadruples this table in both time and memory, per layer and per head. That single fact explains long-context pricing, the 128-token truncation in the fine-tuning script, and the key-value cache that Module 12 unpacks.
Anatomy of attention — the one line to know by heart (numbered in the order the computer evaluates it)
Attention(Q, K, V) = softmax4( Q1 · Kᵀ2 / √d3 ) · V5
  1. Q, the queries. One row per token, meaning "what am I looking for?". It is the token's embedding multiplied by a learned matrix WQ. In attention_from_scratch.py that matrix is the identity, so Q equals E; in a trained model it is not. The mistake: treating Q as the raw embedding, then wondering why a real model attends to tokens that look nothing like the asker.
  2. Kᵀ, the keys, transposed. Each token's "what do I contain?", WK times the embedding, laid on its side so the multiply lines up. Q is n × d and Kᵀ is d × n, so the product is n × n: every asker against every token. The mistake: forgetting the transpose, which either raises a shape error or, when the shapes happen to be square, silently computes the wrong table.
  3. √d, the divisor. d is the length of each key vector: 4 in the file, 64 per head in most real models. Dot products grow with d, and large scores push softmax toward all-or-nothing. Dividing by √d keeps the scores in the range where softmax still has a slope to learn from — it is the "÷ 1.4142" step at marker 2 of Fig. 5.2c, which turned a raw 4.25 into 3.0052. The mistake: dividing by d instead, or dropping the term because the toy works without it.
  4. softmax, per row. Turns each row of scores into weights that are positive and sum to 1. It runs after the three steps inside the brackets. In NumPy it is exp, then divide by the row sums with axis=1. The mistake: normalizing down the columns instead, which makes each column sum to 1 and every row meaningless.
  5. · V, the values. Each token's "here is my content", WV times the embedding. Multiplying the weights by V hands every token a weighted average of everyone's values. The mistake: reading the weight table as the output. The weights are a by-product you print for debugging; the output is this blended vector, one per token, the same shape as the input.

Questions you might be asking now

The pencil row, the 40-line script and the one-line formula above move fast. The questions below slow down for the four places first-time readers most often get stuck. Every answer reuses the three tokens from the pencil exercise, so every number can be checked by hand.

The three tokens every answer below uses. The two positions are invented, exactly as in the pencil exercise: position 1 means "filler word" and position 2 means "infrastructure noun". The ids are row numbers in a toy vocabulary.
TokenToy id (row number)Embedding row [filler, infra]What the numbers say
the0[2, 0]All filler, no infrastructure
database1[0, 2]No filler, all infrastructure
crashed2[0.5, 2]Mostly infrastructure, a little filler
Is an embedding the same thing as a token? The page uses both words for what goes into attention.

No. A token is a piece of text, and its id is only a row number. The embedding is the row of numbers stored at that row. "crashed" is always id 2 and always the row [0.5, 2]; only after attention does it become [0.3616, 1.8964] in one ticket and [0.2720, 2.0000] in another.

The mix-up is fair. The page uses the two words a sentence apart, and it uses "embedding" for more than one thing. Walking one ticket through the first stations of Fig. 5.2 pulls them apart. Take the ticket "the database crashed" and the toy vocabulary in the table above.

  1. Cut the text into tokens. The ticket becomes three pieces: the, database, crashed. A token is still text. This toy cuts at spaces; a real tokenizer cuts wherever its learned merges say, as in Fig. 5.2b.
  2. Swap each token for its id. The ticket becomes [0, 1, 2]. An id is a row number and nothing more. Id 2 is not "more" than id 1; it is just further down the table.
  3. Fetch each id's row. Row 2 holds [0.5, 2]. That row is the token's embedding. The fetch never looks at the rest of the ticket, so id 2 returns [0.5, 2] in every ticket ever sent.
  4. Run attention. Each row is blended with the others. With the weights from the pencil exercise, "crashed" becomes 0.0518 × [2, 0] + 0.4323 × [0, 2] + 0.5159 × [0.5, 2] = [0.3616, 1.8964]. This new vector is the contextual embedding of "crashed".

Now send a shorter ticket, "database crashed". Steps A to C hand "crashed" exactly the same id and the same row, [0.5, 2]. Step D does not repeat itself. With no "the" to look at, "crashed" gives 0.4559 of its attention to "database" and 0.5441 to itself, and leaves as [0.2720, 2.0000].

TICKET TOKENS IDS EMBEDDING ROWS ATTENTION OUTPUT row numbers [filler, infra] crashed asks for crashed ticket 1 the database crashed the database crashed 0 1 2 [2, 0] [0, 2] [0.5, 2] 0.0518 0.4323 0.5159 [0.3616, 1.8964] 1 text becomes row numbers 2 same id, same row 3 different output ticket 2 database crashed database crashed 1 2 [0, 2] [0.5, 2] 0.4559 0.5441 [0.2720, 2.0000] the ids and rows never look at the rest of the ticket; attention is the first step that does
Fig. 5.2g — Two tickets through the first stations of a transformer. "crashed" gets the same id and the same embedding row in both (marker 2); only attention, which looks at the rest of the ticket, gives it a different vector in each (marker 3). Values from rerunning attention_by_hand.py.
  1. Text becomes row numbers. The tokenizer cuts the ticket into pieces and swaps each piece for its row number. No meaning is involved. "crashed" is id 2 because of where it sits in the toy vocabulary, not because of what it says.
  2. The fetch is blind to the ticket. Id 2 returns the row [0.5, 2] in ticket 1 and in ticket 2. That row is the embedding. It was fixed during training and is identical in every ticket, which is the one-vector-per-word ceiling of Fig. 5.0c.
  3. Attention is where the ticket enters. "crashed" asks the other tokens, gets different weights in each ticket, and leaves as a different vector: [0.3616, 1.8964] with "the" present and [0.2720, 2.0000] without it. That output is the contextual embedding the next layer receives.
Five things with similar names, side by side. The first four are the stations of Fig. 5.2g.
ThingWhat it isIn the tiny exampleIn the real models on this pageChanges with the other words?
TokenA piece of text cut by the tokenizercrashed␣re, th and inks in Fig. 5.2bNo
Token idThat piece's row number in the vocabulary2An integer from 0 to 30,521 in DistilBERTNo
Embedding (the row)The learned numbers stored at that row; also called a static or word embedding, like word2vec's in Fig. 5.0c[0.5, 2]768 numbers per row in DistilBERT (Fig. 5.5d)No: same id, same row
Contextual embeddingThe row after attention has blended in the other tokens[0.3616, 1.8964] or [0.2720, 2.0000]768 numbers per token after each of DistilBERT's six blocksYes
Sentence embeddingOne vector for a whole text, usually the average of its contextual embeddingsNot computed here384 numbers per sentence in paraphrase_gap.py (Fig. 5.2e)Yes

The toy simplifies two things. A real model adds a position vector to each row before attention (the "Add position" row of the stage table), so what enters attention is row plus position. And real rows are long: DistilBERT's table has 30,522 rows of 768 numbers. Neither changes the lesson.

A token is text, its id is a row number, and its embedding is the row stored there. Only the vector that comes out of attention knows which ticket it was in.

What are Q, K and V, really? In attention_from_scratch.py all three are just copies of E.

They are three views of each token, each made by multiplying its embedding by its own learned matrix. Q is what a token looks for, K is what it advertises, and V is what it hands over. Change only the key matrix, and "the" stops attending to itself (0.8482 becomes 0.0381) and looks at "database" instead (0.0501 becomes 0.6443).

In the script, WQ, WK and WV are the identity matrix: the matrix that changes nothing when you multiply by it. So Q, K and V are all copies of E, and every score is plain similarity between two embeddings. With identity matrices, "the" gives 0.8482 of its attention to itself, because a filler word is most similar to itself.

A trained model does not keep the identity. Training adjusts the numbers in all three matrices until the attention weights help the model predict well. Each matrix then has its own job:

  • Query, Q = embedding × WQ. What this token is looking for.
  • Key, K = embedding × WK. What this token advertises to every token that asks.
  • Value, V = embedding × WV. What this token hands over when it is picked.

A score is one token's query dotted with another token's key. Because a different matrix makes each, a token can score high against a token that looks nothing like it. To watch that happen, change only WK. The hand-made matrix below flips the sign of the filler position and leaves the infra position alone.

WK = [[−1, 0], [0, 1]]

In plain words: every token now advertises its filler-ness as a minus sign. A real WK is learned, not written by hand; this one was chosen so the arithmetic fits on a pencil. Here is the row for "the", with WQ and WV still the identity.

  1. Make the new keys. Multiplying by WK flips each row's first number: the [2, 0] becomes [−2, 0], database stays [0, 2], and crashed [0.5, 2] becomes [−0.5, 2].
  2. Dot the query of "the" with each key. The query is still [2, 0]. Against the: 2 × −2 + 0 × 0 = −4. Against database: 2 × 0 + 0 × 2 = 0. Against crashed: 2 × −0.5 + 0 × 2 = −1.
  3. Divide by √2 (1.4142). −4 ÷ 1.4142 = −2.8284; 0 stays 0; −1 ÷ 1.4142 = −0.7071.
  4. Softmax. e to each score gives 0.0591, 1.0000 and 0.4931, which total 1.5522. Dividing each by the total gives the weights 0.0381, 0.6443 and 0.3177.
  5. Blend the values. The values are still the embeddings: 0.0381 × [2, 0] + 0.6443 × [0, 2] + 0.3177 × [0.5, 2] = [0.2350, 1.9238]. With the rounded weights you get [0.2351, 1.9240]; the script uses the unrounded ones.
The same three tokens with identity keys and with flipped keys. Weights are listed in the order the, database, crashed.
Asking tokenIdentity WK (the pencil exercise)Flipped WKWhat changed
the0.8482 · 0.0501 · 0.10170.0381 · 0.6443 · 0.3177Stops looking at itself and looks at the noun
database0.0287 · 0.4856 · 0.48560.0287 · 0.4856 · 0.4856Nothing: its query [0, 2] has no filler part for the flip to meet
crashed0.0518 · 0.4323 · 0.51590.0156 · 0.5356 · 0.4488Now looks at "database" more than at itself
New vector for "the"[1.7472, 0.3036], still mostly filler[0.2350, 1.9238], now mostly infrastructureIt carries the noun's content instead of its own
IDENTITY KEYS: THE PENCIL EXERCISE "the" asks the 0.8482 1 database 0.0501 crashed 0.1017 "crashed" asks the 0.0518 database 0.4323 crashed 0.5159 new "the": [1.7472, 0.3036], still filler keys: the [2, 0], database [0, 2], crashed [0.5, 2] KEYS MADE WITH W_K = [[−1, 0], [0, 1]] "the" asks: now it looks at the noun the 0.0381 database 0.6443 2 crashed 0.3177 "crashed" asks: database now leads the 0.0156 database 0.5356 3 crashed 0.4488 new "the": [0.2350, 1.9238], now infrastructure keys: the [−2, 0], database [0, 2], crashed [−0.5, 2] same embeddings, same queries, same values, same softmax: only the keys changed
Fig. 5.2h — One hand-made key matrix, before and after. Left: identity keys, where "the" mostly attends to itself (marker 1). Right: keys made with WK = [[−1, 0], [0, 1]], where "the" looks at the noun (marker 2) and "crashed" now leans towards "database" (marker 3). Bar length is the attention weight; 1.0 would be 200 px. Values from rerunning attention_by_hand.py.
  1. Identity keys measure plain similarity. With Q = K = E, a score only says how alike two embeddings are. "the" is most like itself, so it keeps 0.8482 of its attention and leaves as [1.7472, 0.3036], still mostly filler. A head like this can never point a word at a different kind of word.
  2. The flip sends "the" to the noun. Its own key is now [−2, 0], so its self-score drops to −2.8284 and softmax shrinks that to 0.0381. "database" scores 0, the best in the row, and takes 0.6443. "the" leaves as [0.2350, 1.9238], carrying the noun's content.
  3. "crashed" changes its mind too. Its query has a small filler part, 0.5, which now meets minus signs. Its score for itself falls from 3.0052 to 2.6517, so "database" leads 0.5356 to 0.4488. "database" itself is untouched, because its query has no filler part.

And V? WV decides what is handed over, separately from who gets picked. attention_by_hand.py also tries a WV that keeps only the infra position. The weights stay exactly the same, and every output loses its filler number: "the" becomes [0, 1.9238]. Q and K choose where to look; V chooses what comes back.

The honest limit is the matrix itself. A trained WK is not a tidy sign flip. In DistilBERT it is 768 × 64 numbers per head (the stage table), and nobody chose them. Working out what a trained head does takes experiments, and many heads match no single neat rule. The toy shows only the mechanism.

Q is what a token looks for, K is what it advertises, and V is what it hands over, each made by its own learned matrix. With identity matrices, a head can only find tokens that look like the asker.

Why raise e to the power of each score? Why not just divide each score by the total of the scores?

Because scores can be negative, and then dividing by the total breaks. On the flipped-key row for "the", the scores −2.8284, 0 and −0.7071 total −3.5355, and plain division hands "the" 0.8 of the attention: the strongest "no" gets the biggest share. Softmax makes every number positive first, so the order survives: 0.0381, 0.6443 and 0.3177.

On the pencil row, plain division looks harmless. The scores 0.7071, 2.8284 and 3.0052 are all positive. Dividing each by their total, 6.5407, gives 0.1081, 0.4324 and 0.4595. That is not far from softmax's 0.0518, 0.4323 and 0.5159. The trouble starts once WQ or WK is learned, because a dot product can then be negative.

A negative score means "poor match". A weight means "this share of that token's content goes into my new vector". Whatever turns scores into weights has to keep three promises:

  1. No weight is below zero. A negative share would subtract a token's content from the new vector.
  2. The weights add up to 1. Then the new vector is an average of the values and stays in their range.
  3. A higher score never gets a lower weight. Otherwise the ranking the scores express is lost.
Plain division against softmax, on the two flipped-key rows from the previous answer and one two-score row. Weights are in the same order as the scores.
RowScoresTotalScore ÷ totalSoftmaxPromise plain division breaks
"crashed" asks the, database, crashed−0.7071, 2.8284, 2.65174.7730−0.1481, 0.5926, 0.55560.0156, 0.5356, 0.44881: "the" gets a negative weight
"the" asks the, database, crashed−2.8284, 0, −0.7071−3.53550.8000, 0.0000, 0.20000.0381, 0.6443, 0.31773: the ranking comes out upside down
Any row scoring −1 and +1−1, +10Division by zero0.1192, 0.88082: there is no share of a total of 0

Softmax keeps all three promises. Here it is by hand on the row for "the":

  1. Raise e to each score. e (about 2.7183) to the power −2.8284 is 0.0591; to the power 0 is 1.0000; to the power −0.7071 is 0.4931. All three are positive, because e to any power is above 0, and a bigger score always gives a bigger result.
  2. Add them up. 0.0591 + 1.0000 + 0.4931 = 1.5522. A total of positive numbers can never be zero or negative.
  3. Divide each by the total. 0.0591 ÷ 1.5522 = 0.0381; 1.0000 ÷ 1.5522 = 0.6443; 0.4931 ÷ 1.5522 = 0.3177. They add up to 1 (1.0001 after rounding), and database, the best score, gets the most.
1 THE SCORES: FLIPPED KEYS, "the" ASKING −3 −2 −1 0 +1 the −2.8284 crashed −0.7071 database 0 total −3.5355 2 PLAIN DIVISION: EACH SCORE ÷ THE TOTAL the strongest "no" gets the biggest share the −2.8284 ÷ −3.5355 = 0.8000 database 0 ÷ −3.5355 = 0.0000 crashed −0.7071 ÷ −3.5355 = 0.2000 3 SOFTMAX: e TO THE SCORE, THEN ÷ THE TOTAL same order as the scores the e^(−2.8284) = 0.0591, ÷ 1.5522 = 0.0381 database e^0 = 1.0000, ÷ 1.5522 = 0.6443 crashed e^(−0.7071) = 0.4931, ÷ 1.5522 = 0.3177 4 add 5 to every score: softmax gives the same three weights; plain division gives 0.1894, 0.4361, 0.3745
Fig. 5.2i — The row for "the" from the flipped-key example, turned into weights two ways. The scores are all "no" or "neutral" (marker 1). Plain division turns their ranking upside down (marker 2); softmax keeps it (marker 3) and ignores a shift shared by every score (marker 4). Bar length is the weight; 1.0 would be 300 px. Values from rerunning attention_by_hand.py.
  1. The scores. With the flipped keys, "the" scores its own key −2.8284, "crashed" −0.7071 and "database" 0. Every score is a "no" or a "neutral", and "database" is the least bad. Their total is negative, −3.5355, and that is where plain division goes wrong.
  2. Plain division. A negative score divided by a negative total comes out positive. So the worst match, "the" itself, receives 0.8000, and the best score, 0, receives nothing. The ranking comes out upside down, and no error is raised.
  3. Softmax. e to any power is positive, and a bigger score always gives a bigger result. So the ranking survives: "database" 0.6443, "crashed" 0.3177, "the" 0.0381. The total, 1.5522, is positive by construction, so there is never a division by zero.
  4. The shift test. Add 5 to every score. Softmax returns exactly the same weights, because e5 multiplies the top and the bottom of every fraction and cancels. Plain division returns 0.1894, 0.4361 and 0.3745: the order is now right, but the numbers moved although the question did not.

Nothing in a trained model pins its scores to a particular zero. That is why the shift test, marker 4 in Fig. 5.2i, matters.

Why e, and not 10? Any base above 1 keeps the three promises. Base 10 on the "crashed" row gives 0.0002, 0.6003 and 0.3996, sharper than base e. That is exactly softmax at temperature 0.4343, which is 1 ÷ ln 10 (ln is the natural logarithm): the temperature dial of Fig. 5.5c. e is the convention because the slope of ex is ex itself, which keeps the training arithmetic short.

Softmax has two costs. No weight is ever exactly zero, so "the" still receives 0.0381 however poor its score. And when scores are far apart, softmax hands almost everything to one token, which is the next question. The same function turns logits into probabilities in section 07: 2.0, 1.0 and 0.5 become 0.63, 0.23 and 0.14, where plain division would give 0.57, 0.29 and 0.14.

Softmax means: raise e to each score, then take each result as a share of their total. It keeps every weight positive, keeps the ranking, and sums to 1, whatever the signs of the scores.

What does dividing by √d actually do? The pencil row barely changed without it.

It keeps the spread of the scores near 1, however long the vectors are. At d = 2 it hardly matters: "crashed" keeps 0.5159 of its attention with the divide and 0.5502 without. At d = 64, the size of one head in DistilBERT, random scores spread 7.97 without it, and in 44.8% of rows one token takes over 0.99 of the attention. Divided by 8, no row does.

Start with why the spread grows. The letter d is the length of each query and key vector, and a dot product adds up d small products. When each is a random amount around ±1, the total of 64 typically lands about √64 = 8 from zero, not 64. Random amounts add up that way: the spread grows with the square root of the count.

Softmax reacts to the gaps between scores. A gap of 1 makes one weight e1 = 2.7 times the other; a gap of 8 makes it e8 = 2,981 times. So widely spread scores hand one token almost everything. That weight then sits near 1, where softmax is flat. Nudge the score and the weight barely moves, so training gets almost no signal to learn from.

10,000 random rows of five scores, from sqrt_d_saturation.py. Query and key entries are random numbers with a spread of 1, the usual stand-in for an untrained head. "Slope" is p × (1 − p) for the top weight p: how far it moves per unit of score, at most 0.25.
dDivide by √d?Spread of the scoresMedian top weightRows where one token gets over 0.99Average slope of the top weight
2No1.410.45410.5%0.2135
2Yes, ÷ 1.41421.000.38300.0%0.2189
64No7.970.982344.8%0.0702
64Yes, ÷ 81.000.43200.0%0.2306

Here is the first of those rows at d = 64, as the script prints it.

  1. Five raw scores. −0.74, −5.52, −9.99, −4.05 and −4.50. The top score beats the next one by 3.31.
  2. Softmax on the raw scores. 0.9358, 0.0079, 0.0001, 0.0343 and 0.0219. One token takes 94%. Its slope is 0.9358 × 0.0642 = 0.0600.
  3. Divide by √64 = 8. −0.09, −0.69, −1.25, −0.51 and −0.56. Same order, eight times closer together.
  4. Softmax again. 0.3173, 0.1746, 0.0999, 0.2099 and 0.1984. The same token still wins, every other token keeps a real share, and the top weight's slope is 0.2166.
d = 64, SCORES NOT DIVIDED 0.9358 0.0079 0.0001 0.0343 0.0219 −0.74 −5.52 −9.99 −4.05 −4.50 raw score under each bar, weight on top 1 one token takes 94% 2 the other four share 6% THE SAME SCORES ÷ 8 0.3173 0.1746 0.0999 0.2099 0.1984 −0.09 −0.69 −1.25 −0.51 −0.56 score ÷ 8 under each bar, weight on top 3 same winner, same order, the others keep 10% to 21% 10,000 random rows: top weight over 0.99 in 44.8% 10,000 random rows: top weight over 0.99 in 0.0%
Fig. 5.2j — One random row of five scores at d = 64, turned into weights without and with the divide. Left: one token takes 0.9358 (marker 1) and the rest sit on the flat tail of softmax (marker 2). Right: the same scores ÷ 8 keep the winner and the order but leave real shares (marker 3). Values from rerunning sqrt_d_saturation.py.
  1. One token takes almost everything. The top raw score beats the next by 3.31, and softmax turns that gap into 0.9358 against 0.0343. Before training has taught the head anything, it already ignores four of the five tokens.
  2. The ignored tokens have no slope. Their weights, 0.0079, 0.0001, 0.0343 and 0.0219, sit where softmax is almost flat, so nudging their scores barely moves them. The top weight's slope is 0.0600 here; over 10,000 rows it averages 0.0702, against 0.2306 with the divide.
  3. The same scores, divided by 8. The winner and the order do not change. The top weight is 0.3173 and the others keep between 0.0999 and 0.2099. Across all 10,000 rows no top weight passes 0.99, so every token still gets a learning signal.

Two limits. Trained vectors are not random, and a trained head can learn to be sharp when that helps. The divide sets a sensible starting spread; it is not a rule that weights stay soft. And at d = 2 the effect is small, which is why the pencil row worked either way. It matters at real sizes: 64 numbers per head in DistilBERT, which is 768 ÷ 12.

Dot products spread out like √d, so dividing by √d keeps the scores' spread near 1. Without it, long vectors make softmax pick one token and leave training nothing to adjust.

05 · Watch it breakWhere Counting Dies: the Paraphrase

The counting baseline scored a perfect 1.00 on its own test set and then sent a production outage to Account. That is the exact failure Maya is paying to remove, so now we reproduce it deliberately, on two short sentences, with a number attached to the damage. Once the size of the gap is visible, spending money on a transformer stops being a preference and becomes arithmetic.

Failure mode

TF-IDF matches spelling, not meaning. "Refund my money" and "give me my cash back" are the same customer intent with almost zero shared words — cosine similarity ≈ 0.11. Meanwhile "please refund my monkey" — one letter from sense, miles from it in meaning — scores ≈ 0.60 against the refund ticket. Your baseline literally prefers the monkey. Every synonym, paraphrase, and typo in Maya's 8,000 daily tickets is a hole in the counting net.

Two pictures of the same three sentences. On the left, the only thing counting can see; on the right, where a transformer puts them. The three numbers are the ones paraphrase_gap.py prints.

1 COUNTING COMPARES SPELLINGS the query please refund my money same intent, different words give me my cash back one word in common ("my") → cosine 0.11 one letter changed, different universe please refund my monkey three words in common → cosine 0.60 counting rates the monkey about six times closer than the paraphrase 2 MEANING COMPARES PLACES meaning space (384 numbers per sentence, drawn as two) please refund my money give me my cash back dot product 0.70 please refund my monkey honest caveat: embeddings also rate the monkey highly
Fig. 5.2e — The paraphrase gap, measured. Counting scores the paraphrase 0.11 and the one-letter distractor 0.60 (marker 1); sentence embeddings put the query and the paraphrase 0.70 apart on a scale where 1.00 is identical (marker 2). All three numbers come from paraphrase_gap.py.
  1. The overlap is all counting has (marker 1). "Please refund my money" and "give me my cash back" share exactly one word, "my", and it is a word every ticket contains. With nothing else in common the cosine lands at 0.11, which the classifier reads as "unrelated".
  2. The distractor wins on spelling (marker 1). Changing one letter of "money" leaves three of four words untouched, so the monkey sentence scores 0.60. Counting cannot tell a typo from a synonym, because it never had access to meaning in the first place.
  3. Meaning is a position, not an overlap (marker 2). A sentence embedding maps each sentence to a point, and points land near each other when the sentences are used the same way. The paraphrase comes back at 0.70 instead of 0.11, which is the difference between routing Maya's ticket and losing it.
Step-by-step: what paraphrase_gap.py does, in plain English
  1. Import the TF-IDF vectorizer and a cosine-similarity helper from scikit-learn.
  2. Define three sentences: the query, a paraphrase that shares almost no words with it, and a distractor that shares almost every word but means something else.
  3. Fit TF-IDF on the three sentences at once and turn them into three sparse count vectors.
  4. Compute the cosine similarity between the query and each of the other two, and print both numbers. Expect the distractor to win by a wide margin.
  5. Load all-MiniLM-L6-v2, a small sentence-embedding transformer. normalize_embeddings=True scales each vector to length 1, so a plain dot product is a cosine.
  6. Encode the query and the paraphrase, take their dot product, and print it. Expect about 0.7 where TF-IDF gave about 0.11.
  7. The closing comment is the honest part: embeddings also score the distractor high. Their advantage is catching the paraphrase, not rejecting the monkey.
paraphrase_gap.pyruns offline
# pip install "scikit-learn>=1.5,<2" "sentence-transformers>=3.0"
"""Lexical overlap vs meaning: the demo that kills keyword-era NLP."""
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

query      = "please refund my money"
paraphrase = "give me my cash back"        # same intent, ~zero shared words
distractor = "please refund my monkey"     # one letter off, different universe

X = TfidfVectorizer().fit_transform([query, paraphrase, distractor])
sims = cosine_similarity(X[0], X[1:]).ravel()
print(f"TF-IDF   paraphrase={sims[0]:.2f}  distractor={sims[1]:.2f}")
# → paraphrase≈0.11, distractor≈0.60 — counting says the monkey is 6× closer.

# Transformer sentence embeddings (~90 MB model download on first run, then offline):
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
emb = model.encode([query, paraphrase], normalize_embeddings=True)
print(f"embeddings  paraphrase={emb[0] @ emb[1]:.2f}")   # ≈0.7 — a real match
# Try adding the distractor here: embeddings also score surface edits high —
# the difference is they ALSO catch the paraphrase, which counting never can.
# Synonymy is only solvable with meaning, and meaning is what attention builds.

This single failure motivates most of Act III. Transformer embeddings that match paraphrases are what make semantic search and RAG retrieval work (Module 08), what power dedupe and clustering, and what let a fine-tuned classifier generalize past its training vocabulary. The counting era isn't wrong — it's a fast, interpretable baseline you should always run first — but the moment your users stop copying your vocabulary, you need era 3.

Questions you might be asking now

The failure box above leans on "cosine similarity" without defining it, and Fig. 5.0b showed the baseline's wrong answer without its arithmetic. The three questions below slow down for both. Every answer uses the same four sentences, and every number comes from rerunning cosine_by_hand.py or outage_ticket_trace.py.

The four sentences every answer below uses. The first three are the ones paraphrase_gap.py compares; the fourth is the ticket tfidf_baseline.py sent to Account.
#SentenceWhere it comes fromWhat a person would say it means
1please refund my moneyThe query in paraphrase_gap.pyBilling: a refund request
2give me my cash backThe paraphraseBilling: the same request in other words
3please refund my monkeyThe one-letter distractorNonsense, or a typo of sentence 1
4URGENT: prod Postgres cluster throwing 500s and timing outMonday's outage ticket in tfidf_baseline.pyTechnical, and urgent
What is cosine similarity, and how exactly does "give me my cash back" score 0.11 while the monkey scores 0.60?

Cosine similarity measures whether two lists of numbers point the same way: 1 means the same direction, 0 means nothing in common. For word-count vectors, only words both sentences contain add anything. Sentence 2 shares only "my" with sentence 1 and scores 0.1057; sentence 3 shares three words and scores 0.6009.

Each sentence first becomes a list of numbers, one per word in the vocabulary. Cosine then compares two lists in two moves. First the dot product: multiply the numbers in matching positions and add them up. Then divide by both lists' lengths. The division makes it about direction, not size: sentence 1 written out twice still scores 1.0 against sentence 1.

Here are the six steps behind the two numbers paraphrase_gap.py prints. Totals use unrounded values, so a hand sum can differ in the fourth decimal.

  1. Split into words. scikit-learn lowercases and keeps runs of two or more letters. The three sentences use 9 different words: back, cash, give, me, money, monkey, my, please and refund. Each word becomes one column.
  2. Count the sentences that contain each word. This is the document frequency, df. "my" is in all 3. "please" and "refund" are in 2. The other six words are in 1.
  3. Turn that count into a weight. This is the inverse document frequency, idf. scikit-learn's default is ln((1 + 3) ÷ (1 + df)) + 1, where ln is the natural logarithm. "my": ln(4 ÷ 4) + 1 = 1.0000. "please": ln(4 ÷ 3) + 1 = 1.2877. A word in one sentence: ln(4 ÷ 2) + 1 = 1.6931. Rarer words weigh more.
  4. Build each sentence's vector. Every word appears once, so its value is its idf. Sentence 1: please 1.2877, refund 1.2877, my 1.0000, money 1.6931, and 0 in the other five columns. Sentence 2: give, me, cash and back at 1.6931 each, and my at 1.0000. Sentence 3 is sentence 1 with monkey in place of money.
  5. Measure each length. Square every number, add, take the square root. Sentence 1: √(1.6581 + 1.6581 + 1.0000 + 2.8667) = √7.1830 = 2.6801. Sentence 2: √(4 × 2.8667 + 1.0000) = √12.4670 = 3.5309. Sentence 3 has the same numbers as sentence 1, so its length is also 2.6801.
  6. Dot product, then divide. Sentences 1 and 2 share only "my": 1.0000 × 1.0000 = 1.0000, and 1.0000 ÷ (2.6801 × 3.5309) = 1.0000 ÷ 9.4631 = 0.1057. Sentences 1 and 3 share please, refund and my: 1.6581 + 1.6581 + 1.0000 = 4.3163, and 4.3163 ÷ 7.1830 = 0.6009.

Those are the 0.11 and 0.60 in the failure box, and scikit-learn's own cosine_similarity returns the same 0.1057 and 0.6009.

Why the monkey wins, side by side
Sentence 1 against sentence 2 (the paraphrase)Sentence 1 against sentence 3 (the distractor)
Words in commonmyplease, refund, my
Dot product1.00004.3163
Lengths multiplied2.6801 × 3.5309 = 9.46312.6801 × 2.6801 = 7.1830
Cosine0.1057, printed as 0.110.6009, printed as 0.60
Angle between the two vectors (the cosine is the cos of this angle, hence the name)83.9°, almost a right angle53.1°
What a person seesThe same requestNonsense
1 EACH SENTENCE IS A ROW OF 9 WEIGHTS, ONE PER WORD my please refund money monkey give me cash back length sentence 1 sentence 2 sentence 3 1.00 1.29 1.29 1.69 0 0 0 0 0 2.6801 1.00 0 0 0 0 1.69 1.69 1.69 1.69 3.5309 1.00 1.29 1.29 0 1.69 0 0 0 0 2.6801 a present word gets its idf; an absent word is 0 and adds nothing to a dot product 2 SENTENCE 1 VS 2: ONE SHARED WORD my: 1.0000 × 1.0000 = 1.0000 dot product = 1.0000 ÷ (2.6801 × 3.5309) = 0.1057 83.9° sentence 1 sentence 2 3 SENTENCE 1 VS 3: THREE SHARED WORDS please: 1.2877 × 1.2877 = 1.6581 refund: 1.2877 × 1.2877 = 1.6581 my: 1.0000 × 1.0000 = 1.0000 dot product = 4.3163 ÷ (2.6801 × 2.6801) = 0.6009 53.1° sentence 1 sentence 3 cosine = dot product ÷ (length × length): 1 = same direction, 0 = no word in common
Fig. 5.2k — The three sentences as rows of TF-IDF weights, and the two cosines worked out. Only columns where both rows are non-zero feed the dot product (marker 1): one column for the paraphrase (marker 2), three for the distractor (marker 3). The angles are drawn to scale. Values from rerunning cosine_by_hand.py.
  1. One row per sentence. The three sentences use 9 different words, so each becomes 9 numbers. A present word gets its idf: 1.00 for "my", which all three use; 1.29 for "please" and "refund"; 1.69 for a word only one sentence uses. An absent word is 0, and 0 times anything adds nothing.
  2. The paraphrase meets sentence 1 in one column. "give", "me", "cash" and "back" land where sentence 1 has zeros. Only "my" overlaps, and it has the lowest weight of all. The dot product is 1.0000, and dividing by the lengths gives 0.1057, an angle of 83.9°.
  3. The distractor meets it in three columns. "money" and "monkey" are different columns, so the changed letter costs just one column. please, refund and my still match, the dot product is 4.3163, and the cosine is 0.6009, an angle of 53.1°. There is no column for meaning.

Cosine itself is not what failed. The same formula compares the sentence embeddings in Fig. 5.2e and gives 0.70 for sentences 1 and 2, because those 384 numbers were trained to encode meaning. A cosine is only as good as the vectors it compares. And these idf values come from three sentences; fitted on Maya's whole queue, "my" and "please" would weigh differently.

Cosine similarity = dot product ÷ (length × length). On word-count vectors, pointing the same way means sharing spelling, which is why one changed letter scores 0.60 and a true paraphrase 0.11.

Walk the outage ticket through the counting baseline, one step at a time. How does it end up at Account, 67%?

Of the ticket's 17 terms, only "and" is in the baseline's vocabulary. After weighting and normalising, that one word is worth exactly 1.0. The model had seen "and" only in Account tickets, so it adds +1.2568 to the Account score and about −0.63 to the other two. Softmax turns the three scores into Account 0.6727.

Fig. 5.0b shows what goes in and what comes out. Here are the six steps in between, as outage_ticket_trace.py prints them. The script rebuilds exactly the model tfidf_baseline.py trains, with the same tickets, seed, split and settings, and prints every intermediate number instead of only the answer.

  1. Split into terms. Lowercase, keep runs of two or more letters or digits, then add each pair of neighbouring words, because ngram_range=(1, 2). Nine words and eight pairs make 17 terms. "URGENT:" loses its colon and becomes "urgent".
  2. Look each term up. The vocabulary has 904 entries: 377 single words and 527 word pairs. Only "and" is found. Even "500s" is missing, although "500" is there: the splitter keeps "500s" whole, and one extra letter makes it a stranger. The other 16 terms are dropped with no warning.
  3. Weight the survivor. With sublinear_tf, the count of 1 becomes 1 + ln(1) = 1. "and" appears in 165 of the 960 training tickets, so its idf is ln(961 ÷ 166) + 1 = 2.7560. Its weight is 1 × 2.7560 = 2.7560.
  4. Divide by the vector's length. This step stops long tickets from scoring higher just for being long. With one non-zero entry, the length is 2.7560 itself, and 2.7560 ÷ 2.7560 = 1.0000. The ticket is now 903 zeros and a single 1.
  5. Score each class. Each class has one learned weight per vocabulary entry, plus an intercept, a starting score that applies to every ticket. Only the weight on "and" meets a non-zero value. Account: +1.2568 × 1 − 0.3103 = +0.9466. Billing: −0.6269 × 1 + 0.0401 = −0.5868. Technical: −0.6300 × 1 + 0.2702 = −0.3598. The Account sum uses unrounded weights; by hand it comes to +0.9465.
  6. Softmax. e to each score gives 2.5769, 0.5561 and 0.6978, which total 3.8308. Account 0.6727, Billing 0.1452, Technical 0.1822: the same three numbers predict_proba prints.
A · SPLIT urgent prod postgres cluster throwing 500s and timing out + 8 word pairs: 17 terms B · LOOK UP 904 vocabulary entries 16 terms not found 1 found: and 500 is known; 500s is not 1 C · WEIGHT tf = 1 + ln(1) = 1 idf = ln(961 ÷ 166) + 1 weight = 2.7560 and is in 165 of 960 D · NORMALISE divide by the length 2.7560 ÷ 2.7560 = 1.0000 903 zeros and one 1 2 E · SCORE EACH CLASS Account +1.2568 × 1 − 0.3103 = +0.9466 Billing −0.6269 × 1 + 0.0401 = −0.5868 Technical −0.6300 × 1 + 0.2702 = −0.3598 weight on "and" × 1, plus the intercept 3 F · SOFTMAX e^0.9466 = 2.5769 e^−0.5868 = 0.5561 e^−0.3598 = 0.6978 total 3.8308 Account 0.6727 Billing 0.1452 Technical 0.1822 answer: Account, 67% 4
Fig. 5.2l — Monday's outage ticket through the six steps of the counting baseline. Sixteen of 17 terms disappear at the lookup (marker 1); the survivor is normalised to 1.0000 (marker 2); its learned weight, not the intercepts, puts Account on top (marker 3); softmax reports that as 67% (marker 4). Bar length is the probability; 1.0 would be 100 px. Values from rerunning outage_ticket_trace.py.
  1. Sixteen terms vanish. The vocabulary was built from 12 template sentences, so it has no entry for postgres, cluster or timing. A term with no entry has no column, and the vectorizer drops it silently. Even "500s" is lost, because the vocabulary only holds "500".
  2. One word becomes the whole ticket. Normalising divides the vector by its length. With a single non-zero entry, that entry becomes exactly 1.0000, the largest value any entry can have. The less a ticket overlaps the vocabulary, the louder its one survivor.
  3. The learned weight is the reason. "and" appears in 165 training tickets, all Account, so the model gave it +1.2568 for Account and about −0.63 for the other two. This is a shortcut the data taught: a word that happens to travel with one label.
  4. Softmax reports it as confidence. The three scores become 0.6727, 0.1452 and 0.1822. The 67% measures how strongly "and" points at Account. It says nothing about the outage.

Step E holds the surprise. To this model, "and" is not a neutral word. Only 2 of the 12 template sentences contain it, "Please update our SSO domain and billing address" and "Requesting GDPR data export and account deletion", and both are Account. All 165 training tickets that contain "and" are labelled Account. The model learned, correctly for its data, that "and" means Account.

What decided the answer: the ticket as sent, against the same ticket with "and" deleted
The ticket as sentThe same ticket without "and"
Terms the model knowsandNone
Account score+1.2568 − 0.3103 = +0.9466−0.3103, the intercept alone
Billing score−0.6269 + 0.0401 = −0.5868+0.0401
Technical score−0.6300 + 0.2702 = −0.3598+0.2702
AnswerAccount 0.6727Technical 0.4248
WhyThe one known word was only ever seen in Account ticketsNothing is known; the intercepts happen to favour Technical

Deleting one conjunction sends the ticket to the right queue. That is not a fix. The model still read nothing about Postgres, 500s or timing out. Neither answer came from the words that describe an outage: one came from "and", the other from the intercepts.

This particular shortcut comes from having only 12 template sentences. In real tickets "and" turns up in every queue, so it could not point this hard at one label. The deeper failure would stay: a word the vocabulary never saw adds nothing, however plainly it means "outage". Subword tokens (section 03) and embeddings (Fig. 5.2e) are what remove it.

The baseline did not misread the outage; it never read it. Sixteen of its 17 terms were dropped, and the one survivor, "and", had only ever been seen in Account tickets.

How can the baseline score a perfect 1.00 and still misroute an obvious outage? Is the test set broken?

The test set is not broken; it is too easy. All 240 test tickets repeat one of the 12 sentences the model trained on, and 154 are identical to a training ticket, character for character. A perfect score on copies measures memory. It could not warn anyone about a ticket written in new words.

Picture a driving test held on the exact route you practised a hundred times. Passing proves you know that route. It says nothing about the first road you have never seen. The baseline took its test on its practice route, and Monday's ticket was a new road.

Here is what the split actually produced. The generator draws 1,200 tickets from 12 template sentences. Eight of the 12 have no {id} slot, so every ticket drawn from them is the same string. When the tickets are split 80/20 at random, those copies land on both sides.

The training set against the test set, as train_test_split made them, from outage_ticket_trace.py
Training setTest set
Tickets960240
Distinct sentences, ignoring the id number1212, the same 12
Copies of each sentence67 to 97—
Tickets whose sentence also appears in training—240 of 240
Tickets identical to a training ticket—154 of 240
Tickets in words the model never saw—0
Score—Precision, recall and F1 of 1.00 in all three classes

So the test asked one question 240 times: do you remember these 12 sentences? It never asked the question Maya cares about, which is what happens to a ticket nobody wrote a template for. To ask that, run this block's four sentences through the same trained model.

The block's four sentences through the model tfidf_baseline.py trains. Learned weights from outage_ticket_trace.py.
SentenceA person saysThe model saysTerms it knewWhy it answered that
1 · please refund my moneyBillingBilling 0.5621my, please, refund"my" (+0.6207) and "refund" (+0.7780) pull towards Billing; "please" pulls towards Account (+0.7531), learned from "Please update our SSO domain"
2 · give me my cash backBillingBilling 0.5660my"my" alone, learned from the Billing template "Payment failed but my card still shows an active charge"
3 · please refund my monkeyNonsenseBilling 0.5621my, please, refundExactly sentence 1's answer: "money" and "monkey" are both unknown, so the two vectors are identical
4 · the outage ticketTechnicalAccount 0.6727and"and", seen only in Account tickets (the previous answer)

Three of the four look right, which flatters the model. Sentence 2 is right on the strength of "my", a word every queue contains. Sentence 3 means nothing and gets sentence 1's answer to four decimals. Only the outage is visibly wrong, and none of this could show up in a test built from the templates.

1 THE 240 TEST TICKETS 154 identical to a training ticket, id number and all 86 the same sentence with a different id number 2 0 in words the model had never seen 12 sentences, 67 to 97 training copies each precision, recall and F1: 1.00 in all three classes 3 THE FOUR SENTENCES OF THIS BLOCK please refund my money Billing 0.5621 · knew my, please, refund right give me my cash back Billing 0.5660 · knew only my right, on my alone please refund my monkey Billing 0.5621 · the same vector as sentence 1 no real answer URGENT: prod Postgres cluster throwing 500s and timing out Account 0.6727 · knew only and wrong a perfect score on copies measures memory; only tickets in new words measure reading
Fig. 5.2m — What the perfect score was measured on, and what it missed. Left: every one of the 240 test tickets repeats a training sentence, and 154 repeat a training ticket exactly (marker 1); none uses new words (marker 2). Right: the block's four sentences, where the model's reasons fall apart (marker 3). Bar length is the share of the 240 tickets. Values from rerunning outage_ticket_trace.py.
  1. The test was the practice route. All 240 test tickets are one of the 12 training sentences, each seen 67 to 97 times in training, and 154 are identical strings, id number included. The 1.00 is real. It measures how well 960 tickets taught 12 sentences.
  2. Nothing new was tested. Not one test ticket uses a word outside the templates. So no score on this test set could have warned about Monday's ticket, which shares a single word with the vocabulary.
  3. New sentences expose the reasons. Sentence 2 is Billing because of "my". Sentence 3 is nonsense and gets sentence 1's 0.5621 exactly. The outage goes to Account because of "and". These are the answers a 1.00 on template copies hides.

A perfect score is not always a warning sign; on a narrow, stable task it can be real. The warning sign is a test set that cannot contain the input you fear. The fix is tickets written by other people, in other words, ideally from a later week. The lab's paraphrase templates and typos (section 10) do exactly that.

None of this breaks the rule to run the baseline first. It means the baseline and the transformer must be compared on a test set like Monday's. The general version of this lesson is Module 02's follow-up on test sets.

A test score only speaks for inputs like the test set. Build the test set from the tickets you are afraid of, not from copies of the ones you trained on.

Before those two argue, look at what each of them actually does, with its own numbers on it. Every line of the chat below points at something in this picture.

1 THE KNIFE The Tokenizer about 2 MB of merge rules ≈100,000 vocabulary entries learns nothing at run time 25 characters → 6 tokens 5 Japanese characters → 6 tokens runs in microseconds, on any CPU decides what the bill is measured in integer ids [791, 2128, …] 2 3 THE LEARNER The Model 66 million weights (DistilBERT) up to 70 billion (Llama 2 70B) embedding table 30,522 × 768 gives "bank" a different vector per sentence every weight was learned from data answers one ticket in under 15 ms decides what the answer is swap the model and the tokenizer survives · swap the tokenizer and every id in the table points at the wrong row
Fig. 5.2f — The two halves of "reading", side by side. The tokenizer is a fixed knife with no learning in it (marker 1); the only thing it hands over is a list of integers (marker 2); the model is everything that was learned, and it can only address the rows those integers name (marker 3).
  1. The knife (marker 1). A couple of megabytes of merge rules and a vocabulary. It never trains, never adapts to your domain, and runs so fast its cost is not worth measuring. Everything it decides — how many pieces your text becomes — is decided before the model exists.
  2. The handoff (marker 2). All that crosses the gap is a list of integers. Not letters, not words, not meaning: row numbers. This is the whole interface between the two, and it is also why the pairing cannot be broken casually.
  3. The learner (marker 3). Tens of millions to tens of billions of numbers, all fitted to data, addressed by those row numbers. It is the only half that can tell the river bank from the bank that declined your card — and the only half that has to be retrained if the row numbers ever change meaning.
Fireside chat

Tonight's talk: The Tokenizer and The Model argue over the question, "Who's more important?"

The Tokenizer
The Model

Let's start with the order of operations, which is drawn as the arrow between us at marker 2. I run first. Nothing reaches you that I have not cut into pieces and numbered. You have never seen a letter in your life — you see [791, 2128, …], and you look up rows in a table whose rows I defined. Your vocabulary is my vocabulary.

the only thing that crosses from the tokenizer to the model is a list of integers. The model addresses rows by those integers, so the tokenizer's vocabulary fixes what the model can even refer to.

A hundred thousand rows is a filing cabinet, not reading. You gave "bank" the same id in the river sentence and in the card sentence. Same id, same row, same vector. Line four of my panel, marker 3: I am the one who looked at the words around it and produced a different vector for each. Context is my job, and you do not have any.

the tokenizer always returns the same id for the same spelling. Only the model, by attending to the surrounding words, can give one spelling two different meanings.

Context is expensive. Read the two panels against each other. I am two megabytes of merge rules and I run in microseconds with no learning at all. You are sixty-six million weights at the small end and seventy billion at the large end, and you need real hardware to have an opinion. Every token I do not hand you is money you do not spend.

the two panels are deliberately unequal. The tokenizer is tiny and fixed; the model is enormous and learned, and its cost scales with how many tokens it is handed.

Every token you waste is also money, and line five of your own panel is the confession: five Japanese characters became six tokens, because your merges were learned from mostly English text. One typo in "unbelievable" hands me pieces I rarely saw in training, and my accuracy drops. My error rate was decided before I ran a single multiply.

a tokenizer tuned on English text cuts other languages and typos into more, rarer pieces. That raises the bill and lowers quality, and the model cannot undo either.

And the 0.11 in Fig. 5.2e was not my doing. I gave "please refund my money" and "give me my cash back" honest pieces. Counting could not see they mean the same thing, and neither could you until somebody trained you on trillions of my tokens. I was there for every one of them.

the tokenizer is not what failed on the paraphrase; the counting model was. Meaning has to be learned from enormous amounts of tokenized text, which is the model's side of the work.

You were there as a knife — that is literally what marker 1 calls you. I was there as the thing that learned. And do not forget "strawberry" at marker 2 of Fig. 5.2b: three sealed boxes, str, aw and berry, and then everyone laughed at me for miscounting the r's inside them. I cannot see through your boxes. Nobody can.

letter-level questions fail because the letters are sealed inside token ids. That is a limit of the handoff, not a limit of the model's intelligence.

Nobody asked you to spell. Maya asked you to route eight thousand tickets a day in under fifteen milliseconds each, and for that you need me to hold still. Read the line across the bottom of the picture: swap you for a better model and I stay; swap me, and every id in your 30,522-row table points at the wrong row.

the tokenizer is a pinned dependency. Changing it invalidates the learned embedding table, because the model's rows are addressed by the old ids.

Which is exactly why Module 11 puts "tokenizer mismatch" on the fine-tuning checklist. You are a dependency, and dependencies get pinned. Being load-bearing is not the same as being important.

"tokenizer mismatch" means fine-tuning a checkpoint with a different tokenizer than it was pretrained with. It is a known, checkable mistake rather than an argument for either side.

A dependency that decides your context window, your bill and your error rate, all three printed on my side of the picture. Fine. We'll revisit who's more important the day someone tries to change my vocabulary and keep your weights.

context length, cost and the shape of the input are all set by tokenization. Nothing the model does afterwards can change them.

Or the day someone asks you what a word means.

the argument ends unresolved on purpose. The tokenizer owns the shape and the cost of the input; the model owns the meaning; neither can do the other's half.

06 · Inside the transformerThe Block, and the Two Families

You can compute one attention head, and you have watched counting die on a paraphrase. What Maya will actually deploy is not one head; it is a stack of blocks with a parameter count and a monthly bill attached. This section opens the block, counts what is inside it, and splits the field into the two families you choose between. Picking the wrong family is how a team ends up paying 100 times the latency for her 8,000 tickets.

A production transformer is your 40-line attention head plus three pieces of engineering, stacked into a repeating unit called the transformer block:

token vectors in (+ position info) multi-head self-attention add & norm feed-forward MLP add & norm context-mixed vectors out residual residual × N layers (12 – 96+)
Fig. 5.3 — One transformer block. Attention mixes information across tokens; the MLP processes each token; residual connections (the ResNet trick from Module 04) keep gradients alive through deep stacks. Stack the block N times and you have GPT or BERT.

Now the same block a second time, with this module's actual files in the boxes. Fig. 5.3 is the abstract picture. Every row below is a line you have already read, or one you are about to read in finetune_distilbert.py, the production classifier of section 08. If a stage feels abstract, find its row.

Fig. 5.3 again, concretely: each stage as it exists in this module's code
StageIn the from-scratch versions (sections 02–04)In finetune_distilbert.py (section 08)What flows out
TokenizeTfidfVectorizer splits on its default word pattern; enc.encode(text) in tokens_up_close.py applies BPE mergestok(b["text"], truncation=True, max_length=128): WordPiece, lowercased, 30,522-entry vocabularyA list of integer ids, at most 128 long, plus a mask saying which positions are real
Look up embeddingsThe hand-typed E matrix in attention_from_scratch.py: 5 rows × 4 numbersThe model's embedding table, 30,522 rows × 768 numbers, learned in pretrainingOne 768-number vector per token
Add positionNone; the toy does not know word orderA learned vector per position (512 × 768) added to each token's vectorVectors that also encode where each token sits
Self-attentionscores = Q @ K.T / np.sqrt(d), one head, identity projections12 heads per block, each with learned WQ, WK, WV of 768 × 64Each token's vector re-mixed with the tokens that matter to it
Feed-forward MLPNoneA two-layer network, 768 → 3072 → 768, applied to every token on its ownEach token's vector, processed individually
Add & norm, repeatNone; one pass and stopResidual add and layer normalization after each sub-layer; six blocks stackedA final contextual vector per token
HeadLogisticRegression on the TF-IDF vector in tfidf_baseline.pyTwo fresh linear layers (768 → 768 → 3) on the first token's vector, added by AutoModelForSequenceClassificationThree logits, one per category
Trainclf.fit(X_tr, y_tr), about two secondstrainer.train(): two epochs at learning rate 5e-5, updating all 66 million weights, about five minutes on CPUtriage-distilbert/final, the directory you deploy
Predictclf.predict([ticket])model(**inputs).logits.softmax(-1) under torch.no_grad()A label and a probability, in under 15 ms

The next question every engineer asks at this point is where the weights actually are, since the attention you built had none at all. Here is the count for one real model, drawn to scale.

1 ONE BLOCK OF LLAMA 2 70B attention projections ≈150 million weights · 18% feed-forward layer ≈700 million · 82% ≈850 million weights in one block bar length = weight count, same scale in both rows 2 THE WHOLE SEVENTY BILLION attention feed-forward 80 blocks × 850 million ≈ 68 billion embedding table 32,000 × 8,192 ≈ 262 million ≈ 70 billion in total 3 every weight is read for every token generated DistilBERT is 66 million — a thousandth of this
Fig. 5.3b — Where the parameters actually live. In Llama 2 70B each block holds about 150 million weights in its attention projections and about 700 million in its feed-forward layer, so roughly four fifths of the model is the part that thinks about one token at a time, not the part that looks around.
  1. Attention is the smaller half (marker 1). The learned matrices WQ, WK, WV and the output projection account for about 150 million of the 850 million weights in a block. Attention decides where to look, and that turns out to be cheap to store.
  2. The feed-forward layer is most of the model (marker 2). The two-layer network applied to each token on its own holds about 700 million weights per block, and 80 blocks of it come to roughly 68 billion. This is where most of what the model knows is kept.
  3. Size is a serving problem, not a quality knob (marker 3). Generating one token means reading all 70 billion weights out of memory. That is why a 70B model costs what it costs, and why a 66-million-parameter encoder is the right tool for Maya's fixed three-label job rather than a worse one.

"If attention is all you need, why is the model seventy billion parameters? Attention on a five-token sentence was forty lines and no weights at all."

— an engineer who just ran attention_from_scratch.py, right about now

The paper's title was a claim about recurrence, not about weight counts. It said you can drop the left-to-right RNN and let attention do the mixing. It never said attention is where the parameters live, and it is not. The toy file used identity projections, so there was nothing to count. A real block has four learned matrices for attention and two or three for the feed-forward layer (two in BERT-style blocks, three in Llama's gated version).

Take Llama 2 70B as a concrete case, drawn to scale in the picture above. Marker 1 is one block: about 150 million weights in the attention projections against about 700 million in the feed-forward layer. Marker 2 totals it up — 80 blocks at roughly 850 million each, plus a 262-million-row embedding table, for about 70 billion. Attention decides where to look; the feed-forward layers hold most of what the model knows.

The honest downside is marker 3. Every one of those weights must be read out of memory for every generated token. That is why serving a 70B model is a memory-bandwidth problem (Module 12), and why it costs what it costs. For Maya's three labels, the 66-million-parameter encoder on the same picture is the right size, and the 70B model is the wrong tool rather than a better one.

Stack that block and you get one of two families, and the split is the single most useful mental model for choosing tools in industry:

BERT-style encoder the payment [MASK] failed attends BOTH directions — sees the whole text pretraining: fill in the [MASK] for: classify · embed · rerank · extract BERT · DistilBERT · ModernBERT · BGE-M3 GPT-style decoder the payment gateway next? attends LEFT only — the causal mask pretraining: predict the NEXT token for: generate · chat · reason · code GPT-5 · Claude · Llama · Qwen
Fig. 5.4 — The two transformer families. Encoders read everything at once and output understanding; decoders read left-to-right and output the next token. Same block, different attention mask, completely different jobs.

The difference between those two families is one grid of allowed pairs, so here is that grid, for the five tokens of a real ticket.

1 ENCODER: EVERY PAIR ALLOWED the pay gate timed out the pay gate timed out 25 of 25 pairs allowed filling in a blank needs the words on both sides of it 2 DECODER: THE CAUSAL MASK the pay gate timed out the pay gate timed out × × × × × × × × × × 15 allowed, 10 blocked predicting the next word must not read the answer
Fig. 5.4b — The only structural difference between the two families. Same block, same weights, same arithmetic: the encoder allows all 25 token pairs (marker 1) and the decoder allows only the 15 on or below the diagonal (marker 2). Everything else — what they are good at, what they are trained on, what they cost — follows from that one grid.
  1. Reading both ways (marker 1). Every row of the encoder grid is full, so the vector for "gateway" is built from the words before it and after it. That is what you want when the whole text already exists and you need one label, one score or one embedding out of it.
  2. Reading forwards only (marker 2). The ten crossed cells are the future, hidden on purpose. If "pay" could attend to "out", next-token training would be a test with the answers printed on it, and the model would learn nothing useful.
  3. Which one for Maya. Her tickets arrive whole and need one of three labels, so the full grid is both allowed and better: an encoder. A decoder is what you reach for when the output is text that does not exist yet.

The rule of thumb for 2026: if the output is a label, a score, or a vector, reach for an encoder; if the output is text, reach for a decoder. Encoders (BERT, DistilBERT, ModernBERT, the BGE embedding family) are small, cheap, and blisteringly fast — they still run classification, embedding, and reranking workloads across the industry, including inside every RAG pipeline you'll build in Module 08. Decoders (GPT, Claude, Llama) generate — and, as the next section shows, generation trained at sufficient scale turns out to swallow most other capabilities.

07 · How ChatGPT happenedPretrain → SFT → Preference Tuning

One of those two families sits behind every chatbot a vendor has demoed to Maya, and she will ask you how it was made. The honest answer is three stages, and only the first one costs hundreds of millions of dollars. You need that narration because it decides what you are allowed to change later: the prompt, the weights, or nothing at all. It is also the most common whiteboard question in the interviews this module is preparing you for.

A decoder fresh out of pretraining is not an assistant. It's an autocomplete of terrifying breadth. The assistant you talk to is that autocomplete plus two rounds of comparatively tiny post-training — a pipeline every serious GenAI interview expects you to narrate:

1 · Pretraining predict the next token ~15T tokens of web + code months · GPU megaclusters base model 2 · SFT imitate demonstrations ~10⁴–10⁶ instruction pairs days · a few GPUs instruct model 3 · RLHF / DPO learn from preferences "A is better than B" pairs reward model · or DPO directly raw autocomplete: "The capital of France is…" follows instructions, rough edges remain helpful assistant — the "ChatGPT moment" ~99% of the compute lives in stage 1 — stages 2 and 3 are cheap, powerful steering
Fig. 5.5 — How an assistant is made. Pretraining buys capability; supervised fine-tuning teaches the instruction-following format; preference tuning (RLHF, or its simpler modern cousin DPO) shapes helpfulness and tone.

Why does predicting the next token produce capabilities at all? Because predicting well is impossible without modeling the process that generated the text. To continue "the capital of France is", you must store geography. To continue a half-written Python traceback, you must model Python's semantics. To continue a mystery novel's final chapter, you must track every clue planted in the first twenty. Next-token prediction is a compression objective — and good compression of the world's text forces a model of the world's structure. The capabilities aren't bolted on; they're the residue of getting the prediction loss down. SFT then teaches the model that "user asks, assistant answers helpfully" is the genre it's continuing, and preference tuning — RLHF with a learned reward model, or DPO, which optimizes on preference pairs directly without one — nudges probability mass toward answers humans prefer. You'll run DPO yourself in Module 11.

The three stages are drawn below at the size they really are, because the picture of equal boxes in Fig. 5.5 hides the thing that matters most about them.

1 WHERE THE COMPUTE GOES stage 1 · pretraining · about 99% of all the compute ever spent on the model stages 2 and 3 together: about 1% 2 1 · pretraining — roughly 15 trillion tokens of web pages and code, months on GPU clusters 2 · supervised fine-tuning — ten thousand to a million written instruction-and-answer pairs, days on a few GPUs 3 · preference tuning — pairs of answers with a human saying "A is better than B" 3 capability comes from stage 1; manners and format come from stages 2 and 3 a vendor can change the manners weekly, and the capability almost never
Fig. 5.5b — The three stages, drawn to their real proportions. The bar is the compute: pretraining is essentially all of it, and the sliver on the right is both post-training stages put together. The stages are equally important and wildly unequal in cost.
  1. The bar is compute, not value (marker 1). About 99% of the arithmetic ever done for a model happens in stage 1. The sliver still decides whether the thing answers your question or continues your sentence, so cheap does not mean unimportant.
  2. The stages consume different things (marker 2). Stage 1 eats raw text by the trillion and needs no labels at all. Stage 2 eats written demonstrations, stage 3 eats comparisons — both are human work, and both are tiny by comparison.
  3. What this buys you as an engineer (marker 3). If a task needs knowledge the model does not have, no amount of stage-2 data will install it — that is a retrieval problem, Module 08. If it needs a different format or tone, stages 2 and 3 are exactly the right lever, and that is Module 11.

Sampling: temperature and top-p

Maya's triage endpoint has to return the same label for the same ticket every time, or her routing rules become a lottery. Her "suggest three replies" button needs the opposite. Both behaviours come out of one knob on the same model, applied after the transformer has finished its work. Here is exactly what that knob moves.

One more mechanism before the toolbox: a decoder doesn't output a token, it outputs a probability distribution over ~100k tokens, and something must pick one. Temperature reshapes the distribution before sampling — divide the logits by T and re-softmax.

Low T sharpens toward the favorite (deterministic, repetitive); high T flattens toward uniform (diverse, eventually incoherent).

Top-p (nucleus) sampling attacks the tail instead: keep only the smallest set of tokens whose probabilities sum to p (say 0.9) and sample within it — so the model can be creative among plausible options without ever picking garbage from the long tail.

Temperature on a toy 3-token distribution (logits 2.0, 1.0, 0.5)
SettingP(token A)P(token B)P(token C)Feels like
T = 0.50.840.110.05Confident, near-deterministic — extraction, classification
T = 1.00.630.230.14The model's honest distribution
T = 2.00.480.290.23Adventurous — brainstorming, at coherence risk

The same three numbers from that table, drawn as bars, so the word "sharpen" has something to point at.

1 T = 0.5 · SHARPENED 0.84 0.11 0.05 A B C the same ticket gets the same label top-p 0.9: A + B = 0.95, so C is cut 2 T = 1.0 · UNTOUCHED 0.63 0.23 0.14 A B C the distribution the model actually produced, untouched 3 T = 2.0 · FLATTENED 0.48 0.29 0.23 A B C three genuinely different drafts — and, eventually, nonsense the same three logits (2.0, 1.0, 0.5) divided by T and softmaxed again — the model itself is identical in all three panels
Fig. 5.5c — What temperature moves. Dividing the logits by a smaller number stretches the gaps between them and the favourite runs away with the probability (marker 1); dividing by a larger number squeezes them together (marker 3). The bars are the same three numbers printed in the table above.
  1. Low temperature is a decision, not a fact (marker 1). At T = 0.5 token A holds 0.84 of the mass, so the same prompt almost always produces the same token. That is what Maya's triage endpoint needs, and it is also why a confidently wrong label at low temperature stays wrong on every retry.
  2. T = 1.0 is the model's own answer (marker 2). Nothing has been rescaled. Anything above or below this is you overriding the model's own opinion about how sure it is.
  3. Top-p cuts the tail instead (marker 1 again). With p = 0.9 at T = 0.5, A and B already total 0.95, so C is dropped from the draw entirely. Temperature changes how confident the distribution looks; top-p decides how far down the list sampling is allowed to reach.

Currency note (Aug 2026): temperature/top-p are OpenAI-style knobs and still standard across open models and vLLM. Anthropic's current models (claude-opus-5 generation) no longer accept a temperature parameter — sampling is managed server-side — so don't pass it in the lab code.

🧠 Brain power

Before reading on: HelpDeskAI wants two LLM features — a JSON ticket-triage endpoint and a "suggest three reply drafts" button. What sampling settings would you pick for each, and what specifically breaks if you swap them?

Reveal the answer

Triage wants determinism: temperature near 0 (or greedy decoding) so the same ticket maps to the same label and the JSON never gets a creative flourish that breaks the parser.

Reply drafts want diversity: moderate-to-high temperature with top-p ≈ 0.9, otherwise all three "different" drafts collapse into near-identical text. Swap them and you get flaky classifications on one side and three clones on the other.

Note temperature ≈ 0 still isn't a reproducibility guarantee — batching and floating-point nondeterminism leak through, which is why Module 07 builds evals instead of trusting fixed seeds.

08 · The industry toolFine-Tune a Small Transformer — Then Decide If You Should

Time to answer the question Maya ended her memo with: build it with our own model, or rent one by the token. Path A comes first, a DistilBERT fine-tune that runs on a CPU and answers in under 15 milliseconds, comfortably inside her 100-millisecond budget. Then we stand it next to the API in a table with the numbers she cares about: latency, cost at 8,000 a day, and what happens the week she adds a category. The table is the deliverable; the model is just how you fill it in.

Now the production version of Maya's classifier. The Hugging Face ecosystem is the industry-standard way to use encoder models: AutoTokenizer and AutoModel* load any of ~1M pretrained checkpoints behind one API, and Trainer runs the fine-tuning loop you hand-rolled in Module 04.

We take DistilBERT — a distilled BERT retaining ~97% of its accuracy at 40% of the size — bolt a fresh classification head onto it, and fine-tune the whole thing on our tickets.

This is transfer learning, the same move as Module 04's vision fine-tune: the expensive language understanding was pretrained for you; you're only teaching the last mile.

Here is the whole of path A as one stack, with the sizes the code actually asks for. Every row is a line in the file you are about to read, and the same stages appear as rows in the stage table above.

one support ticket, as text cut at 128 tokens (truncation=True) 1 WordPiece tokenizer 30,522-entry lowercased vocabulary embedding table 30,522 × 768 one 768-number vector per token 2 transformer block × 6 12 heads × 64 numbers = 768 per block feed-forward 768 → 3072 → 768 the first token's vector 768 numbers standing for the whole ticket 3 new head 768 → 768 → 3 softmax → Billing · Technical · Account 66 million weights in total everything above the dashed line was pretrained by somebody else and is only nudged by your training run learning rate 5e-5, two passes, about five minutes on a CPU below the line: two brand-new layers, starting from random numbers
Fig. 5.5d — Maya's classifier, end to end. Every size on this stack is one you can read off finetune_distilbert.py or the checkpoint it loads: a 30,522-word vocabulary, 768 numbers per token, six blocks of twelve heads, and a freshly initialised head that turns 768 numbers into three.
  1. The tokenizer must match the checkpoint (marker 1). DistilBERT was pretrained with this exact 30,522-entry WordPiece vocabulary, which lowercases everything. Loading a different tokenizer would hand the model ids that point at the wrong rows, which is the "tokenizer mismatch" the fireside chat above argued about.
  2. Six blocks, not one head (marker 2). The single head you built by hand becomes twelve heads per block, and the block repeats six times. Between the blocks sits the feed-forward layer that widens 768 numbers to 3,072 and back, which is where most of these 66 million weights live.
  3. Only the last box is new (marker 3). Fine-tuning adds two small layers on top of a pretrained stack and then nudges everything with a deliberately small learning rate. That is why five minutes of CPU time is enough: you are not teaching English, you are teaching three labels.
Step-by-step: what finetune_distilbert.py does, in plain English
  1. Imports: random, time, torch, the Hugging Face Dataset class, two metric functions from scikit-learn, and four Hugging Face classes: AutoTokenizer, AutoModelForSequenceClassification, Trainer and TrainingArguments.
  2. Define LABELS and the same TEMPLATES as the baseline, so both models are judged on the same data.
  3. Build 1,200 rows of {"text", "label"}. The label is stored as an integer position in LABELS, which is what the model's loss function expects.
  4. Convert the rows into a Hugging Face Dataset and split it 80/20 with a fixed seed.
  5. Name the checkpoint, distilbert-base-uncased, and load its tokenizer. This is a WordPiece tokenizer that lowercases everything, and it must be the one the checkpoint was trained with.
  6. Map the tokenizer over the dataset in batches: each text becomes a list of ids plus an attention mask, cut at 128 tokens.
  7. Load the pretrained model with a new classification head for three labels. The library warns that the head is untrained; that is expected. id2label makes the saved model report names instead of numbers.
  8. Define metrics: take the highest logit per row as the prediction and compute accuracy and macro-F1 against the true labels.
  9. Set the training arguments: batch size 16, two passes over the data, learning rate 5e-5 (small, because the weights are already good), evaluate at the end of each epoch, and no experiment-tracking service.
  10. Build the Trainer from the model, arguments, datasets, tokenizer and metrics, then call train(). This is the loop you wrote by hand in Module 04, run for you.
  11. Evaluate on the test split and print the metrics.
  12. Inference: switch the model to eval mode, tokenize one new ticket as PyTorch tensors, run it under torch.no_grad() so no gradients are stored, apply softmax to the logits, and time the whole thing.
  13. Print the predicted label, its probability, and the milliseconds taken. Save the model directory; that directory is what gets deployed.

Build it in chunks

We build finetune_distilbert.py in five chunks. Chunks 1 to 3 run in seconds on their own; chunks 4 and 5 train and use the model, so they are marked as not run here. The whole file comes after them.

  1. Chunk 1 — make 1,200 labelled tickets

    A classifier needs examples before it needs a model, so the first chunk only builds data: twelve template sentences, three labels, a fixed random seed. Nothing is trained or tokenized yet, and it needs only Python itself.

    Step-by-step: what this chunk does, in plain English
    1. Import random and fix the seed to 42, so every run draws the same tickets.
    2. Define the three labels. A label's position in the list (0, 1, 2) is the number the model will later predict.
    3. Write four template sentences per label. {id} is a blank filled with a random four-digit number.
    4. Loop 1,200 times: pick a label, pick one of its templates, fill the blank, and store the text with its label number.
    5. Print the row count, the first row, and how many rows each label got.
    finetune_distilbert.py — chunk 1runs offline
    import random
    
    LABELS = ["Billing", "Technical", "Account"]
    
    TEMPLATES = {   # same generator as tfidf_baseline.py — keep the comparison fair
        "Billing": [
            "I was double charged on invoice {id}, need this reversed",
            "Payment failed but my card still shows an active charge",
            "Where do I download the VAT receipt for order {id}?",
            "Requesting a refund for the annual license renewal",
        ],
        "Technical": [
            "Database connection pool exhausted, error {id}",
            "API endpoint /v1/users returning 500 internal server error",
            "Production CPU pinned at 99 percent since the deploy",
            "Container keeps restarting, OOM-killed after {id} seconds",
        ],
        "Account": [
            "Password reset email never arrives",
            "How do I add a teammate with admin permissions?",
            "Please update our SSO domain and billing address",
            "Requesting GDPR data export and account deletion",
        ],
    }
    
    random.seed(42)
    rows = []
    for _ in range(1200):
        cat = random.choice(LABELS)
        text = random.choice(TEMPLATES[cat]).format(id=random.randint(1000, 9999))
        rows.append({"text": text, "label": LABELS.index(cat)})
    
    print(len(rows), "rows; first:", rows[0])
    print("per label:", [sum(r["label"] == i for r in rows) for i in range(len(LABELS))])

    random.choice picks one item from a list; str.format fills the {id} blank.

    Run python3 chunk1_data.py. You should see 1,200 rows with roughly 400 per label (the exact split is fixed by the seed).

    terminalactual output
    1200 rows; first: {'text': 'Password reset email never arrives', 'label': 2}
    per label: [399, 395, 406]
  2. Chunk 2 — split into train and test, and turn text into token numbers

    A model reads numbers, not sentences. Before any learning, we hold back 20% of the tickets for an honest test and let the DistilBERT tokenizer cut each ticket into word pieces. This is the first chunk that needs the Hugging Face libraries and the cached model files.

    Step-by-step: what this chunk does, in plain English
    1. Wrap the rows in a Hugging Face Dataset and split them 80/20 with a fixed seed.
    2. Load the tokenizer that belongs to distilbert-base-uncased. It must match the model you load next.
    3. ds.map(...) runs the tokenizer over every ticket in batches and adds input_ids and attention_mask columns.
    4. Print the split sizes and the first few tokens of one ticket.
    finetune_distilbert.py — chunk 2runs offline
    from datasets import Dataset
    from transformers import AutoTokenizer
    ds = Dataset.from_list(rows).train_test_split(test_size=0.2, seed=42)
    
    MODEL = "distilbert-base-uncased"     # 2026 upgrade path: "answerdotai/ModernBERT-base"
    tok = AutoTokenizer.from_pretrained(MODEL)
    ds = ds.map(lambda b: tok(b["text"], truncation=True, max_length=128), batched=True)
    
    print(ds)
    print("tokens in row 0:", len(ds["train"][0]["input_ids"]), "->", tok.convert_ids_to_tokens(ds["train"][0]["input_ids"])[:8], "...")

    Dataset.train_test_split and Dataset.map(batched=True) — split a table, and apply a function to many rows at once. The chunk 1 print lines are replaced by new ones.

    Run python3 chunk2_tokenize.py. You should see 960 training rows, 240 test rows, and one ticket cut into lower-cased pieces starting with [CLS].

    terminalactual output
    DatasetDict({
        train: Dataset({
            features: ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
            num_rows: 960
        })
        test: Dataset({
            features: ['text', 'label', 'input_ids', 'token_type_ids', 'attention_mask'],
            num_rows: 240
        })
    })
    tokens in row 0: 14 -> ['[CLS]', 'how', 'do', 'i', 'add', 'a', 'teammate', 'with'] ...
  3. Chunk 3 — load DistilBERT with a fresh 3-way head, and define the score

    Now the model. We load the pretrained body and bolt a new, untrained layer on top that outputs three numbers, one per label. Then we write the function that turns the model's raw outputs into accuracy and macro-F1, because training is not worth starting until you can score it.

    Step-by-step: what this chunk does, in plain English
    1. Load DistilBERT for sequence classification with num_labels=3. The library adds a new head on top of the pretrained body.
    2. Pass the label names in both directions, so the saved model can say "Billing" instead of "0".
    3. Write metrics: take the logits, pick the largest per ticket with argmax, and compare with the true labels.
    4. Print the parameter count and the new head.
    finetune_distilbert.py — chunk 3runs offline
    from sklearn.metrics import accuracy_score, f1_score
    from transformers import AutoTokenizer, AutoModelForSequenceClassification
    model = AutoModelForSequenceClassification.from_pretrained(
        MODEL, num_labels=len(LABELS),
        id2label=dict(enumerate(LABELS)),
        label2id={l: i for i, l in enumerate(LABELS)},
    )
    def metrics(eval_pred):
        logits, y = eval_pred
        preds = logits.argmax(-1)
        return {"accuracy": accuracy_score(y, preds),
                "macro_f1": f1_score(y, preds, average="macro")}
    
    print("parameters:", sum(p.numel() for p in model.parameters()))
    print("new head:", model.classifier)

    AutoModelForSequenceClassification.from_pretrained — loads the body and adds an untrained classifier. A long warning about "newly initialized" weights is normal and expected here.

    Run python3 chunk3_model.py. You should see about 66.96 million parameters and a Linear(768 → 3) head. The model is still untrained at this point, so its guesses are no better than chance.

    terminalactual output
    parameters: 66955779
    new head: Linear(in_features=768, out_features=3, bias=True)
  4. Chunk 4 — fine-tune for two passes and score on the test split

    Everything is ready: tokenized data, a model, a scoring function. The Trainer runs the loop you wrote by hand in Module 04. This is the only slow chunk (about five minutes on a CPU).

    Step-by-step: what this chunk does, in plain English
    1. Set the training arguments: batch size 16, two epochs, learning rate 5e-5 (small, because we nudge pretrained weights), evaluate each epoch.
    2. Build the Trainer from the model, arguments, both splits, the tokenizer and the metrics function.
    3. trainer.train() runs the loop; trainer.evaluate() scores the test split.
    finetune_distilbert.py — chunk 4not run here: training
    from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                              Trainer, TrainingArguments)
    args = TrainingArguments(
        output_dir="triage-distilbert",
        per_device_train_batch_size=16,
        num_train_epochs=2,
        learning_rate=5e-5,       # small: we're nudging pretrained weights, not resetting them
        eval_strategy="epoch",
        logging_steps=20,
        report_to="none",         # no wandb prompts on a course machine
    )
    trainer = Trainer(model=model, args=args,
                      train_dataset=ds["train"], eval_dataset=ds["test"],
                      processing_class=tok,     # current name for the old tokenizer= arg
                      compute_metrics=metrics)
    trainer.train()
    print(trainer.evaluate())     # expect accuracy ≈ 1.0 on template data

    TrainingArguments and Trainer — the settings, and the object that runs the loop. processing_class=tok hands the tokenizer over so batches are padded.

    Not run here: training is a five-minute CPU job. When this course was first built, the same script logged a loss of 0.586 at step 20 falling to 0.0054 at step 120, and an evaluation accuracy and macro-F1 of 1.0 after the first epoch (the template tickets are easy). Run python3 chunk4_train.py to see your own numbers.

  5. Chunk 5 — answer one new ticket, time it, and save the model

    A trained model that cannot answer a single ticket is a science project. This chunk is the production path: one ticket in, one label and one probability out, timed, then the folder saved so a server can load it.

    Step-by-step: what this chunk does, in plain English
    1. Switch to eval() mode so dropout is off.
    2. Tokenize one new ticket as PyTorch tensors.
    3. Run the model inside torch.no_grad() so no gradients are stored, and apply softmax to turn the three scores into probabilities.
    4. Measure the elapsed milliseconds, print the winning label with its probability, and save the model folder.
    finetune_distilbert.py — chunk 5not run here: training
    import time
    import torch
    # --- inference: the <15 ms path that will triage 8,000 tickets/day ---
    model.eval()
    ticket = "URGENT: production Postgres cluster throwing 500s, connections timing out"
    inputs = tok(ticket, return_tensors="pt", truncation=True)
    t0 = time.perf_counter()
    with torch.no_grad():
        probs = model(**inputs).logits.softmax(-1)[0]
    ms = (time.perf_counter() - t0) * 1000
    top = int(probs.argmax())
    print(f"{LABELS[top]}  p={probs[top]:.3f}  ({ms:.1f} ms on CPU)")
    trainer.save_model("triage-distilbert/final")   # ship this directory

    torch.no_grad() — skips gradient bookkeeping at inference. softmax — turns raw scores into probabilities that sum to 1. This chunk adds the time and torch imports at the top.

    Not run here, for the same reason as chunk 4. Running python3 chunk5_infer.py prints one line shaped like Technical p=0.9xx (N ms on CPU). The page's claim is a few milliseconds per ticket on a CPU; measure it on your own machine.

The whole program

Lines 1–11 are the header and imports (each chunk file above imports only what it needs). Chunk 1 is lines 12–42, chunk 2 lines 43–49, chunk 3 lines 50–62, chunk 4 lines 63–80, and chunk 5 lines 81–92. Every chunk starts with a # ── chunk n ── comment.

finetune_distilbert.pyruns offline
# pip install "transformers>=4.48,<6" "datasets>=4.0,<6" "torch>=2.4" "scikit-learn>=1.5,<2" "accelerate>=1.0"
"""Fine-tune DistilBERT as a ticket-triage classifier. Runs on CPU in ~5 minutes.
First run downloads the model (~260 MB); afterwards fully offline."""
import random
import time
import torch
from datasets import Dataset
from sklearn.metrics import accuracy_score, f1_score
from transformers import (AutoTokenizer, AutoModelForSequenceClassification,
                          Trainer, TrainingArguments)

# ── chunk 1: make the data ──
LABELS = ["Billing", "Technical", "Account"]

TEMPLATES = {   # same generator as tfidf_baseline.py — keep the comparison fair
    "Billing": [
        "I was double charged on invoice {id}, need this reversed",
        "Payment failed but my card still shows an active charge",
        "Where do I download the VAT receipt for order {id}?",
        "Requesting a refund for the annual license renewal",
    ],
    "Technical": [
        "Database connection pool exhausted, error {id}",
        "API endpoint /v1/users returning 500 internal server error",
        "Production CPU pinned at 99 percent since the deploy",
        "Container keeps restarting, OOM-killed after {id} seconds",
    ],
    "Account": [
        "Password reset email never arrives",
        "How do I add a teammate with admin permissions?",
        "Please update our SSO domain and billing address",
        "Requesting GDPR data export and account deletion",
    ],
}

random.seed(42)
rows = []
for _ in range(1200):
    cat = random.choice(LABELS)
    text = random.choice(TEMPLATES[cat]).format(id=random.randint(1000, 9999))
    rows.append({"text": text, "label": LABELS.index(cat)})

# ── chunk 2: split and tokenize ──
ds = Dataset.from_list(rows).train_test_split(test_size=0.2, seed=42)

MODEL = "distilbert-base-uncased"     # 2026 upgrade path: "answerdotai/ModernBERT-base"
tok = AutoTokenizer.from_pretrained(MODEL)
ds = ds.map(lambda b: tok(b["text"], truncation=True, max_length=128), batched=True)

# ── chunk 3: the model and the score ──
model = AutoModelForSequenceClassification.from_pretrained(
    MODEL, num_labels=len(LABELS),
    id2label=dict(enumerate(LABELS)),
    label2id={l: i for i, l in enumerate(LABELS)},
)

def metrics(eval_pred):
    logits, y = eval_pred
    preds = logits.argmax(-1)
    return {"accuracy": accuracy_score(y, preds),
            "macro_f1": f1_score(y, preds, average="macro")}

# ── chunk 4: train and evaluate ──
args = TrainingArguments(
    output_dir="triage-distilbert",
    per_device_train_batch_size=16,
    num_train_epochs=2,
    learning_rate=5e-5,       # small: we're nudging pretrained weights, not resetting them
    eval_strategy="epoch",
    logging_steps=20,
    report_to="none",         # no wandb prompts on a course machine
)

trainer = Trainer(model=model, args=args,
                  train_dataset=ds["train"], eval_dataset=ds["test"],
                  processing_class=tok,     # current name for the old tokenizer= arg
                  compute_metrics=metrics)
trainer.train()
print(trainer.evaluate())     # expect accuracy ≈ 1.0 on template data

# ── chunk 5: answer one ticket and save ──
# --- inference: the <15 ms path that will triage 8,000 tickets/day ---
model.eval()
ticket = "URGENT: production Postgres cluster throwing 500s, connections timing out"
inputs = tok(ticket, return_tensors="pt", truncation=True)
t0 = time.perf_counter()
with torch.no_grad():
    probs = model(**inputs).logits.softmax(-1)[0]
ms = (time.perf_counter() - t0) * 1000
top = int(probs.argmax())
print(f"{LABELS[top]}  p={probs[top]:.3f}  ({ms:.1f} ms on CPU)")
trainer.save_model("triage-distilbert/final")   # ship this directory

Two honest caveats. Our synthetic templates make this look trivially easy — both the baseline and DistilBERT ace them. The transformer's edge appears on real tickets, where paraphrase and typos rule (the lab injects exactly that). And DistilBERT (2019) is deliberately chosen for CPU-friendliness; when you have a GPU and want the current state of the encoder art, ModernBERT-base (2024) is a drop-in swap of one string.

The 2026 decision: fine-tune a small encoder vs prompt an LLM API

You have a trained classifier and a measured latency. What you do not yet have is the recommendation Maya asked for. This is the comparison that ends her meeting, and it is the same comparison almost every GenAI interview asks for: own a small model, or rent a big one, at this volume, with these numbers.

This is the real engineering question Maya is paying for, and it recurs in every GenAI role: for a high-volume, narrow task, do you own a small model or rent a giant one? Run the table, not your enthusiasm:

Decision table — ticket classification at HelpDeskAI scale (8,000/day), as of Aug 2026
DimensionFine-tuned encoder (DistilBERT/ModernBERT)LLM API (claude-haiku-4-5, few-shot)
Latency2–15 ms local; no network hop300–1500 ms per call
Cost at 8k/day≈ one small CPU box, ~$30–60/month flat~$1 in / $5 out per 1M tokens → roughly $5–8/day with a ~600-token prompt; scales linearly with volume
Quality on a narrow, stable label setExcellent once trained on 500–2,000 labeled examplesExcellent zero/few-shot; better on weird edge cases and long tickets
Data neededHundreds of labeled examples per class3–10 examples in the prompt; no training set
New category tomorrow?Relabel + retrain (hours)Edit the prompt (minutes)
Ops burdenYou own serving, monitoring, retrainingVendor owns the model; you own prompts, evals, rate limits, and an outage dependency
Privacy / residencyData never leaves your VPCData transits a vendor (contracts permitting)
Choose when…High volume, tight latency, stable labels, labeled data existsLow volume, shifting labels, no training data, or task needs open-ended reasoning

Two rows of that table decide most arguments, so here they are drawn: what a ticket waits, and what a month costs as the queue grows.

1 WHAT ONE TICKET WAITS fine-tuned encoder, in your own process 2–15 ms LLM API call, over the network 300–1,500 ms same scale in both bars: 1 ms = 0.2 px the same three labels, up to a hundred times the wait 2 WHAT A MONTH COSTS $ per month tickets per day → own it: about $50 a month, flat rent it: grows with volume they cross near 2,200 tickets a day ≈$180 a month at Maya's 8,000 a day 8,000 about $6 a day at 8,000 tickets is $180 a month
Fig. 5.5e — The two rows of the decision table that decide most arguments, drawn. Latency differs by about two orders of magnitude (marker 1), and the cost lines cross at roughly 2,200 tickets a day, so at Maya's 8,000 the owned model is both faster and cheaper (marker 2).
  1. Latency is structural, not tuning (marker 1). The encoder runs inside your own process and finishes in single-digit milliseconds. The API adds a network round trip and a much larger model, and no prompt engineering removes either. For a "production database is down" ticket, that difference is the whole product.
  2. Cost is a crossing, not a winner (marker 2). Renting costs per ticket, so its line rises; owning costs per month, so its line is flat. Below roughly 2,200 tickets a day the API is cheaper and you should rent. Maya is at 8,000, which is well past the crossing.
  3. What the picture leaves out. Owning adds work that does not appear on either axis: labelling, retraining when a category is added, and somebody on call for the serving box. That is why the table has seven more rows and why the recommendation is a paragraph, not a number.

The pattern you'll see in mature teams: prototype with the API, then graduate hot paths to a small model — often using the LLM itself to label the training data (you'll try that as the lab's stretch goal, and meet it again as distillation in Module 11).

There are no dumb questions

Is TF-IDF dead, then?
No — it's demoted, not dead. It's still the right first baseline for any text classification task (train in seconds, fully interpretable, no GPU), and its cousin BM25 is half of every hybrid-search RAG pipeline in Module 08. The rule: never ship a transformer you haven't benchmarked against the counting baseline — if TF-IDF hits your accuracy bar, the transformer is unjustified cost.
DistilBERT is from 2019. Why is a 2026 course teaching it?
Because the encoder-classifier pattern is timeless economics, and DistilBERT is its most CPU-friendly teaching vehicle. In production you'd swap the checkpoint string for ModernBERT (2024) or a domain model and change nothing else — that's the point of the AutoModel API. What matters is knowing when a 66M-parameter encoder beats a trillion-parameter API, which is a judgment call interviewers explicitly probe.
If next-token prediction is "just autocomplete", where does reasoning come from?
From the fact that predicting text about reasoning requires doing some. A model that completes mathematical proofs, code, and chains of argument at low loss has internalized reusable structure — and post-training amplifies it by rewarding worked-out answers. Honest caveat: how deep that structure goes is genuinely contested territory, which is why Module 07 teaches you to measure capability on your task rather than argue about it.
Why do these models hallucinate?
The pretraining objective rewards plausible continuation, not truth — a fluent wrong answer scores better than an honest "I don't know" in raw next-token terms. Preference tuning reduces this but can't eliminate it, because the model has no ground-truth lookup, only compressed statistics. Engineering answers — retrieval grounding, structured outputs, evals — are Modules 06–08's whole agenda.
Boardroom translation

The pitch to Maya's CFO: "45% of agent time goes to tagging. Automated triage at 8,000 tickets/day reclaims roughly 30 agent-hours daily and cuts time-to-first-touch on P1 outages from hours to seconds — for either ~$50/month (own model) or ~$200/month (rented API), versus ~$0.70 per human-tagged ticket today. Pilot both for two weeks, ship the winner, measure deflection."

And the strategic kicker: the same embedding machinery that classifies tickets also powers semantic search over past resolutions, duplicate-ticket detection, and clustering that surfaces emerging incident themes before the status page knows. One representation, four line items of business value.

Before you leave this section, here is every tool the module leaned on, what you could have picked instead, and when you would change your mind.

The stack, and why

The one question that decides it: do you own a small model or rent a big one for this task, and at what volume? Prices and model names below are as of October 2026; check the vendors' pages before you copy a number.

The tools this module uses, what else you could use, and when to switch (as of October 2026)
LayerWe useAlternativesWhy this oneSwitch when
Language and librariesPython 3.12, NumPyJulia, R, JavaScript with transformers.jsEvery example in this course is Python, and every model library below ships Python first. Honest weakness: slow loops, so we lean on vectorised libraries.You must run the model inside a browser or an edge device with no Python: use transformers.js or ONNX Runtime.
Counting baselinescikit-learn TF-IDF + logistic regressionspaCy, gensim, BM25 (rank_bm25)Trains in a second, needs no GPU, and gives the number a transformer has to beat. Weakness: it cannot see that two differently worded tickets mean the same thing.The baseline misses your accuracy bar on real, paraphrased tickets (the lab measures that gap): move to embeddings or a fine-tune.
Tokenizer (inspection)tiktokenHugging Face tokenizers, SentencePieceShows exactly how an OpenAI-style model splits text and counts your bill. Weakness: it only knows OpenAI's vocabularies, not DistilBERT's or Claude's.You are tokenizing for another model family or training your own vocabulary: use the tokenizer that ships with that model, or SentencePiece for languages without spaces.
Embeddingssentence-transformers, all-MiniLM-L6-v2 (384 numbers per sentence)OpenAI or Cohere embedding APIs, BGE and E5 open modelsSmall enough to run on a laptop CPU, free, and good enough to show the paraphrase gap. Weakness: English-centred and short-context.Your texts are multilingual or longer than a few hundred words, or retrieval quality is the product: use a larger BGE/E5 model or a hosted embedding API.
Fine-tuningHugging Face Transformers Trainer + DistilBERT on PyTorchPlain PyTorch loop, ModernBERT-base, SetFit, Keras or JAXOne object runs the loop you wrote by hand in Module 04, and DistilBERT trains on a CPU in minutes. Weakness: 2019 architecture, and the library moves fast (the pin here allows transformers 4.48 up to 5.x; this code was run on 5.5, and processing_class= is the version-5 name for the old tokenizer=).You have a GPU and want higher accuracy: swap one string for ModernBERT-base. You have under about 50 labelled examples per class: try SetFit or an LLM prompt instead.
Rented alternativeClaude Haiku through the Anthropic APIOpenAI or Gemini APIs, an open model served with vLLMNo training, and a new category is a one-line prompt edit. Weakness: 300–1,500 ms per call and a per-token bill that grows with volume.Volume passes roughly 2,200 tickets a day (the cost crossover in Fig. 5.5e), or latency must stay under about 100 ms: own a small model.

Use TF-IDF to set the floor, a small fine-tuned encoder when volume is high and labels are fixed, and an LLM API when the labels change weekly or the volume is small.

09 · Under the hoodThe Math, If You Want It

Everything Maya needs is built. This section is the algebra underneath it, folded away, for the day a code review asks why you divided by the square root of 64 and you would rather answer than guess. Nothing here is required to ship her classifier or to pass the lab.

Scaled dot-product attention — the formula behind Fig. 5.1

The whole mechanism is one line:

Attention(Q, K, V) = softmax( QKᵀ / √dₖ ) V

Every symbol, in words. Stack your n token embeddings into a matrix X (n rows, d columns). Three learned projection matrices produce Q = XWQ (queries — "what am I looking for?"), K = XWK (keys — "what do I contain?"), and V = XWV (values — "here is my actual content").

QKᵀ is an n×n matrix of dot products — every query against every key. A dot product measures alignment: vectors pointing the same way score high, orthogonal vectors score zero. So entry (i,j) reads "how relevant is token j to token i's question?"

Why divide by √dₖ? For random-ish vectors of dimension dₖ, dot products have variance proportional to dₖ — at dₖ = 64 the raw scores get large, softmax saturates toward one-hot, and the gradients through it vanish (Module 04's disease in a new costume). Dividing by √dₖ normalizes the variance to ~1 and keeps softmax in its trainable regime. It's a numerical-stability trick with a billion-dollar job.

softmax(zᵢ) = ezᵢ / Σⱼ ezⱼ turns each row of scores into a probability distribution — non-negative weights summing to 1, exactly as in the by-hand weights 0.0518, 0.4323 and 0.5159. Multiplying by V then takes, for each token, a weighted average of all value vectors. That average is the contextual embedding.

Multi-head: instead of one attention over d dimensions, run h heads over d/h dimensions each with independent W matrices, and concatenate. Cheap (same total compute), and each head can specialize in a different relation.

Cost: QKᵀ is O(n²·d) in time and O(n²) in memory per layer. Sequence length is the quadratic axis — the root cause of context-window pricing, and the reason inference engines cache K and V per generated token instead of recomputing them (the KV cache — held for Module 12).

TF-IDF and sublinear scaling — why the baseline weighs words the way it does

tfidf(t, d) = tf(t, d) × log(N / df(t)) — term frequency in this document times the log of (total documents N over documents containing t). If every ticket contains "the", N/df = 1 and log(1) = 0: the word contributes nothing.

A word in one ticket of a thousand gets weight log(1000) ≈ 6.9.

With sublinear_tf=True, tf is replaced by 1 + log(tf), so a ticket shouting "error" twenty times isn't treated as 20× more error-ish than one saying it twice — evidence saturates, exactly like your intuition does.

10 · The labTicket Triage, Both Ways — With a Verdict

Maya wants a verdict, and a verdict needs evidence from both paths on the same tickets. The lab hands you roughly 80% of the code and asks for the 20% that turns it into a decision: harder tickets full of paraphrase and typos, one shared evaluation loop, and measured latency and cost at her 8,000-a-day volume. What you hand over at the end is the report, not the notebook.

LAB 05 — Triage Showdown: fine-tuned DistilBERT vs claude-haiku-4-5

Mission: build Maya's classifier both ways, benchmark them on the same held-out set, and fill in the decision table with your own measurements instead of the book's. You have ~80% of the code: finetune_distilbert.py above is path A complete; the snippet below is path B's core. You build the harness — harder test data, shared eval loop, measurements, verdict.

  • Harden the dataset: extend the generator with 5+ paraphrase templates per class ("give me my cash back", "can't get into my account"), random typos, and mixed casing — so template-matching stops being enough
  • Evaluate BOTH classifiers on the same 200 held-out tickets: accuracy and macro-F1, per-class
  • Measure p50/p95 latency per ticket for each path, and compute cost per 1,000 tickets (haiku: from the API's usage token counts at $1/$5 per 1M; DistilBERT: amortized instance cost)
  • Stress test: add a 4th category "Outage" with only 25 training examples — report which approach adapts better and why (data efficiency is the point)
  • README: comparison table, three failure modes you found with example tickets, fix iterations, and a one-paragraph recommendation for 8,000/day

Offline path (no API key): substitute the Hugging Face zero-shot pipeline — pipeline("zero-shot-classification", model="typeform/distilbert-base-uncased-mnli") — as path B. It plays the same role (no task-specific training) with the same comparison structure. Stretch goal: have haiku label 500 fresh unlabeled tickets, fine-tune DistilBERT on those labels, and compare against training on ground truth — you've just performed model distillation, Module 11's opening move.

Step-by-step: what haiku_triage.py does, in plain English
  1. Import Literal for fixed choices, the anthropic client library, and Pydantic's BaseModel.
  2. Define Triage, the shape every answer must take: a category chosen from three fixed strings and an urgency of low or high. The model is not allowed to answer outside this shape.
  3. Create the client. It reads ANTHROPIC_API_KEY from the environment; nothing is hard-coded.
  4. Write the system prompt: the job, a one-line definition of each category, the rule for urgency, and three worked examples. The examples are the "few-shot" part; they replace the 1,200-row training set.
  5. Define classify(ticket): call client.messages.parse with the model name, a token cap, the system prompt, the ticket as the user message, and output_format=Triage. The library validates the reply against Triage, so there is no JSON parsing by hand.
  6. Read msg.usage for the input and output token counts and turn them into dollars at $1 and $5 per million.
  7. Return the parsed object and the cost together.
  8. When run as a script, classify one urgent ticket, print the structured result, and scale the per-ticket cost to 8,000 tickets a day.
haiku_triage.pyneeds API key
# pip install "anthropic>=0.69" "pydantic>=2.8"
"""Path B: few-shot triage with claude-haiku-4-5 + structured output.
Reads ANTHROPIC_API_KEY from the environment — never hardcode keys."""
from typing import Literal
import anthropic
from pydantic import BaseModel

class Triage(BaseModel):
    category: Literal["Billing", "Technical", "Account"]
    urgency: Literal["low", "high"]

client = anthropic.Anthropic()

SYSTEM = """You triage enterprise support tickets.
Categories:
- Billing: charges, refunds, invoices, receipts, payment methods
- Technical: errors, outages, latency, infrastructure, API failures
- Account: access, passwords, permissions, SSO, data requests
urgency=high only for production impact or blocked revenue.

Examples:
ticket: "I was double charged on invoice 4412" → Billing, low
ticket: "prod API returning 500s since 09:00" → Technical, high
ticket: "add a teammate with admin rights" → Account, low"""

def classify(ticket: str) -> tuple[Triage, float]:
    msg = client.messages.parse(          # validated structured output — no JSON parsing
        model="claude-haiku-4-5",
        max_tokens=200,
        system=SYSTEM,
        messages=[{"role": "user", "content": f"ticket: {ticket!r}"}],
        output_format=Triage,
    )
    usage = msg.usage                     # token counts → the lab's cost column
    cost = usage.input_tokens * 1 / 1e6 + usage.output_tokens * 5 / 1e6
    return msg.parsed_output, cost

if __name__ == "__main__":
    result, cost = classify("URGENT: Postgres cluster down, checkout is failing")
    print(result)                         # category='Technical' urgency='high'
    print(f"≈ ${cost:.5f}/ticket → ${cost * 8000:.2f}/day at HelpDeskAI volume")

11 · Interview radarHow This Shows Up in Interviews

Interview radar

"Explain attention to a PM."

The real test No math allowed — can you translate the mechanism into plain language a non-engineer could repeat back?

Strong answer Use one concrete sentence: "In 'the server crashed because the database timed out', the model asks, for the word 'crashed', which other words matter to its meaning — and learns to weight 'database' heavily and 'the' barely at all. Every word does this to every other word at once, which is why the model gets context instead of just keywords."

Land it Connect it to a business capability — search that survives paraphrasing — rather than stopping at the mechanism.

"BERT vs GPT — when would you use each? When would you NOT call an LLM API?"

The real test Vendor-agnostic judgment backed by numbers — staff-level postings (XPENG's, at $215–364K base) literally spec "strong understanding of Transformer architectures and LLM inference".

Strong answer Start with the structural difference: BERT is a bidirectional mask-filling encoder, so it produces understanding outputs like labels and embeddings, while GPT is a causal next-token decoder built for generation. The rule of thumb is that a label, a score or a vector means encoder, and text means decoder. Then make it concrete: 8,000 classifications a day with a stable label set is an encoder job — a fine-tuned DistilBERT costs about $50/month and answers in 10 ms, while an API is 100× the latency and an external dependency in your critical path.

Land it Give the converse decision: I'd rent the LLM when labels shift weekly, volume is low, or the task needs open-ended reasoning.

"Why subword tokenization instead of words or characters?"

Strong answer Walk the trade across the three options:

  • Word-level — the vocabulary explodes, and the model dies on out-of-vocabulary terms
  • Character-level — sequences get about 5× longer, which is brutal under an O(n²) attention bill
  • BPE — compresses frequent patterns into single tokens while keeping byte fallback, so nothing is ever unknown

Land it Cite a consequence you can point to: the strawberry letter-counting failures, and the fact that tokens are the billing unit, with non-English text running 2–3× higher for the same content.

"What does temperature actually do? What breaks at 0? At 2?"

Strong answer Temperature rescales the logits before softmax, sharpening or flattening the output distribution — it does not make the model 'smarter' or 'more random' in any deeper sense. Near 0 the model turns repetitive, which is safe for structured extraction, but that is still not a determinism guarantee. Turned high, you get diversity first and then incoherence, like an autocomplete that keeps picking the tenth-best word.

Land it Mention top-p as the complement that clips the tail instead of rescaling it — marker 1 of Fig. 5.5c, where p = 0.9 keeps A and B and drops C — and that some current APIs (Anthropic's) now manage sampling server-side.

"Why is generating 1,000 tokens so much slower than reading 1,000?"

The real test The staff-level follow-up — a sketch of what happens inside decode is enough; knowing the mechanism at all is the point.

Strong answer Reading is one parallel pass over the whole input, but generation is 1,000 sequential passes, one per token, each attending over everything before it. Engines avoid recomputing keys and values for old tokens by caching them — the KV cache — which turns decode into a memory-bandwidth problem rather than a compute one.

Land it Naming the mechanism here is what separates staff-level answers; the full treatment, plus GQA and batching, arrives in Module 12.

Quick reference — NLP and transformers

stack rule
Fine-tune a small encoder when volume is high and the labels are stable; rent an LLM API when labels change often or volume is low. Measure both before you decide.
tokenizer
Splits text into pieces the model knows. Tokens are money and latency — you pay per token and wait per token.
embedding
A vector that carries meaning, so that similar things sit close together in the space.
The problem with static word embeddings
One vector per word, forever. “Bank” gets a single meaning no matter what surrounds it. (TF-IDF's own problem is different: it counts words and knows nothing about meaning at all.)
self-attention
Every word looks at every other word and decides which ones matter to it. That is what produces a contextual embedding — a different vector for “bank” in each sentence.
Q, K, V
Query, key, value. Each word asks a question (Q), every word offers a label (K), and the answer is a weighted blend of their contents (V).
Multi-head attention
Several attention mechanisms in parallel, each free to track a different kind of relationship.
token id vs embedding
The id is a row number; the embedding is the row stored there. Same token, same row, in every ticket. Only the output of attention changes with context.
softmax
Raise e to each score, then divide by the total. The weights come out positive, in the same order as the scores, and sum to 1.
cosine similarity
Dot product ÷ (length × length): 1 means the same direction, 0 means nothing shared. On TF-IDF vectors that means shared spelling, not shared meaning.
temperature / top-p
Two dials on randomness. Temperature flattens or sharpens the probabilities; top-p keeps only the most likely options that together reach p.

12 · RecapWhat You Can Do Now

  • You can explain the three eras of NLP — counting, meaning, context — and defend when a TF-IDF baseline is still the right ship decision
  • You can compute a TF-IDF cosine similarity by hand, and trace a ticket through a counting classifier to the one feature that decided its label
  • You can trace text → tokens → ids → embeddings, explain why "strawberry has 3 r's" fails, and estimate the token cost of a workload before writing code
  • You can implement scaled dot-product attention in NumPy and read an attention-weight matrix like a debugging artifact
  • You can say by hand what WK, softmax and the √d divide each do to one row of attention weights
  • You can choose encoder vs decoder for a task and justify it with latency and cost numbers, not vibes
  • You can narrate pretrain → SFT → RLHF/DPO and explain why next-token prediction produces capabilities
  • You can fine-tune DistilBERT on a CPU with the Hugging Face Trainer and serve sub-15 ms predictions
  • You can run the fine-tune-vs-API decision with a filled-in cost/latency/quality table and pitch the verdict to a stakeholder
  • You can set temperature and top-p deliberately and predict the failure mode of getting them wrong
🧠 Flex your memory

From this module: close the page and sketch the full pipeline from raw ticket text to a predicted label — tokenizer, embedding lookup, N transformer blocks (what's inside each?), classification head. Annotate where the O(n²) cost lives. Reaching back to Module 04: the transformer block adds each sub-layer's input to its output before normalizing. What is that trick called in the ResNet story, what gradient disease does it prevent, and why does a 96-layer transformer need it even more than a 34-layer CNN did?