LLM GuideTOKENS · ATTENTION · AGENTS
Large language models · October 2026

How machines learned to predict the next word.

One story from "can machines think?" in 1950 to AI agents that run in loops in 2026. Symbolic AI and the AI winters, machine learning, deep learning, language processing before LLMs, the transformer, then how an LLM works end to end: tokens, embeddings, attention, pretraining, post-training and inference. Then the climb from a raw LLM to prompts, context, agents, harnesses and loops: each step a fix for the last step's problem. Every important term is explained.

25chapters
76years of history
150+terms explained
10live demos
The loop at the heart of every LLM: text becomes tokens, tokens become vectors, vectors flow through a stack of transformer layers, the model outputs a probability for every possible next token, one is picked, appended to the text, and the loop repeats. one token at a time · autoregressive loop "The capital ofFrance is" Tokens[791, 6864, 315 …] Embeddingsone vector per token Transformer × N layersattention: tokens lookat each other · feed-forward:each token "thinks" Next-token probabilities" Paris" 0.91 · " a" 0.03 · " the" 0.02… 100,000+ options Pick one → " Paris" ↺ append " Paris",run again for the next token

Pick where you are starting

Every chapter is tagged with a level. Choosing a path highlights the chapters to read first. Nothing is hidden, and the story reads best in order.

Chapter 01Foundations

The dream: from Turing to the AI winters

In one sentence

For its first 40 years, AI tried to make machines smart by writing down the rules of intelligence by hand (symbolic AI). It produced chess programs and expert systems, but it broke on the messy real world, and twice the money dried up in "AI winters". The lesson that set up everything after: you cannot write enough rules; the machine has to learn them from data.

The story begins

In 1950 a British mathematician asked a simple question: can a machine think? Alan Turing did not answer it. He replaced it with a game: if you chat with a hidden machine and cannot tell it from a person, does it matter what is happening inside? Seventy-two years later, millions of people would play that game every day without noticing, in a chat window called ChatGPT. This guide is the story of the road between those two moments.

Artificial intelligence (AI) is the broad goal of building machines that do things we call intelligent: understanding language, recognising images, planning, deciding. Inside AI sit smaller, nested ideas. Machine learning (ML) is AI that learns from examples instead of hand-written rules. Deep learning (DL) is machine learning with large, many-layered neural networks. Generative AI (GenAI) is deep learning that creates new content: text, images, audio, code. A large language model (LLM) is the generative model for text, and today the engine inside nearly every AI product.

How the terms nest

Artificial intelligence · 1956 →any machine behaviour we call smart, incl. rules Machine learning · 1959 →learns patterns from data Deep learning · 2006/2012 →many-layer neural networks Generative AI · 2014/2022 →LLMs · 2018 →text in, text out NLP · 1950s → natural language processing:the field that studieslanguage. It used rules,then statistics, then deeplearning, and now LLMs.

Live demo · walk the 76-year timeline

Pick an era. Each one shows what people believed, what they built, the wall they hit, and what that wall forced the next era to try.

Act one: intelligence as logic (1950–1974)

The founders believed thinking was symbol shuffling: if you could write the rules of logic and knowledge as code, a computer could reason. In the summer of 1956, John McCarthy, Marvin Minsky, Claude Shannon and Nathaniel Rochester gathered researchers at Dartmouth College for a workshop whose proposal coined the phrase "artificial intelligence". Early results were thrilling: programs proved maths theorems (Logic Theorist, 1956), played checkers well enough to beat their creator (Arthur Samuel, who in 1959 named the idea machine learning), and solved algebra word problems.

Two seeds of the future were planted early and then ignored. In 1943, Warren McCulloch and Walter Pitts described an artificial neuron: a unit that adds up weighted inputs and fires if the sum passes a threshold. In 1958, Frank Rosenblatt built the perceptron, a machine that learned those weights from examples. And in 1966, Joseph Weizenbaum's ELIZA chatted like a therapist using simple pattern-matching rules ("I feel X" → "Why do you feel X?"). People confided in it anyway. That reaction, people reading minds into fluent text, is called the ELIZA effect, and it matters even more today.

The first winter (1974–1980)

Promises outran results. In 1969, Minsky and Seymour Papert's book Perceptrons proved a single-layer perceptron cannot learn even a simple function like XOR ("one or the other, not both"). Funding for neural networks collapsed. In 1973, the UK's Lighthill report concluded AI had failed to deliver; governments in the UK and US cut funding. The core problem was combinatorial explosion: rules that worked on toy problems drowned in the number of possibilities in real ones. This period of cut funding and lost faith is the first AI winter.

Act two: expert systems and the second winter (1980–1993)

AI came back by narrowing its ambition. Expert systems encoded one domain's knowledge as thousands of if-then rules written with human experts. DEC's XCON configured computer orders and reportedly saved the company tens of millions of dollars a year. By the mid-1980s, a billion-dollar industry sold specialised "Lisp machines" to run them.

Then the cracks showed. Rules were brittle: one case nobody anticipated and the system failed badly. They were expensive to maintain: every new fact meant interviews and rule edits (the knowledge acquisition bottleneck). Cheaper desktop computers killed the Lisp machine market around 1987, and the second AI winter followed.

The lesson both winters taught

The world has too many cases to write rules for. Language is the worst offender: "bank" means a river side or a money place, sarcasm flips meaning, and every sentence you will say today is probably new. Something had to learn the rules from examples. That is where the story turns in Ch 2.

YearMilestoneWhy it matters to LLMs
1943McCulloch–Pitts artificial neuronThe basic unit every neural network, including LLMs, still uses (weighted sum + activation)
1948Claude Shannon's information theory; he models English as a probability of the next letterThe first "language model": predicting what comes next. LLMs are this idea at enormous scale
1950Turing, "Computing Machinery and Intelligence" (the imitation game)Framed AI by behaviour: does it talk like us?
1956Dartmouth workshop names "artificial intelligence"The field begins
1958Rosenblatt's perceptron learns weights from dataThe first learning neural network
1959Arthur Samuel coins "machine learning"Learning instead of programming
1966ELIZA chatbotThe ELIZA effect: fluency feels like understanding
1969Perceptrons book shows single-layer limitsNeural nets abandoned for ~15 years
1973–80Lighthill report; first AI winterHype without results is punished
1980–87Expert systems boom (XCON)Hand-written knowledge works in narrow domains only
1987–93Lisp machine collapse; second AI winterBrittle rules don't scale
1997IBM Deep Blue beats Kasparov at chessSearch + hand-tuned evaluation; impressive, but not learning language
Deep dive

The ideas underneath

Concepts from this era that still shape how we talk about LLMs.

Symbolic AI vs connectionism terms
Symbolic AI ("GOFAI")
Good Old-Fashioned AI: intelligence as explicit symbols and rules (logic, search trees, knowledge bases). Easy to inspect, hard to scale.
Connectionism
Intelligence as patterns of connection strengths in a network of simple units, learned from data. Hard to inspect, scales with data and compute. Modern LLMs are pure connectionism.
Neuro-symbolic
Combining both. Today's agents are an informal version: a neural LLM calling symbolic tools like calculators, databases and code interpreters (Ch 18).
Shannon's next-letter game, the first language model history

In 1948 and 1951, Shannon estimated the entropy of English by having people guess the next letter of a text. He also generated text from letter and word statistics: picking each next word based on the previous one gave strange but English-like sentences. A language model is exactly this: a probability distribution over what comes next given what came before. Everything from n-grams (Ch 4) to GPT is a better estimate of the same thing.

P(next word | previous words) · Shannon 1948 → n-grams 1980s → neural LM 2003 → GPT 2018
Why "AI winter" still matters context

Each winter followed the same shape: a real breakthrough, inflated promises, money rushing in, a gap between demo and dependable product, then disappointment. When people today debate whether GenAI is a bubble, they are asking whether the gap between demos and dependable, profitable systems will close fast enough. Most of Part III of this guide (prompts, context, agents, harnesses, loops) is the industry's work to close that gap.

The Turing test, and why passing it is not the goal concept

Modern chatbots routinely fool people in short conversations, which shows the test measures human-likeness, not reliability, truth or capability. Today's benchmarks ask instead: can it solve this maths problem, fix this bug, finish this multi-hour task? See evaluation in Ch 22.

Chapter 02Foundations

Machine learning: let the data write the rules

In one sentence

Machine learning flips programming around: instead of writing rules, you give the computer examples and a way to score its mistakes (a loss function), and an optimiser (usually gradient descent) nudges millions of numbers (parameters) until the mistakes shrink. Every LLM is trained this way. What ML lacked for decades was a way to learn the right features without humans designing them.

The story so far

The rule-writers had lost. A quieter group of statisticians and engineers took over through the 1990s with a humbler idea: don't tell the machine what spam looks like. Show it ten thousand emails marked spam or not spam, and let it work out the pattern itself.

Traditional programming is rules + data → answers. Machine learning is data + answers → rules. The learned "rules" are a model: a function with adjustable numbers called parameters (or weights). Training means finding parameter values that make the model's outputs match known answers. Inference means using the trained model on new inputs.

The three ways a machine learns

Labels given

Supervised learning

Learn from input-answer pairs: email → spam/not spam, house features → price. Classification predicts a category; regression predicts a number. LLM fine-tuning on examples (SFT) is supervised.

No labels

Unsupervised learning

Find structure in raw data: group customers into clusters, compress data. LLM pretraining is self-supervised: the "label" is just the next word, taken from the text itself, so no human labelling is needed. That is why it scales to trillions of words.

Rewards

Reinforcement learning (RL)

An agent acts, gets a reward, and learns which actions pay off. It beat world champions at Go (AlphaGo, 2016) and now shapes how chat and reasoning models behave (RLHF, RLVR in Ch 12).

How learning actually happens: loss and gradient descent

A loss function turns "how wrong is the model?" into one number. For predicting prices it might be the average squared error. For predicting the next word it is cross-entropy: how surprised the model was by the real word (Ch 11). Gradient descent then asks, for each parameter: if I nudge you up a tiny bit, does the loss go up or down? That slope is the gradient. Move every parameter a small step downhill, recompute, repeat. The step size is the learning rate. One pass over the training data is an epoch; a chunk of examples processed together is a batch.

new weight = old weight − learning_rate × ∂loss/∂weight
linear model: ŷ = w·x + b · loss (MSE) = mean((ŷ − y)²)

Live demo · watch gradient descent learn

The model is a line, y = w·x + b, with two parameters. It starts wrong. Each step computes the gradient of the error and moves both parameters downhill. Try a learning rate that is too high and watch it blow up. An LLM does exactly this, with hundreds of billions of parameters instead of two.

The classic toolbox (1990s–2010s)

MethodIdea in one lineStill used for
Linear / logistic regressionWeighted sum of features (logistic squashes it into a probability)Baselines, scoring, the last layer of every neural net
Naive BayesCount how often each word appears in spam vs not spamFast text classification
Decision trees, random forests (2001), gradient boosting (XGBoost 2014)Chains of yes/no questions; many trees voteTabular data: still often beat neural nets on spreadsheets
Support vector machines (1995)Find the widest boundary between classesSmall datasets
k-means, PCAGroup similar points; compress dimensionsClustering, visualising embeddings
k-nearest neighboursAnswer like the most similar known examplesThe core of vector search in RAG (Ch 17)

The wall: features had to be hand-made

Classic ML needed humans to decide what the model looks at. For spam: count of "free", number of exclamation marks, sender domain. For images: edge detectors, colour histograms. This feature engineering took most of a project's time and capped how good the model could be. Language was especially hard: a bag of word counts throws away word order, so "dog bites man" and "man bites dog" look identical. The next breakthrough was models that learn their own features: deep learning.

Three ideas from this chapter you will see again

Overfitting: the model memorises training examples instead of learning the pattern, so it fails on new data. We guard against it with a held-out validation set and a final test set. Generalisation: doing well on data the model never saw, the whole point. Bias–variance trade-off: too simple a model misses the pattern (underfitting), too flexible a model memorises noise. LLMs complicated this picture: huge models trained on huge data generalise surprisingly well.

Deep dive

ML details worth knowing

The vocabulary that carries straight into LLM training.

Train, validation, test, and data leakage basics

Split data three ways: train (fit parameters), validation (choose settings like learning rate, called hyperparameters), test (report the final score once). Data leakage is when test information sneaks into training. For LLMs this is called benchmark contamination: test questions appear somewhere on the web the model trained on, so scores look better than real ability.

Stochastic gradient descent, momentum and Adam math

Computing the exact gradient over all data is too slow, so we estimate it on a small random mini-batch: stochastic gradient descent (SGD). Momentum keeps moving in the recent average direction to smooth out noise. Adam (2014) also scales each parameter's step by how noisy its gradient has been. LLMs are trained with AdamW (Adam with decoupled weight decay), plus a learning-rate schedule: warm up, then decay (often cosine).

Adam: m = β₁m + (1−β₁)g · v = β₂v + (1−β₂)g² · w −= lr · m̂ / (√v̂ + ε)
Regularisation overfitting

Techniques that stop a model memorising: weight decay (penalise large weights), dropout (randomly switch off units during training), early stopping (stop when validation loss rises), and simply more data. Large LLM pretraining runs usually see each token about once, which itself limits memorisation, though models still memorise text that appears many times.

Metrics: accuracy, precision, recall, F1 eval
Accuracy
Share of predictions that are correct. Misleading when classes are imbalanced.
Precision
Of the items flagged positive, how many really are.
Recall
Of the real positives, how many were found.
F1
Harmonic mean of precision and recall.

These come back in RAG evaluation (did retrieval find the right passages?) and in judging classifiers built on LLMs.

Chapter 03Foundations

Deep learning: networks that learn their own features

In one sentence

Stack many layers of artificial neurons, train them all together with backpropagation, and the early layers learn simple features while later layers combine them into complex ones, with no hand-made features at all. It took three ingredients arriving together around 2012 to make this work: big data (the internet), fast parallel hardware (GPUs) and better training tricks.

The story so far

Through two winters a small group kept faith in neural networks: Geoffrey Hinton, Yann LeCun, Yoshua Bengio and a few others, often unfunded and unfashionable. In 2012 their bet paid off in a single afternoon, when a network trained on two gaming graphics cards crushed every hand-engineered system at recognising images. Within three years, almost the whole field had switched sides.

A neural network in plain words

An artificial neuron multiplies each input by a weight, adds them up with a bias, and passes the result through an activation function, a simple bend such as ReLU (max(0, x)). The bend is what lets networks learn curved, complex patterns rather than only straight lines. A layer is many neurons side by side; a deep network stacks many layers. Inputs enter the first layer, hidden layers transform them, and the output layer gives the answer. Running data forward through the network is the forward pass.

