Lesson 1.1Module 1: Understanding Claude and modern AI
What is Claude?
Learning objectives
- Describe what Claude is, who makes it and how the model family is organised into tiers.
- Tell apart the model (a file of learned numbers) from the product built around it (system prompt, tools, memory, interface).
- Explain what Claude is not: not a database, not a search engine, and not always right.
- Separate what Anthropic has published about Claude from what is proprietary.
- Read a minimal API call, and see the same call against a local open-weight model.
This course is called "How to Build Claude from Scratch", so the first job is to be precise about what "Claude" actually is. The word is used for several different things at once: a chat app on your phone, an API that programmers call, a coding tool in the terminal, and a family of neural networks running in data centres. Untangling those is the single most useful idea in this module, because it tells you which parts you can really build yourself (quite a lot) and which parts only a frontier lab can build (the very large model).
Analogy: the engine and the car
Think of the model as an engine and the product as the car built around it. The engine turns fuel into motion; on its own it has no seats, no steering wheel and no dashboard. Carmakers put the same engine into different cars, and two cars with the same engine can feel very different to drive. Claude-the-model is the engine: it turns text into more text. Claude-the-app is one car (chat window, saved conversations, file upload, safety checks, tools). Your own chatbot, built later in this course, is another car, possibly with the same engine rented through the API, or with a smaller open-weight engine running on your laptop.
Claude in one paragraph
Claude is an AI assistant made by Anthropic, an AI safety and research company founded in 2021. The first Claude model was released to the public in 2023, and new generations have followed regularly since. Under the hood, Claude is a large language model (LLM): a neural network trained on very large amounts of text to predict what text comes next, then trained further to behave like a helpful assistant. You talk to it in ordinary language and it answers in ordinary language, but it can also write and explain code, summarise long documents, reason through problems step by step, read images, and call tools such as a web search or a code runner when the application gives it those tools.
Anthropic describes its goal for Claude as being helpful, honest and harmless. That phrase came out of Anthropic's early alignment research and still shapes how the models are trained and evaluated. We come back to it below and in much more depth in lesson 6.2 on Constitutional AI.
A family of models, not one model
"Claude" is not one fixed program. It is a model family that is released in generations, and each generation comes in several sizes or tiers. Larger models are generally more capable but slower and more expensive to run; smaller models answer faster and cost less per request. Anthropic has used poetic names for the tiers:
| Tier | Positioning | Typical uses |
|---|---|---|
| Haiku | Smallest and fastest; lowest cost per token | High-volume classification, extraction, quick replies, sub-tasks inside larger systems |
| Sonnet | Balance of capability, speed and cost | Everyday coding, writing, analysis, most production chat and agent workloads |
| Opus | Most capable of the three classic tiers | Hard reasoning, long multi-step agent tasks, difficult code changes |
Newer generations have added further tiers and names, and every model has a version. When you call the API you choose a model by its model id, a string such as claude-opus-5-5 or claude-haiku-5-5. These names change as new models ship and old ones are retired, so treat any id in this course as an example and check the models page in Anthropic's documentation for the current list.
Why offer several sizes instead of just the best one? Because cost and speed matter in real products. A support bot that sorts 10 million emails a month into five categories does not need the largest model; a cheap, fast one is good enough and the bill is a fraction of the size. A coding agent that has to change twenty files without breaking anything benefits from the most capable model. Choosing the right tier for each job is a real engineering skill, and we practise it in lesson 11.9 on cost optimisation.
How people use Claude
The same models reach people through several doors:
- Chat apps. The Claude apps on the web, desktop and mobile. You type, Claude answers; the app keeps your conversations, lets you upload files and turns on features such as web search.
- The API. Programmers send HTTPS requests to Anthropic's Messages API and get the model's reply back as JSON. This is how companies put Claude inside their own products, and how you will connect your own app to a real model in module 7.
- Coding tools. Claude Code runs in a terminal or editor and lets the model read files, run commands and edit code, with the developer approving actions.
- Cloud platforms. The models are also offered through major cloud providers such as Amazon Bedrock and Google Cloud Vertex AI, so companies can use them inside the cloud account they already have.
Every one of these is a different product. They share model families, but each adds its own instructions, tools and interface. That is why the same question can get a slightly different answer in the chat app and through a bare API call: the model is similar, the car around it is not.
The model versus the product
Here is the picture that frames the whole course. Click any box for an explanation.
- You
- The person typing. Everything you type becomes part of the text the model reads.
- Interface
- The chat window, mobile app or terminal tool. It shows a conversation, renders Markdown and code, and streams the answer as it arrives. You build one in module 7.
- System prompt
- Instructions written by whoever built the product ("You are a support assistant for…, answer briefly, never…"). The user usually doesn't see it, but the model reads it first on every request. See lesson 6.7.
- History + memory
- The model itself remembers nothing between requests. The product stores the conversation and sends it again each time; some products also save long-term notes or search your documents (module 8).
- API + inference server
- Receives the request, checks the API key and limits, turns the conversation into tokens, runs the model on accelerators and streams tokens back.
- Tools
- Functions the application lets the model call: web search, a calculator, code execution, your database. The model only asks for a tool; the application runs it and returns the result (module 9).
- Safety checks
- Usage policies, abuse monitoring and classifiers that can flag or block some requests or outputs. They sit around the model in addition to the behaviour trained into it.
- Model weights
- The trained neural network: a very large set of numbers (parameters) plus the code that runs them. Given tokens, it outputs probabilities for the next token. That is all it does. You build tiny versions in module 4 and module 5.
- Training
- The expensive, one-off process that produced the weights: pretraining on huge text collections, then fine-tuning and preference training to make it a helpful assistant (lesson 1.3, module 6).
Keep this picture in mind. When people say "Claude remembered my name", it was the product that stored the conversation and sent it back. When people say "Claude searched the web", the model asked for a search and the application performed it. When people say "Claude knows Python", that knowledge lives in the weights. Modules 2 to 5 build the right-hand side in miniature; modules 7 to 12 build the left-hand side for real.
Helpful, honest and harmless
A raw language model will continue any text in any direction, including unhelpful, false or dangerous ones. Anthropic's stated aim is an assistant that is helpful (it actually does what you need, well), honest (it doesn't make things up on purpose, admits uncertainty and doesn't deceive) and harmless (it declines to help with things that could seriously hurt people). These goals sometimes pull against each other: refusing everything is harmless but useless, and agreeing to everything is "helpful" but harmful. Much of the post-training work you will meet in module 6 is about balancing them.
Anthropic has published several pieces of how it approaches this, including the Constitutional AI method (Bai et al., 2022), in which a written set of principles is used to have the model critique and revise its own answers and to train a preference model from AI feedback, and a public document describing the values and priorities it wants Claude to have (often called Claude's constitution). It has also published a Responsible Scaling Policy that ties safety measures to model capability levels.
What Claude is not
Beginners often picture an AI assistant as a very smart search engine or a giant database of facts. Both pictures lead to bad decisions.
Database / search engine
Stores exact records and returns them unchanged. Knows exactly what it has and what it doesn't. Search engines crawl the live web and point you to sources.
Language model
Has no table of facts. Knowledge is spread across millions of numbers as statistical patterns. It generates a plausible answer each time, has a training cutoff date, and can't tell for certain whether a detail is remembered or invented.
- Not a database. Ask for the exact text of page 214 of a book and you may get something plausible but wrong. If exact data matters, give the model the data (paste it, attach the document, or retrieve it with RAG in lesson 8.5).
- Not a search engine. The weights were frozen at the end of training. Without a search tool the model does not know today's news, prices or the latest library version.
- Not always right. LLMs can produce confident, fluent statements that are false, often called hallucinations. Careful training reduces them but nobody has eliminated them. Lesson 5.9 explains where they come from.
- Not a person with memory. Each API request is independent. Any "memory" is the product re-sending text.
What is public and what is not
Because this course is about building something like Claude, we must be honest about which parts are documented. Throughout the course you will see these badges: Public means Anthropic or a peer-reviewed paper has described it; Industry practice means it is how LLMs are generally built, not confirmed for Claude; Not public means it is proprietary and we will not guess.
| Topic | Status | What we can say |
|---|---|---|
| Basic kind of model | Public | A transformer-based large language model. |
| Alignment approach | Public | RLHF research for helpful and harmless assistants, Constitutional AI, a published constitution. |
| API features | Public | System prompts, streaming, tool use, vision, long context windows (check the docs for current limits). |
| Pretraining then fine-tuning recipe | Industry practice | The general pipeline every assistant follows (lesson 1.3); exact details for Claude are not published. |
| Parameter count and layer layout | Not public | Not disclosed. |
| Training data mix, hardware, cost | Not public | Not disclosed beyond high-level descriptions. |
Your first API call Optional
You don't need an account to follow this course; every runnable example works offline. But it helps to see how small the gap is between "a model in a data centre" and "my code". Below is the same question asked three ways: with Anthropic's Python SDK, with a raw HTTP request, and to a free open-weight model running locally with Ollama. These examples were not executed by our tests, because they need an API key or a local model server.
pip install anthropic
export ANTHROPIC_API_KEY="sk-ant-..." # your key from the Claude Console# Minimal Claude API call.
# Needs: pip install anthropic, and an API key in the ANTHROPIC_API_KEY environment variable.
# Not executed by the course tests: it calls a paid web API.
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
response = client.messages.create(
model="claude-opus-5-5", # model ids change over time: check the docs for current ones
max_tokens=1024, # the longest reply we accept, counted in tokens
system="You are a patient tutor for beginner programmers. Answer briefly.",
messages=[
{"role": "user", "content": "In one sentence, what is a large language model?"},
],
)
# The reply is a list of content blocks; we only print the text ones.
for block in response.content:
if block.type == "text":
print(block.text)
print("stop_reason:", response.stop_reason)
print("tokens in/out:", response.usage.input_tokens, response.usage.output_tokens)curl https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2026-10-21" \
-H "content-type: application/json" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"system": "You are a patient tutor for beginner programmers. Answer briefly.",
"messages": [
{"role": "user", "content": "In one sentence, what is a large language model?"}
]
}'ollama pull llama3.2 # downloads an open-weight model (a few GB) once# The same conversation sent to an open-weight model running on your own computer with Ollama.
# Needs: Ollama installed (https://ollama.com), then `ollama pull llama3.2` once.
# Uses only the Python standard library. Not executed by the course tests (it needs a local Ollama server).
import json
import urllib.request
body = {
"model": "llama3.2", # any model you have pulled locally
"messages": [
{"role": "system", "content": "You are a patient tutor for beginner programmers. Answer briefly."},
{"role": "user", "content": "In one sentence, what is a large language model?"},
],
"stream": False, # ask for one complete JSON answer instead of a stream of pieces
}
request = urllib.request.Request(
"http://localhost:11434/api/chat", # Ollama listens on port 11434 by default
data=json.dumps(body).encode("utf-8"),
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request) as response:
reply = json.load(response)
print(reply["message"]["content"])What the SDK version does, line by line:
import anthropic: loads Anthropic's official Python library, which wraps the HTTPS calls, retries and error types for you.client = anthropic.Anthropic(): creates a client. With no arguments it reads your key from theANTHROPIC_API_KEYenvironment variable, so the key never appears in your code.model="claude-opus-5-5": chooses which model in the family answers. Swap in a Haiku or Sonnet id to trade capability for speed and cost.max_tokens=1024: a hard upper limit on the reply length, measured in tokens (word pieces, see lesson 1.6). If the model hits it, the reply is cut off andstop_reasonsaysmax_tokens.system=…: the system prompt, the product-builder's instructions from the diagram above.messages=[…]: the conversation so far, as a list of turns with arole(userorassistant) andcontent. To continue a chat you append the reply and the next question and send the whole list again.for block in response.content: the answer comes back as a list of content blocks (text, and for some features tool calls or reasoning blocks). We print only the text blocks.response.usage: how many tokens you sent and received. API pricing is per token, so this is how you track cost.
A large language model is a neural network trained on huge amounts of text to predict the next piece of text, which lets it answer questions, write and summarise.
stop_reason: end_turn
tokens in/out: 39 37The Ollama version sends almost the same JSON (a model name and a list of messages) to a server on your own machine. That similarity is not an accident: nearly every chat model API today uses this "list of role-tagged messages" shape, which makes it easy to swap providers. The open model you download is much smaller than a frontier model and will make more mistakes, but it is free, private and runs offline, which is perfect for learning. Lesson 11.4 covers running open-weight models properly.
Why the model/product split matters to an engineer
Once you see the split, a lot of confusing behaviour becomes predictable:
- Statelessness. The Messages API is stateless: every request carries the full conversation. A 30-turn chat sends turn 1 thirty times. That is why long chats cost more per message, why context windows matter (lesson 1.6) and why techniques such as prompt caching exist.
- Same weights, different behaviour. Chat apps add a long system prompt, tools and formatting rules. A bare API call has none of that unless you add it, so answers can be shorter, plainer or differently formatted.
- Versioned snapshots. A model id refers to a fixed set of weights. Providers release new models and eventually retire old ones, so production code should keep the model id in configuration and you should re-test your prompts when you upgrade.
- Where the work happens. Inference (running the model) needs specialised accelerators with a lot of fast memory. The product side is ordinary web engineering: HTTP, databases, queues, auth and front-end code. That second half is exactly the part you can build completely yourself.
- Swappable engines. If your product talks to the model through a thin interface ("send messages, receive text"), you can switch between a hosted Claude model, another provider and a local model with one setting. The capstone in lesson 12.5 does exactly this.
A realistic note on scale: training a frontier model is publicly estimated to use thousands to tens of thousands of accelerators for weeks to months, trillions of tokens of text and tens to hundreds of millions of dollars. Those are general industry estimates, not Claude figures. This course will not pretend otherwise: you will build small but real versions of every component, then use hosted or open-weight models for the heavy lifting.
Common mistakes and debugging tips
Expecting the API to remember the previous request
Beginners send "My name is Sam", then in a separate request ask "What's my name?" and are surprised the model doesn't know. Each request is independent.
Fix: keep a list of messages in your program, append both the user turn and the assistant reply, and send the full list every time.
Putting the API key in source code
Keys pasted into a script end up in Git history, screenshots and shared notebooks, and anyone who has the key can spend your money.
Fix: read the key from an environment variable or a secrets manager, add .env to .gitignore, and revoke any key that has leaked.
Treating answers as looked-up facts
Fluent, confident text feels authoritative, but the model generated it from patterns. Quotes, numbers, citations and API names are where errors hide most often.
Fix: give the model the source material, ask it to quote from it, and verify anything important against a primary source.
Hard-coding a model id forever
Model ids are retired over time; code that hard-codes one can suddenly fail with a "model not found" error.
Fix: keep the model id in configuration, watch the provider's deprecation notices and re-run your tests when you switch.
Key takeaways
- Claude is a family of LLMs from Anthropic, offered in tiers that trade capability for speed and cost.
- The model only maps tokens to next-token probabilities; the product adds instructions, memory, tools, safety checks and an interface.
- An LLM is not a database or a search engine; it generates plausible text and can be wrong.
- Architecture size, data and training details of Claude are not public; the general recipe and the API are.
Exercise: model or product?
For each behaviour, decide whether it comes mainly from the model weights or from the product around them, and say why: (a) the app shows your chats from last week; (b) Claude writes a correct Python list comprehension; (c) the answer streams in word by word; (d) Claude quotes today's headline; (e) a company's support bot only talks about that company's products; (f) the reply is in French because you wrote in French.
Hint
Ask: "Would this still happen if I sent a single bare API request with no system prompt and no tools?" If yes, it's mostly the model. If it needs stored data, live data, instructions or display code, it's the product.
Show a solution
- (a) Product: chats are stored in the app's database; the model remembers nothing.
- (b) Model: knowledge of Python syntax is learned during training and lives in the weights.
- (c) Both, mostly product: the model produces one token at a time, but streaming them to your screen is the server and interface (lesson 1.5).
- (d) Product: the weights are frozen at a training cutoff, so a fresh headline must come from a search tool the app provides.
- (e) Product: a system prompt (and possibly retrieved documents) restricts the topic.
- (f) Model: matching the user's language is learned behaviour, although a system prompt could override it.
Check your understanding
You ask the same question in the Claude chat app and with a bare API call to a similar model, and the answers differ in style. What is the most likely reason?
- The API uses a completely different kind of AI
- The app adds its own system prompt, tools and formatting around the model
- The API is always less capable than the app
Which statement about Claude is public information?
- Its exact parameter count
- The exact mix of its training data
- That Anthropic uses Constitutional AI and RLHF-style training for helpfulness and harmlessness
Why do model families come in several tiers such as Haiku, Sonnet and Opus?
- To let builders trade capability against speed and cost per task
- Because each tier speaks a different language
- Because smaller tiers are trained on secret data
Lesson 1.2Module 1: Understanding Claude and modern AI
What is an LLM?
Learning objectives
- Explain the one job every large language model is trained to do: predict the next token.
- Say what "large" means in practice: parameters, training data and compute, with honest, dated numbers.
- Build and run a tiny counting-based language model and see generation as a loop of predictions.
- Explain why next-token prediction at scale produces abilities such as translation, coding and summarising, and where it breaks.
In lesson 1.1 we separated the model from the product. This lesson opens up the model. The good news is that the idea at its centre is small enough to fit in one sentence and in about forty lines of Python. The surprising news is that the same idea, scaled up by many orders of magnitude, is what powers Claude, ChatGPT, Gemini and every other modern chat assistant.
Analogy: the phone keyboard that read a library
Your phone keyboard suggests the next word as you type: after "see you" it offers "soon", "tomorrow" and "later". It learned those suggestions from lots of typed messages. Now imagine a keyboard that has read a large slice of the public internet, millions of books and most open-source code, and that considers the whole page you have written so far rather than just the last two words. Its suggestions would stop being single words and start being whole, sensible paragraphs. That is a large language model: an autocomplete so well read that continuing your text looks like understanding it.
The one job: predict what comes next
A language model is a program that assigns probabilities to text. Give it the beginning of a piece of text, called the context or prompt, and it returns a probability for every possible next piece. For the context "The cat sat on the", a good English language model might give "mat" a probability of 0.31, "floor" 0.12, "sofa" 0.09, "roof" 0.04, and so on, down to tiny probabilities for pieces that make no sense, such as "purple" or "the". All of those probabilities add up to 1.
The pieces are not exactly words. Models work with tokens: common words, parts of words, punctuation and single bytes. "unbelievably" might be three tokens, "the" is usually one. Lesson 1.6 covers tokens properly; for now, read "token" as "a word or a piece of a word".
Predicting one token is all the model does. To write a whole answer, software around the model runs a loop: ask for the probabilities, pick one token, add it to the end of the text, and ask again with the slightly longer text. Repeat until the model produces a special "end" token or a length limit is reached. Every paragraph Claude has ever written was produced this way, one token at a time. You will see the loop in code below and again, in more detail, in lesson 1.5.
What makes it "large"
"Large" refers to three things that grow together.
- Parameters. The model is a neural network, and a neural network is mostly a very long list of numbers called parameters or weights. During training these numbers are nudged, billions of times, until the network's predictions get good. For scale: GPT-2 (OpenAI, 2019) had 1.5 billion parameters; GPT-3 (2020) had 175 billion. Open-weight models you can download today range from under 1 billion to several hundred billion parameters. Frontier labs, including Anthropic, do not publish the parameter counts of their current models, so any number you read for Claude is a guess.
- Training data. Models learn from text measured in tokens. Published examples: Meta reported training its Llama 3 models (2024) on more than 15 trillion tokens. A human reading 300 words a minute for 8 hours a day would need hundreds of thousands of years to read that much.
- Compute. Training multiplies every parameter by numbers from every token, many times over. Public estimates for frontier models in general are thousands to tens of thousands of accelerators (GPUs or similar chips) running for weeks to months, at a cost of tens to hundreds of millions of US dollars (estimates as of 2026, not figures for Claude specifically).
Researchers found around 2020 (for example Kaplan et al., 2020, and Hoffmann et al., 2022) that prediction quality improves smoothly and predictably as these three grow together, a pattern described as scaling laws. That finding is why labs kept building bigger models: they could forecast roughly how much better the next one would be before training it.
A language model you can read
Before neural networks, the classic way to build a language model was to count. A bigram model looks only at the previous word and asks: in my training text, which words followed this one, and how often? Turn those counts into fractions and you have probabilities for the next word. It is far too simple to be useful, but it has the same shape as an LLM: train on text, predict the next piece, generate by looping.
Simplified implementation Simplified
This model works on whole words, sees only one word of context and stores a table of counts. Real LLMs work on tokens, see hundreds of thousands of tokens of context and use a neural network instead of a table. Do not read this as a small Claude: read it as the shape of the problem.
# @run
# A tiny "language model": count which word follows which (a bigram model), then predict the next word.
# Simplified on purpose: real LLMs use neural networks over tokens, not a table of word pairs.
from collections import Counter, defaultdict
import random
corpus = """
the cat sat on the mat .
the cat chased the mouse .
the dog sat on the rug .
the dog chased the cat .
a mouse ate the cheese .
the cat ate the fish .
"""
# 1. Training: split the text into words and count every (word, next word) pair.
words = corpus.split()
counts = defaultdict(Counter)
for current, nxt in zip(words, words[1:]):
counts[current][nxt] += 1
# 2. Turn counts into probabilities: P(next | current) = count / total.
def next_word_probs(word):
following = counts[word]
total = sum(following.values())
return {w: c / total for w, c in following.most_common()}
for word in ["the", "cat", "sat"]:
probs = next_word_probs(word)
shown = ", ".join(f"{w} {p:.2f}" for w, p in probs.items())
print(f"after '{word}': {shown}")
# 3. Generation: repeatedly predict a next word and append it.
def generate(start, n, rng=None):
out = [start]
for _ in range(n):
probs = next_word_probs(out[-1])
if not probs:
break
if rng is None: # greedy: always take the most likely word
out.append(max(probs, key=probs.get))
else: # sampling: pick in proportion to probability
out.append(rng.choices(list(probs), weights=list(probs.values()))[0])
return " ".join(out)
print("greedy :", generate("the", 6))
rng = random.Random(0)
for i in range(3):
print(f"sample {i + 1}:", generate("the", 6, rng))
# 4. How big is this "model"? One number per (word, next word) cell of the table.
vocab = sorted(set(words))
print(f"vocabulary: {len(vocab)} words, table cells (parameters): {len(vocab) ** 2}")Line by line:
corpus = """…""": the training data, six short sentences. Real models use trillions of tokens; we use 38 words.words = corpus.split(): a crude tokenizer that splits on spaces, so "." becomes its own word.counts = defaultdict(Counter): a table wherecounts["the"]["cat"]will hold how often "cat" followed "the".for current, nxt in zip(words, words[1:]): walks over every neighbouring pair of words. This is the whole "training" step: one pass of counting.next_word_probs(word): divides each count by the total for that word, givingP(next | current). After "the", "cat" appeared 4 times out of 11, so its probability is 0.36.generate(start, n, rng): the generation loop. It asks for probabilities for the last word, picks one, appends it and repeats.max(probs, key=probs.get): greedy decoding, always choose the single most likely word.rng.choices(…, weights=…): sampling, choose at random in proportion to probability, so likely words win more often but not always.random.Random(0)fixes the random seed so the output is the same every run.len(vocab) ** 2: the size of the full table, one cell for every (word, next word) pair. These cells are this model's "parameters".
after 'the': cat 0.36, dog 0.18, mat 0.09, mouse 0.09, rug 0.09, cheese 0.09, fish 0.09
after 'cat': sat 0.25, chased 0.25, . 0.25, ate 0.25
after 'sat': on 1.00
greedy : the cat sat on the cat sat
sample 1: the cheese . the cat . the
sample 2: the rug . the mat . the
sample 3: the cat ate the cat ate the
vocabulary: 14 words, table cells (parameters): 196Notice three things in the output. First, the probabilities are just counting: "sat" was always followed by "on", so P(on | sat) = 1.00. Second, greedy decoding gets stuck in a loop ("the cat sat on the cat sat") because it always makes the same choice; real systems also suffer from repetition when they decode greedily. Third, the sampled sentences are varied and locally sensible but globally meaningless ("the cheese . the cat ."), because the model only ever sees one word back. Fixing that last weakness, by looking at far more context in a smarter way, is the entire story of modules 4 and 5.
Probabilities for the next word. Click one to append it, or let the model choose.
From a table of counts to a neural network
Why not just count longer phrases? Because the table explodes. With a vocabulary of 100,000 tokens, a table for one token of context has 10 billion cells; for two tokens of context, a million billion; for a paragraph, more cells than there are atoms in the universe. Worse, almost every long context is new: the exact sentence you are reading right now has probably never been written before, so there is nothing to count.
A neural network solves both problems. Instead of storing one number per possible context, it learns a function that takes any context and computes the probabilities. Similar contexts produce similar outputs, so the model can generalise to sentences it has never seen. The architecture that does this best for text is the transformer (2017), which lets every token look at every earlier token and decide which ones matter. You will build one in lesson 4.9.
| Our bigram model | A modern LLM | |
|---|---|---|
| Unit of text | Whole words split on spaces | Subword tokens from a learned vocabulary (tens of thousands to a few hundred thousand pieces) |
| Context it sees | 1 word | Up to hundreds of thousands of tokens (check each model's docs) |
| How it predicts | Looks up a count | Runs the context through a deep transformer network |
| Parameters | 196 table cells | Billions (open-weight models publish theirs; frontier labs usually do not) |
| Training data | 38 words | Trillions of tokens |
| Training cost | Microseconds on a laptop | Weeks to months on large accelerator clusters |
Why predicting the next word produces "intelligence"
It sounds too simple. How can "guess the next word" lead to a model that writes working code or explains quantum mechanics? The answer is that predicting text well is a very hard task that rewards understanding. To continue "The capital of Australia is" correctly, the model must have absorbed a fact. To continue a half-finished Python function, it must track variable names and what the code is trying to do. To continue "Translate to French: I am tired →", it must have learned French. To continue a worked maths solution, it must follow the steps. Every skill that shows up in text becomes useful for lowering prediction error, so training pushes the network to acquire a little of all of them.
That framing also explains the limits. The model learns what text is likely, not what is true. Where the training data is thin, contradictory or out of date, it still produces fluent, likely-looking text, and that is how hallucinations happen. It has no built-in sense of "I don't know" unless training taught it to say so. And because the weights are frozen after training, it knows nothing that happened after its training data was collected. These are not bugs that will be patched in the next version; they follow from what the model is. Lesson 1.3 shows how post-training reduces them, and lesson 5.9 analyses them in depth.
Base model versus assistant
A model trained only on next-token prediction is called a base model (or pretrained model). It continues documents; it does not follow instructions. Ask a base model "What is the capital of France?" and it may continue with "What is the capital of Germany? What is the capital of Spain?", because quiz lists are common on the web. Turning a base model into an assistant that answers is the subject of the next lesson.
How "good at predicting" is measured: cross-entropy and perplexity
Training needs a single number that says how wrong the model is. For next-token prediction that number is the cross-entropy loss: look at the probability the model gave to the token that actually came next, and take the negative logarithm.
In words: if the model gave the real next token probability 1, the loss is 0; if it gave it 0.5, the loss is about 0.69; if it gave it 0.01, the loss is about 4.6. Confident wrong guesses are punished hard.
The loss is averaged over every position in a huge batch of text, and training adjusts the parameters to lower it (gradient descent, lesson 2.4). Because the "right answer" is simply the next token of real text, no human labelling is needed: this is called self-supervised learning, and it is why models can learn from trillions of tokens.
Perplexity is the exponential of the average loss. It can be read as "the model is as uncertain as if it were choosing uniformly among this many tokens". A perplexity of 20 means the model is, on average, about as unsure as picking one of 20 equally likely options. Perplexity is useful for comparing models on the same text with the same tokenizer, but it does not measure helpfulness or truthfulness, which is why assistants are also judged with task benchmarks and human evaluations (lesson 10.8).
Common mistakes and debugging tips
Thinking the model looks answers up
Because answers are often correct, it is natural to imagine a lookup in a stored database of facts. There is no such database; there is a function that turns context into probabilities. Facts are stored only as patterns spread across the weights.
Fix: when exactness matters, put the source text into the context and ask the model to work from it.
Reading a high probability as "this is true"
A token's probability measures how likely it is to appear next in text like the training data, not how likely the statement is to be correct. Popular misconceptions can be highly probable.
Fix: treat probabilities as a fluency signal; verify claims with sources, tests or tools.
Assuming greedy decoding gives the best answer
Always picking the top token is deterministic, but as the bigram output shows, it can loop and repeat. The most likely next token does not always lead to the most likely or best full answer.
Fix: use sampling with a moderate temperature for open-ended text, and greedy or low temperature for short, factual or structured outputs (lesson 1.5).
Equating bigger with always better
Larger models are generally more capable, but they are slower and cost more, and many tasks are handled perfectly well by small ones.
Fix: measure on your own task. Start with the smallest model that passes your tests.
Key takeaways
- An LLM computes a probability for every possible next token given the context; generation is a loop of predict, pick, append.
- "Large" means billions of parameters, trillions of training tokens and very large compute budgets.
- Counting tables cannot scale to long contexts; neural networks (transformers) generalise instead of memorising.
- Predicting text well rewards learning facts, grammar, code and reasoning patterns, but it optimises for likely text, not true text.
Exercise: give the model more context (a trigram)
Copy bigram.py and change it into a trigram model that predicts the next word from the previous two words. Train it on the same corpus, generate 6 words greedily from "the cat", and compare with the bigram output. Then answer: what happens to the probabilities after "the cat", and what would happen with a much larger corpus?
Hint
Use a tuple of two words as the key: counts[(w1, w2)][w3] += 1, and loop with zip(words, words[1:], words[2:]). When generating, look up (out[-2], out[-1]).
Show a solution
from collections import Counter, defaultdict
words = corpus.split() # same corpus as bigram.py
counts = defaultdict(Counter)
for w1, w2, w3 in zip(words, words[1:], words[2:]):
counts[(w1, w2)][w3] += 1
def generate(a, b, n):
out = [a, b]
for _ in range(n):
following = counts[(out[-2], out[-1])]
if not following:
break
out.append(following.most_common(1)[0][0])
return " ".join(out)
print(generate("the", "cat", 6))With two words of context, predictions are sharper (after "the cat" only "sat", "chased", "ate" and "." are possible, each seen once), and generations copy whole training phrases. With a tiny corpus, a trigram model mostly memorises; with a large corpus, most two-word contexts would still be seen rarely or never. That data sparsity is exactly why counting was replaced by neural networks.
Check your understanding
What does a language model output for a given context?
- The single correct next word, looked up in a database
- A complete answer, written all at once
- A probability for every possible next token
Why does the greedy bigram output repeat "the cat sat on the cat sat"?
- It always picks the most likely word and only sees one word back, so the same states recur
- The random seed was set to 0
- The corpus contains that exact sentence twice
Which statement about Claude's size is accurate?
- It has exactly 175 billion parameters
- Anthropic has not published its parameter counts
- It is a counting-based n-gram model
Lesson 1.3Module 1: Understanding Claude and modern AI
How ChatGPT, Claude, Gemini and other AI assistants work
Learning objectives
- Describe the shared recipe behind modern assistants: pretraining, supervised fine-tuning, preference training and a product layer.
- Explain what a base model is and why it does not behave like an assistant.
- Describe RLHF and Constitutional AI at a high level, and say which parts Anthropic has published.
- See how a chat conversation is flattened into one long text with a chat template.
- Compare assistants from different labs honestly: what is shared, what differs and what is not public.
ChatGPT (OpenAI), Claude (Anthropic), Gemini (Google) and assistants built on open-weight models such as Llama (Meta), Mistral, Qwen (Alibaba) or Gemma (Google) look different and have different strengths. Underneath, they are built with the same broad recipe. Once you know the recipe, the marketing names stop being mysterious: each assistant is a particular set of choices at each stage, plus a particular product wrapped around the result.
Analogy: from bookworm to professional
Picture someone who has spent years reading everything in a giant library but has never had a job (pretraining). They know a lot but do not know how to help a customer. Next they shadow experienced staff and copy thousands of good example answers (supervised fine-tuning). Then a coach watches them work and says "this answer was better than that one" over and over, and they adjust (preference training). Finally they start a real job with an employee handbook, a phone, a computer and a manager who checks risky actions (the product layer: system prompt, tools, safety checks). Each assistant on the market is a different person who went through the same four steps at a different school.
The recipe at a glance
Click any box to see what happens in that stage, or press the step player to follow the pipeline from raw text to the app on your phone.
- Text collection
- A very large, filtered collection of text: public web pages, books, articles, code and more, cleaned to remove duplicates, spam and low-quality pages. Exact data mixes are rarely published; Anthropic does not disclose Claude's beyond high-level descriptions.
- Pretraining
- Next-token prediction on trillions of tokens. This stage uses most of the compute, and it is where the model gains its broad knowledge of language, facts and code.
- Base model
- The result of pretraining: a powerful document completer that does not reliably follow instructions, has no consistent persona and has not learned when to decline.
- Supervised fine-tuning
- Further training on example conversations written or curated by people (and increasingly by models, checked by people), so the model learns the format and style of a helpful reply.
- Preference training
- The model's own answers are compared ("A is better than B"), by people (RLHF) or by an AI judge following written principles (RLAIF, as in Constitutional AI), and the model is trained to produce the preferred kind of answer.
- Assistant model
- The weights that are deployed behind the API. They are fixed until the lab releases a new version.
- Product
- The app or API around the model: system prompt, conversation storage, tools, safety classifiers and the user interface (lesson 1.1).
- A huge text collection is tokenized and streamed through the network for weeks to months.
- Pretraining produces a base model: it can continue any document but does not act like an assistant.
- Fine-tuning on example conversations teaches the turn-taking format and a helpful style.
- Preference training pushes the model towards answers judged more helpful, honest and harmless.
- The final weights are evaluated, safety-tested and released as a versioned model.
- Products wrap the model with instructions, memory and tools, and serve it to people.
Stage 1: pretraining builds a base model
Pretraining is the next-token prediction you met in lesson 1.2, done at enormous scale. The result is a base model. Base models are impressive and odd. Give one the start of a news article and it writes a convincing continuation. Give it a question and it might answer, or it might write three more questions, a forum signature and a cookie banner, because that is what often follows a question on a web page. It has no idea that it is supposed to be "an assistant" because nothing in pretraining told it so.
Pretraining is where nearly all the knowledge comes from. Later stages mostly shape how the model uses that knowledge. That is why fine-tuning a small model on expert answers does not make it an expert: you can teach it the style but not the missing knowledge.
Stage 2: supervised fine-tuning teaches the format
In supervised fine-tuning (SFT, also called instruction tuning), training continues on a much smaller, carefully curated set of conversations: a user message followed by the kind of answer the developers want. The training objective is unchanged (predict the next token), but now the "documents" are good conversations, so the model learns to produce an answer after a question, to follow instructions such as "in three bullet points", and to use a consistent voice. Tens of thousands to millions of examples are typical in published open-model work; that is tiny next to pretraining data.
For SFT to work, conversations must be turned into plain text the model can predict. That is the job of a chat template: special marker tokens show where each role's turn starts and ends. The script below shows the idea with markers we invented for this course.
Simplified implementation Simplified
Every model family has its own template and special tokens, and token counts here use a rough 4-characters-per-token estimate. The exact format Claude sees internally is not public; with the Messages API you send structured JSON and never write the markers yourself.
# @run
# How a chat becomes one long text: a "chat template" flattens role-tagged messages into a single string.
# Simplified on purpose: the markers below (<|system|>, <|user|>, ...) are made up for this course. Each model
# family uses its own special tokens, and the exact format Claude sees is not public: the API hides it from you.
MARK = {"system": "<|system|>", "user": "<|user|>", "assistant": "<|assistant|>"}
END = "<|end|>"
def render(system, messages):
parts = [f"{MARK['system']}\n{system}{END}"]
for m in messages:
parts.append(f"{MARK[m['role']]}\n{m['content']}{END}")
parts.append(MARK["assistant"]) # an open assistant turn: the model continues from here
return "\n".join(parts)
def rough_tokens(text):
return max(1, round(len(text) / 4)) # rule of thumb for English text (lesson 1.6)
system = "You are a friendly cooking assistant. Answer in two sentences."
turns = [
("How long do I boil an egg?",
"About 7 minutes for a jammy yolk and 10 for hard-boiled. Start timing when the water boils again."),
("And a soft one?",
"Around 5 to 6 minutes. Put it in cold water afterwards so it stops cooking."),
("Can I use a microwave?", None), # the model has not answered this one yet
]
chat = [] # the application keeps the history, not the model
total = 0
for i, (question, answer) in enumerate(turns, 1):
chat.append({"role": "user", "content": question})
prompt = render(system, chat) # the WHOLE conversation is sent every time
n = rough_tokens(prompt)
total += n
print(f"request {i}: {len(chat)} message{'s' if len(chat) > 1 else ''}, {len(prompt):3} characters, about {n} tokens sent")
if answer is not None:
chat.append({"role": "assistant", "content": answer})
print(f"input tokens over all 3 requests: about {total}")
print()
print("What the model reads on request 3:")
print(render(system, chat))MARK = {…}andEND: the made-up markers that open and close each turn. In a real model they are special tokens that cannot be typed as normal text, which stops users from faking a system turn.render(system, messages): joins the system prompt and every message into one string, in order.parts.append(MARK["assistant"]): ends with an open assistant turn. The model's next-token prediction therefore starts writing the assistant's reply, which is exactly the behaviour SFT trained.rough_tokens(text): estimates tokens as characters divided by 4 (a common rule of thumb for English, see lesson 1.6).chat = []: the application, not the model, owns the history.prompt = render(system, chat)inside the loop: each request re-sends the whole conversation, so request 3 contains requests 1 and 2.total += n: adds up input tokens across requests, which is what you pay for with an API.
request 1: 1 message, 137 characters, about 34 tokens sent
request 2: 3 messages, 288 characters, about 72 tokens sent
request 3: 5 messages, 424 characters, about 106 tokens sent
input tokens over all 3 requests: about 212
What the model reads on request 3:
<|system|>
You are a friendly cooking assistant. Answer in two sentences.<|end|>
<|user|>
How long do I boil an egg?<|end|>
<|assistant|>
About 7 minutes for a jammy yolk and 10 for hard-boiled. Start timing when the water boils again.<|end|>
<|user|>
And a soft one?<|end|>
<|assistant|>
Around 5 to 6 minutes. Put it in cold water afterwards so it stops cooking.<|end|>
<|user|>
Can I use a microwave?<|end|>
<|assistant|>Two lessons hide in this output. The model reads one flat text, so "a conversation" is a convention it learned during fine-tuning, not a data structure inside it. And the input grows with every turn (34, then 72, then 106 tokens here), so total cost grows faster than the number of messages. Real products use techniques such as prompt caching and history trimming to manage that (lesson 7.4).
Stage 3: preference training shapes behaviour
Writing perfect example answers is slow, and for many questions there is no single right answer. It is much easier to compare: shown two answers to the same prompt, a person can usually say which is better. Reinforcement learning from human feedback (RLHF) builds on that. The published recipe (for example OpenAI's InstructGPT paper, Ouyang et al., 2022, and Anthropic's Bai et al., 2022 on helpful and harmless assistants) has three steps:
- Generate several answers to many prompts and collect human comparisons of which answer is better.
- Train a reward model (or preference model) that predicts those comparisons, producing a score for any answer.
- Use reinforcement learning to update the assistant so that its answers get higher scores, while a penalty keeps it from drifting too far from the fine-tuned model.
Anthropic also published Constitutional AI (Bai et al., 2022). Instead of relying only on human labels for harmlessness, the model is given a written list of principles (a "constitution"). In a supervised phase, the model critiques and revises its own answers according to those principles, and is fine-tuned on the revisions. In a reinforcement phase, an AI judge compares pairs of answers using the principles, those AI preferences train a preference model, and that model provides the reward. This is called RL from AI feedback (RLAIF). Anthropic has also published a document describing the values and priorities it wants Claude to have. How exactly these methods are combined for current Claude models is not public; lesson 6.2 covers them in depth.
Other labs use related methods, and newer techniques such as direct preference optimisation (DPO, Rafailov et al., 2023) learn from comparisons without a separate reward model. Labs also increasingly train with reinforcement learning on tasks whose results can be checked automatically, such as maths answers or code that must pass tests. Which mix each lab uses for each model is mostly not disclosed.
Stage 4: the product layer
The trained model is then wrapped in a product, as you saw in lesson 1.1. This is where many visible differences between assistants come from: the length and content of the default system prompt, which tools are switched on (web search, code execution, image generation, file reading), how long conversations are stored, whether the app has long-term memory, and which safety classifiers screen inputs and outputs. Some assistants also offer modes in which the model writes out intermediate reasoning before its final answer; Anthropic's documentation calls this extended thinking.
So how do the big assistants differ?
| Question | Answer | Status |
|---|---|---|
| Are they all transformer-based LLMs? | The labs describe their flagship models as transformer-based (sometimes with variations such as mixture-of-experts). | Public |
| Do they all use pretraining plus post-training with feedback? | Yes, in broad terms; each lab has published papers or reports on its approach. | Industry practice |
| What data, how many parameters, how much compute? | For closed frontier models, generally not disclosed. Open-weight releases publish sizes and some data details. | Not public |
| Why does each one "feel" different? | Different data mixes, post-training choices, written principles, system prompts and product features. | Industry practice |
| Which is best? | It depends on the task and changes with every release. Test the ones you consider on your own examples. |
A useful mental model: the base model decides what the assistant can do; post-training decides what it tends to do; the product decides what it is allowed and equipped to do in a given app.
Why fine-tuning alone is not enough, and what can go wrong with preferences
Supervised fine-tuning only shows the model good answers; it never shows it its own mistakes. Preference training closes that gap: the model generates answers, they are scored, and the update pushes probability towards better answers and away from worse ones that the model itself actually produces. This is why RL-style methods are good at reducing specific failure modes, such as rambling, unsafe compliance or needless refusals.
Preference training has well-known failure modes, discussed openly in published research:
- Reward hacking. The model finds ways to score highly on the reward model without really being better, for example by being longer, more confident or more flattering, because raters or the reward model happened to like that. The penalty for drifting from the fine-tuned model limits this.
- Sycophancy. People tend to rate agreement highly, so models can learn to agree with the user even when the user is wrong. Labs evaluate and train against this.
- Over-refusal versus under-refusal. Pushing hard on harmlessness can make a model refuse harmless requests; pushing hard on helpfulness can make it comply with harmful ones. Anthropic's helpful-and-harmless research describes this tension directly.
Compute split, as publicly described for open models and in industry reports: pretraining dominates the compute budget, while post-training uses far less compute but much more carefully designed data. That is why a small team can fine-tune an open-weight model on one GPU with LoRA (lesson 10.5) but cannot pretrain a frontier model.
Common mistakes and debugging tips
Prompting a base model like a chat model
Downloaded open-weight models often come in two versions, such as "base" and "instruct" (or "chat"). The base version continues text and ignores instructions, which looks like the model is broken.
Fix: use the instruct/chat variant for assistants, or frame base-model prompts as a document to continue.
Building a chat template by hand
Each open model family has its own markers. Writing them by hand with a typo or the wrong family's markers silently degrades answers, because the model sees an unfamiliar format.
Fix: let the library apply the template (for example the tokenizer's chat-template function in Hugging Face Transformers, or Ollama's chat endpoint), and with hosted APIs send structured messages.
Expecting fine-tuning to add lots of new knowledge
Fine-tuning a model on a few hundred documents mostly changes style and format. The model may still make up details about the new material.
Fix: for new or private knowledge, retrieve the relevant documents and put them in the context (RAG, lesson 8.5); fine-tune for behaviour.
Treating rumours as facts about closed models
Parameter counts and training details for closed models circulate online, but they are usually guesses.
Fix: cite only what the lab has published (papers, model cards, docs) and label the rest as unknown.
Key takeaways
- All major assistants share a recipe: pretraining, supervised fine-tuning, preference training, then a product layer.
- Pretraining gives knowledge; post-training gives behaviour; the product gives instructions, tools and memory.
- Anthropic has published RLHF research and Constitutional AI (critique and revision, then RL from AI feedback).
- A chat is flattened into one text with a template, and the whole history is re-sent on every request.
Exercise: which stage is responsible?
For each behaviour, name the stage mainly responsible (pretraining, supervised fine-tuning, preference training or product) and explain in one sentence: (a) the model knows the plot of a famous novel; (b) it answers a question instead of writing more questions; (c) given two drafts, it tends to choose the more honest, less flattering wording; (d) it can tell you today's weather; (e) its replies always start with "Thanks for contacting Acme support"; (f) it declines to give step-by-step instructions for making a weapon, even with no system prompt.
Hint
Ask what data or mechanism could have produced the behaviour: raw text (pretraining), example conversations (SFT), comparisons between answers (preferences), or something added at run time (product).
Show a solution
- (a) Pretraining: book summaries and discussions are in the training text.
- (b) Supervised fine-tuning: example conversations taught the question-then-answer format.
- (c) Preference training: comparisons favoured honest answers over flattering ones (with principles in Constitutional AI).
- (d) Product: the weights are frozen, so live weather must come from a tool the app provides.
- (e) Product: a system prompt written by Acme.
- (f) Mostly post-training (SFT and preference training on harmlessness); the product may add classifiers on top.
Check your understanding
A base model is asked "What is the capital of France?" and replies with a list of more quiz questions. Why?
- The model does not know the answer
- It was only pretrained to continue documents and has not been taught to answer like an assistant
- The temperature is set too low
In Constitutional AI as published by Anthropic, where does the reinforcement learning reward mainly come from for harmlessness?
- A hand-written list of banned words
- Only human raters scoring every answer
- A preference model trained on AI comparisons guided by written principles
Why does request 3 in chat_template.py contain the earlier questions and answers?
- The model is stateless, so the application must re-send the whole conversation each time
- The model stores conversations in its weights
- The chat template duplicates messages by mistake
Lesson 1.4Module 1: Understanding Claude and modern AI
AI, machine learning, deep learning, transformers and LLMs
Learning objectives
- Place AI, machine learning, deep learning, transformers and LLMs correctly inside one another.
- Explain the difference between writing rules by hand and learning them from examples, with running code.
- Name the main kinds of machine learning (supervised, unsupervised, self-supervised, reinforcement).
- Outline the key milestones from early AI to today's assistants, with dates.
News articles use "AI", "machine learning", "deep learning", "neural networks", "transformers", "LLMs" and "generative AI" almost interchangeably. They are not the same thing. They are nested: each term is a smaller, more specific region inside the previous one. Getting the nesting right helps you read papers and job ads, and it tells you which tool fits a problem. Many real problems are still best solved with a few rules or a small classic model, not an LLM.
Analogy: vehicles, cars, electric cars
"Vehicle" includes bicycles, ships and cars. "Car" is one kind of vehicle. "Electric car" is one kind of car, and a particular electric model is one kind of electric car. Every electric car is a vehicle, but calling a bicycle an electric car is wrong. In the same way, every LLM is deep learning, and all deep learning is machine learning, which is part of AI, but a chess program from 1997 or a spam filter is AI without being an LLM.
Artificial intelligence: the whole field
Artificial intelligence (AI) is the broad field of making computers do tasks that we would call intelligent if a person did them: playing games, understanding speech, planning routes, diagnosing faults, translating. The term was coined for a 1956 workshop at Dartmouth College. For decades, much of AI was symbolic: programmers wrote rules, logic and search procedures by hand. "Expert systems" in the 1980s encoded thousands of if-then rules from human experts. IBM's Deep Blue, which beat chess world champion Garry Kasparov in 1997, combined fast search with an evaluation function tuned largely by hand. All of that is AI, and none of it is machine learning in the modern sense.
Hand-written rules work well when the rules are known and stable: tax calculations, a thermostat, a route planner. They break down when the rules are fuzzy, numerous or unknown. Nobody can write down the rules for recognising a cat in a photo or for what makes a sentence sound natural.
Machine learning: rules learned from examples
Machine learning (ML) flips the approach. Instead of writing the rules, you write a program with adjustable numbers (parameters) and a way to measure mistakes, then show it many examples. The program adjusts its parameters to make fewer mistakes. The "rules" end up stored in those numbers. The script below solves the same task both ways.
Simplified implementation Simplified
Ten training messages and a word-count model (a version of naive Bayes) are enough to show the idea. Real spam filters learn from millions of messages and many more signals.
# @run
# The same task solved two ways: a spam filter written as hand-made rules, and one that learns word weights from examples.
# Simplified on purpose: real spam filters use far more data and features.
import math
from collections import Counter
# ---- Approach 1: classic programming. A human writes the rules. ----
SPAM_WORDS = {"free", "winner", "prize", "click"}
def rule_based(message):
words = message.lower().split()
return "spam" if any(w in SPAM_WORDS for w in words) else "ham"
# ---- Approach 2: machine learning. The program finds the rules in labelled examples. ----
train = [
("win a free prize now", "spam"),
("claim your cash reward today", "spam"),
("cheap pills discount offer", "spam"),
("you are a winner click here", "spam"),
("exclusive offer claim cash now", "spam"),
("lunch at noon tomorrow", "ham"),
("can you review my code today", "ham"),
("meeting moved to friday", "ham"),
("the free workshop starts at noon", "ham"),
("here are the notes from class", "ham"),
]
spam_counts, ham_counts = Counter(), Counter()
for text, label in train:
(spam_counts if label == "spam" else ham_counts).update(text.split())
vocab = set(spam_counts) | set(ham_counts)
# Each word gets a learned weight: log of how much more often it appears in spam than in ham.
# (+1 "smoothing" so a word never seen in one class doesn't give log(0).)
def weight(word):
p_spam = (spam_counts[word] + 1) / (sum(spam_counts.values()) + len(vocab))
p_ham = (ham_counts[word] + 1) / (sum(ham_counts.values()) + len(vocab))
return math.log(p_spam / p_ham)
def learned(message):
score = sum(weight(w) for w in message.lower().split() if w in vocab)
return ("spam" if score > 0 else "ham"), score
print("learned weights (positive = spammy):")
for w in ["cash", "claim", "free", "noon", "code"]:
print(f" {w:6} {weight(w):+.2f}")
tests = [
("claim your cash reward", "spam"),
("free lunch at noon", "ham"),
("exclusive discount offer", "spam"),
("review the notes", "ham"),
]
print()
print(f"{'message':28} {'truth':5} {'rules':5} learned (score)")
for text, truth in tests:
label, score = learned(text)
print(f"{text:28} {truth:5} {rule_based(text):5} {label} ({score:+.2f})")SPAM_WORDS = {…}andrule_based(): classic programming. A person decided that any message containing "free", "winner", "prize" or "click" is spam.train = [(text, label), …]: labelled examples. This is supervised learning: each example comes with the right answer.spam_counts/ham_counts: count how often each word appears in spam and in normal mail ("ham"). Counting is the training step.weight(word): the learned parameter for each word: the logarithm of how much more common it is in spam than in ham. The+ 1is smoothing, so unseen words do not producelog(0).learned(message): adds up the weights of the words in a message. A positive total means "spam".- The final loop prints the true label, the rule-based answer and the learned answer for four new messages.
learned weights (positive = spammy):
cash +1.11
claim +1.11
free +0.02
noon -1.08
code -0.68
message truth rules learned (score)
claim your cash reward spam ham spam (+3.65)
free lunch at noon ham spam ham (-2.83)
exclusive discount offer spam ham spam (+2.53)
review the notes ham ham ham (-2.44)The hand-written rules get two of four wrong: they miss spam that avoids the four magic words, and they flag "free lunch at noon" because it contains "free". The learned model gets all four right, because it discovered from data that "cash" and "claim" are spammy while "noon" is not, and that "free" is nearly neutral in this data (it appears in one spam and one normal message). Nobody told it any of this. That is the core promise of machine learning, and its core risk: the model learns whatever patterns the data contains, including accidental ones.
Machine learning comes in a few flavours:
- Supervised learning: examples with answers (spam or not, house price, the right translation).
- Unsupervised learning: no answers; find structure, such as grouping customers into clusters.
- Self-supervised learning: the answers come from the data itself, such as "the next word" in a sentence. This is how LLMs are pretrained, and why they can use trillions of tokens without human labels.
- Reinforcement learning: an agent tries actions and receives rewards, as in game-playing systems and the preference training of lesson 1.3.
Deep learning: many layers of learned features
Classic ML often relied on people to choose the features, the inputs worth measuring, such as word counts or the edges in an image. Deep learning uses neural networks with many layers that learn their own features from raw data: early layers detect simple patterns, later layers combine them into complex ones. The maths behind training them (backpropagation) was popularised in 1986, but deep networks only took off once there was enough data and enough parallel compute. A turning point came in 2012, when a deep convolutional network (AlexNet) trained on GPUs won the ImageNet image-recognition competition by a wide margin. Since then deep learning has taken over speech recognition, translation, image generation and language. You will build a small network from scratch in module 3.
Transformers: the architecture behind modern LLMs
A transformer is a particular kind of neural network, introduced in the 2017 paper "Attention Is All You Need" (Vaswani et al.). Its key idea, attention, lets every position in a sequence look directly at every other position and decide which ones are relevant. Earlier language networks (recurrent networks) read text one word at a time and struggled to carry information across long passages; transformers process all positions in parallel, which suits GPUs and makes training on huge datasets practical. Transformers are now used for text, images, audio, video and even protein structures. Module 4 builds one step by step.
LLMs and generative AI
A large language model is a (usually transformer) network trained on very large amounts of text to predict the next token, typically followed by post-training to make it an assistant. Generative AI is the wider family of models that produce new content: text, images, audio, video. Foundation model is a term for a large model trained on broad data that can be adapted to many tasks. Many current LLMs, including Claude, also accept images as input, so you will also hear multimodal.
| Year | Milestone | Circle |
|---|---|---|
| 1956 | Dartmouth workshop names the field "artificial intelligence" | AI |
| 1986 | Backpropagation popularised for training multi-layer networks | ML / deep learning |
| 1997 | Deep Blue beats the world chess champion (search plus hand-tuned evaluation) | AI, not ML-centred |
| 2012 | AlexNet wins ImageNet with a deep network trained on GPUs | Deep learning |
| 2017 | The transformer is published | Transformers |
| 2018–2020 | BERT and the GPT series show the power of pretraining at scale; GPT-3 (175B parameters) | LLMs |
| 2022 | RLHF-trained chat assistants reach the public; ChatGPT launches | LLM assistants |
| 2023 onward | Claude, Gemini and strong open-weight families (Llama, Mistral, Qwen, Gemma) follow | LLM assistants |
Inside the transformer family, and beyond it
Transformers come in three classic layouts. Encoder-only models such as BERT read a whole text at once and are good at understanding tasks (classification, search embeddings). Encoder-decoder models such as T5 read an input and then write an output, a natural fit for translation. Decoder-only models such as the GPT series read left to right and predict the next token; most chat LLMs are described as decoder-only. You will build a decoder-only model in lesson 5.5.
Two widely used variations: mixture-of-experts (MoE) layers, where each token is routed to a few of many sub-networks so the model can have many parameters but use only some per token (publicly documented in open models such as Mixtral), and architectures that replace or mix attention with other sequence layers, such as state-space models (for example Mamba, 2023). Whether and how any of these are used in Claude is Not public; Anthropic describes Claude only as a transformer-based LLM.
A practical rule for engineers: try the simplest circle that solves the problem. A regular expression or a rule table is cheap and explainable. A small classic ML model (logistic regression, gradient-boosted trees) is often best for tabular data. Deep learning wins on images, audio and raw text. An LLM wins when the task needs flexible language understanding or generation, and when its cost and latency are acceptable.
Common mistakes and debugging tips
Using "AI" to mean "an LLM"
Most AI in production is not an LLM: recommendation systems, fraud detection, route planning, search ranking. Mixing the terms leads to choosing an expensive tool for a simple job.
Fix: name the actual technique, and ask whether rules or a small model would do.
Believing machine learning needs no rules or code
ML replaces hand-written decision rules, but you still write code for data cleaning, features, training, evaluation and serving, and the data itself encodes assumptions.
Fix: budget most of an ML project for data and evaluation, not the model.
Testing on the training examples
A model can memorise its training data. Measuring accuracy on the same examples it learned from gives a flattering, useless number.
Fix: always keep a separate test set the model never saw, as the script does with its four new messages.
Assuming every transformer is an LLM
Vision transformers classify images and speech models transcribe audio; neither generates language like an assistant.
Fix: say what the model is trained to do (its objective and data), not just its architecture.
Key takeaways
- AI ⊃ machine learning ⊃ deep learning ⊃ transformers; today's LLMs are (almost all) transformers.
- Classic programming writes rules; machine learning learns them from examples and stores them as parameters.
- LLMs are pretrained with self-supervised learning and post-trained with supervised and reinforcement learning.
- Pick the simplest technique that works; an LLM is not always the right tool.
Exercise: put each system in its smallest circle
For each system, choose the most specific circle it belongs to (AI but not ML, machine learning, deep learning, transformer, or LLM) and justify it: (a) a 1990s chess program using search and a hand-written evaluation; (b) a house-price predictor using linear regression on size and location; (c) phone face unlock using a convolutional neural network; (d) Claude; (e) a vision transformer that labels photos; (f) the learned spam filter in rules_vs_learning.py. Bonus: add the training message ("free money claim now", "spam") to the script and predict what happens to the weight of "free" before running it.
Hint
Ask two questions: are the decision rules learned from data? If so, is it a multi-layer neural network, and is it an attention-based one trained on text to predict tokens?
Show a solution
- (a) AI but not ML: the rules and evaluation are written by people.
- (b) Machine learning: parameters are fitted to data, but it is not a deep network.
- (c) Deep learning: a multi-layer neural network, not a transformer.
- (d) LLM: a transformer-based language model.
- (e) Transformer, but not an LLM: it does not model language.
- (f) Machine learning: weights are learned by counting, no neural network.
Bonus: "free" now appears in two spam messages and one normal message, so its weight becomes clearly positive, and "free lunch at noon" moves closer to being called spam. A single example can shift a small model, which is why data quality matters so much.
Check your understanding
Which statement about the nesting is correct?
- Every AI system is a large language model
- Every LLM is a deep learning model, but not every deep learning model is an LLM
- Machine learning is a kind of deep learning
In rules_vs_learning.py, why does the learned filter classify "free lunch at noon" correctly while the rules do not?
- The learned filter has a longer list of banned words
- The learned filter ignores the word "free"
- It learned from examples that "free" is nearly neutral and "noon" points to normal mail
What kind of learning is LLM pretraining?
- Self-supervised: the next token in real text is the label
- Unsupervised clustering of documents
- Reinforcement learning from game rewards
Lesson 1.5Module 1: Understanding Claude and modern AI
What happens when you send a message to an AI?
Learning objectives
- Trace a chat message from the moment you press Send to the moment the reply appears.
- Explain the two phases of inference: reading the prompt (prefill) and writing the reply one token at a time (decoding).
- Explain temperature and sampling, and predict how they change an answer.
- Explain streaming, stop reasons and why a KV cache makes generation fast.
You type "Explain recursion with an example" and, a moment later, words start appearing. In between, your message travels across the internet, is checked, combined with instructions and history, converted into numbers, pushed through a neural network with billions of parameters, and turned back into text one small piece at a time. This lesson follows that journey step by step. Almost every step is ordinary software you can build yourself; only one step is "the model".
Analogy: ordering at a restaurant
The waiter (the app) writes down your order and, because the kitchen has no memory, staples it to a copy of everything you ordered earlier tonight. At the door, a manager checks you are allowed to order (the API gateway). The chef (the model) reads the whole ticket once, then plates the dish one ingredient at a time, each time looking at what is already on the plate to decide what comes next. A runner carries each ingredient to your table the moment it is placed (streaming), so you can start eating before the dish is finished. When the chef rings the bell (a stop token) or the plate is full (a length limit), the dish is done.
The journey, step by step
Press Play to follow one message through a typical hosted assistant. The exact internals of any commercial service are not public; this is the generally described pattern Industry practice.
- You type a message and press Send. The app adds it to the conversation it has stored.
- The app sends one HTTPS request containing the model id, the system prompt, the whole history and settings such as max_tokens.
- The API server checks the key, rate limits and usage policies, then passes the request on.
- The prompt is assembled with the chat template and tokenized. The model reads all of it at once (prefill).
- The model outputs a probability for every token in its vocabulary.
- The sampler picks one token (using temperature) and appends it; the model runs again for the next one. This loop repeats.
- Each new token is sent back immediately as a streamed event, so text appears while it is still being written.
- At a stop token or max_tokens, the stream ends with a stop reason. The app renders the Markdown and saves the reply in the history.
1. The app builds a request
The model keeps no memory between requests, so the app sends everything the model needs every time. With Anthropic's Messages API the request body is JSON like this (lesson 1.1 showed full code):
{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"system": "You are a patient programming tutor.",
"messages": [
{"role": "user", "content": "What is a function?"},
{"role": "assistant", "content": "A named, reusable block of code..."},
{"role": "user", "content": "Explain recursion with an example"}
],
"stream": true
}The messages list is the conversation so far; the last entry is your new message. "stream": true asks for the reply piece by piece. Model ids change over time, so check the current list in the docs.
2. The server checks and assembles
Before any model runs, the service authenticates the API key, applies rate limits (how many requests and tokens per minute your account may use), and may run safety classifiers on the input. It then turns the structured request into the single sequence the model reads, using the model's chat template (you saw a made-up version in lesson 1.3), and converts that text into token ids with the tokenizer (lesson 1.6). If tools are enabled, their descriptions are included in the prompt too, which is why tool definitions count towards your input tokens.
3. Prefill: the model reads the whole prompt
The token ids go to accelerators (GPUs or similar chips) holding the model weights. In the first phase, prefill, the model processes every prompt token in parallel and computes, for each layer, internal summaries of each position. Prefill is limited mostly by raw arithmetic and is fast per token, because the hardware handles thousands of positions at once. It determines the time to first token: a long prompt (a whole book pasted in) means a noticeable pause before anything appears.
4. Decoding: one token at a time
The second phase, decoding, is the loop from lesson 1.2. The model produces scores (logits) for every token in the vocabulary; they are converted into probabilities; the sampler picks one token; it is appended; repeat. Each new token requires a full pass through the network, so decoding is sequential and is usually what you notice as "typing speed". Hosted models commonly decode at tens to a couple of hundred tokens per second per request (a rough 2026 figure that depends heavily on model size, hardware and load).
Simplified implementation Simplified
The "model" below is a hand-written table of scores that looks only at the previous token. A real model computes the scores with a transformer over the whole context. The loop around it (score, softmax, sample, append, stop) is the real thing.
# @run
# The generation loop every chat model runs: predict probabilities -> pick a token -> append -> repeat.
# The "model" here is a toy table of scores, so you can see the loop itself. Real models compute the scores
# with a transformer over the whole context (module 4), but the loop around it is the same.
import math
import random
VOCAB = ["Paris", "is", "the", "capital", "of", "France", ".", "<end>"]
# Toy scores ("logits"): how strongly each token is expected after the previous one.
LOGITS = {
"France": {".": 3.0, "is": 0.5},
".": {"<end>": 3.0, "Paris": 0.5},
"Paris": {"is": 3.0, ".": 0.5},
"is": {"the": 3.0, "Paris": 0.2},
"the": {"capital": 3.0, "France": 0.3},
"capital": {"of": 3.5},
"of": {"France": 3.0, "the": 0.5},
}
def softmax(scores, temperature):
exps = [math.exp(s / temperature) for s in scores]
total = sum(exps)
return [e / total for e in exps]
def next_token_probs(context, temperature):
table = LOGITS.get(context[-1], {})
scores = [table.get(tok, -2.0) for tok in VOCAB] # unknown pairs get a low score
return softmax(scores, temperature)
def generate(prompt, temperature, rng, max_new=8):
context = prompt.split()
reply = []
for step in range(max_new):
probs = next_token_probs(context, temperature)
token = rng.choices(VOCAB, weights=probs)[0] # sampling
if token == "<end>":
break
context.append(token)
reply.append(token) # a real server streams this token now
return " ".join(reply)
probs = next_token_probs(["the"], 1.0)
top = sorted(zip(VOCAB, probs), key=lambda x: -x[1])[:3]
print("after 'the':", ", ".join(f"{t} {p:.3f}" for t, p in top))
for temperature in [0.5, 1.0, 2.0]:
rng = random.Random(42)
print(f"temperature {temperature}:")
for _ in range(2):
print(" Paris", generate("Paris", temperature, rng))
# Why a KV cache matters: without it, step n re-reads all n tokens of the context.
prompt_len, new_tokens = 1000, 200
without = sum(prompt_len + i for i in range(new_tokens))
with_cache = prompt_len + new_tokens
print(f"token positions processed for {new_tokens} new tokens after a {prompt_len}-token prompt:")
print(f" without KV cache: {without:,}")
print(f" with KV cache: {with_cache:,}")VOCAB: the 8 tokens this toy model knows, including a special<end>token that means "stop". Real vocabularies have tens of thousands to a few hundred thousand entries.LOGITS: raw scores for "which token follows which". Higher means more likely. A real model computes these numbers; here they are typed in.softmax(scores, temperature): turns scores into probabilities that add up to 1. Each score is divided by the temperature before exponentiating, which sharpens (low temperature) or flattens (high temperature) the distribution.next_token_probs(context, …): looks up the scores for the last token; unknown pairs get a low score of -2.0, so they are unlikely but possible.rng.choices(VOCAB, weights=probs): the sampler, a weighted random pick.if token == "<end>": break: a stop token ends the reply (the API reportsstop_reason: "end_turn").max_new=8plays the role ofmax_tokens.reply.append(token): this is the moment a real server would stream the token to you.- The last block compares how many token positions must be processed with and without a KV cache (explained below).
after 'the': capital 0.903, France 0.061, Paris 0.006
temperature 0.5:
Paris is the capital of France .
Paris is the capital of France .
temperature 1.0:
Paris is Paris is the capital of France capital
Paris is Paris is the capital of France .
temperature 2.0:
Paris the Paris is the of France . Paris
Paris is Paris is the Paris is the capital
token positions processed for 200 new tokens after a 1000-token prompt:
without KV cache: 219,900
with KV cache: 1,200At temperature 0.5 the model produces the most likely sentence both times. At 1.0 it sometimes takes a less likely path ("Paris is Paris is…"), and both samples use up the 8-token limit before producing <end>: in an API that would be stop_reason: "max_tokens" and a cut-off reply. At 2.0 the distribution is so flat that the output becomes word salad. The same trade-off applies to real models: low temperature gives focused, repeatable answers; higher temperature gives more variety and more mistakes.
Temperature, by hand
Below, a toy model is completing "The capital of France is". Move the slider to change the temperature and watch the probabilities, then sample to see how often each token wins.
The capital of France is …
Toy scores (logits): Paris 6.0, located 3.5, a 3.0, the 2.5, beautiful 2.0, Lyon 1.0.
In production: who controls sampling? (as of late 2026)
Open-weight runtimes such as Ollama and most inference libraries let you set temperature, top_k and top_p yourself. Hosted APIs are moving the other way: Anthropic's newest Messages API version rejects requests that set these parameters, and the provider chooses the sampling settings for each model. The mechanism above still runs inside the service; you just do not tune it. Check the docs for the API version and model you use.
5. Streaming and stop reasons
With streaming on, the server keeps the HTTP connection open and sends a series of small events, typically using server-sent events (SSE): one when the message starts, many small "text delta" events each carrying a few characters, and a final event with the stop reason and token usage. Your app appends each delta to the screen. Streaming does not make the model faster; it makes waiting feel shorter, because you can start reading after the first token instead of after the last. Common stop reasons in Anthropic's API are end_turn (the model finished), max_tokens (your limit cut it off), stop_sequence (it produced a string you asked it to stop at) and tool_use (it wants your app to run a tool); newer API versions add a few more, such as refusal, so check the docs for the full list. You will implement streaming in lesson 7.5.
6. When the model asks for a tool
If your request included tools, the model can respond with a structured request such as "call get_weather with {"city": "Paris"}" instead of text, and stop with tool_use. The model does not run anything. Your app runs the function, appends the result to the messages, and sends a new request; the model then writes its answer using the result. A single user message can therefore cause several model requests behind the scenes. That loop is the heart of agents (lesson 9.4).
7. After the reply
The app renders the Markdown (headings, lists, code blocks), stores the assistant message so it can be re-sent next time, and records token usage for billing. Nothing about your conversation changed the model's weights: the next request starts from the same frozen network.
Softmax with temperature, top-k / top-p, and the KV cache
The sampler starts from the logits , one per token, and a temperature :
In words: divide every score by the temperature, raise e to each result, and divide by the total so they add up to 1. Small T exaggerates gaps between scores (the top token dominates); large T shrinks them (choices become more even). As T approaches 0 this becomes greedy decoding.
Two common filters are applied before sampling. Top-k keeps only the k highest-probability tokens. Top-p (nucleus sampling) keeps the smallest set of tokens whose probabilities add up to p, such as 0.9. Both cut off the long tail of unlikely tokens that cause nonsense. Lesson 5.8 implements them.
The KV cache. In a transformer, each token at each layer produces "key" and "value" vectors that later tokens attend to. Those vectors never change once computed, so servers store them. Without a cache, generating token number would recompute the whole context; with it, each step only computes the newest token and reads the stored rest. The script's numbers (219,900 versus 1,200 token positions for 200 new tokens after a 1,000-token prompt) show why every serious inference server uses one. The cost is memory: the cache grows with context length, layers and batch size, and for long contexts it can take many gigabytes per request. That memory, more than arithmetic, is what limits decoding speed and how many users a GPU can serve at once, which is why servers batch many users' requests together.
A note on determinism: temperature 0 is close to deterministic, but hosted services do not always guarantee identical output for identical input, because of floating-point effects of batching and hardware. Do not build features that depend on bit-for-bit repeatable replies.
Common mistakes and debugging tips
Not checking the stop reason
A reply that ends mid-sentence or produces invalid JSON is often just cut off by max_tokens, and the code treats it as complete.
Fix: check stop_reason on every response; on max_tokens, raise the limit, ask for shorter output or continue the reply.
Turning temperature up to get "smarter" answers
Higher temperature adds randomness, not intelligence. For extraction, classification and code it usually adds errors. (Where an API does not expose temperature at all, the same idea applies to retrying: a different sample is not a smarter one.)
Fix: use low temperature for precise tasks and moderate temperature for brainstorming or creative writing. Only change one sampling setting at a time and test.
Assuming streaming makes the full answer arrive sooner
Total time is the same; only the first visible text arrives earlier. Long prompts still delay the first token.
Fix: to cut total latency, shorten prompts and outputs, cache repeated prompt prefixes or use a smaller model.
Ignoring errors in the middle of a stream
A network drop or an overloaded server can end a stream early, leaving a half-written message on screen and in history.
Fix: detect missing final events, show a retry button, and do not save incomplete replies as if they were complete (lesson 7.8).
Key takeaways
- Each message triggers a full request containing the system prompt and the whole history.
- Inference has two phases: prefill reads the prompt in parallel; decoding writes one token per network pass.
- Temperature reshapes the probabilities; sampling picks from them; stop tokens and max_tokens end the loop.
- Streaming shows tokens as they are generated; a KV cache avoids recomputing the context on every step.
Exercise: add a stop sequence
APIs let you pass stop sequences: strings that end generation as soon as they appear. Change generate() in generate_loop.py to accept a stop argument (a list of tokens) and end the reply, without including that token, when one is produced. Then generate from "Paris" with stop=["of"] at temperature 0.5. What reply do you expect, and what stop_reason would an API report?
Hint
The check is the same shape as the <end> check. Return the reason too, so you can print it: "end_turn", "stop_sequence" or "max_tokens".
Show a solution
def generate(prompt, temperature, rng, max_new=8, stop=()):
context = prompt.split()
reply = []
for step in range(max_new):
probs = next_token_probs(context, temperature)
token = rng.choices(VOCAB, weights=probs)[0]
if token == "<end>":
return " ".join(reply), "end_turn"
if token in stop:
return " ".join(reply), "stop_sequence"
context.append(token)
reply.append(token)
return " ".join(reply), "max_tokens"
print(generate("Paris", 0.5, random.Random(42), stop=["of"]))Expected: ('is the capital', 'stop_sequence'). At low temperature the model follows "Paris is the capital" and the stop sequence fires when "of" is produced. Real APIs check stop sequences on the decoded text, so a stop string can also match across or inside tokens.
Check your understanding
Why can there be a pause before the first word appears when you paste a very long document?
- The model has to download the document from the internet
- Prefill must process every prompt token before the first new token can be generated
- Streaming is turned off for long prompts
What happens to the probabilities when you lower the temperature?
- The most likely tokens get even more probability and unlikely ones get less
- All tokens become equally likely
- The model learns new facts
Your app gets stop_reason: "tool_use". What should it do next?
- Show the reply to the user; it is finished
- Retry the same request with a higher temperature
- Run the requested tool, append its result to the messages and send another request
Lesson 1.6Module 1: Understanding Claude and modern AI
Tokens, context windows and embeddings
Learning objectives
- Explain what tokens are, why models use subword tokens, and how to estimate token counts.
- Explain the context window: what must fit inside it, what happens when it is full, and how apps trim history.
- Explain embeddings as vectors whose directions carry meaning, and measure similarity with cosine similarity.
- Run a toy tokenizer, a context-budget trimmer and a toy embedding space, and read their output.
Three words come up in every conversation about LLMs: tokens (the units the model reads and writes), the context window (how many tokens it can consider at once) and embeddings (how tokens become numbers that carry meaning). They also decide very practical things: what an API call costs, why a long chat "forgets" its beginning, and how document search works. This lesson takes them one at a time, each with code you can run.
Analogy: bricks, a desk and a map
Tokens are like Lego bricks: instead of one brick per letter, the set has ready-made pieces for common chunks ("the", "ing", " token"), and rare words are built from smaller pieces. The context window is the size of your desk: everything you want to work with at once must fit on it, and when it is full, something has to go back on the shelf. Embeddings are map coordinates: every token gets a location in a space with hundreds of directions, and words with related meanings end up close together, like neighbouring towns.
Tokens: the units the model sees
A neural network works with numbers, so text must first be cut into pieces and each piece mapped to an integer id. There are three obvious ways to cut, and two of them are bad. Characters make sequences very long (a page becomes thousands of steps) and force the model to learn spelling from scratch. Whole words need an enormous vocabulary and still fail on new words, typos, names and other languages. Modern models use subword tokens: a learned vocabulary of common words and word pieces, usually tens of thousands to a few hundred thousand entries, plus a fallback to raw bytes so that any text, including emoji and every language, can be encoded.
The most common way to learn such a vocabulary is byte-pair encoding (BPE) and its relatives: start from single bytes, then repeatedly merge the most frequent neighbouring pair into a new token, until the vocabulary reaches the target size. Frequent words become single tokens; rare words are split into pieces. Each model family has its own tokenizer, so the same sentence can be a different number of tokens for different models, even for different generations from the same lab.
Useful rules of thumb for English prose: one token is roughly 4 characters or about three quarters of a word, so 100 tokens is about 75 words. These are approximations. Code, numbers, unusual names and many non-English languages use noticeably more tokens per word. When cost or limits matter, count with the provider's own tokenizer or token-counting endpoint instead of estimating.
Try a toy tokenizer below. It uses the same tiny vocabulary as the Python script that follows, so the splits are much cruder than a real tokenizer's, but the behaviour is the same: common pieces become one token, uncommon text falls back to single letters or bytes.
Legend: piece learned piece · <0xC3> byte fallback · ␣ marks a space inside a token.
Simplified implementation Simplified
Our tokenizer has a hand-picked vocabulary of about 60 pieces and uses greedy longest match. Real tokenizers learn their vocabulary from data and apply learned merge rules, so their splits and counts differ.
# @run
# A toy subword tokenizer: greedy longest match over a fixed vocabulary, with a byte fallback.
# Simplified on purpose: real tokenizers (BPE and relatives) learn tens of thousands to a few hundred
# thousand pieces from data and merge them by learned rules, so their splits and counts differ.
# ids 0-255 are reserved for raw bytes (the fallback); learned pieces start at 256.
PIECES = [
" the", " cat", " sat", " on", " mat", " un", " believ", "believ", "able", "ably", " token", "ization",
"ize", " is", " a", " model", " predict", "s", "ed", "ing", ".", ",", " ", "The", "the", "Hello",
" world", "!", " caf", "na", "ive", " new", "er", "est", " learn", " language",
] + list("abcdefghijklmnopqrstuvwxyz") # single letters, so plain English never needs the byte fallback
VOCAB = {piece: 256 + i for i, piece in enumerate(PIECES)}
LONGEST = max(len(p) for p in PIECES)
def tokenize(text):
tokens, i = [], 0
while i < len(text):
# try the longest piece first, then shorter ones
for size in range(min(LONGEST, len(text) - i), 0, -1):
piece = text[i:i + size]
if piece in VOCAB:
tokens.append((piece, VOCAB[piece]))
i += size
break
else:
# no piece matches this character: emit its UTF-8 bytes, one token per byte
for b in text[i].encode("utf-8"):
tokens.append((f"<0x{b:02X}>", b))
i += 1
return tokens
def detokenize(ids):
by_id = {v: k for k, v in VOCAB.items()}
data = b"".join(bytes([i]) if i < 256 else by_id[i].encode("utf-8") for i in ids)
return data.decode("utf-8")
for text in ["The cat sat on the mat.", " unbelievably", " tokenization", "tokenization", "naïve café 🙂"]:
toks = tokenize(text)
ids = [t[1] for t in toks]
print(repr(text))
print(" pieces:", " | ".join(p for p, _ in toks))
print(" ids: ", ids)
print(f" {len(text)} characters -> {len(toks)} tokens; round trip ok: {detokenize(ids) == text}")PIECES = […] + list("abc…z"): the vocabulary. Note the leading spaces in" cat"and" the": real tokenizers also fold the space before a word into the token, so " cat" and "cat" are different tokens.VOCAB = {piece: 256 + i …}: gives each piece an id. Ids 0 to 255 are reserved for raw bytes.for size in range(…, 0, -1): at each position, try the longest possible piece first, then shorter ones (greedy longest match).else:on theforloop: runs only if no piece matched. The character is encoded as UTF-8 and every byte becomes its own token (the byte fallback), so nothing is ever "unknown".detokenize(ids): the reverse mapping. It rebuilds the bytes and decodes them, and the script checks that the round trip gives back the exact original text.
'The cat sat on the mat.'
pieces: The | cat | sat | on | the | mat | .
ids: [279, 257, 258, 259, 256, 260, 276]
23 characters -> 7 tokens; round trip ok: True
' unbelievably'
pieces: un | believ | ably
ids: [261, 263, 265]
13 characters -> 3 tokens; round trip ok: True
' tokenization'
pieces: token | ization
ids: [266, 267]
13 characters -> 2 tokens; round trip ok: True
'tokenization'
pieces: t | o | k | e | n | ization
ids: [311, 306, 302, 296, 305, 267]
12 characters -> 6 tokens; round trip ok: True
'naïve café 🙂'
pieces: na | <0xC3> | <0xAF> | v | e | caf | <0xC3> | <0xA9> | | <0xF0> | <0x9F> | <0x99> | <0x82>
ids: [285, 195, 175, 313, 296, 284, 195, 169, 278, 240, 159, 153, 130]
12 characters -> 13 tokens; round trip ok: TrueRead the output closely. " tokenization" with a leading space is 2 tokens, but "tokenization" without one is 6, because our vocabulary only has the piece with a space. "naïve café 🙂" is 12 characters but 13 tokens: "ï", "é" and the emoji are not in the vocabulary, so they fall back to 2, 2 and 4 bytes. Real tokenizers have the same kinds of quirks, which explains several famous LLM weaknesses: models can struggle to count the letters in a word or reverse a string, because they never see individual letters, only tokens.
Tokens also set the bill. API pricing is per token, usually with output tokens costing several times more than input tokens, and rate limits are counted in tokens per minute. Both input (system prompt, history, documents, tool definitions) and output count.
The context window: the model's desk
The context window is the maximum number of tokens the model can process in one request: everything it reads plus everything it writes. That includes the system prompt, tool definitions, the whole conversation history, any pasted or retrieved documents, the new message and the reply. Anthropic's current models offer windows of hundreds of thousands of tokens, and some offer up to 1 million tokens; limits change between models and over time, so check the models page in the docs rather than memorising a number.
The model has no memory outside this window. If a conversation grows beyond it, the API returns an error, so applications must decide what to leave out. The simplest strategy is a sliding window: keep the system prompt, reserve room for the reply, then keep the most recent messages that fit. Smarter strategies summarise old turns, or store everything and retrieve only the relevant parts (lesson 8.2). The script below implements the simple one with a deliberately tiny window so you can see it work.
Simplified implementation Simplified
Token counts here are estimated as characters divided by 4, and the window is 120 tokens instead of hundreds of thousands. Production code counts with the provider's tokenizer or token-counting endpoint.
# @run
# Fitting a conversation into a context window: estimate tokens, keep room for the reply, drop the oldest turns.
# Simplified: real code counts tokens with the provider's tokenizer or token-counting endpoint. "4 characters
# per token" is only a rough rule of thumb for English; code, other languages and emoji use more tokens.
WINDOW = 120 # tiny on purpose so the effect is visible; real windows hold hundreds of thousands of tokens
MAX_REPLY = 40 # tokens reserved for the answer (like max_tokens in an API call)
PER_MESSAGE = 3 # rough overhead for the role markers around each message
def estimate(text):
return (len(text) + 3) // 4 # 4 characters per token, rounded up
system = "You are a helpful travel assistant."
history = [
("user", "I am planning a week in Japan in April. Where should I start?"),
("assistant", "Start in Tokyo for three days, then take the train to Kyoto for temples and gardens."),
("user", "Is April a good time for cherry blossoms?"),
("assistant", "Yes, early April is usually peak season in Tokyo and Kyoto, but dates vary each year."),
("user", "What about food I should try?"),
("assistant", "Try ramen, sushi, okonomiyaki in Osaka and a kaiseki dinner in Kyoto."),
("user", "Can you summarise my plan in one line?"),
]
def fit(system, history, window, max_reply):
budget = window - max_reply - estimate(system) - PER_MESSAGE
kept, used = [], 0
for role, text in reversed(history): # newest first: recent turns matter most
cost = estimate(text) + PER_MESSAGE
if used + cost > budget:
break
kept.insert(0, (role, text))
used += cost
while kept and kept[0][0] != "user": # many chat APIs expect the history to start with a user turn
used -= estimate(kept[0][1]) + PER_MESSAGE
kept.pop(0)
return kept, used, budget
kept, used, budget = fit(system, history, WINDOW, MAX_REPLY)
print(f"window {WINDOW} = system {estimate(system) + PER_MESSAGE} + reply {MAX_REPLY} + history budget {budget}")
for role, text in history:
status = "kept " if (role, text) in kept else "DROPPED"
short = text if len(text) <= 38 else text[:35] + "..."
print(f" {status} {role:9} ~{estimate(text) + PER_MESSAGE:2} tokens {short}")
print(f"history sent: {len(kept)} of {len(history)} messages, ~{used} of {budget} tokens")
print()
# The same rule of thumb at real scale (approximate, English prose only).
for window in [8_000, 128_000, 200_000, 1_000_000]:
words = window * 3 // 4 # about 0.75 English words per token
pages = words // 300 # about 300 words on a printed page
print(f"{window:>9,} tokens ~ {words:>7,} words ~ {pages:>5,} pages")WINDOW,MAX_REPLY,PER_MESSAGE: the window size, the space reserved for the answer, and a rough overhead for the role markers around each message.estimate(text): the 4-characters-per-token rule of thumb, rounded up.budget = window - max_reply - …: what is left for history after the system prompt and the reply reservation.for role, text in reversed(history): walks from the newest message backwards, keeping messages until the next one would not fit. Recent turns usually matter most.while kept and kept[0][0] != "user": drops a leading assistant message, because many chat APIs expect the history to start with a user turn.- The final loop converts some real window sizes into words and pages using the same rough rules (0.75 words per token, about 300 words per page).
window 120 = system 12 + reply 40 + history budget 68
DROPPED user ~19 tokens I am planning a week in Japan in Ap...
DROPPED assistant ~24 tokens Start in Tokyo for three days, then...
DROPPED user ~14 tokens Is April a good time for cherry blo...
DROPPED assistant ~25 tokens Yes, early April is usually peak se...
kept user ~11 tokens What about food I should try?
kept assistant ~21 tokens Try ramen, sushi, okonomiyaki in Os...
kept user ~13 tokens Can you summarise my plan in one line?
history sent: 3 of 7 messages, ~45 of 68 tokens
8,000 tokens ~ 6,000 words ~ 20 pages
128,000 tokens ~ 96,000 words ~ 320 pages
200,000 tokens ~ 150,000 words ~ 500 pages
1,000,000 tokens ~ 750,000 words ~ 2,500 pagesLook at what was dropped: the first four messages, which contained the trip's key facts (Tokyo, Kyoto, April). The final request asks for a one-line summary of the plan, but the model will only see the food discussion. This is exactly how long chats "forget" their beginning, and why good assistants summarise or retrieve old context instead of silently dropping it. The scale table shows why the problem is rarer than it used to be: 200,000 tokens is roughly 500 printed pages of English.
A large window is not free, though. Every token in it is processed (and, with APIs, paid for) on every request; prefill time grows with input length; and research has found that models can use information in the middle of very long contexts less reliably than information near the start or end (for example Liu et al., 2023, "Lost in the Middle"), although newer models have improved a lot. Put the most important instructions and documents where they are easy to find, and do not fill the window just because you can.
Embeddings: turning tokens into meaning
A token id such as 4,812 is just a label; the number itself means nothing, and token 4,813 is not "close" to it in meaning. The first layer of every LLM therefore converts each token id into an embedding: a list of numbers (a vector) with hundreds to thousands of entries, looked up in a big learned table with one row per token. During training these vectors are adjusted together with the rest of the network, and tokens used in similar ways end up with similar vectors. Nobody designs the dimensions; their meaning emerges from training and is usually not human-readable.
Similarity between two vectors is usually measured with cosine similarity: how closely they point in the same direction. It ranges from 1 (same direction) through 0 (unrelated, at right angles) to -1 (opposite). To make the idea visible, the script below uses hand-written 4-dimensional "embeddings" whose dimensions we gave names.
Simplified implementation Simplified
We wrote these vectors by hand with 4 named dimensions (royalty, male, female, animal) so you can read them. Learned embeddings have hundreds to thousands of unnamed dimensions.
# @run
# Toy word embeddings: every word is a short vector of numbers; similar meanings point in similar directions.
# Simplified on purpose: these 4 dimensions were written by hand so you can read them
# (royalty, male, female, animal-ness). Real embeddings have hundreds to thousands of
# learned dimensions that do not have tidy names.
import numpy as np
words = ["king", "queen", "man", "woman", "prince", "princess", "cat", "dog", "kitten", "puppy"]
E = np.array([
# royal male female animal
[0.95, 0.90, 0.05, 0.02], # king
[0.95, 0.05, 0.90, 0.02], # queen
[0.05, 0.92, 0.04, 0.10], # man
[0.05, 0.04, 0.92, 0.10], # woman
[0.80, 0.85, 0.05, 0.02], # prince
[0.80, 0.05, 0.85, 0.02], # princess
[0.02, 0.10, 0.10, 0.95], # cat
[0.02, 0.12, 0.08, 0.93], # dog
[0.02, 0.08, 0.10, 0.90], # kitten
[0.02, 0.10, 0.08, 0.88], # puppy
])
index = {w: i for i, w in enumerate(words)}
def cosine(a, b):
return float(a @ b / (np.linalg.norm(a) * np.linalg.norm(b)))
def nearest(vec, k=3, exclude=()):
scores = [(cosine(vec, E[i]), w) for w, i in index.items() if w not in exclude]
return sorted(scores, reverse=True)[:k]
for a, b in [("king", "prince"), ("king", "queen"), ("king", "cat")]:
print(f"cosine({a}, {b})".ljust(22), "=", f"{cosine(E[index[a]], E[index[b]]):.3f}")
print()
for w in ["queen", "dog"]:
near = nearest(E[index[w]], exclude=(w,))
print(f"nearest to {w:5}:", ", ".join(f"{n} {s:.3f}" for s, n in near))
# Directions carry meaning: king - man + woman lands near queen.
target = E[index["king"]] - E[index["man"]] + E[index["woman"]]
print()
print("king - man + woman =", np.round(target, 2))
best = nearest(target, k=2, exclude=("king", "man", "woman"))
print("closest words:", ", ".join(f"{n} {s:.3f}" for s, n in best))E = np.array([…]): the embedding table, one row (vector) per word. In an LLM this table has one row per token and is learned.index = {w: i …}: maps a word to its row, the same job a token id does.cosine(a, b): the dot product divided by both lengths, i.e. how aligned two vectors are regardless of their size.nearest(vec, k, exclude): scores every word against a vector and returns the topk, which is exactly what a semantic search does over document embeddings.E[king] - E[man] + E[woman]: vector arithmetic. Removing "male" and adding "female" to "king" lands near "queen", showing that directions can encode relationships.
cosine(king, prince) = 0.998
cosine(king, queen) = 0.579
cosine(king, cat) = 0.106
nearest to queen: princess 0.998, woman 0.724, king 0.579
nearest to dog : puppy 1.000, cat 1.000, kitten 0.999
king - man + woman = [0.95 0.02 0.93 0.02]
closest words: queen 1.000, princess 0.999"king" and "prince" are almost identical (0.998), "king" and "queen" share royalty but differ in gender (0.579), and "king" and "cat" have little in common (0.106). Notice a flaw that teaches something: "dog" scores 1.000 against both "puppy" and "cat", because our four dimensions have no way to tell cats from dogs. Real embeddings need many dimensions precisely so that they can separate thousands of shades of meaning. The famous "king − man + woman ≈ queen" result was first reported for learned word vectors (word2vec, 2013); in modern LLMs such clean arithmetic holds only roughly.
Embeddings are used in two places you will meet again. Inside the LLM they are the first layer, and every later layer transforms these vectors (modules 4 and 5). Outside the LLM, separate embedding models turn whole sentences or documents into one vector each, so you can search by meaning instead of keywords; that is the basis of retrieval-augmented generation (lesson 8.3).
Cosine similarity, embedding sizes and how BPE is trained
Cosine similarity of vectors and :
In words: multiply the vectors entry by entry and add up (the dot product), then divide by the length of each vector. Only the angle between them matters, not how long they are.
Sizes. Published examples: GPT-2 small used 768-dimensional embeddings and a vocabulary of about 50,000 tokens; GPT-3's largest model used 12,288 dimensions. The embedding table alone is vocabulary × dimension numbers, so a 100,000-token vocabulary with 4,096 dimensions is about 410 million parameters. Many models reuse the same table, transposed, in the final layer that turns vectors back into next-token scores ("tied embeddings"). Claude's tokenizer, vocabulary size and embedding width are Not public.
Training BPE (sketch): split a large text sample into bytes; count every adjacent pair; merge the most frequent pair into a new token; replace it everywhere; repeat until the vocabulary is the size you want. The list of merges, in order, is the tokenizer. Encoding new text replays the merges. You will write one in lesson 5.1.
Order. Embeddings alone say nothing about word order: "dog bites man" and "man bites dog" have the same three vectors. Transformers add position information separately (lesson 4.4).
Common mistakes and debugging tips
Counting words or characters instead of tokens
Limits and prices are in tokens. A prompt of "only 50,000 words" may be 65,000 tokens or more, and much more if it is code or another language.
Fix: count with the provider's tokenizer or token-counting endpoint, and keep a safety margin.
Forgetting that the reply needs room too
If the input nearly fills the window, there is no space left for max_tokens, and the request fails or the answer is cut off.
Fix: budget as the script does: window minus reply reservation minus system prompt equals history budget.
Silently dropping the start of a conversation
A sliding window throws away early messages that may hold the most important facts, like the trip plan in our example.
Fix: pin key facts in the system prompt, summarise old turns, or retrieve relevant past messages (module 8).
Comparing embeddings from different models
Each embedding model has its own space. A vector from model A cannot be meaningfully compared with one from model B, even if both have the same length.
Fix: embed queries and documents with the same model and version, and re-embed everything when you switch.
Key takeaways
- Models read and write subword tokens; about 4 characters or 0.75 English words per token is a rough rule of thumb.
- The context window must hold the system prompt, tools, documents, history, the new message and the reply.
- When a chat outgrows the window, the app must drop, summarise or retrieve; the model itself remembers nothing.
- Embeddings are learned vectors whose directions carry meaning; cosine similarity measures how related two are.
Exercise: tune the tokenizer and the budget
Part 1: in tokenizer_toy.py, add one piece to PIECES so that "tokenization" (no leading space) becomes 2 tokens instead of 6, and check the round trip still works. Part 2: in context_budget.py, find the smallest WINDOW for which all 7 history messages are kept. Part 3 (reasoning): a support bot has a 3,000-token system prompt, 8,000 tokens of tool definitions, retrieves 5 documents of about 2,000 tokens each, and reserves 4,000 tokens for the reply. How many tokens are left for conversation history in a 200,000-token window?
Hint
Part 1: what piece is missing at the start of the word? Part 2: add up every message's estimated cost (shown in the output) and the fixed costs. Part 3: subtract all fixed costs from the window.
Show a solution
Part 1: add "token" (without a space). Greedy longest match then produces token | ization, ids change for later pieces but the round trip stays True.
Part 2: the messages cost 19 + 24 + 14 + 25 + 11 + 21 + 13 = 127 tokens; fixed costs are 12 (system with overhead) + 40 (reply) = 52, so the window must be at least 127 + 52 = 179. With WINDOW = 179 the script reports 7 of 7 messages kept.
Part 3: 200,000 − 3,000 − 8,000 − 5 × 2,000 − 4,000 = 175,000 tokens for history (roughly 130,000 English words). Fixed overhead is re-sent on every request, so it costs money each turn even though it fits easily.
Check your understanding
Why do modern LLMs use subword tokens instead of whole words?
- Because whole words cannot be stored as numbers
- To make the model forget spelling
- So common words are single tokens while any rare word, name or language can still be built from pieces
A long chat starts ignoring facts from its first messages. What is the most likely cause?
- The app trimmed old messages to fit the context window
- The model's weights changed during the chat
- The temperature was too high
Two sentence embeddings have a cosine similarity of 0.95. What does that suggest?
- The sentences contain exactly the same words
- The embedding model places them very close in meaning
- One sentence is 95% as long as the other