Mathematical and Computational Foundations
local graph
Chapter 2 — Mathematical and Computational Foundations
Section titled “Chapter 2 — Mathematical and Computational Foundations”You can build a language model with a surprisingly small mathematical toolkit, but you must own that toolkit completely — not as theorems to recite, but as operations you can see happening inside a tensor. This chapter assembles the minimum: the linear algebra every layer is made of, the probability that defines the training objective, the calculus that makes learning possible, and a working mental model of the hardware that runs it all. Nothing here is for its own sake; each idea is chosen because a later chapter depends on it. Readers fluent in these topics can skim, but the notation in Section 2.1 is used throughout the book.
2.1 Linear Algebra for Deep Learning
Section titled “2.1 Linear Algebra for Deep Learning”A neural network is, to first approximation, a sequence of matrix multiplications with nonlinearities wedged between them. Master the matrix multiply and you have mastered most of what a GPU spends its time doing. We will track everything by shape, because shape bugs are the most common error in model code and shape reasoning is how experts read it.
| Symbol | Meaning | Typical shape |
|---|---|---|
| B | batch size (sequences per step) | scalar |
| T | sequence length (tokens) | scalar |
| d or d_model | model / hidden dimension | scalar |
| V | vocabulary size | scalar |
| x | a hidden-state tensor | (B, T, d) |
| W | a weight matrix | (d_in, d_out) |
| h, d_head | number of heads, per-head dim | scalar |
| θ | all trainable parameters | — |
Table 2.1 — Notation used throughout the book
Vectors, matrices, tensors, and shapes
Section titled “Vectors, matrices, tensors, and shapes”A tensor is an n-dimensional array. A token embedding is a vector in Rᵈ; a sequence of T embeddings is a matrix (T, d); a batch of B such sequences is a rank-3 tensor (B, T, d). Every operation in a transformer either mixes information across the d axis (a linear layer, applied independently per position) or across the T axis (attention, which lets positions exchange information). Keeping those two kinds of mixing straight is the conceptual core of Part III.
Matrix multiplication is the atom
Section titled “Matrix multiplication is the atom”A linear layer computes y = xW + b. For input x of shape (B, T, d_in) and weight W of shape (d_in, d_out), the output is (B, T, d_out) — the last axis is transformed, the batch and time axes are carried along. In code, the same operation is clearest with explicit indices via einsum, which names every axis and leaves no ambiguity:
import torchx = torch.randn(8, 128, 512) # (B, T, d_in)W = torch.randn(512, 2048) # (d_in, d_out)
y1 = x @ W # batched matmul, broadcasts over B, Ty2 = torch.einsum("bti,io->bto", x, W) # identical, axes namedy3 = torch.nn.functional.linear(x, W.T) # what nn.Linear callsassert torch.allclose(y1, y2) and torch.allclose(y1, y3)print(y1.shape) # torch.Size([8, 128, 2048])Python — a linear layer, three equivalent ways
The cost of this multiply is 2 · B · T · d_in · d_out floating-point operations (one multiply and one add per output element). That formula, summed over every layer, is the model’s training and inference FLOP budget — the number that decides how many GPUs you need and for how long. We will return to it constantly.
Low-rank structure: the idea behind MLA and LoRA
Section titled “Low-rank structure: the idea behind MLA and LoRA”Any matrix W of shape (m, n) can be approximated by the product of two thin matrices, W ≈ A B with A of shape (m, r) and B of shape (r, n) for some rank r < min(m, n). When r is small, this stores and computes far less: r(m+n) numbers instead of mn. The singular value decomposition (SVD) tells you the best such approximation for a given rank. This single idea reappears in two pillars of the book: LoRA (Chapter 20) freezes W and learns a low-rank update A B, making fine-tuning cheap; and Multi-head Latent Attention (Chapter 12) compresses the keys and values into a low-rank latent so the inference cache shrinks by an order of magnitude. Recognizing low-rank structure when you see it is a recurring “aha” of modern LLM design.
2.2 Probability and Information Theory
Section titled “2.2 Probability and Information Theory”A language model is a probability distribution over the next token. Training it is maximum-likelihood estimation; evaluating it is measuring surprise. A few quantities, in Table 2.2, carry the whole story.
| Quantity | Definition (discrete) | Role in LLMs |
|---|---|---|
| Softmax | turns raw logits into a distribution over the vocabulary | |
| Entropy | the model’s average uncertainty | |
| Cross-entropy | the training loss (q = model, p = data) | |
| KL divergence | penalty keeping a tuned model near a reference (RLHF, Ch 23) | |
| Perplexity | headline pretraining metric; “effective branching factor” |
Table 2.2 — The information-theoretic quantities a language model lives by
The connection from likelihood to loss is direct. The model assigns probability q(xₜ | x<t) to each true next token. Maximizing the log-likelihood of the data is the same as minimizing the average negative log-probability — which is exactly cross-entropy with the one-hot true token. So “predict the next token well” and “minimize cross-entropy” are the same sentence said two ways. In code it is a single call:
import torch.nn.functional as F# logits: (B, T, V) ; targets: (B, T) integer token idsloss = F.cross_entropy(logits.view(-1, logits.size(-1)), targets.view(-1))ppl = loss.exp() # perplexityPython — the language-modeling loss is one line
Perplexity deserves a sentence of intuition: a perplexity of 10 means the model is, on average, as uncertain as if it were choosing uniformly among 10 equally likely next tokens. Lower is better; a strong model on English web text reaches single digits. Because perplexity depends on the tokenizer, it is only comparable across models that share one — a caveat we revisit when we evaluate models in Chapter 29.
2.3 Calculus and Optimization
Section titled “2.3 Calculus and Optimization”Training is the repeated application of one idea: nudge every parameter a little in the direction that reduces the loss. The “direction” is the negative gradient, and computing it efficiently for billions of parameters is what backpropagation does.
Gradients and the chain rule
Section titled “Gradients and the chain rule”The gradient ∇θ L is the vector of partial derivatives of the loss with respect to each parameter; it points in the direction of steepest increase, so we step the other way. A neural network is a composition of functions, and the chain rule says the derivative of a composition is the product of the derivatives of its parts. Backpropagation is simply the chain rule applied in reverse over the computational graph: a forward pass computes outputs and caches intermediates, then a backward pass multiplies local derivatives from the loss back to every parameter, reusing shared sub-results so the whole thing costs about as much as one extra forward pass. Chapter 3 builds a working autograd engine that does exactly this in a few dozen lines, so the mechanism never feels like magic.
The optimizers that train language models
Section titled “The optimizers that train language models”Plain gradient descent is too noisy and ill-conditioned for models this large. In practice almost every LLM is trained with Adam or its variant AdamW, which adapts a per-parameter learning rate from running estimates of the gradient’s mean and variance. Table 2.3 compares the options and their memory cost — a cost that matters, because optimizer state can equal or exceed the size of the model itself.
| Optimizer | Extra state / param | Idea | Use in LLMs |
|---|---|---|---|
| SGD | 0 | step along the raw gradient | rare alone; too unstable at scale |
| SGD + momentum | 1 | accumulate a velocity | vision more than language |
| Adam | 2 | adapt rate from 1st/2nd moments | the historical default |
| AdamW | 2 | Adam with decoupled weight decay | the standard today |
| Muon / matrix methods | 1–2 | orthogonalized momentum updates | emerging in recent large runs |
Table 2.3 — Optimizers and their per-parameter state
“State / param” counts optimizer tensors the same size as the weights. AdamW at 2 means a model with N parameters needs roughly 2N extra values in the optimizer (plus gradients), in addition to the weights — which is why memory budgeting (Section 2.4 and Chapter 17) is unavoidable.
Two practical knobs ride alongside the optimizer and decide whether a large run converges at all: the learning-rate schedule (a warmup followed by a decay — cosine, or the warmup-stable-decay schedule popularized for large models) and gradient clipping (capping the gradient norm to survive the occasional loss spike). Both get their own treatment in Chapter 17; mention them here only so the vocabulary is in place.
2.4 The Compute Stack
Section titled “2.4 The Compute Stack”Models run on accelerators whose defining feature is enormous arithmetic throughput sitting behind comparatively scarce memory bandwidth. Understanding that imbalance is the difference between code that uses 10% of a GPU and code that uses 50%.
The memory hierarchy and why bandwidth is destiny
Section titled “The memory hierarchy and why bandwidth is destiny”A modern GPU has a steep memory hierarchy (Table 2.4). Computation is fast; moving data is slow. Whether an operation is compute-bound (limited by arithmetic) or memory-bound (limited by data movement) determines how to optimize it — and most of inference, dominated by reading weights and the KV cache, is memory-bound. This is the single fact that motivates GQA, MLA, FlashAttention, and quantization later in the book.
| Tier | Size | Bandwidth | Character |
|---|---|---|---|
| Registers | ~256 KB / SM | ~tens of TB/s | fastest, tiny, per-thread |
| Shared memory / L1 | ~256 KB / SM | ~20+ TB/s | on-chip, programmer-managed (FlashAttention lives here) |
| L2 cache | ~50 MB | ~10 TB/s | shared across the chip |
| HBM (global) | ~80 GB | ~3.4 TB/s | the “GPU memory” you budget; weights and cache live here |
| NVLink (GPU-GPU) | — | ~0.9 TB/s | inter-GPU within a node (Chapter 19) |
| PCIe / host | — | ~0.06 TB/s | GPU-CPU; avoid on the hot path |
Table 2.4 — Approximate memory hierarchy of a data-center GPU (H100-class)
Figures are order-of-magnitude and vary by GPU. The two lessons that never change: keep data as high in the hierarchy as possible, and minimize trips down to HBM and across PCIe.
Arithmetic intensity and the roofline
Section titled “Arithmetic intensity and the roofline”A useful predictor is arithmetic intensity: the number of floating-point operations performed per byte of memory traffic. The roofline model plots achievable performance against intensity: below a threshold you are memory-bound (a sloped roof), above it compute-bound (a flat roof at peak FLOP/s). Large matrix multiplications with big batches have high intensity and approach the compute roof; token-by-token decoding has low intensity and slams into the memory roof. The whole inference-optimization literature — batching, paging, speculative decoding, MLA — is a campaign to raise arithmetic intensity. We make this quantitative in Chapters 27 and 28.
Numerical precision: the formats that make training affordable
Section titled “Numerical precision: the formats that make training affordable”Every number in a model is stored in a floating-point format with a fixed budget of bits split between exponent (range) and mantissa (precision). The industry’s move from 32-bit to 16-bit to 8-bit formats is one of the largest sources of efficiency in recent years, and DeepSeek-V3’s native FP8 training (Chapter 18) is a centerpiece of this book. Table 2.5 lays out the formats you will meet.
| Format | Sign/Exp/Mant | Max magnitude | Where it is used |
|---|---|---|---|
| FP32 | 1/8/23 | ~3.4×10³⁸ | master weights, accumulation, “ground truth” |
| TF32 | 1/8/10 | ~3.4×10³⁸ | NVIDIA matmul default; FP32 range, reduced precision |
| FP16 | 1/5/10 | 65,504 | mixed precision; needs loss scaling (narrow range) |
| BF16 | 1/8/7 | ~3.4×10³⁸ | the default training dtype; wide range, low precision |
| FP8 (E4M3) | 1/4/3 | 448 | forward activations and weights in FP8 training |
| FP8 (E5M2) | 1/5/2 | 57,344 | gradients in FP8 training (more range, less precision) |
| MXFP4 | 4-bit, block-scaled | — | weight quantization for inference (e.g., gpt-oss) |
Table 2.5 — Floating-point formats in modern training and inference
BF16 trades mantissa bits for FP32’s exponent range, which is why it rarely overflows and has become the workhorse. FP8 halves memory and doubles math throughput again but demands careful scaling — the subject of Chapter 18.
With the mathematics, the objective, the optimizer, and the hardware in view, we have the vocabulary the rest of the book speaks. The next chapter turns it into running code: tensors, a hand-built autograd engine, and a training loop you can read end to end.
2.5 Backpropagation by Hand
Section titled “2.5 Backpropagation by Hand”Every model in this book learns by gradient descent, and every gradient comes from backpropagation — which is nothing more than the chain rule applied systematically. The idea is clearest on an example small enough to differentiate by hand. Take a single linear neuron with a squared-error loss:
# forward passy = w * x + bloss = (y - t) ** 2
# backward pass: the chain rule, by handdL_dy = 2 * (y - t) # d loss / d ydL_dw = dL_dy * x # dy/dw = xdL_db = dL_dy * 1 # dy/db = 1Python — grad/byhand.py: forward and backward for one neuron
Read the backward pass right to left. The loss depends on y, so we first compute how the loss changes with y — that is dL_dy. Then y depends on w and b, so we multiply dL_dy by how y changes with each: by x for the weight, by one for the bias. The gradient with respect to each parameter is a product of local derivatives chained back from the loss — which is the entire principle, no matter how deep the network. A real model simply has thousands of these chained steps, and the only thing that changes is that we let the computer track them automatically rather than writing each by hand. That automation is exactly what the autograd engine of Chapter 3 provides: you specify the forward computation, and it constructs and traverses this backward chain for you, across millions of parameters, every training step.
Backprop is the chain rule, bookkept The gradient of the loss with respect to any parameter is a product of local derivatives chained back from the loss. One neuron makes it visible; a deep network is the same rule applied thousands of times, which autograd tracks automatically.