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."
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.
"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."
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.
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.
Step-by-step: what tfidf_baseline.py does, in plain English
- Bring in
randomfor building the toy dataset, and five pieces of scikit-learn: the TF-IDF vectorizer, logistic regression, a scoring report, a train/test splitter, andPipeline, which chains steps into one object. - 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. - 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.
- Split the tickets 80/20 into training and test sets.
stratify=labelskeeps the three categories in the same proportions in both halves. - 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, andsublinear_tf=Truereplaces a raw count with 1 + log(count), so repeating a word does not multiply its weight. - Step two is the logistic regression from Module 02, with
max_iter=1000so the solver has room to converge. clf.fitruns both steps in order: learn the vocabulary and word weights from the training texts, then fit the classifier on the resulting vectors.- Predict a category for every test ticket and print precision, recall and F1 per category.
- 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.
# 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.
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.- 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.
- 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.
- 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.
- 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.
- 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.
- 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 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.
- 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.
- 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.
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 (marker 1). The string as the customer typed it, punctuation and typos included. This is the last point at which letters exist.
- 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.
- 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.
- 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.
Step-by-step: what tokens_up_close.py does, in plain English
- 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. - Load the
cl100k_basevocabulary, about 100,000 tokens. Newer OpenAI models useo200k_base; the mechanism is the same, the cuts differ. - 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. - Print the text, how many tokens it became, and the pieces, lined up in columns.
- Call
showfive 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. - 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.
# 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.
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).- 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.
- 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.
- 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:
- "How many r's in strawberry?" fails because the model receives three opaque ids — the r's are sealed inside tokens it never sees as letters. Character-level tasks (counting, reversing, spelling) fight the representation itself.
- Tokens are money and latency. Every API in Act III bills per token and every context window is measured in tokens. Code, JSON, and non-English text tokenize less efficiently than English prose — the same ticket in Japanese can cost 2–3× the tokens.
- Vocabularies differ per model family. Token counts from one tokenizer don't transfer to another; count with the tokenizer of the model you're billing against.
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.
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.
- 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.
- 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.
- 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
- Import NumPy. No framework, on purpose: the whole mechanism is two matrix multiplies and a softmax.
- Name the five tokens of the sentence.
- 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. - Set
W_q,W_kandW_vto 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. - 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. - 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=1means "per row"; per column would be wrong. - Print the table with token names on both axes. A row is the token asking; a column is the token being looked at.
- 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. - Print "crashed" before and after. The after vector has moved toward "database" and "server". That moved vector is the contextual embedding.
# 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.
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.- 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.
- 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.
- 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.
Attention(Q, K, V) = softmax4( Q1 · Kᵀ2 / √d3 ) · V5
- 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.pythat 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. - 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.
- √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.
- 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. - · 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.
| Token | Toy id (row number) | Embedding row [filler, infra] | What the numbers say |
|---|---|---|---|
| the | 0 | [2, 0] | All filler, no infrastructure |
| database | 1 | [0, 2] | No filler, all infrastructure |
| crashed | 2 | [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.
- 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.
- 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.
- 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.
- 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].
- 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.
- 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.
- 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.
| Thing | What it is | In the tiny example | In the real models on this page | Changes with the other words? |
|---|---|---|---|---|
| Token | A piece of text cut by the tokenizer | crashed | ␣re, th and inks in Fig. 5.2b | No |
| Token id | That piece's row number in the vocabulary | 2 | An integer from 0 to 30,521 in DistilBERT | No |
| 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 embedding | The 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 blocks | Yes |
| Sentence embedding | One vector for a whole text, usually the average of its contextual embeddings | Not computed here | 384 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.
- 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].
- 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.
- Divide by √2 (1.4142). −4 ÷ 1.4142 = −2.8284; 0 stays 0; −1 ÷ 1.4142 = −0.7071.
- 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.
- 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.
| Asking token | Identity WK (the pencil exercise) | Flipped WK | What changed |
|---|---|---|---|
| the | 0.8482 · 0.0501 · 0.1017 | 0.0381 · 0.6443 · 0.3177 | Stops looking at itself and looks at the noun |
| database | 0.0287 · 0.4856 · 0.4856 | 0.0287 · 0.4856 · 0.4856 | Nothing: its query [0, 2] has no filler part for the flip to meet |
| crashed | 0.0518 · 0.4323 · 0.5159 | 0.0156 · 0.5356 · 0.4488 | Now looks at "database" more than at itself |
| New vector for "the" | [1.7472, 0.3036], still mostly filler | [0.2350, 1.9238], now mostly infrastructure | It carries the noun's content instead of its own |
- 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.
- 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.
- "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:
- No weight is below zero. A negative share would subtract a token's content from the new vector.
- The weights add up to 1. Then the new vector is an average of the values and stays in their range.
- A higher score never gets a lower weight. Otherwise the ranking the scores express is lost.
| Row | Scores | Total | Score ÷ total | Softmax | Promise plain division breaks |
|---|---|---|---|---|---|
| "crashed" asks the, database, crashed | −0.7071, 2.8284, 2.6517 | 4.7730 | −0.1481, 0.5926, 0.5556 | 0.0156, 0.5356, 0.4488 | 1: "the" gets a negative weight |
| "the" asks the, database, crashed | −2.8284, 0, −0.7071 | −3.5355 | 0.8000, 0.0000, 0.2000 | 0.0381, 0.6443, 0.3177 | 3: the ranking comes out upside down |
| Any row scoring −1 and +1 | −1, +1 | 0 | Division by zero | 0.1192, 0.8808 | 2: there is no share of a total of 0 |
Softmax keeps all three promises. Here it is by hand on the row for "the":
- 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.
- Add them up. 0.0591 + 1.0000 + 0.4931 = 1.5522. A total of positive numbers can never be zero or negative.
- 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.
- 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.
- 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.
- 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.
- 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.
| d | Divide by √d? | Spread of the scores | Median top weight | Rows where one token gets over 0.99 | Average slope of the top weight |
|---|---|---|---|---|---|
| 2 | No | 1.41 | 0.4541 | 0.5% | 0.2135 |
| 2 | Yes, ÷ 1.4142 | 1.00 | 0.3830 | 0.0% | 0.2189 |
| 64 | No | 7.97 | 0.9823 | 44.8% | 0.0702 |
| 64 | Yes, ÷ 8 | 1.00 | 0.4320 | 0.0% | 0.2306 |
Here is the first of those rows at d = 64, as the script prints it.
- Five raw scores. −0.74, −5.52, −9.99, −4.05 and −4.50. The top score beats the next one by 3.31.
- 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.
- Divide by √64 = 8. −0.09, −0.69, −1.25, −0.51 and −0.56. Same order, eight times closer together.
- 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.
- 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.
- 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.
- 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.
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.
paraphrase_gap.py.- 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".
- 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.
- 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
- Import the TF-IDF vectorizer and a cosine-similarity helper from scikit-learn.
- 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.
- Fit TF-IDF on the three sentences at once and turn them into three sparse count vectors.
- 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.
- Load
all-MiniLM-L6-v2, a small sentence-embedding transformer.normalize_embeddings=Truescales each vector to length 1, so a plain dot product is a cosine. - Encode the query and the paraphrase, take their dot product, and print it. Expect about 0.7 where TF-IDF gave about 0.11.
- The closing comment is the honest part: embeddings also score the distractor high. Their advantage is catching the paraphrase, not rejecting the monkey.
# 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.
| # | Sentence | Where it comes from | What a person would say it means |
|---|---|---|---|
| 1 | please refund my money | The query in paraphrase_gap.py | Billing: a refund request |
| 2 | give me my cash back | The paraphrase | Billing: the same request in other words |
| 3 | please refund my monkey | The one-letter distractor | Nonsense, or a typo of sentence 1 |
| 4 | URGENT: prod Postgres cluster throwing 500s and timing out | Monday's outage ticket in tfidf_baseline.py | Technical, 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
| Sentence 1 against sentence 2 (the paraphrase) | Sentence 1 against sentence 3 (the distractor) | |
|---|---|---|
| Words in common | my | please, refund, my |
| Dot product | 1.0000 | 4.3163 |
| Lengths multiplied | 2.6801 × 3.5309 = 9.4631 | 2.6801 × 2.6801 = 7.1830 |
| Cosine | 0.1057, printed as 0.11 | 0.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 angle | 53.1° |
| What a person sees | The same request | Nonsense |
- 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.
- 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°.
- 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.
- 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".
- 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.
- 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.
- 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.
- 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.
- 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.
- 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".
- 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.
- 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.
- 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.
| The ticket as sent | The same ticket without "and" | |
|---|---|---|
| Terms the model knows | and | None |
| 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 |
| Answer | Account 0.6727 | Technical 0.4248 |
| Why | The one known word was only ever seen in Account tickets | Nothing 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.
| Training set | Test set | |
|---|---|---|
| Tickets | 960 | 240 |
| Distinct sentences, ignoring the id number | 12 | 12, the same 12 |
| Copies of each sentence | 67 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.
| Sentence | A person says | The model says | Terms it knew | Why it answered that |
|---|---|---|---|---|
| 1 · please refund my money | Billing | Billing 0.5621 | my, 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 back | Billing | Billing 0.5660 | my | "my" alone, learned from the Billing template "Payment failed but my card still shows an active charge" |
| 3 · please refund my monkey | Nonsense | Billing 0.5621 | my, please, refund | Exactly sentence 1's answer: "money" and "monkey" are both unknown, so the two vectors are identical |
| 4 · the outage ticket | Technical | Account 0.6727 | and | "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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
Tonight's talk: The Tokenizer and The Model argue over the question, "Who's more important?"
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:
- Multi-head attention — run 8–128 spotlights in parallel, each with its own learned Q/K/V projections, and concatenate the results. Different heads specialize in different relationships.
- A feed-forward MLP — after attention mixes information across tokens, a two-layer network (Module 04's dense layers) processes each token individually. Rough intuition: attention gathers, the MLP thinks. Most of a model's parameters live here.
- Residual connections + normalization — each sub-layer's output is added to its input rather than replacing it. This is exactly the ResNet skip-connection trick from Module 04, and it's what lets gradients survive a 96-layer stack. Position information is injected at the bottom so attention — which is otherwise order-blind — knows token 3 from token 30.
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.
| Stage | In the from-scratch versions (sections 02–04) | In finetune_distilbert.py (section 08) | What flows out |
|---|---|---|---|
| Tokenize | TfidfVectorizer splits on its default word pattern; enc.encode(text) in tokens_up_close.py applies BPE merges | tok(b["text"], truncation=True, max_length=128): WordPiece, lowercased, 30,522-entry vocabulary | A list of integer ids, at most 128 long, plus a mask saying which positions are real |
| Look up embeddings | The hand-typed E matrix in attention_from_scratch.py: 5 rows × 4 numbers | The model's embedding table, 30,522 rows × 768 numbers, learned in pretraining | One 768-number vector per token |
| Add position | None; the toy does not know word order | A learned vector per position (512 × 768) added to each token's vector | Vectors that also encode where each token sits |
| Self-attention | scores = Q @ K.T / np.sqrt(d), one head, identity projections | 12 heads per block, each with learned WQ, WK, WV of 768 × 64 | Each token's vector re-mixed with the tokens that matter to it |
| Feed-forward MLP | None | A two-layer network, 768 → 3072 → 768, applied to every token on its own | Each token's vector, processed individually |
| Add & norm, repeat | None; one pass and stop | Residual add and layer normalization after each sub-layer; six blocks stacked | A final contextual vector per token |
| Head | LogisticRegression on the TF-IDF vector in tfidf_baseline.py | Two fresh linear layers (768 → 768 → 3) on the first token's vector, added by AutoModelForSequenceClassification | Three logits, one per category |
| Train | clf.fit(X_tr, y_tr), about two seconds | trainer.train(): two epochs at learning rate 5e-5, updating all 66 million weights, about five minutes on CPU | triage-distilbert/final, the directory you deploy |
| Predict | clf.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.
- 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.
- 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.
- 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:
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.
- 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.
- 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.
- 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:
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.
- 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.
- 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.
- 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.
| Setting | P(token A) | P(token B) | P(token C) | Feels like |
|---|---|---|---|---|
| T = 0.5 | 0.84 | 0.11 | 0.05 | Confident, near-deterministic — extraction, classification |
| T = 1.0 | 0.63 | 0.23 | 0.14 | The model's honest distribution |
| T = 2.0 | 0.48 | 0.29 | 0.23 | Adventurous — brainstorming, at coherence risk |
The same three numbers from that table, drawn as bars, so the word "sharpen" has something to point at.
- 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.
- 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.
- 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.
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.
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.- 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.
- 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.
- 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
- Imports:
random,time,torch, the Hugging FaceDatasetclass, two metric functions from scikit-learn, and four Hugging Face classes:AutoTokenizer,AutoModelForSequenceClassification,TrainerandTrainingArguments. - Define
LABELSand the sameTEMPLATESas the baseline, so both models are judged on the same data. - Build 1,200 rows of
{"text", "label"}. The label is stored as an integer position inLABELS, which is what the model's loss function expects. - Convert the rows into a Hugging Face
Datasetand split it 80/20 with a fixed seed. - 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. - Map the tokenizer over the dataset in batches: each text becomes a list of ids plus an attention mask, cut at 128 tokens.
- Load the pretrained model with a new classification head for three labels. The library warns that the head is untrained; that is expected.
id2labelmakes the saved model report names instead of numbers. - Define
metrics: take the highest logit per row as the prediction and compute accuracy and macro-F1 against the true labels. - 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.
- Build the
Trainerfrom the model, arguments, datasets, tokenizer and metrics, then calltrain(). This is the loop you wrote by hand in Module 04, run for you. - Evaluate on the test split and print the metrics.
- 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. - 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.
-
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
- Import
randomand fix the seed to 42, so every run draws the same tickets. - Define the three labels. A label's position in the list (0, 1, 2) is the number the model will later predict.
- Write four template sentences per label.
{id}is a blank filled with a random four-digit number. - Loop 1,200 times: pick a label, pick one of its templates, fill the blank, and store the text with its label number.
- Print the row count, the first row, and how many rows each label got.
finetune_distilbert.py — chunk 1runs offlineimport 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.choicepicks one item from a list;str.formatfills 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 output1200 rows; first: {'text': 'Password reset email never arrives', 'label': 2} per label: [399, 395, 406] - Import
-
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
- Wrap the rows in a Hugging Face
Datasetand split them 80/20 with a fixed seed. - Load the tokenizer that belongs to
distilbert-base-uncased. It must match the model you load next. ds.map(...)runs the tokenizer over every ticket in batches and addsinput_idsandattention_maskcolumns.- Print the split sizes and the first few tokens of one ticket.
finetune_distilbert.py — chunk 2runs offlinefrom 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_splitandDataset.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 outputDatasetDict({ 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'] ... - Wrap the rows in a Hugging Face
-
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
- Load
DistilBERTfor sequence classification withnum_labels=3. The library adds a new head on top of the pretrained body. - Pass the label names in both directions, so the saved model can say "Billing" instead of "0".
- Write
metrics: take the logits, pick the largest per ticket withargmax, and compare with the true labels. - Print the parameter count and the new head.
finetune_distilbert.py — chunk 3runs offlinefrom 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 aLinear(768 → 3)head. The model is still untrained at this point, so its guesses are no better than chance.terminalactual outputparameters: 66955779 new head: Linear(in_features=768, out_features=3, bias=True) - Load
-
Chunk 4 — fine-tune for two passes and score on the test split
Everything is ready: tokenized data, a model, a scoring function. The
Trainerruns 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
- Set the training arguments: batch size 16, two epochs, learning rate 5e-5 (small, because we nudge pretrained weights), evaluate each epoch.
- Build the
Trainerfrom the model, arguments, both splits, the tokenizer and themetricsfunction. trainer.train()runs the loop;trainer.evaluate()scores the test split.
finetune_distilbert.py — chunk 4not run here: trainingfrom 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 dataTrainingArgumentsandTrainer— the settings, and the object that runs the loop.processing_class=tokhands 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.pyto see your own numbers. -
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
- Switch to
eval()mode so dropout is off. - Tokenize one new ticket as PyTorch tensors.
- Run the model inside
torch.no_grad()so no gradients are stored, and apply softmax to turn the three scores into probabilities. - Measure the elapsed milliseconds, print the winning label with its probability, and save the model folder.
finetune_distilbert.py — chunk 5not run here: trainingimport 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 directorytorch.no_grad()— skips gradient bookkeeping at inference.softmax— turns raw scores into probabilities that sum to 1. This chunk adds thetimeandtorchimports at the top.Not run here, for the same reason as chunk 4. Running
python3 chunk5_infer.pyprints one line shaped likeTechnical 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. - Switch to
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.
# 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:
| Dimension | Fine-tuned encoder (DistilBERT/ModernBERT) | LLM API (claude-haiku-4-5, few-shot) |
|---|---|---|
| Latency | 2–15 ms local; no network hop | 300–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 set | Excellent once trained on 500–2,000 labeled examples | Excellent zero/few-shot; better on weird edge cases and long tickets |
| Data needed | Hundreds of labeled examples per class | 3–10 examples in the prompt; no training set |
| New category tomorrow? | Relabel + retrain (hours) | Edit the prompt (minutes) |
| Ops burden | You own serving, monitoring, retraining | Vendor owns the model; you own prompts, evals, rate limits, and an outage dependency |
| Privacy / residency | Data never leaves your VPC | Data transits a vendor (contracts permitting) |
| Choose when… | High volume, tight latency, stable labels, labeled data exists | Low 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.
- 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.
- 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.
- 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.
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.
| Layer | We use | Alternatives | Why this one | Switch when |
|---|---|---|---|---|
| Language and libraries | Python 3.12, NumPy | Julia, R, JavaScript with transformers.js | Every 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 baseline | scikit-learn TF-IDF + logistic regression | spaCy, 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) | tiktoken | Hugging Face tokenizers, SentencePiece | Shows 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. |
| Embeddings | sentence-transformers, all-MiniLM-L6-v2 (384 numbers per sentence) | OpenAI or Cohere embedding APIs, BGE and E5 open models | Small 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-tuning | Hugging Face Transformers Trainer + DistilBERT on PyTorch | Plain PyTorch loop, ModernBERT-base, SetFit, Keras or JAX | One 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 alternative | Claude Haiku through the Anthropic API | OpenAI or Gemini APIs, an open model served with vLLM | No 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.
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
usagetoken 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
- Import
Literalfor fixed choices, theanthropicclient library, and Pydantic'sBaseModel. - 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. - Create the client. It reads
ANTHROPIC_API_KEYfrom the environment; nothing is hard-coded. - 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.
- Define
classify(ticket): callclient.messages.parsewith the model name, a token cap, the system prompt, the ticket as the user message, andoutput_format=Triage. The library validates the reply againstTriage, so there is no JSON parsing by hand. - Read
msg.usagefor the input and output token counts and turn them into dollars at $1 and $5 per million. - Return the parsed object and the cost together.
- 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.
# 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
"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
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?