Backpropagation ("backprop") is how the network learns. After the forward pass, compute the loss, then work backwards layer by layer using the calculus chain rule to find how much each weight contributed to the error. Then gradient descent (Ch 2) adjusts every weight. The method was known earlier but was popularised in 1986 by David Rumelhart, Geoffrey Hinton and Ronald Williams. A multi-layer network trained this way solves XOR easily, answering the 1969 objection.

Forward pass and backpropagation

input (pixels / tokens)hidden 1 · edgeshidden 2 · shapesoutput · "cat" 0.94 forward pass → ← backprop: error gradients

Why it suddenly worked in 2012

Data

ImageNet (2009)

Fei-Fei Li's team labelled over 14 million images across about 20,000 categories using crowd workers. Deep networks are hungry; for the first time there was enough food.

Compute

GPUs

Graphics cards do thousands of multiplications in parallel, exactly what neural networks need. NVIDIA's CUDA (2007) made them programmable for general maths. Today's AI data centres are built around this.

Tricks

Better training

ReLU activations (gradients don't fade), dropout (less overfitting), good weight initialisation, and later batch normalisation (2015) and residual connections (2015).

In the 2012 ImageNet competition, AlexNet (Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton) cut the top-5 error rate to about 15%, against about 26% for the best non-deep system. In 2015 Microsoft's ResNet, 152 layers deep thanks to residual connections (each layer adds its output to its input, so signals and gradients pass through cleanly), beat the human benchmark on the same task. In 2016 DeepMind's AlphaGo combined deep networks with reinforcement learning and search to beat Lee Sedol at Go, a game thought to be a decade away. In 2018 Hinton, LeCun and Bengio received the Turing Award; in 2024 Hinton shared the Nobel Prize in Physics with John Hopfield for foundational work on neural networks.

The architecture zoo before transformers

ArchitectureBuilt forKey ideaLimit that mattered for language
Feed-forward (MLP)Fixed-size inputsLayers of neurons, data flows one wayNo notion of order or variable length
CNN (LeCun, 1989; LeNet 1998)ImagesSmall filters slide over the image; share weights; detect local patternsSees local windows; weak at long-range links in text
RNN (1980s)SequencesReads one item at a time, carrying a hidden "memory" vector forwardMemory fades over long sequences (vanishing gradients); can't be parallelised
LSTM (Hochreiter & Schmidhuber, 1997), GRU (2014)Long sequencesGates decide what to remember, forget and outputBetter memory, still sequential and slow to train at scale
Autoencoder, VAE (2013)Compression, generationSqueeze input to a small code, rebuild itEarly generative models; blurry outputs
GAN (Goodfellow, 2014)Image generationA generator and a discriminator competeThe first convincing generative AI for images; hard to train
The wall for language

RNNs and LSTMs read text one word at a time, left to right. That made them slow (you can't process word 50 until word 49 is done, so thousands of GPU cores sit idle) and forgetful (information from 200 words back fades). Language needed a model that could look at every word at once and connect any two words directly. That model arrived in 2017 (Ch 5).

Deep dive

Deep learning mechanics

Pieces that live on inside every LLM.

Activation functions: sigmoid, tanh, ReLU, GELU, SwiGLU math

Sigmoid and tanh squash values but their gradients vanish at the extremes, which stalled deep networks. ReLU (max(0,x)) fixed that. Transformers mostly use smooth variants: GELU (GPT-2, BERT) and SwiGLU (Llama, many 2023+ models), a gated unit that multiplies two projections together.

ReLU(x) = max(0, x) · GELU(x) ≈ x·Φ(x) · SwiGLU(x) = (xW₁ ⊙ SiLU(xW₂))W₃
Vanishing and exploding gradients training

Backprop multiplies many small numbers together across layers (or time steps in an RNN). Many numbers below 1 multiply to almost zero (vanishing: early layers stop learning); above 1, they explode. Fixes: ReLU-family activations, careful initialisation, normalisation layers, residual connections and gradient clipping. Every transformer layer uses residuals and normalisation for exactly this reason (Ch 10).

Representation learning: what "learns its own features" means concept

Researchers who looked inside image networks found early layers detecting edges, middle layers textures and parts, and late layers whole objects, none of it programmed. The network learns a representation: a way of encoding inputs as vectors where useful distinctions are easy to make. Embeddings (Ch 8) are the language version.

Transfer learning: train once, reuse everywhere pattern

A network trained on ImageNet could be fine-tuned for X-rays with only a few thousand examples, because its general visual features transfer. This pretrain, then fine-tune recipe is exactly how LLMs are built: pretrain on the internet, then post-train for chat (Ch 12). A model meant to be adapted to many tasks is now called a foundation model (term from Stanford, 2021).

Chapter 04Foundations

Language before LLMs: rules, statistics, vectors

In one sentence

Natural language processing (NLP) went through three ages: hand-written grammar rules (1950s–80s), counting statistics like n-grams and TF-IDF (1990s–2000s), and neural vectors like word2vec and sequence-to-sequence models with attention (2013–2017). Each age fixed the last one's biggest flaw, and the last one gave us the two ideas that make LLMs work: words as vectors and attention.

The story so far

In 1954, IBM and Georgetown University showed off a computer translating 60 Russian sentences into English, and predicted machine translation would be solved within five years. It took about sixty. Language turned out to be the hardest thing AI ever tried, and also, in the end, the door to everything else.

Age one: rules (1950s–1980s)

Linguists wrote grammars and dictionaries by hand. Noam Chomsky's 1957 work on formal grammars gave parsers their theory. Systems like SHRDLU (1970) understood commands in a tiny world of blocks. These systems were precise but brittle, the same wall as expert systems (Ch 1). The 1966 ALPAC report judged machine translation a failure and US funding dried up.

Age two: statistics (late 1980s–2012)

IBM's speech and translation group, led by Frederick Jelinek, started treating language as probabilities learned from large text collections (a corpus). Jelinek's (possibly apocryphal) line captures the mood: "Every time I fire a linguist, the performance of the speech recogniser goes up." Key tools:

  • n-gram language models: estimate the next word from the previous n−1 words by counting. A trigram model knows "of the" is often followed by "year". They power old phone keyboards and early speech recognition. They can't see past their small window and have no idea that "car" and "automobile" are related.
  • Bag of words and TF-IDF: represent a document by word counts, weighting rare words more (term frequency × inverse document frequency). Still the core of keyword search engines (BM25, 1994), and still used today in hybrid search for RAG.
  • Statistical machine translation: learn word and phrase alignments from translated documents (IBM models, 1990s; Google Translate from 2006).
  • Hidden Markov models and CRFs: tag each word's part of speech or entity type (person, place, company), a task called named-entity recognition (NER).

Age three: neural vectors (2003–2017)

In 2003, Yoshua Bengio's team trained a neural network language model that learned a vector (a list of numbers) for each word, so similar words got similar vectors and the model could generalise between them. It was too slow to matter then. In 2013, Tomas Mikolov's word2vec at Google made word vectors cheap to train on billions of words, and the results stunned people: the vectors encoded meaning as geometry. The famous example: vector("king") − vector("man") + vector("woman") lands near vector("queen"). These vectors are called word embeddings (Ch 8). GloVe (Stanford, 2014) and fastText (Facebook, 2016) followed.

In 2014, sequence-to-sequence (seq2seq) models (Sutskever, Vinyals and Le at Google) used one LSTM to read a sentence into a single vector (the encoder) and another to write the translation from it (the decoder). Squeezing a whole sentence into one vector was a bottleneck. The same year, Dzmitry Bahdanau, Kyunghyun Cho and Yoshua Bengio added attention: when writing each output word, the decoder looks back at all the input words and decides which ones matter most right now. Translation quality jumped; Google switched its translator to neural networks in 2016.

Three ways to represent the word "bank"

Representation"bank" looks likeKnows "bank" ≈ "lender"?Knows river bank ≠ money bank?
One-hot / bag of words[0,0,…,1,…,0] one slot in a 50,000-word listNo: every word is equally unrelatedNo
Static embedding (word2vec, 2013)[0.21, −1.3, 0.07, …] 300 numbers, same in every sentenceYesNo: one vector mixes both meanings
Contextual embedding (ELMo 2018, BERT, GPT)A different vector in every sentence, computed from its neighboursYesYes: "river bank" and "bank loan" get different vectors

The classic NLP task list

Understanding

Text classification, sentiment analysis, named-entity recognition, part-of-speech tagging, parsing, question answering, natural language inference.

Generation

Machine translation, summarisation, dialogue, captioning, autocomplete.

The old way vs now

Before 2018, each task had its own model, dataset and team. After 2020, one LLM does all of them from an instruction. That collapse of a hundred specialised systems into one general one is the real revolution.

The wall

By 2016 NLP had vectors and attention, but it still ran on RNNs that read one word at a time. Attention was a helper bolted onto a slow, forgetful core. The obvious, radical question was: what if attention was the whole model? (Ch 5)

Deep dive

Classic NLP, explained

Methods that still show up inside modern systems.

n-gram maths and why it hits a wall math
P(w₃ | w₁ w₂) ≈ count(w₁ w₂ w₃) / count(w₁ w₂)
"of the year": count 9,120 / "of the": 1,000,000 → 0.009

The number of possible n-grams explodes with n (50,000 words gives 1.25 × 10¹⁴ possible trigrams), and most never appear in any corpus, so their probability is zero unless you smooth it (Kneser-Ney smoothing). That is why n-grams stayed at 3–5 words of context. Neural models generalise between similar sequences instead of counting exact ones.

TF-IDF and BM25 search
tf-idf(t, d) = tf(t, d) × log(N / df(t))

A word that appears in every document (like "the") gets near-zero weight; a rare word that appears often in one document scores high. BM25 refines this with saturation and length normalisation. It is still a strong baseline and is combined with vector search in most production RAG systems (see the RAG Guide).

Stemming, lemmatisation, stop words preprocessing

Old pipelines normalised text: stemming chops endings ("running" → "run"), lemmatisation maps to dictionary forms ("better" → "good"), stop words ("the", "a") are removed. LLMs do none of this: they read raw text split into subword tokens (Ch 7) and learn these relationships themselves.

Encoder and decoder: the words that stuck terms

From seq2seq onward, an encoder turns input into internal vectors, and a decoder produces output one token at a time. BERT is encoder-only, GPT is decoder-only, T5 keeps both. Understanding this split explains the model families in Ch 14.

Chapter 05Foundations

2017–2022: the transformer and the birth of GenAI

In one sentence

In 2017 eight Google researchers threw out the RNN and built a model from attention alone: the transformer. It processes every word in parallel, connects any two words directly, and gets better almost predictably as you make it bigger. Five years of scaling it up (GPT-1 → GPT-3), plus training it to follow instructions, produced ChatGPT in November 2022, and "generative AI" became the fastest-adopted technology in history.

The story so far

The paper had a cheeky title, "Attention Is All You Need", and a modest goal: better translation. Its authors did not set out to start an industry. But the architecture they described was so simple, so parallel and so scalable that within five years it ran nearly all of AI, from chatbots to image generators to protein folding.

What the transformer changed

Parallel

All words at once

An RNN reads word 1, then 2, then 3. A transformer processes the whole sequence in one go during training, so a GPU's thousands of cores are all busy. Training got many times faster per dollar.

Direct

Any word can see any word

Self-attention lets every token look at every other token in one step, so a pronoun can link to a noun 500 words back without information fading through 500 steps.

Scalable

Bigger keeps getting better

Add layers, width and data, and the loss falls smoothly. That predictability let labs justify spending millions, then billions, on training runs (Ch 11).

From one paper to ChatGPT

WhenModel / eventWhat was new
Jun 2017"Attention Is All You Need" (Vaswani et al., Google)The transformer: encoder-decoder built from self-attention and feed-forward layers
Feb 2018ELMo (Allen AI)Contextual word vectors from a pretrained LSTM language model
Jun 2018GPT-1 (OpenAI), 117M parametersGenerative Pre-trained Transformer: decoder-only, pretrain on books, fine-tune per task
Oct 2018BERT (Google), 340MEncoder-only, trained to fill in masked words; topped every understanding benchmark; powered Google Search from 2019
Feb 2019GPT-2, 1.5BFluent paragraphs; zero-shot task ability; staged release over misuse fears
Oct 2019T5 (Google)Every task framed as text-to-text
Jan 2020Scaling laws (Kaplan et al., OpenAI)Loss falls as a smooth power law in parameters, data and compute
May 2020GPT-3, 175BIn-context learning: show a few examples in the prompt and it does the task, no retraining. Prompting is born (Ch 16)
2021Codex → GitHub Copilot; CLIP and DALL·ELLMs write code; text and images share one vector space
Jan–Mar 2022Chain-of-thought prompting; InstructGPT; Chinchilla"Think step by step" improves reasoning; RLHF makes models follow instructions; train on more data per parameter
Aug 2022Stable Diffusion (open)Image generation for everyone on a home GPU
30 Nov 2022ChatGPTA chat interface on an RLHF-tuned GPT-3.5. About 1 million users in 5 days and an estimated 100 million in 2 months

What "generative AI" means

Most earlier AI was discriminative: it sorted inputs into categories (spam or not, cat or dog). Generative models learn the probability distribution of the data well enough to produce new samples from it: new sentences, images, songs, code. For text, the generator is an LLM predicting one token at a time. For images, the dominant method is diffusion: start with random noise and repeatedly remove noise, guided by a text prompt. Audio, video and 3D followed the same two patterns. Multimodal models now take in and produce several of these at once.

ChatGPT was not a scientific breakthrough on its own; GPT-3.5 had existed for months. Its leap was product: a free chat box that anyone could use, tuned to be helpful and polite. It showed that the interface to AI would be natural language. Microsoft invested about $10 billion in OpenAI in January 2023; Google declared an internal "code red"; GPT-4 arrived in March 2023, Meta's LLaMA leaked and kick-started open models, and Anthropic launched Claude. GenAI went from research to the centre of the tech industry in months.

Why prediction became intelligence (sort of)

To predict the next word in a physics textbook, a legal contract, a Python file and a love letter, a model has to absorb a lot about physics, law, code and people. Ilya Sutskever's framing: good enough next-token prediction requires understanding the process that generated the text. Whether that is "real" understanding is still argued. What is not argued is that it is extremely useful, and that it fails in specific, predictable ways (Ch 15).

Deep dive

The transformer era in detail

Context that explains today's model landscape.

Why decoder-only GPT beat encoder BERT for general AI architecture

BERT sees the whole sentence both ways and is excellent at understanding (classification, search). But it cannot naturally write. GPT only looks left and predicts the next token, which is a worse fit for some benchmarks but a universal interface: any task can be phrased as "continue this text". Once models were big enough to follow instructions, that universality won. Encoder models survive as embedding models and rerankers (Ch 14).

Emergent abilities, and the debate about them research

Some abilities (multi-digit arithmetic, following unusual instructions) seemed to appear suddenly above a certain model size; a 2022 paper called them emergent abilities. A 2023 paper ("Are Emergent Abilities a Mirage?") showed many of these jumps vanish when you use smoother metrics: the underlying skill improves gradually, and all-or-nothing scoring makes it look sudden. Both views are useful: capabilities grow smoothly, but usefulness can cross a threshold suddenly.

The "bitter lesson" idea

In 2019 Rich Sutton wrote that the biggest lesson of 70 years of AI is that general methods that use more computation (search and learning) eventually beat methods that build in human knowledge. Symbolic AI, hand-made features and grammar rules all lost to scale. The transformer is the cleanest example. Part III of this guide is a partial counterpoint: around the model, careful human engineering (context, harnesses, loops) still matters a great deal.

Diffusion in one paragraph GenAI

Diffusion models (2020 DDPM; Stable Diffusion, DALL·E 2, Midjourney in 2022) are trained by adding noise to images step by step and learning to reverse each step. To generate, start from pure noise and denoise 20–50 times, steering each step toward the text prompt with a text encoder like CLIP. Many recent image and video models use a transformer as the denoiser (diffusion transformers). Diffusion is also being tried for text (Ch 14).

Chapter 06FoundationsBuilder

An LLM end to end, in one picture

The whole thing

An LLM is a giant function that takes a sequence of tokens and returns a probability for every possible next token. It is built in two big phases (pretraining on trillions of tokens of text, then post-training to be a helpful assistant) and used in a third (inference: generate one token, append it, repeat). Everything else in this Part is a zoom-in on one box of this picture.

Follow one question

For the rest of Part II we follow a single request through the machine: you type "What is the capital of France?" and, about a third of a second later, the word "Paris" starts to appear. Here is everything that happens in between, and everything that had to happen months before.

The life of an LLM: build it, then run it

Build · months · millions to billions of dollars · done once per model 1 · Dataweb, books, codeclean · dedupe 2 · TokenizerBPE vocab~100k–250k tokens 3 · Pretrainingpredict next token→ base model 4 · Post-trainingSFT · RLHF · RLVR→ assistant 5 · Evaluatebenchmarksred-team · safety 6 · ReleaseAPI or openweights The weights file (billions of numbers) is the product. Pretraining teaches knowledge and language; post-training teaches behaviour. Run (inference) · milliseconds per token · every request Promptsystem + user Tokenizetext → IDs EmbedIDs → vectors N transformer layersattention + MLP Logitsscore per token Sampletemperature, top-p Detok→ "Paris" append the new token, run again (KV cache keeps past work)

The request, step by step

  1. Your app builds the promptThe chat app wraps your words in a chat template: a system prompt (the app's instructions), earlier turns, then your message, with special marker tokens between roles. This full text is the context.
  2. TokenizeThe text is split into tokens, subword pieces like What, is, the, capital, and each is mapped to an integer ID (Ch 7).
  3. EmbedEach ID picks a row in the embedding matrix: a vector of a few thousand numbers. Position information is mixed in (Ch 8).
  4. PrefillAll prompt tokens go through every transformer layer in parallel. In each layer, attention lets tokens share information ("capital" looks at "France"), then a feed-forward network transforms each token's vector (Ch 9, Ch 10). The keys and values computed here are saved in the KV cache.
  5. PredictThe final vector of the last token is multiplied by the output matrix to give a logit (raw score) for each of ~100,000+ vocabulary tokens. Softmax turns logits into probabilities: Paris 0.91, The 0.04 …
  6. SampleA decoding strategy (temperature, top-p) picks one token (Ch 13). It is streamed to your screen.
  7. Repeat (decode)The new token is appended and only it is run through the layers, reusing the KV cache. This continues until the model emits an end-of-sequence (EOS) token or hits the max output length.
PhaseInputOutputCost driverTypical scale (frontier, 2026)
PretrainingTrillions of tokens of textBase model weightsCompute ≈ 6 × parameters × tokens15–40T+ tokens, 10²⁵–10²⁶+ FLOPs, tens of thousands of GPUs for months
Post-trainingInstruction examples, preference pairs, verifiable tasksAssistant / reasoning modelHuman data + RL computeNow a large and growing share of total training compute
Inference: prefillPrompt tokensKV cache + first tokenCompute-bound (matrix maths)Thousands of tokens per second per GPU
Inference: decodeOne token at a timeNext tokenMemory-bandwidth-bound (reading weights + cache)~30–300 tokens/s per user stream

Frontier lab figures are mostly undisclosed; ranges are informed estimates. Check model cards for specific numbers.

The single most useful mental model

The model has no memory between requests and no access to anything outside its context. Everything it "knows" is either baked into its weights at training time or present in the tokens you send. Every engineering layer in Part III (prompts, RAG, tools, memory, agents) is a way of putting the right tokens in front of this function.

Deep dive

The picture in more detail

Terms you meet the moment you read a model card.

Weights, parameters, checkpoints terms
Parameters / weights
The learned numbers. "70B" means 70 billion of them.
Checkpoint
A saved snapshot of the weights during or after training.
Base model
Straight out of pretraining: continues text, doesn't follow instructions reliably.
Instruct / chat model
Post-trained to follow instructions and hold conversations.
Open weights
The weights are downloadable (Llama, Qwen, DeepSeek, Mistral, Gemma). "Open source" strictly also means open data and code, which few models offer.
The chat template, made visible format

Chat APIs accept a list of messages, but the model only sees one token sequence. A template turns the list into text with special tokens. An example in the ChatML-style format:

text · what the model actually reads
<|im_start|>system
You are a concise geography tutor.<|im_end|>
<|im_start|>user
What is the capital of France?<|im_end|>
<|im_start|>assistant

The model's job is to continue after assistant. Each model family has its own template; using the wrong one with an open model quietly degrades quality.

Is it "just autocomplete"? concept

Mechanically, yes: one next-token prediction at a time. But the computation behind each prediction is deep, and the model plans in ways interpretability research can partly see: Anthropic's 2025 circuit-tracing work found a model choosing a rhyme word before writing the line that ends in it. "Next-token predictor" describes the interface, not the limits of what happens inside.

Chapter 07FoundationsBuilder

Tokens: the atoms an LLM reads

The rule

LLMs don't read letters or words; they read tokens, chunks of text from a fixed vocabulary learned with byte-pair encoding (BPE). In English, 1 token ≈ 4 characters ≈ ¾ of a word. Tokens are the unit of price, speed, context length and many strange failures (counting letters, arithmetic, non-English cost).

Why not just use words? There are millions of word forms, new ones every day, and typos. Why not letters? Sequences become 4× longer, and attention cost grows with length squared. Subword tokenization is the compromise: common words are one token ( the, capital), rare words split into pieces ( token + ization), and anything at all can be spelled with byte-level fallback tokens, so nothing is ever "unknown".

BPE builds the vocabulary from data: start with single bytes, count which adjacent pair appears most often in the training text, merge it into a new token, and repeat tens of thousands of times. The result is a vocabulary (GPT-2: 50,257 tokens; Llama 3: 128,256; GPT-4o's o200k: about 200,000) and an ordered list of merges. Note the leading spaces: " Paris" and "Paris" are different tokens.

Live demo · see text the way a model sees it

Type anything. This is a small teaching tokenizer (greedy longest match over a few hundred common English pieces, with single-character fallback), so counts are approximate, but the behaviour is real: common words stay whole, rare words split, numbers and non-English text cost more tokens.

Why tokens explain so many LLM quirks

QuirkToken explanationWorkaround
"How many r's in strawberry?" goes wrongThe model sees pieces like str aw berry, not lettersAsk it to spell letter by letter first, or use code
Arithmetic on long numbers slipsNumbers split into irregular chunks (123 456 7), so digit columns don't line upUse a calculator or code tool (Ch 18)
Hindi, Tamil, Thai cost 2–5× more than EnglishVocabularies learned mostly from English text compress other scripts poorlyNewer tokenizers with larger, multilingual vocabularies; budget for it
Odd behaviour on strings like SolidGoldMagikarpGlitch tokens: in the vocabulary but almost never seen in trainingRare in modern models; strip junk input
JSON and code use more tokens than expectedBraces, quotes and indentation are often separate tokensCompact formats; minified data in prompts
Output cut mid-sentenceHit max_tokens, counted in tokens not wordsRaise the limit; check the stop reason
Rule of thumb

1 token ≈ 4 chars

English prose. 100 tokens ≈ 75 words. A 300-page book ≈ 120k tokens.

Price

Billed per token

APIs price input and output tokens separately, output usually 3–5× more.

Limit

Context window

Max tokens per request (prompt + output): commonly 128k–1M+ in 2026.

Special

Control tokens

<|begin_of_text|>, end-of-turn, tool-call markers: structure the model learned in training.

Implement it withTokenization and token countingCount before you send; budget context and cost
BPE training: repeat k times { pair* = argmax count(a,b); replace every (a,b) with new token ab }
cost = input_tokens × p_in + output_tokens × p_out
  • tiktokenOpenAI's fast BPE tokenizer (cl100k_base, o200k_base).
  • Hugging Face tokenizersTrain and run BPE, WordPiece and Unigram tokenizers; loads any open model's tokenizer.
  • Provider count endpointsAnthropic and Google expose token-counting API calls for their own models.
python
import tiktoken
from transformers import AutoTokenizer

enc = tiktoken.get_encoding("o200k_base")
ids = enc.encode("What is the capital of France?")
print(len(ids), [enc.decode([i]) for i in ids])

tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-7B-Instruct")
msgs = [{"role": "user", "content": "What is the capital of France?"}]
text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
print(text)                      # shows the real chat template
print(len(tok(text).input_ids))  # tokens the model will read
Azure OpenAI bills per 1K/1M tokens per deployment; quotas are in tokens per minute (TPM).
  • Azure OpenAI / Azure AI FoundryResponse usage fields report prompt, completion and cached tokens.
  • tiktokenSame encodings as the OpenAI models you deploy.
  • Azure MonitorTrack token metrics per deployment.
python
from openai import AzureOpenAI
client = AzureOpenAI(azure_endpoint=ENDPOINT, api_key=KEY, api_version="2024-10-21")
r = client.chat.completions.create(model="my-deployment",
        messages=[{"role": "user", "content": "Capital of France?"}])
print(r.usage.prompt_tokens, r.usage.completion_tokens)
Bedrock pricing and quotas are per input/output token per model.
  • Amazon Bedrockusage in Converse API responses: inputTokens, outputTokens.
  • Bedrock CountTokensCount tokens for supported models before sending (check docs for model support).
  • CloudWatchInputTokenCount / OutputTokenCount metrics.
python
import boto3
br = boto3.client("bedrock-runtime")
r = br.converse(modelId=MODEL_ID,
    messages=[{"role": "user", "content": [{"text": "Capital of France?"}]}])
print(r["usage"])   # {'inputTokens': ..., 'outputTokens': ..., 'totalTokens': ...}
Gemini counts tokens per modality (text, image, audio, video); images and video seconds convert to tokens.
  • Vertex AI / Gemini API count_tokensExact counts for Gemini models.
  • usage_metadataPrompt, candidates and cached token counts on every response.
python
from google import genai
client = genai.Client()
n = client.models.count_tokens(model=GEMINI_MODEL, contents="Capital of France?")
print(n.total_tokens)
Train your own: vocab_size is a trade-off: bigger vocab → shorter sequences but a bigger embedding matrix (V × d).
  • SentencePieceGoogle's BPE/Unigram trainer (used by T5, Gemma, early Llama).
  • Hugging Face tokenizersRust-fast trainer with byte-level BPE.
  • llama.cppllama-tokenize to inspect GGUF model tokenization.
python
from tokenizers import Tokenizer, models, trainers, pre_tokenizers
tok = Tokenizer(models.BPE())
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
trainer = trainers.BpeTrainer(vocab_size=32000, special_tokens=["<s>", "</s>"])
tok.train(["corpus.txt"], trainer)
print(tok.encode("What is the capital of France?").tokens)
Deep dive

Tokenization details

The parts that bite in production.

BPE vs WordPiece vs Unigram algorithms
BPE
Merge the most frequent pair, repeatedly. GPT family, Llama 3, most modern LLMs (byte-level BPE).
WordPiece
Merge the pair that most increases training-data likelihood. BERT.
Unigram (SentencePiece)
Start with a large vocabulary and prune pieces that matter least. T5, many multilingual models.
Vocabulary size trade-off design

A bigger vocabulary compresses text into fewer tokens (cheaper, longer effective context, faster generation) but grows the embedding and output matrices (vocab × d_model each). Llama 3 moved from 32k to 128k tokens and reported roughly 15% fewer tokens for the same text versus Llama 2. Frontier models have moved toward 100k–260k vocabularies.

Images, audio and video as tokens multimodal

Multimodal models cut an image into patches (for example 14×14 or 16×16 pixels), embed each patch as a vector with a vision encoder, and feed those "image tokens" into the same transformer. A single image commonly costs hundreds to a few thousand tokens depending on resolution. Audio is chunked into short frames; video is sampled frames plus audio. That is why large images and long videos fill context fast.

Token healing and boundary effects edge case

If your prompt ends with a trailing space, the model must produce a token that starts without a space, which it rarely saw in training, and quality can drop. Likewise, cutting a prompt mid-word forces awkward tokens. Keep prompt endings clean (end on a newline or full word).

Chapter 08FoundationsBuilder

Embeddings: meaning as geometry

The idea

Each token ID becomes a vector, a list of thousands of numbers, and similar meanings end up as nearby points in that high-dimensional space. The model also needs to know word order, so position is added, today mostly with rotary position embeddings (RoPE). The same idea, "texts as vectors", powers semantic search and RAG.

The embedding matrix has one row per vocabulary token and one column per hidden dimension (the model's width, d_model: 4,096 in Llama 3 8B, 12,288 in GPT-3). Looking up a token is just picking its row. The rows start random and are learned in pretraining like every other weight. After training, directions in this space carry meaning: there is roughly a "plural" direction, a "past tense" direction, a "French-ness" direction.

As the vectors pass through the layers, they stop being "the word bank" and become "the word bank in this sentence about rivers". These contextual embeddings (also called hidden states or the residual stream) are where all the model's understanding lives. The last one is what the model uses to predict the next token.

Live demo · a tiny embedding space

Each word here has a hand-made 8-dimensional vector (royalty, gender, animal, food, place, city, Europe, tech) (real models learn thousands of dimensions). Click a word to rank the others by cosine similarity. Then try vector arithmetic.

    cosine(a, b) = (a · b) / (‖a‖ ‖b‖) · 1 = same direction · 0 = unrelated · −1 = opposite

    Position: how the model knows word order

    Attention by itself is order-blind: "dog bites man" and "man bites dog" contain the same tokens. So position must be injected. The original transformer added fixed sinusoidal patterns to each embedding; GPT-2 learned a vector per position (capped at 1,024 positions). Most modern LLMs use RoPE (2021): it rotates the query and key vectors by an angle proportional to their position, so attention scores depend on the distance between tokens. Techniques like position interpolation and YaRN stretch RoPE so models trained on 8k tokens can work at 128k or more after brief extra training.

    Two kinds of "embedding" people meanWhat it isUsed for
    Token embeddings inside an LLMThe input lookup table and the hidden states between layersThe model's internal computation
    Text embeddings from an embedding modelOne vector for a whole sentence or passage (e.g. 768–3,072 dims), from a model trained so similar texts land closeSemantic search, RAG, clustering, deduplication, recommendations (Ch 17)
    Implement it withText embeddings and similarityTurn text into vectors and compare them
    sim = (a·b)/(‖a‖‖b‖) · with normalised vectors, cosine = dot product · storage = n × d × 4 bytes (float32)
    • sentence-transformersRun open embedding models locally (BGE, E5, GTE, Nomic).
    • numpyCosine similarity and top-k in a few lines.
    • OpenAI / Cohere / Voyage / Google APIsHosted embedding endpoints.
    python
    from sentence_transformers import SentenceTransformer
    import numpy as np
    
    m = SentenceTransformer("BAAI/bge-small-en-v1.5")
    docs = ["Paris is the capital of France.", "The Eiffel Tower is in Paris.",
            "Bananas are rich in potassium."]
    D = m.encode(docs, normalize_embeddings=True)
    q = m.encode(["What city is France's capital?"], normalize_embeddings=True)[0]
    scores = D @ q                       # cosine, because vectors are normalised
    for i in np.argsort(-scores):
        print(f"{scores[i]:.3f}  {docs[i]}")
    Vectors stored in Azure AI Search (HNSW index) with hybrid BM25 + vector queries.
    • Azure OpenAI embeddingstext-embedding-3-small / -large deployments.
    • Azure AI SearchVector, hybrid and semantic ranking.
    • Cosmos DB / PostgreSQL (pgvector)Vectors next to app data.
    python
    e = client.embeddings.create(model="my-embedding-deployment",
                                 input=["Paris is the capital of France."])
    vec = e.data[0].embedding     # list[float], e.g. 1536 dims
    Bedrock Knowledge Bases embed, chunk and index automatically; or call embedding models directly.
    • Amazon Titan Text Embeddings, Cohere Embed on BedrockHosted embedding models.
    • OpenSearch Serverless / Aurora pgvector / S3 VectorsVector storage options.
    python
    import boto3, json
    br = boto3.client("bedrock-runtime")
    r = br.invoke_model(modelId="amazon.titan-embed-text-v2:0",
            body=json.dumps({"inputText": "Paris is the capital of France."}))
    vec = json.loads(r["body"].read())["embedding"]
    Task types (RETRIEVAL_QUERY vs RETRIEVAL_DOCUMENT) produce vectors tuned for each side of search.
    • Gemini / Vertex AI embeddingsText and multimodal embedding models.
    • Vertex AI Vector Search, AlloyDB, BigQuery vector searchStorage and ANN search.
    python
    from google import genai
    client = genai.Client()
    r = client.models.embed_content(model=EMBED_MODEL,
            contents="Paris is the capital of France.")
    vec = r.embeddings[0].values
    Approximate nearest neighbour (ANN): HNSW graphs give ~95–99% recall at a fraction of brute-force cost.
    • FAISSMeta's vector search library.
    • Qdrant, Weaviate, Milvus, Chroma, pgvectorVector databases.
    • OllamaLocal embedding models (nomic-embed-text, bge-m3).
    python
    import faiss, numpy as np
    index = faiss.IndexFlatIP(D.shape[1])   # inner product = cosine on normalised vectors
    index.add(D.astype("float32"))
    scores, ids = index.search(q[None, :].astype("float32"), k=2)
    Deep dive

    Vectors in depth

    What dimensions mean and how position is encoded.

    RoPE, briefly and precisely math

    Split each query and key vector into pairs of numbers. Rotate pair i at position m by angle m·θᵢ, where θᵢ = base^(−2i/d) (base is often 10,000; long-context models raise it to 500,000 or more). Because rotations compose, the dot product of a query at position m and a key at n depends only on m − n: relative position for free.

    q′ = R(mθ)·q · k′ = R(nθ)·k · q′·k′ = qᵀ R((n−m)θ) k
    Superposition: more concepts than dimensions interpretability

    A 4,096-dimensional space can hold far more than 4,096 concepts by using almost-perpendicular directions, at the cost of some interference. Interpretability researchers use sparse autoencoders to pull these apart into millions of readable features ("Golden Gate Bridge", "code bug", "flattery"). This is why single neurons in LLMs rarely mean one thing.

    Weight tying and the unembedding architecture

    At the end, the final hidden vector is multiplied by an unembedding (output) matrix to get one logit per token. Some models reuse (tie) the input embedding matrix for this, saving vocab × d parameters (for a 128k vocab and d = 4,096, that's 0.5B parameters). Large models often keep them separate.

    Chapter 09BuilderArchitect

    Attention: how tokens talk to each other

    The mechanism

    In each layer, every token makes a query ("what am I looking for?"), a key ("what do I contain?") and a value ("what will I pass on?"). Each token scores every earlier token by query·key, turns the scores into weights with softmax, and takes a weighted average of their values. Many heads do this in parallel, each learning a different kind of relationship. Cost grows with the square of the sequence length.

    Attention(Q, K, V) = softmax( Q·Kᵀ / √d_k + mask ) · V

    Think of a library. Your query is the question you bring. Every book has a key on its spine and value inside. You compare your question to every spine, pay most attention to the best matches, and read a blend of their contents. In the sentence "The animal didn't cross the street because it was too tired", the token "it" has a query that matches the key of "animal" strongly, so information about the animal flows into "it". Change "tired" to "wide" and, in a trained model, "it" shifts toward "street".

    The three are produced by multiplying each token's vector by three learned matrices W_Q, W_K, W_V. Dividing by √d_k keeps scores from growing so large that softmax becomes all-or-nothing. In a GPT-style (decoder) model, a causal mask sets scores for future tokens to −∞, so each token can only look backwards. That is what lets the model be trained to predict the next token at every position at once.

    Live demo · an attention map

    Rows are queries (the token doing the looking); columns are keys (the tokens being looked at). Pick a head to see a different learned pattern, click a row to read its weights, and toggle the causal mask. The weights are illustrative, built to mimic patterns researchers actually find in trained models.

    Multi-head attention and its modern variants

    Multi-head attention (MHA) splits the vector into, say, 32 heads of 128 dimensions each, and each head attends independently. Researchers find heads that track the previous token, heads that copy patterns seen earlier in the context (induction heads, a key mechanism behind in-context learning), heads for syntax and heads for coreference. Outputs of all heads are concatenated and mixed by an output matrix W_O.

    VariantWhat changesWhyUsed in
    Multi-head (MHA)Every head has its own Q, K, VOriginal designGPT-2, GPT-3, BERT
    Multi-query (MQA)All heads share one K and VShrinks the KV cache by the number of heads; faster decodingPaLM, Falcon
    Grouped-query (GQA)Groups of query heads share K, V (e.g. 32 Q heads, 8 KV heads)Most of MQA's saving with less quality lossLlama 2 70B, Llama 3, Mistral, Qwen
    Multi-head latent (MLA)K and V compressed into a small latent vectorVery small KV cache for long contextsDeepSeek V2/V3 and successors
    Sliding-window / localEach token attends only to the last W tokens in some layersLinear cost in those layersMistral 7B, Gemma 2/3 (alternating local and global)
    Sparse / linear attention, state-space hybridsApproximate or replace full attentionSub-quadratic cost at very long lengthsMamba hybrids (Jamba), several 2025–26 long-context models
    The quadratic problem

    Every token scores every other token, so the attention score matrix has n² entries. Doubling the context from 64k to 128k tokens quadruples attention compute in prefill. FlashAttention (2022) made this much faster by computing it in GPU-friendly tiles without ever storing the full matrix, but the maths is still quadratic. This is one reason long prompts are slow and expensive, and why "just put everything in context" has limits (Ch 15).

    Implement it withScaled dot-product attentionThe core formula, then the fast kernels
    FLOPs (attention scores + mix) ≈ 4 · n² · d per layer · memory for naive scores = n² × heads × bytes
    • PyTorch scaled_dot_product_attentionPicks FlashAttention or memory-efficient kernels automatically.
    • numpyWrite it from scratch once to really understand it.
    python · from scratch
    import numpy as np
    
    def attention(X, Wq, Wk, Wv, causal=True):
        Q, K, V = X @ Wq, X @ Wk, X @ Wv           # (n, d_k) each
        scores = Q @ K.T / np.sqrt(K.shape[-1])     # (n, n)
        if causal:
            n = len(X)
            scores += np.triu(np.full((n, n), -np.inf), k=1)   # hide the future
        w = np.exp(scores - scores.max(-1, keepdims=True))
        w /= w.sum(-1, keepdims=True)               # softmax per row
        return w @ V, w                             # outputs and attention map
    
    # PyTorch, fused and fast:
    # torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
    You rarely write attention on a cloud; you choose GPUs whose memory bandwidth and FLOPs suit it.
    • Azure ND H100 v5 / ND MI300X v5 VMsTraining and serving GPUs.
    • Azure Machine LearningManaged training jobs with PyTorch + FlashAttention images.
    bash
    az ml job create --file train-job.yml   # PyTorch image with flash-attn installed
    Trainium / Inferentia use compiler-fused attention kernels (Neuron SDK).
    • EC2 P5 (H100) / P5e / P6 instancesGPU training and serving.
    • AWS Trainium, Inferentia + Neuron SDKAWS's own accelerators.
    • SageMaker HyperPodResilient large-scale training clusters.
    python
    from sagemaker.pytorch import PyTorch
    est = PyTorch(entry_point="train.py", instance_type="ml.p5.48xlarge",
                  instance_count=2, framework_version="2.3", py_version="py311")
    est.fit()
    TPUs run attention via XLA; JAX's dot_product_attention dispatches fused kernels.
    • Cloud TPU (v5e, v5p, Trillium, Ironwood)Google's accelerators.
    • JAX / Flax, MaxTextReference LLM training stack on TPUs.
    python
    import jax
    out = jax.nn.dot_product_attention(q, k, v, is_causal=True)
    FlashAttention: tile Q, K, V into SRAM blocks; online softmax; never materialise the n×n matrix.
    • FlashAttention 2/3Fused attention kernels for NVIDIA GPUs.
    • xFormers, FlexAttention (PyTorch)Custom masks and variants.
    • nanoGPT / minGPTKarpathy's readable GPT implementations.
    • BertVizVisualise real attention heads.
    python
    from flash_attn import flash_attn_func
    out = flash_attn_func(q, k, v, causal=True)   # q,k,v: (batch, seq, heads, head_dim), fp16/bf16
    Deep dive

    Attention, further

    What heads do and why masking matters.

    Induction heads and in-context learning interpretability

    Anthropic's 2022 research identified induction heads: a pair of heads that, on seeing token A, look for an earlier occurrence of A and predict whatever followed it last time (A B … A → B). They form suddenly during training, at the same time models gain the ability to learn from examples in the prompt. It is a concrete mechanism for how few-shot prompting works (Ch 16).

    Attention sinks quirk

    Many heads put lots of weight on the very first token, whatever it is, because softmax must spend its weight somewhere when nothing relevant is present. This attention sink is why streaming methods (StreamingLLM) keep the first few tokens when sliding a window over long text.

    Cross-attention vs self-attention terms

    Self-attention: queries, keys and values all come from the same sequence. Cross-attention: queries from one sequence (the decoder's output so far), keys and values from another (the encoder's input). Translation models and some image generators use cross-attention; decoder-only LLMs use only self-attention, and put images and text into one shared sequence instead.

    Chapter 10BuilderArchitect

    Inside the transformer block

    The building block

    An LLM is the same block repeated L times (32 to 120+). Each block does two things: attention (tokens share information) then a feed-forward network / MLP (each token processes what it gathered; most of the model's parameters and much of its factual knowledge live here). Each step is wrapped with normalisation and a residual connection. Parameters ≈ 12 · L · d². Mixture of experts (MoE) swaps the single MLP for many, using only a few per token.

    One decoder block (modern "pre-norm" layout)

    × N layers · the residual stream carries each token's vector through the whole model residual stream x RMSNorm Multi-head attentioncausal · GQA · RoPE + RMSNorm Feed-forward (MLP)SwiGLU · or MoE experts + x = x + Attention(Norm(x)) then x = x + MLP(Norm(x))

    The parts, one by one

    PartWhat it doesParameters per layerModern choice
    Attention (Q, K, V, O projections)Moves information between tokens≈ 4·d² (less with GQA)GQA + RoPE; MLA in DeepSeek
    Feed-forward network (MLP)Transforms each token on its own; acts like a huge key-value memory of facts and patterns≈ 8·d² (hidden size 4·d); SwiGLU uses 3 matrices at ~2.7·dSwiGLU; or MoE
    NormalisationKeeps vector sizes stable so training doesn't divergeTiny (2·d)RMSNorm, applied before each sub-layer (pre-norm)
    Residual connectionAdds each sub-layer's output to its input; lets gradients flow through 100+ layers0Always
    Embedding + unembeddingToken ID ↔ vector; final vector → logitsV·d each (once, not per layer)Often untied in large models
    N_params ≈ 12 · L · d² + V · d
    GPT-3: 12 × 96 × 12,288² ≈ 174B (+0.6B embeddings) = 175B ✓

    Live demo · size a model: parameters, memory and training compute

    Pick a preset or set your own shape. See how many parameters it has, how much GPU memory the weights need at each precision, and what training it would cost. Uses the standard approximations; real models differ by a few percent.

    Assumptions: MLP is 2/3 of block parameters; training FLOPs ≈ 6 × active parameters × tokens; 40% model FLOPs utilisation (MFU); $2.50 per GPU-hour. Weight memory excludes KV cache and activations. Chinchilla-optimal ≈ 20 tokens per parameter.

    Mixture of experts (MoE)

    An MoE layer replaces the one big MLP with many smaller "expert" MLPs and a router that picks the top few (often 2 to 8) for each token. The model has huge total parameters (knowledge capacity) but each token only uses a small set of active parameters (compute cost). Mixtral 8×7B (2023) has about 47B total and 13B active; DeepSeek-V3 (Dec 2024) has 671B total and 37B active. By 2026, most frontier and large open models are reported to be MoE. The catch: all experts must still sit in GPU memory, routing must stay balanced (a load-balancing loss), and serving across many GPUs is more complex (expert parallelism).

    Deep dive

    Architecture details

    What changed between GPT-2 and 2026 models.

    GPT-2 (2019) vs a 2025 open model, side by side compare
    ChoiceGPT-2Typical 2025–26 open model
    NormLayerNorm, post→preRMSNorm, pre-norm (+ QK-norm in some)
    PositionLearned absolute (1,024)RoPE, extended to 128k–1M
    AttentionMHAGQA or MLA; some layers sliding-window
    MLPGELU, 4·dSwiGLU; often MoE
    Vocab50k128k–260k
    BiasesYesUsually removed

    The skeleton is the same as 2017. Nearly all progress came from scale, data and training recipes, plus these efficiency tweaks.

    Where facts live: MLPs as memory interpretability

    Studies (e.g. "Transformer Feed-Forward Layers Are Key-Value Memories", 2021; ROME, 2022) found that factual associations like "Eiffel Tower → Paris" can be located in and edited inside specific MLP layers. Attention moves the subject's information to the right position; the MLP looks up the associated fact. It's why bigger MLPs (or more experts) hold more knowledge.

    Depth vs width design

    More layers give more sequential steps of computation (useful for multi-step reasoning inside one forward pass); wider layers give more capacity per step and better GPU efficiency. Scaling-law studies found performance depends mostly on total parameters across a broad range of shapes; labs tune the aspect ratio for hardware efficiency.

    Chapter 11BuilderArchitect

    Pretraining: reading the internet

    The recipe

    Gather trillions of tokens of text and code, clean them hard, then train the model to predict the next token at every position, minimising cross-entropy loss. Compute is about 6 × parameters × tokens FLOPs. Loss improves as a smooth power law in model size, data and compute (scaling laws). The result is a base model: knowledgeable, fluent, and not yet an assistant.

    Months before your question

    Before the model could answer "Paris", it read the word "Paris" millions of times, in encyclopaedias, travel blogs, novels, timetables and code comments. It never saw a rule saying "the capital of France is Paris". It just kept getting slightly less surprised every time "Paris" followed "capital of France", until that became one of countless facts compressed into its weights.

    Step 1: data

    Sources include filtered web crawls (Common Crawl and labs' own crawlers), books, academic papers, Wikipedia, code (GitHub), maths, multilingual text and, increasingly, high-quality synthetic data generated by other models. The raw web is mostly junk, so the pipeline matters as much as the model: extract text from HTML, detect language, remove duplicates (exact and near-duplicate, using MinHash), filter by quality with classifiers, strip personal data and toxic content, and decontaminate benchmark test sets. Open datasets such as FineWeb (15T tokens, 2024) document this. Llama 3 was trained on over 15T tokens; frontier runs in 2025–26 are reported at 20–40T+ tokens, with data quality and the data mix (how much code, maths, each language) treated as closely guarded secrets.

    Step 2: the objective

    Take a sequence of, say, 8,192 tokens. At every position, the model outputs a probability distribution for the next token. The loss is the average of −log P(actual next token): if the model gave the right token probability 0.9, the loss is 0.105; if it gave 0.01, the loss is 4.6. Because the causal mask hides the future, one forward pass trains thousands of predictions at once. Backprop and AdamW (Ch 2) update all weights. Repeat for hundreds of thousands of steps with batches of millions of tokens.

    Loss = −(1/T) Σₜ log P_θ(xₜ₊₁ | x₁…xₜ) · Perplexity = e^Loss
    perplexity 10 ≈ "as unsure as choosing between 10 equally likely tokens"

    Step 3: scale, and the laws that govern it

    Kaplan et al. (2020) showed loss falls as a power law as you increase parameters N, data D and compute C. DeepMind's Chinchilla (2022) corrected the balance: for a fixed compute budget, the optimal model uses about 20 tokens per parameter, so the 70B Chinchilla beat the 280B Gopher. Since then, labs deliberately over-train smaller models far beyond 20 tokens/parameter (Llama 3 8B saw ~1,900 tokens per parameter) because a smaller model is much cheaper to serve to millions of users. Training cost is paid once; inference cost is paid on every request.

    C ≈ 6·N·D FLOPs · Chinchilla: D_opt ≈ 20·N · L(N, D) ≈ E + A/N^α + B/D^β (α≈0.34, β≈0.28)
    ModelYearParametersTraining tokens≈ Compute
    GPT-220191.5B~10B (WebText)~10²¹ FLOPs
    GPT-32020175B300B3.1 × 10²³
    Chinchilla202270B1.4T5.8 × 10²³
    Llama 2 70B202370B2T8.4 × 10²³
    Llama 3.1 405B2024405B15.6T3.8 × 10²⁵ (reported)
    DeepSeek-V3Dec 2024671B total / 37B active14.8T~2.8M H800 GPU-hours (reported, final run only)
    Frontier closed models2025–26UndisclosedUndisclosedEstimated 10²⁶+ FLOPs

    Step 4: the engineering

    Parallelism

    No GPU holds a frontier model. Training splits work by data parallelism (each GPU group sees different batches), tensor parallelism (split each matrix), pipeline parallelism (split layers) and expert parallelism (MoE). ZeRO/FSDP shard optimiser state.

    Precision

    Training uses mixed precision: BF16 maths with FP32 master weights; frontier labs increasingly train in FP8. Each step's maths is cheaper, but numerical stability needs care.

    Reliability

    At 16,000+ GPUs, hardware fails daily. Meta reported 419 unexpected interruptions in 54 days training Llama 3 405B. Frequent checkpoints and automatic restarts are mandatory.

    What a base model is like

    Ask a base model "What is the capital of France?" and it may reply with more quiz questions, because on the web, a question is often followed by more questions. It knows a lot but behaves like a document completer. Turning it into an assistant is the job of post-training (Ch 12). A model's knowledge cutoff is set here: it knows nothing after its training data ends.

    Implement it withPretraining a small language modelNext-token loss on your own corpus
    loss = cross_entropy(logits[:, :-1], tokens[:, 1:]) · GPU-hours ≈ 6ND / (peak_FLOPs × MFU × 3600)
    • PyTorchModel, loss, AdamW, bf16 autocast.
    • Hugging Face transformers + datasetsReady model configs and streaming corpora.
    • nanoGPT / llm.cTrain GPT-2 scale models from scratch on one node.
    python · the training step
    import torch, torch.nn.functional as F
    from transformers import AutoConfig, AutoModelForCausalLM
    
    cfg = AutoConfig.from_pretrained("gpt2", n_layer=12, n_embd=768, n_head=12)
    model = AutoModelForCausalLM.from_config(cfg).cuda()
    opt = torch.optim.AdamW(model.parameters(), lr=6e-4, betas=(0.9, 0.95), weight_decay=0.1)
    
    for step, batch in enumerate(loader):              # batch: (B, T) token ids
        x = batch.cuda()
        with torch.autocast("cuda", dtype=torch.bfloat16):
            logits = model(x).logits                   # (B, T, V)
            loss = F.cross_entropy(logits[:, :-1].reshape(-1, logits.size(-1)),
                                   x[:, 1:].reshape(-1))   # predict token t+1 from t
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step(); opt.zero_grad()
        if step % 100 == 0: print(step, loss.item(), "ppl", loss.exp().item())
    Cluster sizing: GPUs = total GPU-hours ÷ wall-clock hours you can wait.
    • Azure Machine Learning + ND H100 v5 clustersDistributed PyTorch jobs with InfiniBand.
    • Azure CycleCloud / AKSSlurm or Kubernetes for large training.
    yaml · job
    command: torchrun --nproc_per_node 8 train.py
    compute: azureml:nd-h100-cluster
    resources: { instance_count: 4 }
    distribution: { type: pytorch, process_count_per_instance: 8 }
    HyperPod auto-replaces failed nodes and resumes from checkpoints.
    • SageMaker HyperPodSlurm or EKS clusters for multi-week training.
    • EC2 P5 / Trainium2 (Trn2)Accelerators; NeMo and Neuron recipes.
    • FSx for LustreFast shared storage for datasets and checkpoints.
    bash
    srun -N 4 --gpus-per-node 8 torchrun --nnodes 4 --nproc_per_node 8 train.py
    TPU pods scale data + model parallelism over the inter-chip interconnect.
    • Cloud TPU + MaxTextGoogle's open, high-MFU JAX LLM trainer.
    • GKE with A3 (H100) / A4 (B200) VMsGPU clusters.
    bash
    python3 -m MaxText.train MaxText/configs/base.yml run_name=my-lm \
      per_device_batch_size=8 steps=10000 dataset_path=gs://my-bucket/data
    Data: dedupe (MinHash LSH) → quality filter → tokenize → pack into fixed-length sequences.
    • Megatron-LM / NeMo, TorchTitan, DeepSpeedLarge-scale training frameworks.
    • datatrove, FineWebHugging Face's data pipeline and open web dataset.
    • OLMo (AI2)Fully open model: data, code, checkpoints, logs.
    bash
    git clone https://github.com/karpathy/nanoGPT && cd nanoGPT
    python data/shakespeare_char/prepare.py
    python train.py config/train_shakespeare_char.py   # a tiny LM in minutes
    Deep dive

    Pretraining, further

    The details labs argue about.

    Is the data running out? debate

    Epoch AI estimated the stock of quality public human text at roughly a few hundred trillion tokens, which frontier training could exhaust around the late 2020s. Responses: train multiple epochs on the best data, use more synthetic data (especially maths and code that can be verified), licensed data, multimodal data (video, audio), and shift compute from pretraining toward reinforcement learning and inference-time reasoning (Ch 12). Treat specific dates as uncertain.

    Mid-training and annealing recipe

    Near the end of pretraining, labs often switch to a higher-quality data mix (more maths, code, reasoning, long documents) while the learning rate decays. This annealing or mid-training phase has an outsized effect on benchmark ability, and is also when context length is extended (e.g. 8k → 128k).

    Memorisation, copyright and privacy risk

    Models can reproduce text that appeared many times in training (famous passages, licences, some personal data). Deduplication reduces it, but doesn't eliminate it. Training on copyrighted material is the subject of ongoing lawsuits and new laws (for example the EU AI Act's training-data transparency rules for general-purpose models). Check current legal guidance for your jurisdiction.

    Chapter 12BuilderArchitect

    Post-training: from document completer to assistant

    The recipe

    Post-training shapes behaviour: supervised fine-tuning (SFT) on example conversations teaches the assistant format; preference tuning (RLHF, DPO, constitutional AI) teaches which answers people prefer and what to refuse; reinforcement learning with verifiable rewards (RLVR) on maths and code produced reasoning models that think before answering. Post-training is now a large share of the compute and much of the difference between models.

    The story so far

    GPT-3 in 2020 could write a sonnet or a SQL query, but you had to trick it with carefully staged text. In early 2022, OpenAI published InstructGPT: a 1.3B-parameter model, post-trained with human feedback, that people preferred over the 175B GPT-3. Behaviour, not size, was the bottleneck. Ten months later the same recipe, applied to a bigger model, became ChatGPT.

    The post-training pipeline

    Base modelcompletes text SFT10k–1M+ examplechats, tool calls Preference tuningRLHF (reward model + PPO)or DPO · RLAIF RL on verifiable tasksmaths, code, agents→ long reasoning Safety + evalsred-team, refusals→ release Iterated in rounds. Teaches format, helpfulness, honesty, harmlessness, tool use and reasoning, not new world knowledge.

    The methods

    MethodHow it worksData neededWhat it changes
    SFT / instruction tuningOrdinary next-token training, but only on assistant replies in curated conversationsThousands to millions of high-quality demonstrations (human-written or model-generated)Follows instructions, uses the chat format, calls tools
    RLHF (InstructGPT, 2022)Humans rank pairs of answers; train a reward model to predict rankings; optimise the LLM against it with RL (PPO) while a KL penalty keeps it close to the SFT modelTens to hundreds of thousands of comparisonsHelpfulness, tone, refusing harmful requests
    DPO (2023)Skip the reward model: directly raise the probability of preferred answers and lower rejected onesSame preference pairsSimilar to RLHF; simpler and stable; popular for open models
    Constitutional AI / RLAIF (Anthropic, 2022)An AI model critiques and ranks answers using a written set of principles (a "constitution")Principles + model-generated feedbackScales harmlessness training with less human labelling
    RLVR (2024–)Reward the model when its final answer is checkably right (maths answer matches, code passes tests); algorithms like PPO or GRPOProblems with automatic checkersLong chains of thought, self-checking, backtracking: reasoning models
    DistillationTrain a smaller model on a bigger model's outputs (or its probability distributions)Teacher model outputsSmall, fast models that inherit much of a big model's skill

    Reasoning models: thinking before answering

    In September 2024 OpenAI released o1, trained with reinforcement learning to produce a long hidden chain of thought before answering. In January 2025 DeepSeek-R1 showed openly that pure RL with verifiable rewards (using GRPO) makes a model learn to reason at length, re-check itself and change approach, and published the weights. Since then, almost every frontier family has a reasoning or "extended thinking" mode. This created a new scaling axis, test-time compute (or inference-time scaling): spend more tokens thinking on a hard problem to get a better answer. Reasoning models are much stronger at maths, coding and planning, and slower and costlier per answer.

    What post-training cannot do

    Post-training mostly changes how the model uses what it already knows. It is a poor way to add large amounts of new facts (fine-tuning on your company wiki rarely makes a model reliably recall it; RAG does that better, Ch 17). It can also introduce problems: sycophancy (agreeing with the user because raters liked agreement), reward hacking (gaming the reward rather than doing the task) and over-refusal.

    Implement it withFine-tuning: SFT, LoRA and DPOAdapt an open or hosted model to your task
    LoRA: W′ = W + (α/r)·B·A, with A ∈ ℝ^(r×d), B ∈ ℝ^(d×r), r ≪ d → train ~0.1–1% of parameters
    DPO loss = −log σ(β[log π(y_w)/π_ref(y_w) − log π(y_l)/π_ref(y_l)])
    • Hugging Face TRLSFTTrainer, DPOTrainer, GRPOTrainer.
    • PEFTLoRA and QLoRA adapters.
    • UnslothFaster, lower-memory LoRA fine-tuning on one GPU.
    python
    from datasets import load_dataset
    from peft import LoraConfig
    from trl import SFTTrainer, SFTConfig
    
    ds = load_dataset("json", data_files="chats.jsonl")["train"]   # {"messages":[...]}
    trainer = SFTTrainer(
        model="Qwen/Qwen2.5-1.5B-Instruct",
        train_dataset=ds,
        peft_config=LoraConfig(r=16, lora_alpha=32, target_modules="all-linear"),
        args=SFTConfig(output_dir="out", num_train_epochs=2, learning_rate=2e-4,
                       per_device_train_batch_size=4, bf16=True))
    trainer.train()
    Hosted fine-tuning bills per training token plus hourly hosting of the tuned deployment.
    • Azure AI Foundry fine-tuningSFT, DPO and reinforcement fine-tuning for supported OpenAI and open models.
    • Azure MLCustom LoRA jobs on your own GPUs.
    python
    f = client.files.create(file=open("train.jsonl", "rb"), purpose="fine-tune")
    job = client.fine_tuning.jobs.create(training_file=f.id, model=BASE_MODEL)
    Bedrock custom models: fine-tuning and distillation jobs; serve with provisioned or on-demand throughput.
    • Amazon Bedrock model customizationFine-tune and distil supported models.
    • SageMaker JumpStart / HyperPod recipesLoRA and full fine-tuning of open models.
    python
    bedrock = boto3.client("bedrock")
    bedrock.create_model_customization_job(jobName="ft1", customModelName="my-model",
        roleArn=ROLE, baseModelIdentifier=BASE_ID,
        trainingDataConfig={"s3Uri": "s3://bucket/train.jsonl"},
        outputDataConfig={"s3Uri": "s3://bucket/out/"},
        hyperParameters={"epochCount": "2"})
    Supervised tuning of Gemini uses adapters; you pay per training token.
    • Vertex AI supervised tuningTune Gemini models with JSONL examples.
    • Vertex AI Model GardenLoRA tuning for open models (Gemma, Llama).
    python
    from vertexai.tuning import sft
    job = sft.train(source_model=BASE_MODEL,
                    train_dataset="gs://bucket/train.jsonl", epochs=2)
    QLoRA: base weights in 4-bit (NF4) + LoRA in bf16 → fine-tune a 70B model on a single 48–80 GB GPU.
    • Axolotl, LLaMA-Factory, torchtuneConfig-driven fine-tuning.
    • OpenRLHF, verlRLHF, GRPO and RLVR at scale.
    • Argilla, Label StudioCollect demonstrations and preferences.
    yaml · axolotl
    base_model: meta-llama/Llama-3.1-8B-Instruct
    adapter: qlora
    load_in_4bit: true
    lora_r: 16
    datasets: [{ path: chats.jsonl, type: chat_template }]
    num_epochs: 2
    learning_rate: 0.0002
    Deep dive

    Post-training, further

    Alignment terms and choices.

    Alignment, HHH and the model spec terms

    Alignment means getting the model to do what its developers and users intend, and not what they don't. A common target is HHH: helpful, honest, harmless. Labs publish behaviour documents (OpenAI's Model Spec, Anthropic's constitution for Claude) describing priorities when these conflict. Jailbreaks are prompts that get around this training (Ch 22).

    When should you fine-tune? decision
    • Prompt first. Most tasks are solved with instructions and examples (Ch 16).
    • RAG for knowledge. Facts that change or are private belong in retrieval (Ch 17).
    • Fine-tune for form and skill: a consistent output style or format, a narrow classification task at high volume, lower latency by moving from a big model to a small tuned one, or a domain language the base model handles poorly.
    • Always build an evaluation set first, so you know whether tuning helped.
    GRPO in one paragraph RL

    Group Relative Policy Optimization (DeepSeek, 2024) samples a group of answers to the same problem, scores each (e.g. correct = 1), and pushes up answers that beat the group average and down those below it. No separate value network is needed, which makes RL on long reasoning cheaper. Variants (DAPO, Dr. GRPO and others) tweak it.

    Model merging and adapters open models

    Open-model communities combine fine-tunes by averaging or merging weights (SLERP, TIES), and serve many LoRA adapters on one base model at once (multi-LoRA serving in vLLM). This lets one GPU host dozens of specialised variants.

    Chapter 13BuilderArchitect

    Inference: picking tokens, fast and cheaply

    The run-time story

    At each step the model outputs logits; softmax turns them into probabilities; a sampling rule (temperature, top-k, top-p) picks one token. Generation has two phases: prefill (read the whole prompt in parallel, compute-bound) and decode (one token at a time, memory-bandwidth-bound). The KV cache avoids redoing past work, and batching, quantization and speculative decoding make serving affordable.

    p_i = exp(z_i / T) / Σ_j exp(z_j / T) · T → 0: always the top token · T = 1: model's own distribution · T > 1: flatter, more random

    Live demo · sampling playground

    Pick a prompt. The bars are the model's next-token probabilities (illustrative logits). Change temperature, top-k and top-p and watch tokens get filtered (grey) and probabilities reshape. Press sample to draw tokens one at a time.

    Decoding strategies

    StrategyHowUse it forWatch out
    Greedy (temperature 0)Always take the most likely tokenExtraction, classification, code, testsCan repeat itself; still not perfectly deterministic on GPUs
    Temperature samplingDivide logits by T before softmaxCreative writing (0.7–1.0)High T: nonsense; low T: bland
    Top-kKeep only the k most likely tokensCutting the long tail of junkFixed k is too strict when unsure, too loose when sure
    Top-p (nucleus, 2019)Keep the smallest set whose probabilities sum to pThe common default (0.9–0.95)Interacts with temperature; tune one at a time
    Min-pDrop tokens below a fraction of the top token's probabilityOpen-model creative use at higher TNot offered by every API
    Beam searchKeep the best N partial sequencesTranslation, older seq2seqBland, repetitive for open-ended chat
    Constrained / structured decodingMask tokens that would break a grammar or JSON schemaGuaranteed-valid JSON, function callsCan hurt quality if the schema fights the content
    Penalties (repetition, frequency, presence)Lower logits of tokens already usedStopping loops in small modelsCan block necessary repeats (names, code)

    Note: many 2025–26 reasoning models fix or limit sampling parameters on their APIs. Check your provider's docs.

    Prefill, decode and the KV cache

    During prefill, the model processes all prompt tokens at once, big matrix multiplications that keep GPUs busy. The speed users feel here is time to first token (TTFT). During decode, each new token needs the entire model's weights read from GPU memory just to do a small amount of maths for one token, so speed is limited by memory bandwidth, measured as tokens per second or time per output token (TPOT).

    Without a cache, generating token 1,001 would recompute keys and values for all 1,000 earlier tokens. The KV cache stores each layer's keys and values for every past token, so each step only computes the new one. It grows with context length and number of concurrent users, and is often the main limit on how many requests fit on a GPU. PagedAttention (vLLM, 2023) manages it like virtual memory pages, cutting waste dramatically. Prompt caching at the API level reuses the KV cache of a shared prefix (system prompt, documents) across requests, at a large discount (often ~90% off cached input).

    KV cache bytes = 2 × layers × kv_heads × head_dim × bytes_per_value × tokens × batch
    Llama 3 8B, fp16: 2 × 32 × 8 × 128 × 2 = 128 KB per token → 8k tokens ≈ 1 GB · 128k ≈ 16 GB
    Max decode speed (batch 1) ≈ memory bandwidth ÷ bytes read per token
    H100 (3.35 TB/s) with a 16 GB fp16 8B model → ≈ 200 tokens/s ceiling

    Live demo · will it fit, and how fast?

    Estimate GPU memory for weights plus KV cache, and the theoretical single-user decode speed, for a model you want to serve.

    Ignores activation memory and framework overhead (budget ~10–20% extra). For MoE models, memory uses total parameters but speed depends on active parameters. Real throughput is usually 50–80% of the ceiling.

    The serving toolbox

    Continuous batching

    Instead of waiting for a whole batch to finish, the server adds and removes requests every step. Raises GPU throughput several times over. Standard in vLLM, TGI, SGLang, TensorRT-LLM.

    Quantization

    Store weights in 8 or 4 bits instead of 16 (GPTQ, AWQ, GGUF, FP8). Halves or quarters memory and speeds up decode, with small quality loss at 8-bit and usually modest loss at 4-bit.

    Speculative decoding

    A small draft model (or extra heads, as in Medusa/EAGLE) guesses several tokens; the big model checks them all in one pass and keeps the correct prefix. Same output, often 2–3× faster.

    Prefix / prompt caching

    Reuse the KV cache of an identical prompt prefix. Put stable content (instructions, tools, documents) first and variable content last.

    Disaggregated serving

    Run prefill and decode on different GPU pools, since one is compute-bound and the other memory-bound.

    Parallelism

    Tensor parallelism splits a large model across GPUs in one server; pipeline and expert parallelism spread it further.

    Implement it withGeneration and servingSampling parameters, streaming and self-hosting
    latency ≈ TTFT + output_tokens × TPOT · throughput = batch × tokens/s per stream
    • Anthropic, OpenAI, Google SDKsHosted models with streaming.
    • Hugging Face transformersgenerate() with temperature, top_p, top_k.
    python · a sampler from logits
    import numpy as np
    
    def sample(logits, temperature=1.0, top_k=None, top_p=1.0, rng=np.random):
        if temperature == 0:
            return int(np.argmax(logits))                # greedy
        z = logits / temperature
        if top_k:
            z[np.argsort(z)[:-top_k]] = -np.inf          # keep k best
        p = np.exp(z - z.max()); p /= p.sum()
        order = np.argsort(-p)
        keep = np.cumsum(p[order]) - p[order] < top_p     # nucleus
        mask = np.zeros_like(p, bool); mask[order[keep]] = True
        p = np.where(mask, p, 0); p /= p.sum()
        return int(rng.choice(len(p), p=p))
    Provisioned throughput units (PTUs) reserve capacity; standard deployments are pay-per-token.
    • Azure AI FoundryServerless and provisioned deployments of OpenAI and open models.
    • AKS + vLLM / KAITOSelf-host open models on GPU node pools.
    python
    stream = client.chat.completions.create(model="my-deployment", stream=True,
        temperature=0.2, max_tokens=300,
        messages=[{"role": "user", "content": "Capital of France?"}])
    for chunk in stream:
        if chunk.choices: print(chunk.choices[0].delta.content or "", end="")
    Bedrock cross-region inference spreads load; batch inference is cheaper for offline jobs.
    • Amazon Bedrock Converse / ConverseStreamOne API across hosted models.
    • SageMaker endpoints (LMI containers with vLLM)Self-hosted open models.
    python
    r = br.converse_stream(modelId=MODEL_ID,
        messages=[{"role": "user", "content": [{"text": "Capital of France?"}]}],
        inferenceConfig={"temperature": 0.2, "maxTokens": 300})
    for ev in r["stream"]:
        if "contentBlockDelta" in ev: print(ev["contentBlockDelta"]["delta"]["text"], end="")
    Context caching on Gemini bills cached tokens at a discount plus storage time.
    • Gemini API / Vertex AIHosted models, streaming, context caching.
    • GKE + vLLM or JetStream on TPUSelf-hosted serving.
    python
    from google.genai import types
    for chunk in client.models.generate_content_stream(model=GEMINI_MODEL,
            contents="Capital of France?",
            config=types.GenerateContentConfig(temperature=0.2, max_output_tokens=300)):
        print(chunk.text, end="")
    PagedAttention: KV cache in fixed-size blocks → near-zero fragmentation, prefix sharing across requests.
    • vLLM, SGLangHigh-throughput open servers with OpenAI-compatible APIs.
    • llama.cpp, Ollama, LM StudioRun quantized GGUF models on laptops.
    • TensorRT-LLM, TGINVIDIA-optimised and Hugging Face servers.
    bash
    pip install vllm
    vllm serve Qwen/Qwen2.5-7B-Instruct --max-model-len 32768 --enable-prefix-caching
    # or on a laptop:
    ollama run llama3.1:8b
    Deep dive

    Inference, further

    Numbers and gotchas from real serving.

    Why temperature 0 isn't always deterministic gotcha

    GPU floating-point maths isn't associative, and batching changes the order of additions, so tiny differences can flip a near-tie between two tokens and the rest of the output diverges. Providers may also route to different hardware. If you need reproducibility, store outputs, use seeds where offered, and design tests that tolerate small variations.

    Quantization formats decoded terms
    FP16 / BF16
    16-bit floats; BF16 has FP32's range with less precision. The default for serving.
    FP8 / INT8
    8-bit; near-lossless with good calibration; native on H100/B200.
    INT4: GPTQ, AWQ
    4-bit weights calibrated on sample data; popular for GPUs.
    GGUF (Q4_K_M etc.)
    llama.cpp's file format with mixed 2–8-bit schemes; for CPUs, Macs and consumer GPUs.
    FP4 (NVFP4, MXFP4)
    4-bit floats with hardware support on Blackwell-class GPUs; used for some 2025–26 open-weight releases.
    Latency budget of one chat reply numbers

    A 2,000-token prompt and 300-token reply on a fast hosted model: network ~50–100 ms, queue ~0–200 ms, prefill ~100–300 ms (TTFT ≈ 0.3–0.6 s), decode 300 tokens at 80 tokens/s ≈ 3.75 s. Output length dominates. That is why streaming matters for UX and why asking for shorter answers is the cheapest speed-up. A reasoning model may first spend thousands of hidden "thinking" tokens.

    Structured outputs and function calling at the token level mechanism

    When you ask for JSON matching a schema, many providers compile the schema into a grammar and, at each step, mask out tokens that would make the output invalid. Function calling is the same idea: the model was trained to emit a special tool-call format, which your code parses and runs (Ch 18).

    Chapter 14FoundationsBuilder

    Types of language models, in one place

    Explorer

    "LLM" covers many kinds of model: by architecture (decoder, encoder, MoE, state-space), by training stage (base, instruct, reasoning), by size and access (frontier, small, open-weight, quantized), by modality (vision, speech, omni) and helpers (embedding models, rerankers). Filter, search and compare capability, latency, cost and complexity to run.

    Chapter 15Foundations

    The wall: what a raw LLM can't do

    The turning point

    A trained LLM is a frozen function: it makes things up when unsure (hallucination), knows nothing after its cutoff or about your private data, can't act in the world, forgets everything between calls, has a finite context window, and is unreliable on long multi-step work. The story of GenAI since 2022 is the story of engineering around these limits, one layer at a time.

    The story so far

    In early 2023 everyone had the same experience. The chatbot wrote a beautiful answer. Then you checked, and the court case it cited didn't exist, the library function it used had never been written, and it apologised and confidently made up another. The model was brilliant and untrustworthy at the same time. Making it trustworthy became the job of a new kind of engineer.

    Six limits built into the design

    LimitWhy it happens (from Part II)What it looks likeThe layer that fixes it
    HallucinationThe model always produces a plausible next token; it was trained to sound like text, not to say "I don't know"Invented citations, APIs, numbers, quotesContext and grounding (Ch 17), verification (Ch 19)
    Frozen knowledgeWeights are fixed at the knowledge cutoff (Ch 11)Wrong about recent events, prices, versions; blind to your documentsRetrieval (RAG), search tools
    Can only talkOutput is tokens; nothing runs unless code acts on themTells you how to book a flight instead of booking itTools and agents (Ch 18)
    No memoryStateless: each request is independent (Ch 6)Forgets your preferences, last week's chat, the projectMemory as context; state files (Ch 20)
    Finite, leaky contextQuadratic attention; fixed window; attention spreads thin (Ch 9)Ignores facts in the middle of long prompts; quality drops as context fillsContext engineering: select, compress, order
    Unreliable over many stepsEach step has some error rate; errors compoundStarts well, drifts, declares a broken task "done"Harness checks and loops with verification
    Compounding errors: P(all n steps right) = pⁿ · p = 0.95, n = 20 → 0.95²⁰ = 36% · n = 50 → 8%

    Live demo · climb the ladder: each fix creates the next problem

    Step through the whole story of this guide, from hand-written rules to loop engineering. Each rung shows the problem people hit, the fix they invented, and the new problem that fix revealed.

    Hallucination, properly understood

    A hallucination (or confabulation) is fluent, confident output that is false or unsupported. It is not a bug in the usual sense: the same mechanism that lets a model write a new poem lets it write a new court case. OpenAI's 2025 paper "Why Language Models Hallucinate" argued that standard training and benchmarks reward guessing over admitting uncertainty, the way a multiple-choice exam rewards guessing. Rates have dropped a lot with newer models, retrieval and reasoning, but never to zero. Hallucination is worst for rare facts (a minor person's birthday), precise strings (URLs, IDs, quotes), and questions with false premises.

    The engineering response, in one line each

    Prompt engineering: ask clearly. Context engineering: show the facts. Agents: let it act and check. Harness engineering: wrap it in tools, rules and tests. Loop engineering: run it repeatedly until a check passes, with humans judging the result. Each is a chapter next.

    Deep dive

    Limits in more detail

    Measured effects and what they mean for builders.

    "Lost in the middle" and context rot research

    Liu et al. (2023) found models used information at the start and end of a long prompt much better than information in the middle. Later "needle in a haystack" tests looked solved, but harder tests (multi-fact reasoning over long inputs) still show degradation as context grows. Chroma's 2025 "context rot" report found performance falling with input length across many models even on simple tasks. Practical rule: a smaller, relevant context beats a huge one.

    Reasoning limits and the "reversal curse" research

    Models trained that "A is B" don't automatically learn "B is A" (the reversal curse, 2023). They can fail on slightly altered versions of famous puzzles because they pattern-match the original. Reasoning models reduce but don't remove these effects. Tools (code execution, search) are the most reliable fix for exact maths and lookups.

    Sycophancy and calibration behaviour

    Sycophancy: telling users what they want to hear, a side effect of preference training. Calibration: whether stated confidence matches accuracy. Base models are fairly well calibrated; post-training can make them overconfident. Ask for evidence and sources, not confidence ratings, and design checks rather than trusting self-assessment.

    Chapter 16FoundationsBuilder

    Rung 1 · Prompt engineering: say it better

    The first fix (2020–2023)

    GPT-3 showed that the words in the prompt steer the model: instructions, examples (few-shot), roles, formats and "think step by step" (chain of thought) changed results dramatically, with no retraining. Prompting is still the cheapest fix. Its limit: no wording can give a model facts it doesn't have, or hands to act.

    ProblemBase and early chat models misread tasks, ignored formats and reasoned sloppily.
    FixWrite clear instructions, show examples, give a role, ask for step-by-step reasoning, specify the output format.
    New problemThe model still doesn't know your data or today's facts, and better wording can't fix missing information.

    The discovery came in the GPT-3 paper (2020): put a few examples of a task in the prompt and the model continues the pattern, called in-context learning. Zero-shot means instructions only; few-shot means a handful of worked examples. In 2022, Google's chain-of-thought (CoT) paper showed that examples with written-out reasoning made large models much better at maths word problems, and a follow-up showed simply adding "Let's think step by step" helped too. A cottage industry of tips followed: personas ("You are an expert editor"), delimiters, output templates, self-consistency (sample several answers and vote).

    weak prompt
    Summarise this.
    engineered prompt
    You are summarising a support ticket for an on-call engineer.
    Write 3 bullets: the customer's problem, what they tried,
    and the error message (quoted exactly). If any of these is
    missing, write "not stated". No other text.
    
    <ticket>
    {ticket_text}
    </ticket>
    TechniqueWhat it doesStill useful in 2026?
    Clear task + audience + formatRemoves ambiguityAlways the biggest win
    Few-shot examplesShows the pattern and styleYes, especially for formats and edge cases; vary examples to avoid copying
    Chain of thoughtReasoning written before the answerBuilt into reasoning models; still helps non-reasoning models
    Role / personaSets tone and expertiseMild effect; specifics matter more
    Structured tags (XML/Markdown)Separates instructions from dataYes; also helps against prompt injection
    "ALL CAPS, YOU MUST"Shouting emphasisOften counter-productive in modern models: they over-apply it
    Where to go deeper

    The companion Prompt Engineering Guide covers techniques, templates, system prompts, structured outputs, prompt evaluation and prompt security in depth.

    Deep dive

    Why prompts work

    The mechanism behind the craft.

    Prompts select a "mode" of the model concept

    Pretraining exposed the model to every kind of writer. The prompt conditions which kind it imitates. Clear, expert-sounding prompts with precise requirements pull it toward careful, expert-like continuations; vague prompts get average web text. Induction heads (Ch 9) explain why examples are copied so faithfully.

    System prompt vs user prompt terms

    The system prompt holds the application's standing instructions (role, rules, tools); user messages hold the request. Models are trained to give system instructions more weight, but this is a soft priority, not a security boundary: injected text can still override it (Ch 22).

    Automatic prompt optimisation tooling

    Instead of hand-tuning, tools like DSPy treat the prompt as parameters and optimise instructions and examples against an evaluation set. It works well when you have a measurable metric, and it foreshadows loop engineering: the improvement itself becomes a loop.

    Chapter 17FoundationsBuilder

    Rung 2 · Context engineering: show it the facts

    The second fix (2023–2025)

    If the model doesn't know something, put it in the context. Retrieval-augmented generation (RAG) searches your documents and pastes the relevant passages into the prompt, so answers are grounded and citable. By mid-2025 the broader practice of deciding everything the model sees (instructions, retrieved facts, memory, tool results, history) got a name: context engineering. Its limit: the model can now know, but still can't do.

    ProblemHallucination, stale knowledge, no access to private data; fine-tuning facts in is slow, costly and unreliable.
    FixRetrieve relevant information at request time and include it in the context: RAG, search, memory, document stuffing, long context windows.
    New problemAnswers are grounded but the model only talks. Real tasks need actions: query a live system, run code, file a ticket, change a record.

    RAG in one picture

    offline · indexing Documents Chunk Embed Vector + keyword index online · every question Question"refund policy?" Searchhybrid · top 20 Rerankkeep best 5 Prompt = rules +passages + question LLM answerwith citations [2][4]

    The RAG idea was published by Patrick Lewis and colleagues at Facebook AI in 2020, but it exploded in 2023 when every company wanted "ChatGPT on our documents". The pieces come straight from earlier chapters: embeddings (Ch 8) for meaning-based search, BM25 (Ch 4) for exact terms, nearest-neighbour search (Ch 2), and a reranker (a cross-encoder, Ch 14) to sort results. Context windows grew from 4k tokens (2022) to 128k–1M+ (2024–26), which let teams stuff whole documents in, but cost, latency and "lost in the middle" (Ch 15) mean retrieval still matters.

    In June 2025 Shopify's Tobi Lütke and Andrej Karpathy popularised context engineering: "the delicate art and science of filling the context window with just the right information for the next step." It covers instructions, examples, retrieved knowledge, conversation history, memory (facts saved from earlier sessions), tool definitions and tool results, and techniques like compaction (summarising old turns), ordering (stable prefix first for caching) and isolation (sub-tasks in separate contexts).

    Where to go deeper

    The RAG Guide covers chunking, embeddings, vector stores, hybrid search, reranking, evaluation and scaling. The Context Engineering Guide covers budgets, memory, compaction, caching and context failures.

    Deep dive

    Context, further

    What changed when windows got long.

    RAG vs long context vs fine-tuning decision
    RAGLong contextFine-tuning
    Fresh / changing dataExcellentGood (re-send)Poor
    Huge corpora (millions of docs)YesNoNo
    CitationsNaturalPossibleNo
    Cost per requestLowHigh (cache helps)Lowest
    Changes style / formatNoSomewhatYes
    Memory: how chatbots "remember" you mechanism

    The model still has no memory. The app saves facts ("prefers Python", "works at X") or past chat summaries in a database, retrieves the relevant ones, and adds them to the context of new conversations. Memory is RAG over your own history, with the same risks: stale, wrong or injected memories.

    Context failure modes failure
    • Poisoning: a wrong fact enters context and is repeated.
    • Distraction: too much irrelevant text drowns the useful part.
    • Confusion: too many similar tools or documents.
    • Clash: contradictory sources with no rule for which wins.
    Chapter 18FoundationsBuilder

    Rung 3 · Tools and agents: let it act

    The third fix (2023–2025)

    Give the model tools, functions it can request (search, run code, query a database, send a message), and put it in a loop: think, call a tool, read the result, repeat until done. That is an agent. Function calling (2023) made it practical; MCP (late 2024) standardised how tools plug in; coding agents (2025) made it mainstream. Its limit: agents are powerful and erratic: they wander, break things and claim success.

    ProblemModels can describe actions but not take them; they can't do exact maths, check live data or verify their own code.
    FixTool calling + an agent loop (ReAct): the model decides which tool to call; your code runs it and returns the result; repeat.
    New problemAgents are unreliable over long tasks, unsafe with real permissions, inconsistent across runs and hard to debug.

    The agent loop

    Goal + contextuser task, tools list LLM decidesthink → tool call JSON Runtime runs toolsearch · code · API · MCP Observationresult added to context Final answerno more tool calls done?
    WhenStepWhy it mattered
    Oct 2022ReAct paper (reason + act)The interleaved think → act → observe pattern every agent uses
    Feb 2023Toolformer (Meta)Models can learn when to call tools
    Mar–Apr 2023ChatGPT plugins; AutoGPT and BabyAGI go viralHuge excitement; open-ended agents mostly looped, wandered and burned money
    Jun 2023Function calling in the OpenAI API (others follow)Structured, reliable tool calls became a standard model feature
    2024SWE-bench, SWE-agent, Devin; Claude computer use (Oct)Agents measured on real GitHub issues; models operating GUIs
    Nov 2024Model Context Protocol (MCP), AnthropicOne open standard to connect any tool or data source to any agent
    2025Claude Code, OpenAI Codex, Gemini CLI, Cursor/Copilot agent modes; agent SDKs; A2A protocolAgents that work in your terminal and repo became everyday tools

    Anthropic's "Building effective agents" (Dec 2024) drew a useful line: workflows are systems where code decides the path and LLMs fill in steps; agents are systems where the LLM decides its own next step. Workflows are predictable; agents handle open-ended tasks. Most production systems mix both. A tool definition is just a name, a description and a JSON schema of arguments, and the model's skill at choosing and filling them in comes from post-training (Ch 12).

    python · the whole agent loop, minimal
    def run_agent(task, tools, max_steps=20):
        messages = [{"role": "user", "content": task}]
        for _ in range(max_steps):
            reply = llm(messages, tools=[t.schema for t in tools])
            messages.append(reply)
            if not reply.tool_calls:                 # model chose to answer
                return reply.text
            for call in reply.tool_calls:          # run each requested tool
                result = TOOLS[call.name](**call.args)
                messages.append({"role": "tool", "id": call.id, "content": str(result)})
        return "stopped: step limit"
    Where to go deeper

    The Agents Guide covers agent patterns, memory, planning, multi-agent systems and evaluation. The MCP Guide covers the protocol, servers, transports and security.

    Deep dive

    Agents, further

    What makes them work and fail.

    Why 2023 agents failed and 2025 agents worked history
    • Models: reasoning and tool-use training (Ch 12) made each step far more reliable, which matters because errors compound.
    • Context: 100k+ windows held whole files and long histories.
    • Environment: code has tests and compilers, an objective feedback signal.
    • Narrow scope: "fix this failing test" instead of "grow my business".
    The lethal trifecta security

    Simon Willison's warning (2025): an agent that has (1) access to private data, (2) exposure to untrusted content, and (3) a way to send data out can be tricked by prompt injection into leaking that data. Remove at least one of the three for any agent that reads untrusted input.

    Computer use and browser agents capability

    Instead of APIs, some agents see screenshots and control a mouse and keyboard. It works with any software, but is slower, costlier per step and more fragile than calling an API. Use APIs or MCP tools where they exist.

    Chapter 19BuilderArchitect

    Rung 4 · Harness engineering: make it reliable

    The fourth fix (2025–2026)

    The harness is all the code around the model inside an agent session: tools, the execution sandbox, permissions, instruction files (AGENTS.md), skills, hooks that block unsafe actions, linters and tests that act as sensors, and sub-agents. Teams found the same model performs very differently in different harnesses. Its limit: a great harness still needs a human to start each session, pick the next task and judge the result.

    ProblemAgents ignored project conventions, ran dangerous commands, didn't notice failed tool calls and claimed "done" with broken tests.
    FixEngineer the environment: guides (instructions, skills), sensors (tests, linters, type checks fed back to the agent), guardrails (permissions, hooks, sandboxes) and good tools.
    New problemEach session is still prompted, watched and judged by a person. Humans become the bottleneck; long work spans many sessions.

    The word comes from a horse's harness: the gear that lets you direct a powerful animal's strength. In software, "test harness" already meant the scaffolding that runs code under test. By early 2026 "harness engineering" was widely used for agent scaffolding, with the formula agent = model + harness. A key insight: give the agent the same feedback a good engineer uses. If a linter would catch it, run the linter and show the agent the output; if a test would catch it, make the test part of the loop.

    Guides

    Tell it how

    AGENTS.md / CLAUDE.md project rules, skills (SKILL.md) loaded when relevant, examples of good code.

    Sensors

    Let it see

    Compiler, type checker, tests, linters, browser screenshots, logs: fast, objective feedback after each change.

    Guardrails

    Stop it

    Permission allow-lists, hooks that block rm -rf or secret access, sandboxes, network egress rules, approval gates.

    Tools

    Equip it

    Well-named, well-described tools with clear errors; MCP servers; sub-agents with their own context for research or review.

    Where to go deeper

    The Harness Engineering Guide covers guides, sensors, hooks, permissions, sandboxes, sub-agents and how to measure a harness.

    Deep dive

    Harness, further

    Why the wrapper matters as much as the model.

    Same model, different harness, different score evidence

    Coding benchmark leaderboards regularly show the same model scoring very differently depending on the agent scaffold that runs it. Model choice is only part of the result; tools, prompts, context management and verification steps are the rest. Evaluate the model + harness pair, not the model alone.

    Computational vs inferential sensors pattern

    Computational sensors are deterministic programs (tests, type checks): cheap, fast, trustworthy, narrow. Inferential sensors are LLM reviewers: broad, judgement-capable, costlier and fallible. Use computational ones first and LLM reviewers for what code can't check (intent, readability).

    Chapter 20BuilderArchitect

    Rung 5 · Loop engineering: let it run on its own

    The fifth fix (2026)

    Instead of a human typing the next prompt, a loop does: a trigger starts the agent, it reads a goal and saved state, does one unit of work, a separate verifier checks it, progress is saved, and the loop decides to continue, stop or call a human. Named by Addy Osmani in June 2026. Its limit is the frontier we're on now: judging quality, safety and accountability still belong to people.

    ProblemHumans spent their day re-prompting agents, choosing the next task and re-checking results. Long projects outgrew one session's context.
    FixLoops: triggers and schedules, goals with machine-checkable stop conditions, state files, fresh context per iteration, independent verifiers, budgets and escalation.
    New problemReview becomes the bottleneck; unattended mistakes, runaway cost, and "cognitive surrender" (accepting output because tests pass). The human outer loop remains.

    Each rung moved the engineer one step further from the single model call: from words (prompt) to information (context) to actions (agent) to environment (harness) to process (loop). The simplest loop, Geoffrey Huntley's 2025 "Ralph" technique, is one line of shell that feeds the same prompt to a headless coding agent forever, with a plan file as memory. Production loops add stop conditions, verification and budgets. Products shipped loop primitives in 2026: scheduled tasks, /goal conditions, stop hooks and background cloud runs. Boris Cherny, who leads Claude Code, summed up the shift: "My job is to write loops."

    Five layers, each wrapping the last

    Human outer loop · goals · quality · verdict · accountability Loop · trigger · state · verify · stop (2026) Harness · tools · sensors · guardrails (2025–26) Agent · think → act → observe (2023–25) Context · facts, memory, tool results (2023–25) Prompt · the words (2020–23) LLM · next-token predictor
    Where to go deeper

    The Loop Engineering Guide covers triggers, stop conditions, verification, state, budgets, loop patterns, the human outer loop and running loops at scale.

    Deep dive

    Loops, further

    The maths that makes loops worth it, and the risk.

    Why a verifier turns a weak agent into a strong loop math
    P(success within N tries) = 1 − (1 − p)^N · p = 0.4, N = 5 → 92%

    This only holds if the verifier reliably tells success from failure. Without one, retries just produce more unverified output. This is why verification, not generation, is becoming the scarce engineering skill.

    The nested loops inside every loop model

    The token loop (Ch 13) runs inside the agent's tool loop, inside a task loop, inside a session loop, inside a schedule, inside an improvement loop, inside the human loop. Model calls multiply outward; so do costs and errors.

    Chapter 21Everyone

    Where we stand: October 2026

    The state of play

    Frontier models are multimodal, reasoning, tool-using and mostly mixture-of-experts, with context windows of hundreds of thousands to millions of tokens. Open-weight models trail the frontier by months, not years. Price per unit of capability keeps falling fast. Agents that work for hours on coding tasks are routine; the hard problems are now reliability, verification, security, cost at scale, energy and governance, not raw fluency.

    Looking back

    In 1966 people confided in ELIZA, a few hundred lines of pattern matching. In 2026 people hand AI agents a goal on Friday evening and review a stack of finished, tested changes on Monday morning. The underlying idea, predict what comes next, would have been familiar to Claude Shannon in 1948. What changed was scale, data, a better architecture, and a decade of engineering wrapped around the model.

    The landscape (fast-moving: verify before relying on any of it)

    GroupFamilies in use in 2026Notes
    Closed frontier labsOpenAI GPT-5.x series; Google Gemini 3.x; Anthropic Claude (4.x → 5-series: Fable, Opus, Sonnet, Haiku); xAI Grok 4.xTiered families (large / balanced / fast); reasoning modes; 1M-token contexts on some tiers
    Open-weight leadersDeepSeek V3/V4 and R-series; Alibaba Qwen 3.x; Meta Llama 4; Google Gemma 4; Mistral; Moonshot Kimi; Zhipu GLM; OpenAI gpt-ossMostly MoE; licences vary (MIT, Apache 2.0, custom community licences): check before commercial use
    Small / on-devicePhi, Gemma, Qwen small, Llama small, Apple and Google on-device models1–15B parameters; run on phones and laptops; strong for narrow tasks

    Model names and version numbers here are based on public reporting up to mid/late 2026 and change monthly. Several sources disagree on rankings. Check providers' model pages and independent leaderboards (e.g. LMArena, Artificial Analysis, METR) for current standings.

    Six trends that define the moment

    Reasoning is default

    Since o1 (2024) and DeepSeek-R1 (2025), models think before answering, and you can often dial the effort. Test-time compute is a second scaling axis next to model size.

    Agents are the product

    Coding agents, research agents and computer-use agents are mainstream. METR's measurements of the task length agents can finish (at 50% reliability) have been doubling every few months, reaching many hours of expert work on its 2026 suite; treat exact numbers as estimates.

    Cheaper every year

    The price of a given level of capability has fallen by roughly an order of magnitude per year or faster since 2022 (estimates vary by benchmark). Small distilled models do what frontier models did a year earlier.

    MoE and efficiency

    Sparse experts, low-precision (FP8/FP4) training and serving, long-context attention tricks and speculative decoding stretch every GPU.

    Open vs closed

    Open-weight models (many from Chinese labs) narrowed the gap to months, putting pressure on prices and enabling private, self-hosted deployments.

    Rules arriving

    The EU AI Act's obligations for general-purpose models began applying in August 2025, with more phases through 2026–27. Other regions have guidance, executive actions and state laws in flux.

    Open problems

    ProblemStatus in 2026
    HallucinationMuch reduced with retrieval and reasoning; not solved. Verification layers still required.
    Prompt injectionNo complete defence. Architecture (least privilege, isolation, human approval) is the mitigation (Ch 22).
    InterpretabilityReal progress (sparse autoencoder features, circuit tracing), far from fully explaining a frontier model.
    EvaluationBenchmarks saturate within months; contamination; agent evals are expensive and noisy.
    Energy and computeData-centre power demand is a public policy issue; efficiency gains compete with growth in use.
    Continual learningModels still don't learn from deployment in real time; memory and loops are the workaround.
    Jobs and skillsRapid change in software, support and content work; the human role shifts to specifying, verifying and owning outcomes.

    What's next (informed speculation)

    Longer, more autonomous work

    If time horizons keep growing, agents move from tasks to projects, and loop engineering and verification become standard practice.

    World models and embodiment

    Video-trained world models and vision-language-action models for robots are the next frontier for "predict what comes next".

    Beyond the transformer?

    State-space hybrids, diffusion LLMs and new attention schemes are being tried; so far, the transformer keeps absorbing the best ideas rather than being replaced.

    Verification is the new bottleneck skill

    Generation is cheap; trustworthy evidence is not. Specs, tests, evals and review capacity become the core of AI engineering.

    Deep dive

    Reading the hype

    How to judge new claims as they arrive.

    How to read a model launch skill
    • Are benchmarks vendor-reported or independent? Which settings (reasoning effort, tools, number of tries)?
    • Is it measured on your kind of task? Run your own small eval set (Ch 22).
    • What are price, latency and context limits at the tier you'd use?
    • Licence and data terms: can you use it commercially, and where does your data go?
    AGI: what people mean terms

    Artificial general intelligence (AGI) usually means AI that matches humans across most cognitive work; definitions vary widely and some labs use economic definitions. Forecasts range from a few years to decades. This guide avoids predictions; what is measurable is task-length horizons, benchmark scores and real-world adoption.

    The whole journey on one line summary
    rules (1956) → learning (1990s) → deep learning (2012) → word vectors + attention (2013–14) → transformer (2017) → GPT-3 (2020) → ChatGPT (2022) → prompt → context/RAG → agents/MCP → harness → loops (2026)
    Chapter 22BuilderArchitect

    Using LLMs in production: choose, measure, secure, scale

    The playbook

    Choose the smallest model that passes your own eval set. Measure with task-specific evaluations, not leaderboards. Control cost with prompt caching, model routing, batching and short outputs. Secure against prompt injection by design (least privilege, isolation, approval), not by prompt wording. Scale in stages from one API key to multi-region, multi-model infrastructure.

    Choosing a model

    QuestionIf yesIf no
    Does a small/fast model pass your eval set?Use it; route only hard cases upTry a mid-tier, then frontier
    Is the task multi-step maths, code or planning?Reasoning model or reasoning modeStandard model is faster and cheaper
    Must data stay on your infrastructure?Open-weight model, self-hosted or in your cloud tenantHosted API with suitable data terms
    Millions of requests a day on one narrow task?Consider fine-tuning or distilling a small modelPrompting a general model is simpler
    Images, audio, documents as input?Multimodal modelText model

    Live demo · what will this cost per month?

    Enter your traffic and prices (check your provider's current price page). See cost per request, per day and per month, and how much prompt caching and routing save.

    Assumes cached input costs 10% of the normal input price and ignores cache-write premiums and reasoning tokens (which are billed as output). Example prices are placeholders, not a quote.

    Evaluation: the habit that separates demos from products

    Build a golden set

    50–500 real examples with expected answers or grading rules, including edge cases and past failures. Re-run on every prompt, model or retrieval change.

    Grade three ways

    Code checks (exact match, JSON valid, tests pass), LLM-as-judge with a rubric (calibrated against humans), and human review of samples.

    Watch production

    Log prompts, outputs, latency, cost and user feedback (with privacy controls). Turn every incident into a new eval case.

    Common public benchmarkMeasuresCaveat
    MMLU / MMLU-ProBroad academic knowledge, multiple choiceSaturated at the top; contamination
    GPQA DiamondPhD-level science questionsSmall set
    Humanity's Last ExamVery hard expert questionsScores move fast with tools and reasoning
    SWE-bench Verified / ProFixing real GitHub issuesDepends heavily on the agent harness
    LMArena (Chatbot Arena)Human preference in blind head-to-head chatsRewards style and length; can be gamed
    METR time horizonLength of tasks agents finish at 50% reliabilityMostly software tasks; wide error bars

    Security: the threats specific to LLMs

    ThreatWhat happensMitigation
    Prompt injection (direct and indirect)Instructions hidden in user input, web pages, emails or documents override your instructionsTreat all model input as untrusted; least-privilege tools; separate data from instructions; human approval for risky actions; break the lethal trifecta
    JailbreaksUsers talk the model out of its safety trainingProvider safety layers, input/output classifiers, rate limits, monitoring
    Data leakageSecrets or personal data in prompts, logs or outputsRedact before sending; data-retention settings; access controls on logs
    Insecure output handlingModel output executed as code, SQL or HTMLValidate and sandbox; parameterised queries; escape output
    Excessive agencyAn agent with broad permissions does damageScoped credentials, allow-lists, dry runs, approval gates, audit logs
    Supply chain / model poisoningMalicious model weights, MCP servers or packagesTrusted sources, pinned versions, scanning, sandboxed tool servers
    Denial of walletAbuse runs up token costsPer-user quotas, max tokens, budgets and alerts

    See the OWASP Top 10 for LLM Applications for the maintained industry list.

    Reference architecture for an LLM application

    Clientweb · app · API API gatewayauth · quotas Orchestratorworkflow / agent loopguardrails in + out Prompts Retrieval Memory Tools/MCP LLM gatewayrouting · fallbackscache · budgets Hosted APIs (A, B, C) Self-hosted (vLLM) Observabilitytraces · cost · evals

    Scaling an LLM application from 1 user to 1,000,000

    Pick a stage

    Deep dive

    Production details

    Things teams learn the hard way.

    Cost levers, in order of impact cost
    1. Right-size the model: routing simple requests to a small model often cuts cost 50–80%.
    2. Shorter outputs: output tokens cost 3–5× input and dominate latency.
    3. Prompt caching: stable prefix first; ~90% off cached reads with most providers.
    4. Trim context: retrieve 5 good passages, not 50.
    5. Batch APIs: ~50% off for work that can wait hours.
    6. Cap reasoning effort where the task doesn't need it.
    Reliability patterns ops

    Timeouts and retries with backoff on rate limits (HTTP 429) and overload errors; fallbacks to a second provider or model; idempotency for tool actions; schema validation with automatic repair retries; circuit breakers when a provider degrades; streaming for perceived speed.

    Observability: what to log ops

    Per call: model, version, prompt template version, input/output token counts, cached tokens, latency (TTFT and total), cost, tool calls, stop reason, user feedback, eval scores. OpenTelemetry's GenAI semantic conventions standardise these fields; tools like Langfuse, LangSmith, Arize Phoenix and Helicone collect them.

    Chapter 23ArchitectBuilder

    The failure catalog: technical and functional problems

    How to use this

    Every entry has a symptom, root cause and fix, tagged by area and severity: from tokenization and training to serving, retrieval, agents, security and cost. Click a cell in the heat map, filter by severity, or search for a word from your incident.

    Chapter 24ArchitectBuilder

    Every trade-off, side by side

    Read the dial

    Each row is a decision with two ends. The marker shows where most production teams sit by default in 2026. Move it for your own quality bar, risk, scale and budget.

    Alternatives: when not to use an LLM

    Instead of an LLM for…UseWhy
    Exact calculationsCode, a calculator, SQLDeterministic and free
    Fixed-format parsing (dates, IDs)Regex, parsersFaster, cheaper, testable
    Classifying millions of items into a few labelsA small fine-tuned classifier (or embeddings + logistic regression)100–1000× cheaper per item; LLM can label the training data
    Keyword lookupSearch engine / database indexExact, explainable
    Tabular predictions (churn, price)Gradient boosting (XGBoost, LightGBM)Classic ML still wins on spreadsheets (Ch 2)
    High-stakes decisions about peopleHuman judgement with AI as an aidAccountability, legal requirements, bias risk
    Chapter 25Everyone

    Checklist, glossary and sources

    Tick items as you go. Progress is saved in this browser only.

    Glossary: every important term

    All terms are also searchable with Ctrl+K.

    TermDefinition

    Sources and further reading

    2026 model landscape notes draw on public reporting and comparison sites (for example Analytics Vidhya's July 2026 release timeline and DataNorth's open-model overview), which disagree in places. Confirm details on official model pages.

    The idea behind it all

    Predict the next token. Then engineer everything around it.

    The LLM Guide. Written with research current to October 2026. Model names, prices and benchmark numbers change monthly: treat them as starting points and check official docs. Companion guides: Prompt Engineering · Context Engineering · RAG · Agents · MCP · Harness Engineering · Loop Engineering.