Shelves / AI and ML Foundations
AI·156
Large Language Models
What an LLM is and how it produces text, end to end: the pipeline from text to tokens, embeddings, Transformer, logits, probabilities and decoding; next-token prediction as the training objective and why it teaches so much; perplexity; a character-level language model built from counting and then trained as a tiny Transformer; the context window and what fills it; prefill and decode phases, the KV cache and why output tokens dominate latency; in-context learning and prompting; base, instruct and reasoning models; mixture-of-experts and model sizes; capabilities and characteristic failure modes (hallucination, knowledge cutoffs, sycophancy, prompt sensitivity); and how engineers access models through APIs and open weights from Python, TypeScript, Java, Go and Rust.
Start here: a language model is a next-token guesser
A large language model (LLM) does one thing: given a sequence of tokens, it outputs a probability for every possible next token. Text generation is just repeating that: pick a next token, append it, ask again. Training is the Start Here chapter's recipe with a different loss: at every position of every training text, how much probability did the model give to the token that actually came next? (The loss is the average of −log of that probability, the cross-entropy.) Because the labels come from the text itself, this needs no human labelling, and it scales to trillions of tokens.
Training a tiny one
Model: 4 Transformer blocks, width 192, 6 attention heads, a 128-token context, a 2,048-token BPE vocabulary; 2,197,632 parameters. Trained for 1,200 steps of 32 sequences × 128 tokens:
untrained: validation loss 7.651 (a uniform guess over 2,048 tokens is ln 2048 = 7.625)
step 100: 5.744
step 300: 5.141
step 600: 4.632
step 1,000: 4.261
step 1,200: 4.227 (612 seconds)
Baselines on the same validation text:
always predict each token's overall frequency (unigram): 6.519
predict from the previous token only (bigram, add-one): 4.985
the tiny GPT (128 tokens of context): 4.227
The model beat a bigram model, so it had learned to use more than the previous token. Its perplexity (e^loss) of 68.5 means it was, on average, about as uncertain as choosing among 68 equally likely tokens; a good large model on ordinary English is in the single digits. In characters, 4.227 nats per token is about 2.1 bits per character.
What it produces
Prompt "A cache stores", most-likely token each time (greedy decoding):
A cache stores the same programs (chapter 21). Experiment 3: the same programming the same programming …
It has learned the textbook's surface habits: chapter references, "Experiment 3:", list bullets, technical-sounding words. It hasn't learned what a cache is: there's far too little data and capacity for that. Scale (chapter 158) is what turns this mechanism into something useful.
From text to probabilities, end to end
text → tokenizer → token IDs → embeddings (+ positions) → N Transformer blocks → final layer norm
→ output layer (vocabulary-sized scores, "logits") → softmax → probability of every next token
The output layer here reuses the embedding matrix (weight tying), a common trick that saves parameters: 2,048 × 192 = 393,216 of the 2.2 million.
How deep to go in large language models
Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.
| Level | What you can do |
|---|---|
| L1 | Explain next-token prediction, tokens, context windows and why LLMs hallucinate |
| L2 | Use LLM APIs well: prompts, context, token budgets, temperature, structured output |
| L3 | Explain the full pipeline (tokenizer → Transformer → logits → decoding), loss, perplexity and KV caching |
| L4 | Train and evaluate a small LM; diagnose training curves, overfitting and data issues |
| L5 | Choose models, context strategies and serving setups for products (with Volumes 14b and 15) |
| L6 | Train and serve foundation models at scale |
The pipeline
The roadmap's one-line summary of every LLM interaction:
text → tokenizer → token IDs → embeddings → Transformer → logits → decoding → output
Every capability of a chat model (answering, summarising, coding, calling tools, "reasoning") is produced by this loop: predict a distribution over the next token, pick one, append, repeat.
Next-token prediction
The objective
Given a training text of tokens x₁ … x_T, the model is trained to maximise the probability of each next token given the previous ones (the chain rule of probability, chapter 147):
log P(x₁ … x_T) = Σₜ log P_θ(xₜ | x₁ … xₜ₋₁)
Loss = average cross-entropy over positions = −(1/T) Σ log P_θ(xₜ | x₍<t₎). The causal mask lets one forward pass compute all T predictions in parallel (chapter 154).
Why such a simple objective teaches so much
To predict the next token of arbitrary internet text, code, maths and books well, it helps to model grammar, facts ("The capital of France is" → " Paris"), styles, reasoning patterns ("therefore x =" → the right value), code semantics, and the intentions of writers. Prediction is compression; compressing the world's text rewards representing the structure behind it. This is self-supervised: the labels are just the next tokens, so training can use trillions of tokens without annotation.
Perplexity
Perplexity = exp(average cross-entropy in nats): the effective number of equally likely choices per token. Lower is better. A model with loss 2.0 has perplexity e² ≈ 7.4. Perplexity is comparable only between models with the same tokenizer on the same data; for different tokenizers use bits per byte (or per character).
A language model from counting
The simplest language model is a bigram model: P(next | current) estimated from counts. It shows the full loop (probabilities → sampling → text) without any neural network:
import numpy as np
text = ( # any text file works; a toy corpus here
"to be or not to be that is the question whether tis nobler in the mind to suffer "
"the slings and arrows of outrageous fortune or to take arms against a sea of troubles ") * 50
chars = sorted(set(text)); stoi = {c: i for i, c in enumerate(chars)}; itos = dict(enumerate(chars))
V = len(chars)
counts = np.ones((V, V)) # add-one smoothing
for a, b in zip(text, text[1:]):
counts[stoi[a], stoi[b]] += 1
P = counts / counts.sum(1, keepdims=True) # P[i, j] = P(next=j | current=i)
ids = np.array([stoi[c] for c in text])
nll = -np.mean(np.log(P[ids[:-1], ids[1:]]))
round(nll, 3), round(np.exp(nll), 2) # loss ≈ 1.6 nats; perplexity ≈ 4.9 vs 20 for uniform guessing over V = 20
rng = np.random.default_rng(0)
c = stoi["t"]; out = ["t"]
for _ in range(60):
c = rng.choice(V, p=P[c]); out.append(itos[c])
"".join(out) # locally plausible, globally meaningless
A bigram model sees one character of context. Neural language models replace the count table with a network that conditions on thousands of previous tokens. Training the GPT from chapter 154 on the same text:
import torch, torch.nn.functional as F
torch.manual_seed(0)
data = torch.tensor(ids, dtype=torch.long)
model = GPT(vocab=V, d=64, layers=2, n_heads=4, n_kv_heads=2, max_len=128) # class from chapter 154
opt = torch.optim.AdamW(model.parameters(), lr=3e-3)
block, batch = 64, 32
for step in range(301):
ix = torch.randint(0, len(data) - block - 1, (batch,))
x = torch.stack([data[i:i + block] for i in ix]); y = torch.stack([data[i + 1:i + block + 1] for i in ix])
_, loss = model(x, y)
opt.zero_grad(); loss.backward(); opt.step()
if step % 100 == 0: print(step, round(loss.item(), 3))
# step 0 ≈ 3.0 (ln 20), then falls far below the bigram's ≈ 1.6: with 64 characters of context
# the model memorises this repetitive text almost perfectly.
@torch.no_grad()
def generate(model, prompt, n=80, temperature=0.8):
x = torch.tensor([[stoi[c] for c in prompt]])
for _ in range(n):
logits, _ = model(x[:, -128:]) # crop to the context window
probs = F.softmax(logits[0, -1] / temperature, dim=-1) # last position → next-token distribution
nxt = torch.multinomial(probs, 1)
x = torch.cat([x, nxt[None]], dim=1)
return "".join(itos[i] for i in x[0].tolist())
generate(model, "to be ")
Real LLMs are the same program with a vastly larger model (billions of parameters), a learned subword tokenizer (chapter 155), trillions of diverse tokens, careful data curation, and post-training (chapter 158).
Logits, probabilities and the output distribution
At each step the model outputs a vector of logits z ∈ ℝ^V for the last position; softmax turns them into probabilities. Engineering-relevant facts:
- Most probability mass is often on a handful of tokens; the long tail contains many low-probability, often nonsensical options. Decoding strategies (chapter 157) decide how to sample from this distribution.
- Log-probabilities of generated tokens (exposed by many APIs as
logprobs) are useful for confidence estimates, classification by comparing label likelihoods, detecting uncertain spans, and evaluation. - A model's probabilities are only roughly calibrated, and post-training (RLHF) tends to make chat models over-confident.
- Constrained decoding masks logits so that only tokens valid under a grammar or JSON schema can be chosen (chapter 167).
The context window
The context window is the maximum number of tokens (input + generated output) the model processes at once: from 2k (GPT-3, 2020) to 128k–1M+ in current models.
What fills it in a real application:
- The model is stateless between requests: "memory" in chat apps is the application re-sending history (or summaries, or retrieved memories: chapter 170).
- Longer contexts cost more (input tokens), add latency (prefill), and dilute attention; place the most important instructions clearly (start or end) and test.
- The model's knowledge cutoff is fixed at training time; anything newer must be supplied in context (RAG, tools, search).
How inference runs
Generation has two phases:
| Phase | What happens | Bound by | Metric |
|---|---|---|---|
| Prefill | Process all prompt tokens in parallel, filling the KV cache | Compute (large matmuls) | Time to first token (TTFT) |
| Decode | Generate one token at a time; each step attends to the cached keys/values | Memory bandwidth (read all weights + KV cache per token) | Time per output token (TPOT), tokens/second |
- The KV cache stores each layer's keys and values for all previous tokens so each decode step computes attention only for the new token (chapter 154's sizing formula).
- Decoding a token requires reading every weight once: a 70B model in bf16 (140 GB) on GPUs with ~3 TB/s aggregate bandwidth can't exceed roughly 20 tokens/s per sequence; serving systems batch many sequences per step to use the hardware (chapter 166).
- This is why output tokens cost more and dominate latency, and why streaming responses token by token improves perceived speed.
Using the model: in-context learning and prompting
Large models can perform new tasks from instructions and examples given in the prompt, without weight updates: in-context learning (GPT-3 paper, 2020).
- Zero-shot: instructions only.
- Few-shot: a few input/output examples, showing format and edge cases.
- Chain of thought: asking for (or training for) intermediate reasoning steps improves multi-step problems; reasoning models do this internally (below).
- Structure helps: clear roles, delimited inputs (XML tags, Markdown sections), explicit output formats, stating what to do when information is missing.
Prompting is the first tool to reach for; retrieval, tools and fine-tuning come next (chapter 158 compares them).
Kinds of models
| Kind | What it is | Use |
|---|---|---|
| Base (pre-trained) model | Next-token predictor on raw data; continues text | Research, fine-tuning starting point, completion tasks |
| Instruct / chat model | Post-trained to follow instructions and converse safely (SFT + preference optimisation) | Most applications |
| Reasoning model | Trained (often with reinforcement learning on verifiable tasks) to produce extended internal reasoning before answering; budget controllable | Maths, code, planning, agents; higher latency and cost per answer |
| Multimodal model | Accepts (and sometimes generates) images, audio, video | Documents, screenshots, voice (chapter 173) |
| Embedding model | Encoder producing vectors, not text | Search and RAG (chapter 159) |
| Small / distilled models | 1–15B parameters, often distilled from larger ones | Low latency, on-device, high volume, fine-tuning |
Dense vs mixture-of-experts: a dense model uses all parameters for every token; an MoE model (chapter 153) has many more total parameters but activates only a fraction per token (e.g. hundreds of billions total, tens of billions active), giving more capacity per unit of compute, at the cost of memory to hold all experts.
Open weights vs API: open-weight models (Llama, Qwen, Mistral, Gemma, DeepSeek, gpt-oss and others) can be self-hosted, fine-tuned and inspected; frontier API models (Claude, GPT, Gemini families) are typically more capable and need no infrastructure but run on the provider's systems under their terms.
Capabilities and failure modes
LLMs are strong at language understanding and generation, summarisation, translation, extraction, classification, coding, and (with reasoning training and tools) multi-step problem solving. Know their characteristic failures:
- Hallucination / confabulation: fluent, confident, wrong statements, especially about specific facts, citations, numbers, rare entities, or when the answer isn't in context. Mitigate with grounding (RAG), tools, citations, asking the model to say when it doesn't know, and verification (chapter 175).
- Knowledge cutoff and staleness.
- Arithmetic, counting and exact string operations (tokenisation, chapter 155): use tools.
- Prompt sensitivity: small wording or ordering changes alter outputs; evaluate across variations.
- Sycophancy: agreeing with the user's stated view or framing; ask for critique explicitly, avoid leading questions.
- Long-context degradation and "lost in the middle".
- Non-determinism: sampling and even batched floating-point arithmetic make outputs vary run to run.
- Prompt injection: instructions hidden in retrieved documents, emails or web pages can hijack behaviour (chapter 176).
- Bias reflecting training data; safety training reduces but doesn't remove it.
Accessing models
# Python: provider SDKs (anthropic, openai, google-genai) or open models via transformers / vLLM
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
msg = client.messages.create(
model="claude-sonnet-5-5", max_tokens=400,
system="Answer in two sentences.",
messages=[{"role": "user", "content": "Why do output tokens cost more than input tokens?"}],
)
print(msg.content[0].text, msg.usage.input_tokens, msg.usage.output_tokens)
// TypeScript: official SDKs; stream tokens to the UI as they're generated
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
const stream = client.messages.stream({
model: "claude-sonnet-5-5", max_tokens: 400,
messages: [{ role: "user", content: "Explain the KV cache in one paragraph." }],
});
for await (const event of stream) {
if (event.type === "content_block_delta" && event.delta.type === "text_delta") process.stdout.write(event.delta.text);
}
// Java: Spring AI 2.x ChatClient (provider-agnostic), or LangChain4j
@RestController
class AskController {
private final ChatClient chat;
AskController(ChatClient.Builder builder) { this.chat = builder.defaultSystem("Answer concisely.").build(); }
@GetMapping("/ask")
String ask(@RequestParam String q) { return chat.prompt().user(q).call().content(); }
}
// Go: official SDKs exist for major providers; plain HTTP + JSON works everywhere
client := anthropic.NewClient() // github.com/anthropics/anthropic-sdk-go
msg, err := client.Messages.New(ctx, anthropic.MessageNewParams{
Model: "claude-sonnet-5-5",
MaxTokens: 400,
Messages: []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock("What is perplexity?"))},
})
// Rust: run open-weight models locally with candle or mistral.rs, or call HTTP APIs with reqwest
let body = serde_json::json!({
"model": "claude-sonnet-5-5", "max_tokens": 400,
"messages": [{"role": "user", "content": "What is perplexity?"}]
});
let resp: serde_json::Value = reqwest::Client::new()
.post("https://api.anthropic.com/v1/messages")
.header("x-api-key", std::env::var("ANTHROPIC_API_KEY")?)
.header("anthropic-version", "2023-06-01")
.json(&body).send().await?.json().await?;
Model identifiers, prices and limits change frequently; read them from configuration rather than hard-coding, and consult the provider's current documentation.
Lab: training a tiny GPT on a laptop CPU
PyTorch 2.14.1 on the lab machine (2 CPU threads). Honest scope: the lab can't download pretrained models, so everything is trained from scratch; the result shows mechanisms, not capabilities.
- Data: this textbook's chapters (all volumes except Volume 10, quizzes and code removed), tokenized with chapter 155's 2,048-token byte-level BPE: 1,761,063 tokens, last 5% (88,054 tokens) for validation.
- Model (
gpt.py, about 40 lines): token + learned position embeddings; 4 pre-LN blocks (scaled_dot_product_attention(is_causal=True), GELU MLP 4×); final LayerNorm; output layer tied to the embedding; weights initialised N(0, 0.02). - Training: AdamW (lr 3e-3, weight decay 0.1), 50-step warm-up then cosine decay, gradient clipping at 1.0, batch 32 × 128 tokens (4,096 tokens per step), 1,200 steps ≈ 4.9 million tokens ≈ 2.9 epochs.
Experiment 1: the training curve
| Step | Validation loss | Elapsed |
|---|---|---|
| 0 | 7.651 | 3 s |
| 100 | 5.744 | 52 s |
| 200 | 5.416 | 106 s |
| 400 | 4.928 | 213 s |
| 600 | 4.632 | 312 s |
| 800 | 4.396 | 412 s |
| 1,000 | 4.261 | 512 s |
| 1,200 | 4.227 | 612 s |
A bug found on the way: the first version left PyTorch's default nn.Embedding initialisation (N(0, 1)) with tied output weights, and the untrained loss was 126.5, not 7.6, because logits came out enormous. The N(0, 0.02) initialisation used by GPT-2 fixed it. "Does the initial loss equal ln(vocabulary size)?" is the first sanity check for any language model. A second, operational lesson: an earlier, un-killed copy of the training script was sharing the CPU and the log file, which doubled step times and interleaved log lines; check ps before trusting timings.
Experiment 2: baselines and units
| Model | Validation loss (nats/token) |
|---|---|
| uniform | 7.625 |
| unigram frequencies (add-one) | 6.519 |
| bigram (add-one smoothing) | 4.985 |
| tiny GPT | 4.227 |
Validation text is 254,987 characters for 88,054 tokens (0.345 tokens per character), so 4.227 nats/token = 2.11 bits per character, and perplexity e^4.227 = 68.5. Compare models with different tokenizers in bits per character (or per byte), never in per-token loss: a bigger vocabulary makes each token harder to predict while needing fewer of them. The add-one bigram is a weak baseline (better smoothing such as Kneser–Ney would do better); the point is the gap a Transformer opens when it can use 128 tokens of context.
Experiment 3: what the curve says
Loss was still falling at step 1,200 but flattening as the cosine schedule wound the learning rate down; with ~3 passes over a small dataset, longer training would soon overfit (validation loss rising while training loss keeps falling, chapter 152). Large-model training runs avoid repeating data much at all: they use trillions of tokens and see most of them once, which is why data quantity and quality (chapter 158) dominate the recipe.
Try it yourself
- Train for 2,400 and 4,800 steps and plot training and validation loss. When does overfitting begin?
- Remove weight tying and compare parameter count and final validation loss.
- Implement a KV cache in
generate(store each block's keys and values, feed only the new token) and measure tokens per second at 1,000 generated tokens with ctx = 512. - Retrain with the 8,192-token tokenizer and compare in bits per character.
Revision sheet: large language models
Key ideas
- Pipeline: tokenizer → embeddings → decoder-only Transformer → logits → softmax → decoding.
- Objective: next-token cross-entropy over huge corpora (self-supervised); perplexity = e^loss; compare across tokenizers in bits per byte/character.
- Context window: maximum tokens attended; cost grows with length (attention O(n²), KV cache memory O(n)).
- Inference: prefill (process the prompt in parallel) then decode (one token at a time, reusing the KV cache); decode is memory-bandwidth-bound.
- Behaviour: models predict plausible continuations; hallucination is fluent text unsupported by facts; knowledge is frozen at the training cut-off.
- After pre-training: instruction tuning and preference optimisation turn a text predictor into an assistant (chapter 158).
- Sanity checks: initial loss ≈ ln V; loss falls smoothly; validation tracks training.
Numbers to remember
- Lab: 2.2 M parameters, 1.76 M tokens, 10 minutes on 2 CPU cores: validation loss 7.65 → 4.23 (perplexity 68.5, 2.11 bits/char).
- Lab: bigram baseline 4.985; unigram 6.519.
- Lab: default N(0,1) embeddings with tied weights gave an initial loss of 126.5.
Pitfalls
- Comparing per-token losses across different tokenizers.
- Treating fluent output as factual.
- Skipping the initial-loss sanity check.
- Repeating a small dataset for many epochs (memorisation).
- Ignoring KV-cache memory when planning context length and batch size.
Glossary
- Autoregressive: generating one token at a time conditioned on previous ones.
- Perplexity: exponentiated average cross-entropy.
- Prefill / decode: prompt processing / token-by-token generation phases.
- KV cache: stored keys and values of previous tokens.
- Hallucination: confident output not grounded in facts or sources.