Skip to content
ImagineWorld

Mathematical and Computational Foundations

node_idnode-book_building-frontier-llm-from-scratch_chapter-02-mathematical-and-computational-foundations
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num2
chapter_titleMathematical and Computational Foundations
governed_byCORPUS
constitutional_citationCONSTITUTION
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.

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.

SymbolMeaningTypical shape
Bbatch size (sequences per step)scalar
Tsequence length (tokens)scalar
d or d_modelmodel / hidden dimensionscalar
Vvocabulary sizescalar
xa hidden-state tensor(B, T, d)
Wa weight matrix(d_in, d_out)
h, d_headnumber of heads, per-head dimscalar
θall trainable parameters—

Table 2.1 — Notation used throughout the book

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.

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 torch
x = 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, T
y2 = torch.einsum("bti,io->bto", x, W) # identical, axes named
y3 = torch.nn.functional.linear(x, W.T) # what nn.Linear calls
assert 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.

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.

QuantityDefinition (discrete)Role in LLMs
Softmaxpi=ezi/∑jezjp_i = e^{z_i} / \sum_j e^{z_j}turns raw logits into a distribution over the vocabulary
Entropy H(p)H(p)−∑pilog⁡pi-\sum p_i \log p_ithe model’s average uncertainty
Cross-entropy H(p,q)H(p, q)−∑pilog⁡qi-\sum p_i \log q_ithe training loss (q = model, p = data)
KL divergence∑pilog⁡(pi/qi)\sum p_i \log(p_i/q_i)penalty keeping a tuned model near a reference (RLHF, Ch 23)
Perplexityecross-entropye^{\text{cross-entropy}}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 ids
loss = F.cross_entropy(logits.view(-1, logits.size(-1)),
targets.view(-1))
ppl = loss.exp() # perplexity

Python — 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.

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.

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.

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.

OptimizerExtra state / paramIdeaUse in LLMs
SGD0step along the raw gradientrare alone; too unstable at scale
SGD + momentum1accumulate a velocityvision more than language
Adam2adapt rate from 1st/2nd momentsthe historical default
AdamW2Adam with decoupled weight decaythe standard today
Muon / matrix methods1–2orthogonalized momentum updatesemerging 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.

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.

TierSizeBandwidthCharacter
Registers~256 KB / SM~tens of TB/sfastest, tiny, per-thread
Shared memory / L1~256 KB / SM~20+ TB/son-chip, programmer-managed (FlashAttention lives here)
L2 cache~50 MB~10 TB/sshared across the chip
HBM (global)~80 GB~3.4 TB/sthe “GPU memory” you budget; weights and cache live here
NVLink (GPU-GPU)—~0.9 TB/sinter-GPU within a node (Chapter 19)
PCIe / host—~0.06 TB/sGPU-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.

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.

FormatSign/Exp/MantMax magnitudeWhere it is used
FP321/8/23~3.4×10³⁸master weights, accumulation, “ground truth”
TF321/8/10~3.4×10³⁸NVIDIA matmul default; FP32 range, reduced precision
FP161/5/1065,504mixed precision; needs loss scaling (narrow range)
BF161/8/7~3.4×10³⁸the default training dtype; wide range, low precision
FP8 (E4M3)1/4/3448forward activations and weights in FP8 training
FP8 (E5M2)1/5/257,344gradients in FP8 training (more range, less precision)
MXFP44-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.

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 pass
y = w * x + b
loss = (y - t) ** 2
# backward pass: the chain rule, by hand
dL_dy = 2 * (y - t) # d loss / d y
dL_dw = dL_dy * x # dy/dw = x
dL_db = dL_dy * 1 # dy/db = 1

Python — 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.