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.
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.
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.
The dream: from Turing to the AI winters
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.
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
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 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.
| Year | Milestone | Why it matters to LLMs |
|---|---|---|
| 1943 | McCulloch–Pitts artificial neuron | The basic unit every neural network, including LLMs, still uses (weighted sum + activation) |
| 1948 | Claude Shannon's information theory; he models English as a probability of the next letter | The first "language model": predicting what comes next. LLMs are this idea at enormous scale |
| 1950 | Turing, "Computing Machinery and Intelligence" (the imitation game) | Framed AI by behaviour: does it talk like us? |
| 1956 | Dartmouth workshop names "artificial intelligence" | The field begins |
| 1958 | Rosenblatt's perceptron learns weights from data | The first learning neural network |
| 1959 | Arthur Samuel coins "machine learning" | Learning instead of programming |
| 1966 | ELIZA chatbot | The ELIZA effect: fluency feels like understanding |
| 1969 | Perceptrons book shows single-layer limits | Neural nets abandoned for ~15 years |
| 1973–80 | Lighthill report; first AI winter | Hype without results is punished |
| 1980–87 | Expert systems boom (XCON) | Hand-written knowledge works in narrow domains only |
| 1987–93 | Lisp machine collapse; second AI winter | Brittle rules don't scale |
| 1997 | IBM Deep Blue beats Kasparov at chess | Search + hand-tuned evaluation; impressive, but not learning language |
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.
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.
Machine learning: let the data write the rules
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 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
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.
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.
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.
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)
| Method | Idea in one line | Still used for |
|---|---|---|
| Linear / logistic regression | Weighted sum of features (logistic squashes it into a probability) | Baselines, scoring, the last layer of every neural net |
| Naive Bayes | Count how often each word appears in spam vs not spam | Fast text classification |
| Decision trees, random forests (2001), gradient boosting (XGBoost 2014) | Chains of yes/no questions; many trees vote | Tabular data: still often beat neural nets on spreadsheets |
| Support vector machines (1995) | Find the widest boundary between classes | Small datasets |
| k-means, PCA | Group similar points; compress dimensions | Clustering, visualising embeddings |
| k-nearest neighbours | Answer like the most similar known examples | The 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.
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.
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).
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.
Deep learning: networks that learn their own features
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.
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
Why it suddenly worked in 2012
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.
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.
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
| Architecture | Built for | Key idea | Limit that mattered for language |
|---|---|---|---|
| Feed-forward (MLP) | Fixed-size inputs | Layers of neurons, data flows one way | No notion of order or variable length |
| CNN (LeCun, 1989; LeNet 1998) | Images | Small filters slide over the image; share weights; detect local patterns | Sees local windows; weak at long-range links in text |
| RNN (1980s) | Sequences | Reads one item at a time, carrying a hidden "memory" vector forward | Memory fades over long sequences (vanishing gradients); can't be parallelised |
| LSTM (Hochreiter & Schmidhuber, 1997), GRU (2014) | Long sequences | Gates decide what to remember, forget and output | Better memory, still sequential and slow to train at scale |
| Autoencoder, VAE (2013) | Compression, generation | Squeeze input to a small code, rebuild it | Early generative models; blurry outputs |
| GAN (Goodfellow, 2014) | Image generation | A generator and a discriminator compete | The first convincing generative AI for images; hard to train |
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 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.
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).
Language before LLMs: rules, statistics, vectors
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.
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 like | Knows "bank" ≈ "lender"? | Knows river bank ≠ money bank? |
|---|---|---|---|
| One-hot / bag of words | [0,0,…,1,…,0] one slot in a 50,000-word list | No: every word is equally unrelated | No |
| Static embedding (word2vec, 2013) | [0.21, −1.3, 0.07, …] 300 numbers, same in every sentence | Yes | No: one vector mixes both meanings |
| Contextual embedding (ELMo 2018, BERT, GPT) | A different vector in every sentence, computed from its neighbours | Yes | Yes: "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.
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)
Classic NLP, explained
Methods that still show up inside modern systems.
n-gram maths and why it hits a wall math
"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
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.
2017–2022: the transformer and the birth of GenAI
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 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
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.
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.
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
| When | Model / event | What 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 2018 | ELMo (Allen AI) | Contextual word vectors from a pretrained LSTM language model |
| Jun 2018 | GPT-1 (OpenAI), 117M parameters | Generative Pre-trained Transformer: decoder-only, pretrain on books, fine-tune per task |
| Oct 2018 | BERT (Google), 340M | Encoder-only, trained to fill in masked words; topped every understanding benchmark; powered Google Search from 2019 |
| Feb 2019 | GPT-2, 1.5B | Fluent paragraphs; zero-shot task ability; staged release over misuse fears |
| Oct 2019 | T5 (Google) | Every task framed as text-to-text |
| Jan 2020 | Scaling laws (Kaplan et al., OpenAI) | Loss falls as a smooth power law in parameters, data and compute |
| May 2020 | GPT-3, 175B | In-context learning: show a few examples in the prompt and it does the task, no retraining. Prompting is born (Ch 16) |
| 2021 | Codex → GitHub Copilot; CLIP and DALL·E | LLMs write code; text and images share one vector space |
| Jan–Mar 2022 | Chain-of-thought prompting; InstructGPT; Chinchilla | "Think step by step" improves reasoning; RLHF makes models follow instructions; train on more data per parameter |
| Aug 2022 | Stable Diffusion (open) | Image generation for everyone on a home GPU |
| 30 Nov 2022 | ChatGPT | A 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.
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).
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).
An LLM end to end, in one picture
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.
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
The request, step by step
- 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.
- TokenizeThe text is split into tokens, subword pieces like
What,is,the,capital, and each is mapped to an integer ID (Ch 7). - EmbedEach ID picks a row in the embedding matrix: a vector of a few thousand numbers. Position information is mixed in (Ch 8).
- 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.
- 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:
Paris0.91,The0.04 … - SampleA decoding strategy (temperature, top-p) picks one token (Ch 13). It is streamed to your screen.
- 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.
| Phase | Input | Output | Cost driver | Typical scale (frontier, 2026) |
|---|---|---|---|---|
| Pretraining | Trillions of tokens of text | Base model weights | Compute ≈ 6 × parameters × tokens | 15–40T+ tokens, 10²⁵–10²⁶+ FLOPs, tens of thousands of GPUs for months |
| Post-training | Instruction examples, preference pairs, verifiable tasks | Assistant / reasoning model | Human data + RL compute | Now a large and growing share of total training compute |
| Inference: prefill | Prompt tokens | KV cache + first token | Compute-bound (matrix maths) | Thousands of tokens per second per GPU |
| Inference: decode | One token at a time | Next token | Memory-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 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.
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:
<|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.
Tokens: the atoms an LLM reads
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
| Quirk | Token explanation | Workaround |
|---|---|---|
| "How many r's in strawberry?" goes wrong | The model sees pieces like str aw berry, not letters | Ask it to spell letter by letter first, or use code |
| Arithmetic on long numbers slips | Numbers split into irregular chunks (123 456 7), so digit columns don't line up | Use a calculator or code tool (Ch 18) |
| Hindi, Tamil, Thai cost 2–5× more than English | Vocabularies learned mostly from English text compress other scripts poorly | Newer tokenizers with larger, multilingual vocabularies; budget for it |
Odd behaviour on strings like SolidGoldMagikarp | Glitch tokens: in the vocabulary but almost never seen in training | Rare in modern models; strip junk input |
| JSON and code use more tokens than expected | Braces, quotes and indentation are often separate tokens | Compact formats; minified data in prompts |
| Output cut mid-sentence | Hit max_tokens, counted in tokens not words | Raise the limit; check the stop reason |
1 token ≈ 4 chars
English prose. 100 tokens ≈ 75 words. A 300-page book ≈ 120k tokens.
Billed per token
APIs price input and output tokens separately, output usually 3–5× more.
Context window
Max tokens per request (prompt + output): commonly 128k–1M+ in 2026.
Control tokens
<|begin_of_text|>, end-of-turn, tool-call markers: structure the model learned in training.
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.
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 / Azure AI FoundryResponse
usagefields report prompt, completion and cached tokens. - tiktokenSame encodings as the OpenAI models you deploy.
- Azure MonitorTrack token metrics per deployment.
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)- Amazon Bedrock
usagein Converse API responses: inputTokens, outputTokens. - Bedrock CountTokensCount tokens for supported models before sending (check docs for model support).
- CloudWatchInputTokenCount / OutputTokenCount metrics.
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': ...}- Vertex AI / Gemini API count_tokensExact counts for Gemini models.
- usage_metadataPrompt, candidates and cached token counts on every response.
from google import genai
client = genai.Client()
n = client.models.count_tokens(model=GEMINI_MODEL, contents="Capital of France?")
print(n.total_tokens)- SentencePieceGoogle's BPE/Unigram trainer (used by T5, Gemma, early Llama).
- Hugging Face tokenizersRust-fast trainer with byte-level BPE.
- llama.cpp
llama-tokenizeto inspect GGUF model tokenization.
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)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).
Embeddings: meaning as geometry
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.
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 mean | What it is | Used for |
|---|---|---|
| Token embeddings inside an LLM | The input lookup table and the hidden states between layers | The model's internal computation |
| Text embeddings from an embedding model | One vector for a whole sentence or passage (e.g. 768–3,072 dims), from a model trained so similar texts land close | Semantic search, RAG, clustering, deduplication, recommendations (Ch 17) |
- 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.
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]}")- Azure OpenAI embeddingstext-embedding-3-small / -large deployments.
- Azure AI SearchVector, hybrid and semantic ranking.
- Cosmos DB / PostgreSQL (pgvector)Vectors next to app data.
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- Amazon Titan Text Embeddings, Cohere Embed on BedrockHosted embedding models.
- OpenSearch Serverless / Aurora pgvector / S3 VectorsVector storage options.
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"]- Gemini / Vertex AI embeddingsText and multimodal embedding models.
- Vertex AI Vector Search, AlloyDB, BigQuery vector searchStorage and ANN search.
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- FAISSMeta's vector search library.
- Qdrant, Weaviate, Milvus, Chroma, pgvectorVector databases.
- OllamaLocal embedding models (nomic-embed-text, bge-m3).
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)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.
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.
Attention: how tokens talk to each other
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.
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.
| Variant | What changes | Why | Used in |
|---|---|---|---|
| Multi-head (MHA) | Every head has its own Q, K, V | Original design | GPT-2, GPT-3, BERT |
| Multi-query (MQA) | All heads share one K and V | Shrinks the KV cache by the number of heads; faster decoding | PaLM, 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 loss | Llama 2 70B, Llama 3, Mistral, Qwen |
| Multi-head latent (MLA) | K and V compressed into a small latent vector | Very small KV cache for long contexts | DeepSeek V2/V3 and successors |
| Sliding-window / local | Each token attends only to the last W tokens in some layers | Linear cost in those layers | Mistral 7B, Gemma 2/3 (alternating local and global) |
| Sparse / linear attention, state-space hybrids | Approximate or replace full attention | Sub-quadratic cost at very long lengths | Mamba hybrids (Jamba), several 2025–26 long-context models |
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).
- PyTorch scaled_dot_product_attentionPicks FlashAttention or memory-efficient kernels automatically.
- numpyWrite it from scratch once to really understand it.
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)- Azure ND H100 v5 / ND MI300X v5 VMsTraining and serving GPUs.
- Azure Machine LearningManaged training jobs with PyTorch + FlashAttention images.
az ml job create --file train-job.yml # PyTorch image with flash-attn installed- EC2 P5 (H100) / P5e / P6 instancesGPU training and serving.
- AWS Trainium, Inferentia + Neuron SDKAWS's own accelerators.
- SageMaker HyperPodResilient large-scale training clusters.
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()- Cloud TPU (v5e, v5p, Trillium, Ironwood)Google's accelerators.
- JAX / Flax, MaxTextReference LLM training stack on TPUs.
import jax
out = jax.nn.dot_product_attention(q, k, v, is_causal=True)- 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.
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/bf16Attention, 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.
Inside the transformer 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)
The parts, one by one
| Part | What it does | Parameters per layer | Modern 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·d | SwiGLU; or MoE |
| Normalisation | Keeps vector sizes stable so training doesn't diverge | Tiny (2·d) | RMSNorm, applied before each sub-layer (pre-norm) |
| Residual connection | Adds each sub-layer's output to its input; lets gradients flow through 100+ layers | 0 | Always |
| Embedding + unembedding | Token ID ↔ vector; final vector → logits | V·d each (once, not per layer) | Often untied in large models |
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).
Architecture details
What changed between GPT-2 and 2026 models.
GPT-2 (2019) vs a 2025 open model, side by side compare
| Choice | GPT-2 | Typical 2025–26 open model |
|---|---|---|
| Norm | LayerNorm, post→pre | RMSNorm, pre-norm (+ QK-norm in some) |
| Position | Learned absolute (1,024) | RoPE, extended to 128k–1M |
| Attention | MHA | GQA or MLA; some layers sliding-window |
| MLP | GELU, 4·d | SwiGLU; often MoE |
| Vocab | 50k | 128k–260k |
| Biases | Yes | Usually 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.
Pretraining: reading the internet
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.
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.
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.
| Model | Year | Parameters | Training tokens | ≈ Compute |
|---|---|---|---|---|
| GPT-2 | 2019 | 1.5B | ~10B (WebText) | ~10²¹ FLOPs |
| GPT-3 | 2020 | 175B | 300B | 3.1 × 10²³ |
| Chinchilla | 2022 | 70B | 1.4T | 5.8 × 10²³ |
| Llama 2 70B | 2023 | 70B | 2T | 8.4 × 10²³ |
| Llama 3.1 405B | 2024 | 405B | 15.6T | 3.8 × 10²⁵ (reported) |
| DeepSeek-V3 | Dec 2024 | 671B total / 37B active | 14.8T | ~2.8M H800 GPU-hours (reported, final run only) |
| Frontier closed models | 2025–26 | Undisclosed | Undisclosed | Estimated 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.
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.
- 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.
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())- Azure Machine Learning + ND H100 v5 clustersDistributed PyTorch jobs with InfiniBand.
- Azure CycleCloud / AKSSlurm or Kubernetes for large training.
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 }- 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.
srun -N 4 --gpus-per-node 8 torchrun --nnodes 4 --nproc_per_node 8 train.py- Cloud TPU + MaxTextGoogle's open, high-MFU JAX LLM trainer.
- GKE with A3 (H100) / A4 (B200) VMsGPU clusters.
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- 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.
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 minutesPretraining, 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.
Post-training: from document completer to assistant
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.
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
The methods
| Method | How it works | Data needed | What it changes |
|---|---|---|---|
| SFT / instruction tuning | Ordinary next-token training, but only on assistant replies in curated conversations | Thousands 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 model | Tens to hundreds of thousands of comparisons | Helpfulness, tone, refusing harmful requests |
| DPO (2023) | Skip the reward model: directly raise the probability of preferred answers and lower rejected ones | Same preference pairs | Similar 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 feedback | Scales 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 GRPO | Problems with automatic checkers | Long chains of thought, self-checking, backtracking: reasoning models |
| Distillation | Train a smaller model on a bigger model's outputs (or its probability distributions) | Teacher model outputs | Small, 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.
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.
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.
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()- Azure AI Foundry fine-tuningSFT, DPO and reinforcement fine-tuning for supported OpenAI and open models.
- Azure MLCustom LoRA jobs on your own GPUs.
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)- Amazon Bedrock model customizationFine-tune and distil supported models.
- SageMaker JumpStart / HyperPod recipesLoRA and full fine-tuning of open models.
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"})- Vertex AI supervised tuningTune Gemini models with JSONL examples.
- Vertex AI Model GardenLoRA tuning for open models (Gemma, Llama).
from vertexai.tuning import sft
job = sft.train(source_model=BASE_MODEL,
train_dataset="gs://bucket/train.jsonl", epochs=2)- Axolotl, LLaMA-Factory, torchtuneConfig-driven fine-tuning.
- OpenRLHF, verlRLHF, GRPO and RLVR at scale.
- Argilla, Label StudioCollect demonstrations and preferences.
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.0002Post-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.
Inference: picking tokens, fast and cheaply
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.
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
| Strategy | How | Use it for | Watch out |
|---|---|---|---|
| Greedy (temperature 0) | Always take the most likely token | Extraction, classification, code, tests | Can repeat itself; still not perfectly deterministic on GPUs |
| Temperature sampling | Divide logits by T before softmax | Creative writing (0.7–1.0) | High T: nonsense; low T: bland |
| Top-k | Keep only the k most likely tokens | Cutting the long tail of junk | Fixed k is too strict when unsure, too loose when sure |
| Top-p (nucleus, 2019) | Keep the smallest set whose probabilities sum to p | The common default (0.9–0.95) | Interacts with temperature; tune one at a time |
| Min-p | Drop tokens below a fraction of the top token's probability | Open-model creative use at higher T | Not offered by every API |
| Beam search | Keep the best N partial sequences | Translation, older seq2seq | Bland, repetitive for open-ended chat |
| Constrained / structured decoding | Mask tokens that would break a grammar or JSON schema | Guaranteed-valid JSON, function calls | Can hurt quality if the schema fights the content |
| Penalties (repetition, frequency, presence) | Lower logits of tokens already used | Stopping loops in small models | Can 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).
Llama 3 8B, fp16: 2 × 32 × 8 × 128 × 2 = 128 KB per token → 8k tokens ≈ 1 GB · 128k ≈ 16 GB
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.
- Anthropic, OpenAI, Google SDKsHosted models with streaming.
- Hugging Face transformers
generate()with temperature, top_p, top_k.
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))- Azure AI FoundryServerless and provisioned deployments of OpenAI and open models.
- AKS + vLLM / KAITOSelf-host open models on GPU node pools.
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="")- Amazon Bedrock Converse / ConverseStreamOne API across hosted models.
- SageMaker endpoints (LMI containers with vLLM)Self-hosted open models.
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="")- Gemini API / Vertex AIHosted models, streaming, context caching.
- GKE + vLLM or JetStream on TPUSelf-hosted serving.
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="")- 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.
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:8bInference, 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).
Types of language models, in one place
"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.
The wall: what a raw LLM can't do
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.
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
| Limit | Why it happens (from Part II) | What it looks like | The layer that fixes it |
|---|---|---|---|
| Hallucination | The 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, quotes | Context and grounding (Ch 17), verification (Ch 19) |
| Frozen knowledge | Weights are fixed at the knowledge cutoff (Ch 11) | Wrong about recent events, prices, versions; blind to your documents | Retrieval (RAG), search tools |
| Can only talk | Output is tokens; nothing runs unless code acts on them | Tells you how to book a flight instead of booking it | Tools and agents (Ch 18) |
| No memory | Stateless: each request is independent (Ch 6) | Forgets your preferences, last week's chat, the project | Memory as context; state files (Ch 20) |
| Finite, leaky context | Quadratic attention; fixed window; attention spreads thin (Ch 9) | Ignores facts in the middle of long prompts; quality drops as context fills | Context engineering: select, compress, order |
| Unreliable over many steps | Each step has some error rate; errors compound | Starts well, drifts, declares a broken task "done" | Harness checks and loops with verification |
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.
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.
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.
Rung 1 · Prompt engineering: say it better
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.
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).
Summarise this.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>| Technique | What it does | Still useful in 2026? |
|---|---|---|
| Clear task + audience + format | Removes ambiguity | Always the biggest win |
| Few-shot examples | Shows the pattern and style | Yes, especially for formats and edge cases; vary examples to avoid copying |
| Chain of thought | Reasoning written before the answer | Built into reasoning models; still helps non-reasoning models |
| Role / persona | Sets tone and expertise | Mild effect; specifics matter more |
| Structured tags (XML/Markdown) | Separates instructions from data | Yes; also helps against prompt injection |
| "ALL CAPS, YOU MUST" | Shouting emphasis | Often counter-productive in modern models: they over-apply it |
The companion Prompt Engineering Guide covers techniques, templates, system prompts, structured outputs, prompt evaluation and prompt security in depth.
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.
Rung 2 · Context engineering: show it the facts
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.
RAG in one picture
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).
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.
Context, further
What changed when windows got long.
RAG vs long context vs fine-tuning decision
| RAG | Long context | Fine-tuning | |
|---|---|---|---|
| Fresh / changing data | Excellent | Good (re-send) | Poor |
| Huge corpora (millions of docs) | Yes | No | No |
| Citations | Natural | Possible | No |
| Cost per request | Low | High (cache helps) | Lowest |
| Changes style / format | No | Somewhat | Yes |
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.
Rung 3 · Tools and agents: let it act
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.
The agent loop
| When | Step | Why it mattered |
|---|---|---|
| Oct 2022 | ReAct paper (reason + act) | The interleaved think → act → observe pattern every agent uses |
| Feb 2023 | Toolformer (Meta) | Models can learn when to call tools |
| Mar–Apr 2023 | ChatGPT plugins; AutoGPT and BabyAGI go viral | Huge excitement; open-ended agents mostly looped, wandered and burned money |
| Jun 2023 | Function calling in the OpenAI API (others follow) | Structured, reliable tool calls became a standard model feature |
| 2024 | SWE-bench, SWE-agent, Devin; Claude computer use (Oct) | Agents measured on real GitHub issues; models operating GUIs |
| Nov 2024 | Model Context Protocol (MCP), Anthropic | One open standard to connect any tool or data source to any agent |
| 2025 | Claude Code, OpenAI Codex, Gemini CLI, Cursor/Copilot agent modes; agent SDKs; A2A protocol | Agents 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).
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"The Agents Guide covers agent patterns, memory, planning, multi-agent systems and evaluation. The MCP Guide covers the protocol, servers, transports and security.
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.
Rung 4 · Harness engineering: make it reliable
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.
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.
Tell it how
AGENTS.md / CLAUDE.md project rules, skills (SKILL.md) loaded when relevant, examples of good code.
Let it see
Compiler, type checker, tests, linters, browser screenshots, logs: fast, objective feedback after each change.
Stop it
Permission allow-lists, hooks that block rm -rf or secret access, sandboxes, network egress rules, approval gates.
Equip it
Well-named, well-described tools with clear errors; MCP servers; sub-agents with their own context for research or review.
The Harness Engineering Guide covers guides, sensors, hooks, permissions, sandboxes, sub-agents and how to measure a harness.
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).
Rung 5 · Loop engineering: let it run on its own
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.
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
The Loop Engineering Guide covers triggers, stop conditions, verification, state, budgets, loop patterns, the human outer loop and running loops at scale.
Loops, further
The maths that makes loops worth it, and the risk.
Why a verifier turns a weak agent into a strong loop math
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.
Where we stand: October 2026
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.
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)
| Group | Families in use in 2026 | Notes |
|---|---|---|
| Closed frontier labs | OpenAI GPT-5.x series; Google Gemini 3.x; Anthropic Claude (4.x → 5-series: Fable, Opus, Sonnet, Haiku); xAI Grok 4.x | Tiered families (large / balanced / fast); reasoning modes; 1M-token contexts on some tiers |
| Open-weight leaders | DeepSeek V3/V4 and R-series; Alibaba Qwen 3.x; Meta Llama 4; Google Gemma 4; Mistral; Moonshot Kimi; Zhipu GLM; OpenAI gpt-oss | Mostly MoE; licences vary (MIT, Apache 2.0, custom community licences): check before commercial use |
| Small / on-device | Phi, Gemma, Qwen small, Llama small, Apple and Google on-device models | 1–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
| Problem | Status in 2026 |
|---|---|
| Hallucination | Much reduced with retrieval and reasoning; not solved. Verification layers still required. |
| Prompt injection | No complete defence. Architecture (least privilege, isolation, human approval) is the mitigation (Ch 22). |
| Interpretability | Real progress (sparse autoencoder features, circuit tracing), far from fully explaining a frontier model. |
| Evaluation | Benchmarks saturate within months; contamination; agent evals are expensive and noisy. |
| Energy and compute | Data-centre power demand is a public policy issue; efficiency gains compete with growth in use. |
| Continual learning | Models still don't learn from deployment in real time; memory and loops are the workaround. |
| Jobs and skills | Rapid 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.
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
Using LLMs in production: choose, measure, secure, scale
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
| Question | If yes | If no |
|---|---|---|
| Does a small/fast model pass your eval set? | Use it; route only hard cases up | Try a mid-tier, then frontier |
| Is the task multi-step maths, code or planning? | Reasoning model or reasoning mode | Standard model is faster and cheaper |
| Must data stay on your infrastructure? | Open-weight model, self-hosted or in your cloud tenant | Hosted API with suitable data terms |
| Millions of requests a day on one narrow task? | Consider fine-tuning or distilling a small model | Prompting a general model is simpler |
| Images, audio, documents as input? | Multimodal model | Text 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 benchmark | Measures | Caveat |
|---|---|---|
| MMLU / MMLU-Pro | Broad academic knowledge, multiple choice | Saturated at the top; contamination |
| GPQA Diamond | PhD-level science questions | Small set |
| Humanity's Last Exam | Very hard expert questions | Scores move fast with tools and reasoning |
| SWE-bench Verified / Pro | Fixing real GitHub issues | Depends heavily on the agent harness |
| LMArena (Chatbot Arena) | Human preference in blind head-to-head chats | Rewards style and length; can be gamed |
| METR time horizon | Length of tasks agents finish at 50% reliability | Mostly software tasks; wide error bars |
Security: the threats specific to LLMs
| Threat | What happens | Mitigation |
|---|---|---|
| Prompt injection (direct and indirect) | Instructions hidden in user input, web pages, emails or documents override your instructions | Treat all model input as untrusted; least-privilege tools; separate data from instructions; human approval for risky actions; break the lethal trifecta |
| Jailbreaks | Users talk the model out of its safety training | Provider safety layers, input/output classifiers, rate limits, monitoring |
| Data leakage | Secrets or personal data in prompts, logs or outputs | Redact before sending; data-retention settings; access controls on logs |
| Insecure output handling | Model output executed as code, SQL or HTML | Validate and sandbox; parameterised queries; escape output |
| Excessive agency | An agent with broad permissions does damage | Scoped credentials, allow-lists, dry runs, approval gates, audit logs |
| Supply chain / model poisoning | Malicious model weights, MCP servers or packages | Trusted sources, pinned versions, scanning, sandboxed tool servers |
| Denial of wallet | Abuse runs up token costs | Per-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
Scaling an LLM application from 1 user to 1,000,000
Pick a stage
Production details
Things teams learn the hard way.
Cost levers, in order of impact cost
- Right-size the model: routing simple requests to a small model often cuts cost 50–80%.
- Shorter outputs: output tokens cost 3–5× input and dominate latency.
- Prompt caching: stable prefix first; ~90% off cached reads with most providers.
- Trim context: retrieve 5 good passages, not 50.
- Batch APIs: ~50% off for work that can wait hours.
- 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.
The failure catalog: technical and functional problems
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.
Every trade-off, side by side
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… | Use | Why |
|---|---|---|
| Exact calculations | Code, a calculator, SQL | Deterministic and free |
| Fixed-format parsing (dates, IDs) | Regex, parsers | Faster, cheaper, testable |
| Classifying millions of items into a few labels | A small fine-tuned classifier (or embeddings + logistic regression) | 100–1000× cheaper per item; LLM can label the training data |
| Keyword lookup | Search engine / database index | Exact, explainable |
| Tabular predictions (churn, price) | Gradient boosting (XGBoost, LightGBM) | Classic ML still wins on spreadsheets (Ch 2) |
| High-stakes decisions about people | Human judgement with AI as an aid | Accountability, legal requirements, bias risk |
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.
| Term | Definition |
|---|
Sources and further reading
History and foundations
- Turing: Computing Machinery and Intelligence (1950)
- Shannon: A Mathematical Theory of Communication (1948)
- Rumelhart, Hinton, Williams: Learning representations by back-propagating errors (1986)
- Krizhevsky et al.: AlexNet (2012)
- Mikolov et al.: word2vec (2013) · Bahdanau et al.: attention (2014)
- Sutton: The Bitter Lesson (2019)
Transformers and LLMs
- Vaswani et al.: Attention Is All You Need (2017)
- Devlin et al.: BERT (2018) · Brown et al.: GPT-3 (2020)
- Kaplan et al.: Scaling Laws (2020) · Hoffmann et al.: Chinchilla (2022)
- Su et al.: RoFormer / RoPE (2021) · Dao et al.: FlashAttention (2022)
- Meta: The Llama 3 Herd of Models (2024) · DeepSeek-V3 Technical Report (2024)
- Anthropic: In-context learning and induction heads (2022)
- Jay Alammar: The Illustrated Transformer · Karpathy: Let's build GPT
Post-training and inference
- Ouyang et al.: InstructGPT / RLHF (2022) · Bai et al.: Constitutional AI (2022)
- Rafailov et al.: DPO (2023) · DeepSeek-R1 (2025)
- Hu et al.: LoRA (2021) · Dettmers et al.: QLoRA (2023)
- Holtzman et al.: nucleus sampling (2019) · Kwon et al.: vLLM / PagedAttention (2023)
- Leviathan et al.: speculative decoding (2022)
- OpenAI: Why language models hallucinate (2025)
From LLM to agents and loops
- Wei et al.: Chain-of-thought prompting (2022) · Yao et al.: ReAct (2022)
- Lewis et al.: Retrieval-Augmented Generation (2020) · Liu et al.: Lost in the Middle (2023)
- Anthropic: Building effective agents (2024) · Model Context Protocol
- Simon Willison: The lethal trifecta (2025)
- Addy Osmani: Loop engineering (2026) · Geoffrey Huntley: Ralph
- METR: AI time-horizon measurements · Epoch AI: compute and data trends
- OWASP Top 10 for LLM Applications · OpenTelemetry GenAI conventions
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.
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.