Free guide73 formulas in 20 sections

The math behind large language models

From byte-pair encoding to speculative decoding, in the order a model uses it. Each formula has a plain explanation, where an LLM uses it, a NumPy snippet that runs and the paper it came from.

01 text becomes integers

Tokenization and byte-pair encoding

A model never sees letters. It sees integer ids from a fixed vocabulary, built by merging frequent pairs of symbols.

1.1The BPE merge rule

(a∗,b∗)=arg⁡max⁡(a,b)count⁡(a b)a∗b∗→new symbol(a^{*}, b^{*}) = \arg\max_{(a,b)} \operatorname{count}(a\,b) \qquad a^{*}b^{*} \to \text{new symbol}
What it means
Count every adjacent pair of symbols in the training text, merge the most frequent pair into one new symbol, and repeat.
Where an LLM uses it
Training a tokenizer. At inference the learned merges are replayed in the same order on new text.
Example
On "low lower lowest" the pair (l, o) is the most frequent first, so "lo" becomes one symbol, then (lo, w) becomes "low".
python
from collections import Counter

def bpe_merge_step(words):
    # words: list of tuples of symbols
    pairs = Counter(p for w in words for p in zip(w, w[1:]))
    a, b = max(pairs, key=pairs.get)
    out = []
    for w in words:
        i, new = 0, []
        while i < len(w):
            if i < len(w) - 1 and (w[i], w[i + 1]) == (a, b):
                new.append(a + b); i += 2
            else:
                new.append(w[i]); i += 1
        out.append(tuple(new))
    return (a, b), out

words = [tuple("low"), tuple("lower"), tuple("lowest")]
pair, words = bpe_merge_step(words)
print(pair, words[0])  # ('l', 'o') ('lo', 'w')

1.2Vocabulary size

∣V∣=∣V0∣+k|V| = |V_0| + k
What it means
Every merge adds one symbol, so the vocabulary is the base alphabet plus the number of merges k (plus any special tokens).
Where an LLM uses it
Choosing vocabulary size trades sequence length against the size of the embedding and output matrices.
Example
GPT-2: 256 byte symbols + 50,000 merges + 1 end-of-text token = 50,257 tokens.
python
def vocab_size(base=256, merges=50_000, special=1):
    return base + merges + special

print(vocab_size())  # 50257

1.3Autoregressive factorization

p(x1,…,xT)=∏t=1Tp(xt∣x<t)p(x_1,\dots,x_T) = \prod_{t=1}^{T} p(x_t \mid x_{<t})
What it means
The probability of a whole sequence is the product of next-token probabilities. This is just the chain rule of probability.
Where an LLM uses it
It is the entire job of a decoder-only LLM: predict the next token given everything before it, then repeat.
python
import numpy as np

def sequence_logprob(next_token_probs):
    # probability the model gave each actual next token
    return float(np.sum(np.log(next_token_probs)))

print(sequence_logprob([0.5, 0.25, 0.8]))  # log(0.1) = -2.302...

02 ids become vectors

Embeddings

Each token id picks one row of a learned matrix. Everything after this point is linear algebra on those rows.

2.1Embedding lookup

xt=E[ it ]=eit⊤E,E∈R∣V∣×d\mathbf{x}_t = E[\,i_t\,] = \mathbf{e}_{i_t}^{\top} E, \qquad E \in \mathbb{R}^{|V| \times d}
What it means
The embedding of token id i is row i of E. Multiplying a one-hot vector by E gives the same row, which is why the lookup is differentiable.
Where an LLM uses it
The first layer of every LLM. Only the rows of tokens in the batch get a gradient.
python
import numpy as np

rng = np.random.default_rng(0)
V, d = 10, 4
E = rng.normal(size=(V, d))
ids = np.array([3, 7, 3])
x = E[ids]                   # (3, d)
one_hot = np.eye(V)[ids]
assert np.allclose(x, one_hot @ E)

2.2Embedding scale

xt←dmodel  xt\mathbf{x}_t \leftarrow \sqrt{d_{\text{model}}}\;\mathbf{x}_t
What it means
The original Transformer multiplies embedding weights by the square root of the model width before adding positional encodings.
Where an LLM uses it
Keeps token embeddings on a similar scale to the sinusoidal position signal. Many later models drop it and rely on normalization.
python
import numpy as np

def scaled_embed(E, ids, d_model):
    return E[ids] * np.sqrt(d_model)

2.3Weight tying

logitst=htE⊤∈R∣V∣\text{logits}_t = \mathbf{h}_t E^{\top} \in \mathbb{R}^{|V|}
What it means
The same matrix E that turns ids into vectors turns the final hidden state back into one score per vocabulary token.
Where an LLM uses it
Saves |V| x d parameters and often improves perplexity. GPT-2 and the original Transformer tie them.
python
import numpy as np

def tied_logits(h, E):
    # h: (T, d), E: (V, d)
    return h @ E.T            # (T, V)

2.4Cosine similarity

cos⁡(u,v)=u⋅v∥u∥ ∥v∥\cos(\mathbf{u},\mathbf{v}) = \frac{\mathbf{u}\cdot\mathbf{v}}{\lVert\mathbf{u}\rVert\,\lVert\mathbf{v}\rVert}
What it means
The angle between two vectors, ignoring their length. 1 is the same direction, 0 is unrelated, -1 is opposite.
Where an LLM uses it
Comparing embeddings for retrieval and search, and inspecting what a model has learned.
python
import numpy as np

def cosine(u, v):
    return float(u @ v / (np.linalg.norm(u) * np.linalg.norm(v)))

print(cosine(np.array([1., 0.]), np.array([1., 1.])))  # 0.7071...

03 where each token sits

Positional encodings

Attention by itself treats its input as a set. Position has to be added to the vectors or built into the attention scores.

3.1Sinusoidal encoding

PE(pos, 2i)=sin⁡ ⁣(pos100002i/d)PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/d)PE_{(pos,\,2i)} = \sin\!\Big(\frac{pos}{10000^{2i/d}}\Big) \qquad PE_{(pos,\,2i+1)} = \cos\!\Big(\frac{pos}{10000^{2i/d}}\Big)
What it means
Each pair of dimensions is a sine and cosine at its own frequency, from fast to very slow, so every position gets a unique pattern.
Where an LLM uses it
Added to the embeddings in the original Transformer. No parameters to learn.
python
import numpy as np

def sinusoidal(n_pos, d):
    pos = np.arange(n_pos)[:, None]
    i = np.arange(0, d, 2)[None, :]
    angle = pos / 10000 ** (i / d)
    pe = np.zeros((n_pos, d))
    pe[:, 0::2], pe[:, 1::2] = np.sin(angle), np.cos(angle)
    return pe

print(sinusoidal(4, 8).shape)  # (4, 8)

3.2Rotary position embedding (RoPE)

(q2i′q2i+1′)=(cos⁡mθi−sin⁡mθisin⁡mθicos⁡mθi)(q2iq2i+1),θi=10000−2i/d\begin{pmatrix} q'_{2i} \\ q'_{2i+1} \end{pmatrix} = \begin{pmatrix} \cos m\theta_i & -\sin m\theta_i \\ \sin m\theta_i & \cos m\theta_i \end{pmatrix} \begin{pmatrix} q_{2i} \\ q_{2i+1} \end{pmatrix}, \quad \theta_i = 10000^{-2i/d}
What it means
Rotate each pair of query and key dimensions by an angle proportional to the token's position m. Nothing is added to the embedding.
Where an LLM uses it
Applied to queries and keys inside every attention layer. Used by LLaMA, Mistral, Qwen and most open models.
python
import numpy as np

def rope(x, pos, base=10000.0):
    # x: (T, d) queries or keys, pos: (T,) positions
    d = x.shape[-1]
    theta = base ** (-np.arange(0, d, 2) / d)
    ang = pos[:, None] * theta[None, :]
    cos, sin = np.cos(ang), np.sin(ang)
    x1, x2 = x[:, 0::2], x[:, 1::2]
    out = np.empty_like(x)
    out[:, 0::2] = x1 * cos - x2 * sin
    out[:, 1::2] = x1 * sin + x2 * cos
    return out

3.3Why RoPE encodes relative position

⟨Rmq, Rnk⟩=⟨q, Rn−m k⟩\langle R_{m}\mathbf{q},\, R_{n}\mathbf{k} \rangle = \langle \mathbf{q},\, R_{n-m}\,\mathbf{k} \rangle
What it means
Rotations compose, so the dot product between a rotated query and key depends only on the distance n - m between the two tokens.
Where an LLM uses it
It is why the attention score between two tokens is the same wherever the pair appears in the context.
python
import numpy as np

rng = np.random.default_rng(1)
q, k = rng.normal(size=(1, 8)), rng.normal(size=(1, 8))

def rope(x, pos, base=10000.0):
    d = x.shape[-1]
    ang = pos * base ** (-np.arange(0, d, 2) / d)
    c, s = np.cos(ang), np.sin(ang)
    o = np.empty_like(x)
    o[:, 0::2] = x[:, 0::2] * c - x[:, 1::2] * s
    o[:, 1::2] = x[:, 0::2] * s + x[:, 1::2] * c
    return o

a = rope(q, 5) @ rope(k, 9).T
b = rope(q, 105) @ rope(k, 109).T
assert np.allclose(a, b)     # same distance, same score

3.4ALiBi linear bias

scoreij=qi⋅kjdk−mh (i−j),mh=2−8h/H\text{score}_{ij} = \frac{\mathbf{q}_i\cdot\mathbf{k}_j}{\sqrt{d_k}} - m_h\,(i-j), \qquad m_h = 2^{-8h/H}
What it means
Leave the vectors alone and subtract a penalty from each attention score that grows linearly with distance. Each head h of H gets its own slope m_h.
Where an LLM uses it
Lets a model trained on short contexts run on longer ones. With 8 heads the slopes are 1/2, 1/4, ..., 1/256.
python
import numpy as np

def alibi_bias(T, n_heads):
    slopes = 2.0 ** (-8.0 * np.arange(1, n_heads + 1) / n_heads)
    dist = np.arange(T)[:, None] - np.arange(T)[None, :]   # i - j
    return -slopes[:, None, None] * np.maximum(dist, 0)    # (H, T, T)

print(2.0 ** (-8.0 * np.arange(1, 9) / 8))  # 0.5 ... 0.00390625

04 tokens read each other

Attention

Every token builds a query, compares it with every earlier token's key, and takes a weighted average of their values.

4.1Query, key and value projections

Q=XWQ,K=XWK,V=XWV,WQ,WK∈Rd×dk,  WV∈Rd×dvQ = XW_Q,\quad K = XW_K,\quad V = XW_V, \qquad W_Q, W_K \in \mathbb{R}^{d\times d_k},\; W_V \in \mathbb{R}^{d\times d_v}
What it means
Three learned linear maps turn each token vector into a question (query), an address (key) and a payload (value).
Where an LLM uses it
The first step of every attention layer, computed for all tokens at once as three matrix multiplies.
python
import numpy as np

rng = np.random.default_rng(0)
T, d, dk = 5, 16, 8
X = rng.normal(size=(T, d))
Wq, Wk, Wv = (rng.normal(size=(d, dk)) / np.sqrt(d) for _ in range(3))
Q, K, V = X @ Wq, X @ Wk, X @ Wv

4.2Scaled dot-product attention

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q,K,V) = \operatorname{softmax}\!\Big(\frac{QK^{\top}}{\sqrt{d_k}}\Big)V
What it means
Score every query against every key, turn each row of scores into weights that sum to 1, and mix the values with those weights.
Where an LLM uses it
The core operation of the Transformer, run in every layer and every head.
python
import numpy as np

def softmax(z, axis=-1):
    z = z - z.max(axis=axis, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=axis, keepdims=True)

def attention(Q, K, V, mask=None):
    s = Q @ K.T / np.sqrt(Q.shape[-1])
    if mask is not None:
        s = s + mask
    return softmax(s) @ V

4.3Why divide by the square root of d_k

qi,ki∼i.i.d.(0,1)  ⇒  Var⁡(q⋅k)=∑i=1dkVar⁡(qiki)=dkq_i, k_i \sim \text{i.i.d.}(0,1) \;\Rightarrow\; \operatorname{Var}(\mathbf{q}\cdot\mathbf{k}) = \sum_{i=1}^{d_k}\operatorname{Var}(q_i k_i) = d_k
What it means
Dot products of random unit-variance vectors grow with dimension. Dividing by the square root brings the variance back to 1.
Where an LLM uses it
Without it, large scores push softmax into a near one-hot region where gradients vanish.
Example
With d_k = 64 the raw scores have standard deviation 8. After scaling it is 1.
python
import numpy as np

rng = np.random.default_rng(0)
dk = 64
q, k = rng.normal(size=(100_000, dk)), rng.normal(size=(100_000, dk))
dots = (q * k).sum(1)
print(dots.std(), (dots / np.sqrt(dk)).std())  # ~8.0, ~1.0

4.4Numerically stable softmax

softmax⁡(z)i=ezi∑jezj=ezi−max⁡jzj∑jezj−max⁡jzj\operatorname{softmax}(\mathbf{z})_i = \frac{e^{z_i}}{\sum_j e^{z_j}} = \frac{e^{z_i - \max_j z_j}}{\sum_j e^{z_j - \max_j z_j}}
What it means
Subtracting the maximum changes nothing mathematically but stops exp from overflowing.
Where an LLM uses it
Every softmax in attention and in the output layer is computed this way.
python
import numpy as np

z = np.array([1000.0, 1001.0, 1002.0])
p = np.exp(z - z.max()); p /= p.sum()
print(p)  # 0.090 0.245 0.665, no overflow

4.5Causal mask

Mij={0j≤i−∞j>isoftmax⁡ ⁣(QK⊤dk+M)M_{ij} = \begin{cases} 0 & j \le i \\ -\infty & j > i \end{cases} \qquad \operatorname{softmax}\!\Big(\frac{QK^{\top}}{\sqrt{d_k}} + M\Big)
What it means
Adding minus infinity to future positions makes their softmax weight exactly zero, so token i can only read tokens 1 to i.
Where an LLM uses it
Decoder-only models train on every position of a sequence in parallel without seeing the answer.
python
import numpy as np

def causal_mask(T):
    return np.triu(np.full((T, T), -np.inf), k=1)

print(causal_mask(3))

4.6Multi-head attention

MultiHead⁡(X)=Concat⁡(head1,…,headh) WO,headi=Attention⁡(XWQi,XWKi,XWVi)\operatorname{MultiHead}(X) = \operatorname{Concat}(\text{head}_1,\dots,\text{head}_h)\,W_O, \quad \text{head}_i = \operatorname{Attention}(XW_Q^{i}, XW_K^{i}, XW_V^{i})
What it means
Run h smaller attentions in parallel, each with d_k = d / h, then concatenate and mix them with one output matrix.
Where an LLM uses it
Different heads learn different patterns (previous token, matching brackets, copying). The base Transformer used h = 8, d_k = 64.
python
import numpy as np

def softmax(z):
    z = z - z.max(-1, keepdims=True); e = np.exp(z)
    return e / e.sum(-1, keepdims=True)

def multi_head(X, Wq, Wk, Wv, Wo, h):
    T, d = X.shape
    dk = d // h
    split = lambda M: M.reshape(T, h, dk).transpose(1, 0, 2)  # (h, T, dk)
    Q, K, V = split(X @ Wq), split(X @ Wk), split(X @ Wv)
    mask = np.triu(np.full((T, T), -np.inf), 1)
    A = softmax(Q @ K.transpose(0, 2, 1) / np.sqrt(dk) + mask)
    out = (A @ V).transpose(1, 0, 2).reshape(T, d)
    return out @ Wo

rng = np.random.default_rng(0)
X = rng.normal(size=(6, 32))
W = [rng.normal(size=(32, 32)) / 6 for _ in range(4)]
print(multi_head(X, *W, h=4).shape)  # (6, 32)

4.7Online softmax (the trick inside FlashAttention)

m′=max⁡(m,x),ℓ′=ℓ e m−m′+e x−m′m' = \max(m, x), \qquad \ell' = \ell\, e^{\,m - m'} + e^{\,x - m'}
What it means
Keep a running maximum m and a running sum l. When a bigger value arrives, rescale the old sum. One pass, no need to store all scores.
Where an LLM uses it
FlashAttention processes keys in tiles with this update, so the T x T score matrix never has to sit in GPU memory.
python
import numpy as np

def online_softmax_denominator(xs):
    m, l = -np.inf, 0.0
    for x in xs:
        m_new = max(m, x)
        l = l * np.exp(m - m_new) + np.exp(x - m_new)
        m = m_new
    return m, l

xs = np.array([3.0, 1.0, 5.0, 2.0])
m, l = online_softmax_denominator(xs)
assert np.isclose(l, np.exp(xs - xs.max()).sum())

05 keeping activations in range

Normalization

Deep stacks drift. A normalization layer rescales each token vector before or after every sublayer so training stays stable.

5.1LayerNorm

LN⁡(x)=γ⊙x−μσ2+ϵ+β,μ=1d∑ixi,  σ2=1d∑i(xi−μ)2\operatorname{LN}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x} - \mu}{\sqrt{\sigma^2 + \epsilon}} + \boldsymbol{\beta}, \quad \mu = \tfrac{1}{d}\sum_i x_i,\; \sigma^2 = \tfrac{1}{d}\sum_i (x_i - \mu)^2
What it means
Shift each token vector to mean 0 and scale it to variance 1 across its own features, then apply a learned gain and bias.
Where an LLM uses it
GPT-2, GPT-3 and BERT use LayerNorm around every attention and MLP block.
python
import numpy as np

def layer_norm(x, gamma, beta, eps=1e-5):
    mu = x.mean(-1, keepdims=True)
    var = x.var(-1, keepdims=True)
    return gamma * (x - mu) / np.sqrt(var + eps) + beta

5.2RMSNorm

RMSNorm⁡(x)=γ⊙x1d∑ixi2+ϵ\operatorname{RMSNorm}(\mathbf{x}) = \boldsymbol{\gamma} \odot \frac{\mathbf{x}}{\sqrt{\tfrac{1}{d}\sum_i x_i^2 + \epsilon}}
What it means
Divide each token vector by its root mean square and apply a learned gain. There is no mean subtraction and no bias.
Where an LLM uses it
Cheaper and works as well in practice. LLaMA, Mistral and most recent open models use it.
python
import numpy as np

def rms_norm(x, gamma, eps=1e-6):
    return gamma * x / np.sqrt((x ** 2).mean(-1, keepdims=True) + eps)

5.3Pre-norm versus post-norm

post: xl+1=LN⁡(xl+F(xl))pre: xl+1=xl+F(LN⁡(xl))\text{post: } \mathbf{x}_{l+1} = \operatorname{LN}(\mathbf{x}_l + F(\mathbf{x}_l)) \qquad \text{pre: } \mathbf{x}_{l+1} = \mathbf{x}_l + F(\operatorname{LN}(\mathbf{x}_l))
What it means
Post-norm normalizes after adding the residual (original Transformer). Pre-norm normalizes only the branch input, leaving a clean residual path.
Where an LLM uses it
Pre-norm trains stably without a long warmup, which is why GPT-2 onwards uses it, plus one final norm before the output layer.
python
def pre_norm_block(x, norm, f):
    return x + f(norm(x))

def post_norm_block(x, norm, f):
    return norm(x + f(x))

06 per-token computation

The MLP block

After attention mixes tokens, a two-layer network transforms each token on its own. It holds about two thirds of a dense model's parameters.

6.1Position-wise feed-forward network

FFN⁡(x)=max⁡(0, xW1+b1) W2+b2,dff=4d\operatorname{FFN}(\mathbf{x}) = \max(0,\, \mathbf{x}W_1 + \mathbf{b}_1)\,W_2 + \mathbf{b}_2, \qquad d_{ff} = 4d
What it means
Expand to a wider hidden layer, apply a nonlinearity, project back. The same weights apply to every position.
Where an LLM uses it
The original Transformer used d = 512 and d_ff = 2048.
python
import numpy as np

def ffn(x, W1, b1, W2, b2):
    return np.maximum(0, x @ W1 + b1) @ W2 + b2

6.2GELU

GELU⁡(x)=x Φ(x)≈0.5 x(1+tanh⁡ ⁣[2/π (x+0.044715 x3)])\operatorname{GELU}(x) = x\,\Phi(x) \approx 0.5\,x\Big(1 + \tanh\!\Big[\sqrt{2/\pi}\,\big(x + 0.044715\,x^3\big)\Big]\Big)
What it means
Weight each input by the probability that a standard normal is below it. A smooth version of ReLU.
Where an LLM uses it
The activation in BERT, GPT-2 and GPT-3.
python
import numpy as np
from math import erf, sqrt

def gelu_exact(x):
    return 0.5 * x * (1 + np.vectorize(erf)(x / sqrt(2)))

def gelu_tanh(x):
    return 0.5 * x * (1 + np.tanh(np.sqrt(2 / np.pi) * (x + 0.044715 * x ** 3)))

x = np.linspace(-3, 3, 7)
print(np.abs(gelu_exact(x) - gelu_tanh(x)).max())  # < 1e-3

6.3SwiGLU

SwiGLU⁡(x)=(Swish⁡(xW)⊙xV) W2,Swish⁡(z)=z σ(z)\operatorname{SwiGLU}(\mathbf{x}) = \big(\operatorname{Swish}(\mathbf{x}W) \odot \mathbf{x}V\big)\,W_2, \qquad \operatorname{Swish}(z) = z\,\sigma(z)
What it means
Two parallel projections: one passes through Swish and acts as a gate on the other. Then project back down.
Where an LLM uses it
LLaMA, Mistral and PaLM use it. To keep the parameter count of a 4d FFN with three matrices, the hidden size is cut to about (2/3) x 4d.
python
import numpy as np

def swish(z):
    return z / (1 + np.exp(-z))

def swiglu(x, W, V, W2):
    return (swish(x @ W) * (x @ V)) @ W2

d = 4096
print(int(2 / 3 * 4 * d))  # 10922 hidden units before rounding

07 stacking layers

Residuals and the full block

A decoder is the same block repeated L times. Residual connections let gradients and information flow straight through the stack.

7.1Residual connection

xl+1=xl+Fl(xl)⇒∂xl+1∂xl=I+∂Fl∂xl\mathbf{x}_{l+1} = \mathbf{x}_l + F_l(\mathbf{x}_l) \quad\Rightarrow\quad \frac{\partial \mathbf{x}_{l+1}}{\partial \mathbf{x}_l} = I + \frac{\partial F_l}{\partial \mathbf{x}_l}
What it means
Each layer adds a correction to its input and passes the sum on. The identity term in the Jacobian keeps gradients from vanishing.
Where an LLM uses it
Every attention and MLP sublayer in every LLM writes into this shared residual stream.
python
def residual(x, f):
    return x + f(x)

7.2A pre-norm decoder block

h=x+MHA⁡(Norm⁡(x))y=h+MLP⁡(Norm⁡(h))\begin{aligned} \mathbf{h} &= \mathbf{x} + \operatorname{MHA}(\operatorname{Norm}(\mathbf{x})) \\ \mathbf{y} &= \mathbf{h} + \operatorname{MLP}(\operatorname{Norm}(\mathbf{h})) \end{aligned}
What it means
Two sublayers, each normalized on the way in and added back on the way out.
Where an LLM uses it
This is the whole GPT-style layer. A model is an embedding, L of these, a final norm and the output projection.
python
def decoder_block(x, attn, mlp, norm1, norm2):
    h = x + attn(norm1(x))
    return h + mlp(norm2(h))

7.3Parameter count

N≈2 d L (2dattn+dff)=12 L d2(dattn=d,  dff=4d)N \approx 2\, d\, L\,(2 d_{\text{attn}} + d_{ff}) = 12\, L\, d^2 \quad (d_{\text{attn}} = d,\; d_{ff} = 4d)
What it means
Attention has four d x d matrices (4d^2) and the MLP has two d x 4d matrices (8d^2), so each layer has about 12d^2 weights. Embeddings and biases are left out.
Where an LLM uses it
Quick sizing of any model from its width and depth.
Example
GPT-3 175B: L = 96, d = 12,288 gives 12 x 96 x 12,288^2 = 174 billion.
python
def params(L, d):
    return 12 * L * d ** 2

print(f"{params(96, 12288) / 1e9:.0f}B")  # 174B

08 what training minimizes

Output, loss and perplexity

The last hidden state becomes a score per vocabulary token. Training pushes up the log-probability of the token that really came next.

8.1Next-token distribution

p(xt+1=v∣x≤t)=softmax⁡(htWU)vp(x_{t+1} = v \mid x_{\le t}) = \operatorname{softmax}(\mathbf{h}_t W_U)_v
What it means
Project the final hidden state to |V| logits with the unembedding W_U and softmax them into a probability for every token.
Where an LLM uses it
The output of every forward pass. Sampling and the loss both start here.
python
import numpy as np

def next_token_probs(h_last, W_U):
    z = h_last @ W_U
    z = z - z.max()
    p = np.exp(z)
    return p / p.sum()

8.2Cross-entropy loss

L=−1T∑t=1Tlog⁡pθ(xt∣x<t)\mathcal{L} = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t})
What it means
The average negative log-probability the model gave the true next token. Zero only if it was certain and right every time.
Where an LLM uses it
The pretraining objective of every GPT-style model, and the number on every training curve.
Example
A model that guesses uniformly over GPT-2's 50,257 tokens has loss ln(50,257) = 10.82 nats.
python
import numpy as np

def cross_entropy(logits, targets):
    # logits: (T, V), targets: (T,)
    z = logits - logits.max(-1, keepdims=True)
    logp = z - np.log(np.exp(z).sum(-1, keepdims=True))
    return float(-logp[np.arange(len(targets)), targets].mean())

print(np.log(50257))  # 10.8249...

8.3Perplexity

PPL⁡=exp⁡(L)=exp⁡ ⁣(−1T∑tlog⁡p(xt∣x<t))\operatorname{PPL} = \exp(\mathcal{L}) = \exp\!\Big(-\frac{1}{T}\sum_t \log p(x_t \mid x_{<t})\Big)
What it means
The effective number of tokens the model is choosing between at each step. Lower is better.
Where an LLM uses it
Reporting language-model quality on held-out text. Only comparable between models that share a tokenizer.
Example
Uniform guessing over |V| tokens gives perplexity exactly |V|. A loss of 2.0 nats is a perplexity of 7.39.
python
import numpy as np

print(np.exp(2.0))  # 7.389...

8.4Gradient of softmax cross-entropy

∂L∂zv=pv−1[v=y]\frac{\partial \mathcal{L}}{\partial z_v} = p_v - \mathbb{1}[v = y]
What it means
The gradient on each logit is the predicted probability minus 1 for the correct token, minus 0 for the rest.
Where an LLM uses it
This is where backpropagation starts on every training step. Simple and cheap.
python
import numpy as np

z = np.array([2.0, 1.0, 0.1]); y = 0
p = np.exp(z - z.max()); p /= p.sum()
grad = p.copy(); grad[y] -= 1

eps = 1e-6
num = []
for v in range(3):
    zp = z.copy(); zp[v] += eps
    pp = np.exp(zp - zp.max()); pp /= pp.sum()
    num.append((-np.log(pp[y]) + np.log(p[y])) / eps)
assert np.allclose(grad, num, atol=1e-4)

8.5KL divergence

DKL(P ∥ Q)=∑xP(x)log⁡P(x)Q(x)  ≥  0D_{\mathrm{KL}}(P \,\|\, Q) = \sum_x P(x) \log \frac{P(x)}{Q(x)} \;\ge\; 0
What it means
How many extra nats you pay for coding samples from P with a code built for Q. Zero only when P = Q. Not symmetric.
Where an LLM uses it
The leash in RLHF that keeps a tuned model near its reference, and the loss in knowledge distillation.
python
import numpy as np

def kl(p, q):
    p, q = np.asarray(p, float), np.asarray(q, float)
    m = p > 0
    return float(np.sum(p[m] * np.log(p[m] / q[m])))

print(kl([0.5, 0.5], [0.9, 0.1]))  # 0.5108...

09 how every weight learns

Backpropagation

Gradients flow backwards through the network by the chain rule, one matrix multiply per layer.

9.1Chain rule

∂L∂x=∂L∂y ∂y∂xfor y=f(x)\frac{\partial \mathcal{L}}{\partial \mathbf{x}} = \frac{\partial \mathcal{L}}{\partial \mathbf{y}}\,\frac{\partial \mathbf{y}}{\partial \mathbf{x}} \qquad \text{for } \mathbf{y} = f(\mathbf{x})
What it means
The gradient at a layer's input is the gradient at its output times the layer's local derivative.
Where an LLM uses it
Autograd frameworks record the forward pass and apply this rule node by node in reverse.
python
import numpy as np

# y = tanh(w * x), L = y^2
x, w = 0.5, 2.0
y = np.tanh(w * x)
dL_dy = 2 * y
dy_dw = (1 - y ** 2) * x
print(dL_dy * dy_dw)

9.2Gradients of a linear layer

Y=XW  ⇒  ∂L∂W=X⊤G,∂L∂X=G W⊤,G=∂L∂YY = XW \;\Rightarrow\; \frac{\partial \mathcal{L}}{\partial W} = X^{\top} G, \qquad \frac{\partial \mathcal{L}}{\partial X} = G\, W^{\top}, \qquad G = \frac{\partial \mathcal{L}}{\partial Y}
What it means
Two matrix multiplies per layer on the way back: one for the weight gradient, one to pass the gradient further down.
Where an LLM uses it
Almost all training compute. Forward is one matmul per weight, backward is two, which is where the 6ND rule comes from.
python
import numpy as np

rng = np.random.default_rng(0)
X, W = rng.normal(size=(4, 3)), rng.normal(size=(3, 2))
G = rng.normal(size=(4, 2))          # upstream gradient dL/dY
dW, dX = X.T @ G, G @ W.T

# check dW numerically for L = sum(G * (X @ W))
eps, i, j = 1e-6, 1, 0
W2 = W.copy(); W2[i, j] += eps
num = ((G * (X @ W2)).sum() - (G * (X @ W)).sum()) / eps
assert np.isclose(dW[i, j], num, atol=1e-4)

9.3Gradient clipping by global norm

g←g⋅min⁡ ⁣(1, c∥g∥2)\mathbf{g} \leftarrow \mathbf{g}\cdot\min\!\Big(1,\, \frac{c}{\lVert \mathbf{g} \rVert_2}\Big)
What it means
If the total gradient norm is above a threshold c, scale the whole gradient down to length c. Direction is kept.
Where an LLM uses it
LLM training runs clip at a norm of about 1.0 to survive occasional loss spikes.
python
import numpy as np

def clip_by_global_norm(grads, c=1.0):
    norm = np.sqrt(sum((g ** 2).sum() for g in grads))
    scale = min(1.0, c / (norm + 1e-12))
    return [g * scale for g in grads], norm

10 turning gradients into updates

Optimizers: Adam and AdamW

Plain gradient descent is too slow for LLMs. Adam adapts the step size of every parameter from running averages of its gradients.

10.1SGD with momentum

vt=μ vt−1+gt,θt=θt−1−η vt\mathbf{v}_t = \mu\,\mathbf{v}_{t-1} + \mathbf{g}_t, \qquad \theta_t = \theta_{t-1} - \eta\,\mathbf{v}_t
What it means
Keep a running sum of past gradients so steps build speed along consistent directions and cancel out noise.
Where an LLM uses it
The baseline. Still common in vision, rarely used for LLM pretraining.
python
def sgd_momentum(theta, v, g, lr=0.01, mu=0.9):
    v = mu * v + g
    return theta - lr * v, v

10.2Adam

mt=β1mt−1+(1−β1) gt,m^t=mt/(1−β1t)vt=β2vt−1+(1−β2) gt2,v^t=vt/(1−β2t)θt=θt−1−η m^t/(v^t+ϵ)\begin{aligned} \mathbf{m}_t &= \beta_1 \mathbf{m}_{t-1} + (1-\beta_1)\,\mathbf{g}_t, & \hat{\mathbf{m}}_t &= \mathbf{m}_t / (1-\beta_1^t) \\ \mathbf{v}_t &= \beta_2 \mathbf{v}_{t-1} + (1-\beta_2)\,\mathbf{g}_t^2, & \hat{\mathbf{v}}_t &= \mathbf{v}_t / (1-\beta_2^t) \\ \theta_t &= \theta_{t-1} - \eta\, \hat{\mathbf{m}}_t / (\sqrt{\hat{\mathbf{v}}_t} + \epsilon) \end{aligned}
What it means
Track the mean (m) and uncentered variance (v) of each parameter's gradient, correct their startup bias, and step by mean over root variance.
Where an LLM uses it
The default optimizer family for LLMs. The paper's defaults are beta1 = 0.9, beta2 = 0.999, eps = 1e-8.
python
import numpy as np

def adam_step(theta, g, m, v, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8):
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g ** 2
    m_hat = m / (1 - b1 ** t)
    v_hat = v / (1 - b2 ** t)
    return theta - lr * m_hat / (np.sqrt(v_hat) + eps), m, v

10.3AdamW: decoupled weight decay

θt=θt−1−η(m^tv^t+ϵ+λ θt−1)\theta_t = \theta_{t-1} - \eta\Big(\frac{\hat{\mathbf{m}}_t}{\sqrt{\hat{\mathbf{v}}_t} + \epsilon} + \lambda\,\theta_{t-1}\Big)
What it means
Shrink the weights directly in the update. Adding L2 to the gradient would let Adam's per-parameter scaling distort it.
Where an LLM uses it
The optimizer behind GPT-3, LLaMA and most open LLMs.
python
import numpy as np

def adamw_step(theta, g, m, v, t, lr=3e-4, b1=0.9, b2=0.95, eps=1e-8, wd=0.1):
    m = b1 * m + (1 - b1) * g
    v = b2 * v + (1 - b2) * g ** 2
    m_hat, v_hat = m / (1 - b1 ** t), v / (1 - b2 ** t)
    theta = theta - lr * (m_hat / (np.sqrt(v_hat) + eps) + wd * theta)
    return theta, m, v

10.4Training memory per parameter

2⏟fp16 θ+2⏟fp16 g+4+4+4⏟fp32 θ, m, v=16 bytes per parameter\underbrace{2}_{\text{fp16 } \theta} + \underbrace{2}_{\text{fp16 } g} + \underbrace{4 + 4 + 4}_{\text{fp32 } \theta,\, m,\, v} = 16 \text{ bytes per parameter}
What it means
Mixed-precision Adam keeps half-precision weights and gradients plus a full-precision master copy and both moments.
Where an LLM uses it
Sizing a training run before activations: a 7B model needs about 112 GB for model and optimizer state alone.
python
def train_state_gb(n_params, bytes_per_param=16):
    return n_params * bytes_per_param / 1e9

print(train_state_gb(7e9))  # 112.0

11 how fast to step, and when

Learning-rate schedules

LLMs ramp the learning rate up from near zero, hold or peak, then decay it. The shape matters as much as the peak.

11.1Linear warmup

ηt=ηmax⁡⋅tTw,t≤Tw\eta_t = \eta_{\max}\cdot \frac{t}{T_w}, \qquad t \le T_w
What it means
Start tiny and grow linearly for T_w steps, while Adam's moment estimates are still noisy.
Where an LLM uses it
Almost every LLM run warms up for the first few hundred to few thousand steps.
python
def warmup(t, lr_max, T_w):
    return lr_max * min(1.0, t / T_w)

11.2Cosine decay

ηt=ηmin⁡+12(ηmax⁡−ηmin⁡)(1+cos⁡ ⁣(π t−TwT−Tw))\eta_t = \eta_{\min} + \tfrac{1}{2}(\eta_{\max} - \eta_{\min})\Big(1 + \cos\!\Big(\pi\,\frac{t - T_w}{T - T_w}\Big)\Big)
What it means
After warmup, follow half a cosine from the peak down to a floor at step T.
Where an LLM uses it
The standard pretraining schedule (GPT-3, LLaMA), usually decaying to about 10% of the peak.
python
import math

def warmup_cosine(t, lr_max, lr_min, T_w, T):
    if t < T_w:
        return lr_max * t / T_w
    p = (t - T_w) / max(1, T - T_w)
    return lr_min + 0.5 * (lr_max - lr_min) * (1 + math.cos(math.pi * p))

11.3Inverse square root (the original Transformer)

η=dmodel−0.5⋅min⁡ ⁣(step−0.5,  step⋅warmup−1.5)\eta = d_{\text{model}}^{-0.5}\cdot \min\!\big(\text{step}^{-0.5},\; \text{step}\cdot \text{warmup}^{-1.5}\big)
What it means
Linear warmup, then decay proportional to one over the square root of the step number.
Where an LLM uses it
Used with warmup = 4000 steps in Attention Is All You Need. Still seen in some encoder and translation models.
python
def noam(step, d_model=512, warmup=4000):
    step = max(step, 1)
    return d_model ** -0.5 * min(step ** -0.5, step * warmup ** -1.5)

12 predicting loss before you train

Scaling laws

Loss falls as a smooth power law in parameters, data and compute. These fits decide how big to make a model and how long to train it.

12.1Kaplan power law in model size

L(N)=(NcN)αN,αN≈0.076,  Nc≈8.8×1013L(N) = \Big(\frac{N_c}{N}\Big)^{\alpha_N}, \qquad \alpha_N \approx 0.076,\; N_c \approx 8.8\times 10^{13}
What it means
With enough data, test loss falls as a power of the number of non-embedding parameters N.
Where an LLM uses it
Extrapolating from small runs to predict a large model's loss.
python
def kaplan_loss_N(N, Nc=8.8e13, alpha=0.076):
    return (Nc / N) ** alpha

12.2Training compute

C≈6 N DC \approx 6\,N\,D
What it means
About 2N FLOPs per token for the forward pass and 4N for the backward pass, times D training tokens.
Where an LLM uses it
The first number in any training budget.
Example
70B parameters on 1.4T tokens: 6 x 70e9 x 1.4e12 = 5.9 x 10^23 FLOPs.
python
def train_flops(N, D):
    return 6 * N * D

print(f"{train_flops(70e9, 1.4e12):.2e}")  # 5.88e+23

12.3Chinchilla loss surface

L^(N,D)=E+ANα+BDβ,E=1.69,  A=406.4,  B=410.7,  α=0.34,  β=0.28\hat{L}(N, D) = E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}}, \qquad E = 1.69,\; A = 406.4,\; B = 410.7,\; \alpha = 0.34,\; \beta = 0.28
What it means
An irreducible term E, plus a penalty for too few parameters and a penalty for too little data.
Where an LLM uses it
Choosing N and D for a fixed compute budget by minimizing this surface subject to C = 6ND.
python
def chinchilla_loss(N, D, E=1.69, A=406.4, B=410.7, a=0.34, b=0.28):
    return E + A / N ** a + B / D ** b

print(round(chinchilla_loss(70e9, 1.4e12), 3))

12.4Compute-optimal allocation

Nopt∝C0.5,Dopt∝C0.5,Dopt≈20 NoptN_{\text{opt}} \propto C^{0.5}, \qquad D_{\text{opt}} \propto C^{0.5}, \qquad D_{\text{opt}} \approx 20\,N_{\text{opt}}
What it means
Scale parameters and tokens equally: double the model, double the data. Roughly 20 tokens per parameter.
Where an LLM uses it
Chinchilla (70B, 1.4T tokens) beat the 280B Gopher with the same compute. Modern models often train far past 20 tokens per parameter to make inference cheaper.
python
import math

def chinchilla_optimal(C, tokens_per_param=20):
    N = math.sqrt(C / (6 * tokens_per_param))
    return N, tokens_per_param * N

N, D = chinchilla_optimal(5.88e23)
print(f"{N/1e9:.0f}B params, {D/1e12:.1f}T tokens")  # 70B, 1.4T

13.1Forward FLOPs per token

Cforward≈2N+2 L nctx dattnC_{\text{forward}} \approx 2N + 2\,L\,n_{\text{ctx}}\,d_{\text{attn}}
What it means
Two FLOPs (a multiply and an add) per weight, plus the attention term that grows with context length.
Where an LLM uses it
Estimating the compute cost of a prompt or a generated token.
python
def forward_flops(N, L, n_ctx, d_attn):
    return 2 * N + 2 * L * n_ctx * d_attn

13.2KV cache size

bytes=2⋅L⋅nkv⋅dhead⋅T⋅B⋅bytes per value\text{bytes} = 2 \cdot L \cdot n_{kv} \cdot d_{\text{head}} \cdot T \cdot B \cdot \text{bytes per value}
What it means
For every layer, every KV head, every past token and every sequence in the batch, store one key and one value vector.
Where an LLM uses it
Decides how many users and how much context fit on a GPU.
Example
Llama 2 7B (32 layers, 32 heads of 128, fp16): 0.5 MiB per token, 2 GiB for one 4,096-token sequence.
python
def kv_cache_bytes(L, n_kv, d_head, T, B=1, bytes_per=2):
    return 2 * L * n_kv * d_head * T * B * bytes_per

print(kv_cache_bytes(32, 32, 128, 1) / 2**20)     # 0.5 MiB per token
print(kv_cache_bytes(32, 32, 128, 4096) / 2**30)  # 2.0 GiB

13.3Grouped-query and multi-query attention

KV cache∝nkv,nkv=h  (MHA),1<nkv<h  (GQA),nkv=1  (MQA)\text{KV cache} \propto n_{kv}, \qquad n_{kv} = h \;(\text{MHA}),\quad 1 < n_{kv} < h \;(\text{GQA}),\quad n_{kv} = 1 \;(\text{MQA})
What it means
Let several query heads share one key and value head. The cache shrinks by a factor of h / n_kv.
Where an LLM uses it
Llama 2 70B uses GQA with 8 KV heads for 64 query heads, an 8x smaller cache.
python
def gqa_savings(n_heads, n_kv):
    return n_heads / n_kv

print(gqa_savings(64, 8))  # 8.0

13.4Memory-bound decoding

tokens/s  ≲  memory bandwidthbytes of weights\text{tokens/s} \;\lesssim\; \frac{\text{memory bandwidth}}{\text{bytes of weights}}
What it means
At batch size 1, every generated token has to stream all weights from memory once, so bandwidth caps speed.
Where an LLM uses it
Why quantization speeds up local inference, and why batching many users raises throughput.
Example
7B weights in fp16 are 14 GB. At 1,000 GB/s of memory bandwidth the ceiling is about 71 tokens per second.
python
def decode_ceiling(n_params, bytes_per_param, bandwidth_gb_s):
    return bandwidth_gb_s * 1e9 / (n_params * bytes_per_param)

print(round(decode_ceiling(7e9, 2, 1000)))  # 71

14 choosing the next token

Sampling

The model gives a distribution. A decoding rule turns it into one token, and the rule changes the text as much as the weights do.

14.1Greedy decoding

xt+1=arg⁡max⁡v  p(v∣x≤t)x_{t+1} = \arg\max_v\; p(v \mid x_{\le t})
What it means
Always take the single most likely token. Deterministic.
Where an LLM uses it
Short factual answers and code completion. Long greedy text tends to repeat itself.
python
import numpy as np

def greedy(logits):
    return int(np.argmax(logits))

14.2Temperature

pi(T)=ezi/T∑jezj/Tp_i(T) = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}
What it means
Divide logits by T before softmax. T below 1 sharpens the distribution, above 1 flattens it, and T to 0 becomes greedy.
Where an LLM uses it
The main creativity dial in every chat API.
python
import numpy as np

def softmax_t(z, T=1.0):
    z = np.asarray(z, float) / T
    z -= z.max(); p = np.exp(z)
    return p / p.sum()

print(softmax_t([2, 1, 0], 0.5).round(3), softmax_t([2, 1, 0], 2).round(3))

14.3Top-k sampling

p′(v)∝{p(v)v∈top-k0otherwisep'(v) \propto \begin{cases} p(v) & v \in \text{top-}k \\ 0 & \text{otherwise} \end{cases}
What it means
Keep only the k most likely tokens, renormalize, sample.
Where an LLM uses it
Cuts off the long tail of unlikely tokens that cause nonsense.
python
import numpy as np

def top_k_sample(p, k, rng):
    idx = np.argsort(p)[-k:]
    q = p[idx] / p[idx].sum()
    return int(rng.choice(idx, p=q))

14.4Top-p (nucleus) sampling

V(p)=smallest set with ∑v∈V(p)p(v)≥p,p′(v)∝p(v) 1[v∈V(p)]V^{(p)} = \text{smallest set with } \sum_{v \in V^{(p)}} p(v) \ge p, \qquad p'(v) \propto p(v)\,\mathbb{1}[v \in V^{(p)}]
What it means
Keep the smallest set of top tokens whose probabilities add up to p, so the candidate pool grows when the model is unsure and shrinks when it is confident.
Where an LLM uses it
Default in most chat products, often with p around 0.9 to 0.95.
python
import numpy as np

def top_p_sample(p, top_p, rng):
    order = np.argsort(p)[::-1]
    cum = np.cumsum(p[order])
    keep = order[: np.searchsorted(cum, top_p) + 1]
    q = p[keep] / p[keep].sum()
    return int(rng.choice(keep, p=q))

rng = np.random.default_rng(0)
print(top_p_sample(np.array([0.5, 0.3, 0.15, 0.05]), 0.9, rng))

15.1Absmax (symmetric) quantization

s=max⁡i∣xi∣2b−1−1,qi=round⁡(xi/s),x^i=s qis = \frac{\max_i |x_i|}{2^{b-1} - 1}, \qquad q_i = \operatorname{round}(x_i / s), \qquad \hat{x}_i = s\, q_i
What it means
Scale so the largest magnitude maps to the largest integer (127 for int8), round, and multiply back to dequantize.
Where an LLM uses it
Simple int8 weight storage. LLM.int8() applies it per row and keeps outlier features in fp16.
python
import numpy as np

def absmax_quant(x, bits=8):
    qmax = 2 ** (bits - 1) - 1
    s = np.abs(x).max() / qmax
    q = np.round(x / s).astype(np.int8 if bits <= 8 else np.int32)
    return q, s

x = np.array([0.1, -0.5, 1.27, -1.0])
q, s = absmax_quant(x)
print(q, np.abs(q * s - x).max())

15.2Affine (zero-point) quantization

s=xmax⁡−xmin⁡2b−1,z=round⁡ ⁣(−xmin⁡s),q=clamp⁡(round⁡(x/s)+z, 0, 2b−1)s = \frac{x_{\max} - x_{\min}}{2^b - 1}, \qquad z = \operatorname{round}\!\Big(-\frac{x_{\min}}{s}\Big), \qquad q = \operatorname{clamp}(\operatorname{round}(x/s) + z,\, 0,\, 2^b - 1)
What it means
Map the actual range from min to max onto the full integer range, with a zero point so that real 0 is exactly representable.
Where an LLM uses it
Activations, which are often not centered at zero, and integer-only inference.
python
import numpy as np

def affine_quant(x, bits=8):
    s = (x.max() - x.min()) / (2 ** bits - 1)
    z = np.round(-x.min() / s)
    q = np.clip(np.round(x / s) + z, 0, 2 ** bits - 1)
    return q, s, z

def dequant(q, s, z):
    return s * (q - z)

15.3Weight memory

bytes=N⋅b8\text{bytes} = N \cdot \frac{b}{8}
What it means
Memory for weights is the parameter count times bits per weight over 8.
Where an LLM uses it
Picking a precision that fits your GPU or laptop.
Example
7B parameters: 14 GB at 16 bits, 7 GB at 8 bits, 3.5 GB at 4 bits, before scales and the KV cache.
python
for bits in (16, 8, 4):
    print(bits, 7e9 * bits / 8 / 1e9, "GB")

15.4Block-wise scales and their overhead

overhead bits per weight=bits per scaleblock size\text{overhead bits per weight} = \frac{\text{bits per scale}}{\text{block size}}
What it means
Give each block of weights its own scale so one outlier only hurts its block. The scales cost extra bits.
Where an LLM uses it
QLoRA uses 64-weight blocks. A 32-bit scale per block is 0.5 extra bits per weight. Quantizing the scales themselves (double quantization) cuts that to about 0.127.
python
print(32 / 64)  # 0.5 bits per weight for fp32 scales on 64-weight blocks

16 training a tiny update

LoRA fine-tuning

Freeze the pretrained weights and learn a low-rank correction. A few million parameters adapt a model of billions.

16.1Low-rank update

W=W0+αr BA,B∈Rd×r,  A∈Rr×k,  r≪min⁡(d,k)W = W_0 + \frac{\alpha}{r}\,BA, \qquad B \in \mathbb{R}^{d \times r},\; A \in \mathbb{R}^{r \times k},\; r \ll \min(d,k)
What it means
Add the product of two thin matrices to a frozen weight. B starts at zero, so training starts from the original model exactly.
Where an LLM uses it
Fine-tuning on one GPU. After training, BA can be merged into W_0, so inference costs nothing extra.
python
import numpy as np

rng = np.random.default_rng(0)
d, k, r, alpha = 64, 64, 4, 8
W0 = rng.normal(size=(d, k))
A = rng.normal(size=(r, k)) * 0.01
B = np.zeros((d, r))                  # zero init
x = rng.normal(size=(1, d))

y = x @ W0 + (alpha / r) * (x @ B @ A)
assert np.allclose(y, x @ W0)          # identical at step 0

16.2Trainable parameter count

r(d+k)⏟LoRAvsd k⏟full\underbrace{r(d + k)}_{\text{LoRA}} \quad\text{vs}\quad \underbrace{d\,k}_{\text{full}}
What it means
The adapter grows linearly with width. A full update grows with the product of both dimensions.
Where an LLM uses it
Deciding the rank r and which matrices (often the attention projections) get adapters.
Example
A 4096 x 4096 matrix with r = 8: 65,536 trainable values against 16,777,216 for the full matrix, about 0.39%.
python
d = k = 4096; r = 8
print(r * (d + k), d * k, f"{r * (d + k) / (d * k):.2%}")  # 65536 16777216 0.39%

17.1Reward model (Bradley-Terry)

LRM=− E(x,yw,yl)[log⁡σ(rϕ(x,yw)−rϕ(x,yl))]\mathcal{L}_{RM} = -\,\mathbb{E}_{(x, y_w, y_l)}\big[\log \sigma\big(r_\phi(x, y_w) - r_\phi(x, y_l)\big)\big]
What it means
Given a preferred answer y_w and a rejected one y_l, train a scorer so the preferred answer scores higher. The probability it wins is the sigmoid of the score gap.
Where an LLM uses it
Step two of InstructGPT-style training, on human comparison data.
python
import numpy as np

def rm_loss(r_chosen, r_rejected):
    return float(np.mean(np.log1p(np.exp(-(r_chosen - r_rejected)))))

print(rm_loss(np.array([2.0]), np.array([0.0])))  # 0.1269...

17.2KL-regularized RL objective

max⁡πθ  Ex, y∼πθ[rϕ(x,y)]−β DKL(πθ(⋅∣x) ∥ πref(⋅∣x))\max_{\pi_\theta}\; \mathbb{E}_{x,\, y \sim \pi_\theta}\big[r_\phi(x,y)\big] - \beta\, D_{\mathrm{KL}}\big(\pi_\theta(\cdot\mid x)\,\|\,\pi_{\text{ref}}(\cdot\mid x)\big)
What it means
Maximize reward, minus a penalty for moving away from the reference (the supervised model). Beta sets the leash length.
Where an LLM uses it
The KL term stops the policy from exploiting flaws in the reward model with strange text.
python
import numpy as np

def kl_penalized_reward(reward, logp_policy, logp_ref, beta=0.1):
    # per-sample estimate: r - beta * (log pi - log pi_ref)
    return reward - beta * (logp_policy - logp_ref)

17.3PPO clipped objective

LCLIP=Et[min⁡(ρtA^t,  clip⁡(ρt,1−ϵ,1+ϵ) A^t)],ρt=πθ(at∣st)πold(at∣st)\mathcal{L}^{\text{CLIP}} = \mathbb{E}_t\Big[\min\big(\rho_t \hat{A}_t,\; \operatorname{clip}(\rho_t, 1-\epsilon, 1+\epsilon)\,\hat{A}_t\big)\Big], \qquad \rho_t = \frac{\pi_\theta(a_t\mid s_t)}{\pi_{\text{old}}(a_t\mid s_t)}
What it means
Increase the probability of actions with positive advantage, but stop pushing once the new policy differs from the old one by more than epsilon.
Where an LLM uses it
The optimizer for the policy in classic RLHF. Each token is an action. The paper uses epsilon = 0.2.
python
import numpy as np

def ppo_clip_loss(logp_new, logp_old, adv, eps=0.2):
    ratio = np.exp(logp_new - logp_old)
    unclipped = ratio * adv
    clipped = np.clip(ratio, 1 - eps, 1 + eps) * adv
    return float(-np.mean(np.minimum(unclipped, clipped)))

17.4Generalized advantage estimation

δt=rt+γV(st+1)−V(st),A^t=∑l=0∞(γλ)l δt+l\delta_t = r_t + \gamma V(s_{t+1}) - V(s_t), \qquad \hat{A}_t = \sum_{l=0}^{\infty} (\gamma\lambda)^l\, \delta_{t+l}
What it means
Measure how much better each step went than the value model expected, and average those surprises with exponentially decaying weights.
Where an LLM uses it
Gives PPO a low-variance advantage per token from a learned value function.
python
import numpy as np

def gae(rewards, values, gamma=1.0, lam=0.95):
    # values has len(rewards) + 1 entries (last is bootstrap)
    adv, running = np.zeros(len(rewards)), 0.0
    for t in reversed(range(len(rewards))):
        delta = rewards[t] + gamma * values[t + 1] - values[t]
        running = delta + gamma * lam * running
        adv[t] = running
    return adv

17.5Group-relative advantage (GRPO)

A^i=ri−mean⁡(r1,…,rG)std⁡(r1,…,rG)\hat{A}_i = \frac{r_i - \operatorname{mean}(r_1,\dots,r_G)}{\operatorname{std}(r_1,\dots,r_G)}
What it means
Sample G answers to the same prompt and score each against the group average. No value model needed.
Where an LLM uses it
Used to train reasoning models on checkable tasks like math, where each answer gets a reward.
python
import numpy as np

def group_advantage(rewards, eps=1e-8):
    r = np.asarray(rewards, float)
    return (r - r.mean()) / (r.std() + eps)

print(group_advantage([1, 0, 0, 1]).round(3))  # 1 -1 -1 1

18 preferences without RL

Direct preference optimization

DPO shows the KL-regularized RLHF objective has a closed-form optimum, so you can train on preference pairs with a plain classification loss.

18.1Optimal policy of the KL objective

π∗(y∣x)=1Z(x) πref(y∣x) exp⁡ ⁣(1β r(x,y))\pi^{*}(y\mid x) = \frac{1}{Z(x)}\,\pi_{\text{ref}}(y\mid x)\,\exp\!\Big(\frac{1}{\beta}\, r(x,y)\Big)
What it means
The best policy under a reward and a KL leash is the reference policy reweighted by exponentiated reward.
Where an LLM uses it
The starting point of the DPO derivation.
python
import numpy as np

def optimal_policy(p_ref, reward, beta):
    w = p_ref * np.exp(reward / beta)
    return w / w.sum()

18.2Implicit reward

r(x,y)=βlog⁡πθ(y∣x)πref(y∣x)+βlog⁡Z(x)r(x, y) = \beta \log \frac{\pi_\theta(y\mid x)}{\pi_{\text{ref}}(y\mid x)} + \beta \log Z(x)
What it means
Invert the line above: any policy defines a reward. The partition term Z(x) cancels when two answers to the same prompt are compared.
Where an LLM uses it
Lets you read a reward straight off a DPO-trained model.
python
def implicit_reward(logp_policy, logp_ref, beta=0.1):
    return beta * (logp_policy - logp_ref)  # up to a per-prompt constant

18.3DPO loss

LDPO=− E[log⁡σ(βlog⁡πθ(yw∣x)πref(yw∣x)−βlog⁡πθ(yl∣x)πref(yl∣x))]\mathcal{L}_{\text{DPO}} = -\,\mathbb{E}\Big[\log \sigma\Big(\beta \log \frac{\pi_\theta(y_w\mid x)}{\pi_{\text{ref}}(y_w\mid x)} - \beta \log \frac{\pi_\theta(y_l\mid x)}{\pi_{\text{ref}}(y_l\mid x)}\Big)\Big]
What it means
Raise the log-probability of the chosen answer relative to the reference more than the rejected one's. Only two forward passes per model, no sampling.
Where an LLM uses it
A common replacement for PPO in open-model alignment because it is simpler and stable.
python
import numpy as np

def dpo_loss(pi_w, pi_l, ref_w, ref_l, beta=0.1):
    # inputs: summed log-probs of chosen (w) and rejected (l) answers
    margin = beta * ((pi_w - ref_w) - (pi_l - ref_l))
    return float(np.mean(np.log1p(np.exp(-margin))))

print(dpo_loss(-10.0, -12.0, -11.0, -11.0))  # margin 0.2 -> 0.598

19 more parameters, same compute

Mixture of experts

Replace one MLP with many expert MLPs and a router that sends each token to only a few of them.

19.1Top-k gating

y=∑i∈TG(x)i Ei(x),G(x)=softmax⁡(TopK⁡(xWg, k))\mathbf{y} = \sum_{i \in \mathcal{T}} G(\mathbf{x})_i\, E_i(\mathbf{x}), \qquad G(\mathbf{x}) = \operatorname{softmax}\big(\operatorname{TopK}(\mathbf{x} W_g,\, k)\big)
What it means
A small linear router scores every expert, keeps the top k, softmaxes those scores and mixes the chosen experts' outputs.
Where an LLM uses it
Mixtral 8x7B routes each token to 2 of 8 experts in every layer.
python
import numpy as np

def moe_forward(x, Wg, experts, k=2):
    logits = x @ Wg                       # (n_experts,)
    top = np.argsort(logits)[-k:]
    g = np.exp(logits[top] - logits[top].max()); g /= g.sum()
    return sum(gi * experts[i](x) for gi, i in zip(g, top))

19.2Load-balancing loss (Switch Transformer)

Laux=α N∑i=1Nfi Pi\mathcal{L}_{\text{aux}} = \alpha\, N \sum_{i=1}^{N} f_i\, P_i
What it means
f_i is the fraction of tokens sent to expert i and P_i the average router probability for it. The sum is smallest when tokens spread evenly over the N experts.
Where an LLM uses it
Added to the training loss with alpha = 0.01 so no expert is overloaded while others sit idle.
python
import numpy as np

def load_balance_loss(router_probs, assignments, n_experts, alpha=0.01):
    # router_probs: (tokens, N); assignments: (tokens,) chosen expert ids
    f = np.bincount(assignments, minlength=n_experts) / len(assignments)
    P = router_probs.mean(0)
    return alpha * n_experts * float(f @ P)

uniform = np.full((8, 4), 0.25)
print(load_balance_loss(uniform, np.array([0, 1, 2, 3] * 2), 4))  # 0.01, the minimum

19.3Total versus active parameters

Nactive=Nshared+k⋅Nexpert,Ntotal=Nshared+nexperts⋅NexpertN_{\text{active}} = N_{\text{shared}} + k \cdot N_{\text{expert}}, \qquad N_{\text{total}} = N_{\text{shared}} + n_{\text{experts}} \cdot N_{\text{expert}}
What it means
Memory pays for every expert. Compute per token pays only for the k experts used.
Where an LLM uses it
Mixtral 8x7B: each token has access to 47B parameters but uses 13B active parameters.
python
def moe_params(shared, per_expert, n_experts, k):
    return shared + n_experts * per_expert, shared + k * per_expert

20 faster with the same output

Speculative decoding

A small draft model guesses several tokens. The large model checks them all in one pass and keeps the ones it agrees with.

20.1Acceptance rule

accept x∼q with probability min⁡ ⁣(1, p(x)q(x)),else resample from max⁡(0, p−q)∑max⁡(0, p−q)\text{accept } x \sim q \text{ with probability } \min\!\Big(1,\, \frac{p(x)}{q(x)}\Big), \quad \text{else resample from } \frac{\max(0,\, p - q)}{\sum \max(0,\, p - q)}
What it means
q is the draft model, p the target model. Accept a drafted token when the target likes it at least as much; otherwise accept by ratio, and on rejection sample from the leftover mass.
Where an LLM uses it
This rule makes the output distribution exactly p, so the speedup costs no quality.
python
import numpy as np

def speculative_accept(x, p, q, rng):
    if rng.random() < min(1.0, p[x] / q[x]):
        return x, True
    resid = np.maximum(0, p - q)
    return int(rng.choice(len(p), p=resid / resid.sum())), False

# check: accepted-or-resampled tokens follow p
rng = np.random.default_rng(0)
p, q = np.array([0.6, 0.3, 0.1]), np.array([0.2, 0.3, 0.5])
draws = [speculative_accept(rng.choice(3, p=q), p, q, rng)[0] for _ in range(100_000)]
print(np.bincount(draws) / len(draws))  # about 0.6 0.3 0.1

20.2Expected tokens per target call

E[tokens]=1−αγ+11−α\mathbb{E}[\text{tokens}] = \frac{1 - \alpha^{\gamma + 1}}{1 - \alpha}
What it means
With gamma drafted tokens and acceptance rate alpha, this is how many tokens one call to the big model produces on average.
Where an LLM uses it
Tuning the draft length: longer drafts only pay off when alpha is high.
Example
alpha = 0.8 and gamma = 4 gives 3.36 tokens per call of the large model.
python
def expected_tokens(alpha, gamma):
    return (1 - alpha ** (gamma + 1)) / (1 - alpha)

print(round(expected_tokens(0.8, 4), 2))  # 3.36

The 44 papers behind these formulas

Every source is the original paper or its arXiv page, free to read.

  1. Sennrich, Haddow & Birch 2016, Neural Machine Translation of Rare Words with Subword Units
  2. Radford et al. 2019, Language Models are Unsupervised Multitask Learners (GPT-2, byte-level BPE)
  3. Vaswani et al. 2017, Attention Is All You Need
  4. Press & Wolf 2017, Using the Output Embedding to Improve Language Models
  5. Su et al. 2021, RoFormer: Enhanced Transformer with Rotary Position Embedding
  6. Press, Smith & Lewis 2021, Train Short, Test Long (ALiBi)
  7. Milakov & Gimelshein 2018, Online normalizer calculation for softmax
  8. Dao et al. 2022, FlashAttention
  9. Ba, Kiros & Hinton 2016, Layer Normalization
  10. Zhang & Sennrich 2019, Root Mean Square Layer Normalization
  11. Xiong et al. 2020, On Layer Normalization in the Transformer Architecture
  12. Hendrycks & Gimpel 2016, Gaussian Error Linear Units (GELUs)
  13. Shazeer 2020, GLU Variants Improve Transformer
  14. He et al. 2015, Deep Residual Learning for Image Recognition
  15. Kaplan et al. 2020, Scaling Laws for Neural Language Models
  16. Radford et al. 2019, Language Models are Unsupervised Multitask Learners
  17. Rumelhart, Hinton & Williams 1986, Learning representations by back-propagating errors
  18. Pascanu, Mikolov & Bengio 2013, On the difficulty of training Recurrent Neural Networks
  19. Kingma & Ba 2014, Adam: A Method for Stochastic Optimization
  20. Loshchilov & Hutter 2017, Decoupled Weight Decay Regularization
  21. Rajbhandari et al. 2019, ZeRO: Memory Optimizations Toward Training Trillion Parameter Models
  22. Loshchilov & Hutter 2016, SGDR: Stochastic Gradient Descent with Warm Restarts
  23. Hoffmann et al. 2022, Training Compute-Optimal Large Language Models (Chinchilla)
  24. Shazeer 2019, Fast Transformer Decoding: One Write-Head is All You Need (MQA)
  25. Ainslie et al. 2023, GQA: Training Generalized Multi-Query Transformer Models
  26. Touvron et al. 2023, Llama 2: Open Foundation and Fine-Tuned Chat Models
  27. Hinton, Vinyals & Dean 2015, Distilling the Knowledge in a Neural Network (softmax temperature)
  28. Fan, Lewis & Dauphin 2018, Hierarchical Neural Story Generation (top-k)
  29. Holtzman et al. 2019, The Curious Case of Neural Text Degeneration (top-p)
  30. Jacob et al. 2017, Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference
  31. Dettmers et al. 2022, LLM.int8(): 8-bit Matrix Multiplication for Transformers at Scale
  32. Dettmers et al. 2023, QLoRA: Efficient Finetuning of Quantized LLMs
  33. Hu et al. 2021, LoRA: Low-Rank Adaptation of Large Language Models
  34. Christiano et al. 2017, Deep reinforcement learning from human preferences
  35. Ouyang et al. 2022, Training language models to follow instructions with human feedback
  36. Schulman et al. 2017, Proximal Policy Optimization Algorithms
  37. Schulman et al. 2015, High-Dimensional Continuous Control Using Generalized Advantage Estimation
  38. Shao et al. 2024, DeepSeekMath (GRPO)
  39. Rafailov et al. 2023, Direct Preference Optimization: Your Language Model is Secretly a Reward Model
  40. Shazeer et al. 2017, Outrageously Large Neural Networks: The Sparsely-Gated Mixture-of-Experts Layer
  41. Fedus, Zoph & Shazeer 2021, Switch Transformers
  42. Jiang et al. 2024, Mixtral of Experts
  43. Leviathan, Kalman & Matias 2022, Fast Inference from Transformers via Speculative Decoding
  44. Chen et al. 2023, Accelerating Large Language Model Decoding with Speculative Sampling

Questions about the math

What math do you need to understand LLMs?

Linear algebra (matrix multiplication, dot products), basic calculus (derivatives and the chain rule) and probability (softmax distributions, log-likelihood). This page uses nothing beyond that.

Which formula matters most?

Scaled dot-product attention and the cross-entropy loss. Attention is what the model computes, and cross-entropy is what training minimizes. Most other sections make one of those two faster, cheaper or more stable.

Are these the exact formulas production models use?

They are the versions from the original papers. Production models combine them (RoPE, RMSNorm, SwiGLU, GQA and AdamW is a common recipe) and add engineering details such as fused kernels and parallelism that do not change the math.

Do the snippets run?

Yes. Every snippet uses only Python and NumPy and was executed before this page was built. They are small building blocks for learning.

Why does 6ND keep showing up?

Each weight costs about 2 FLOPs per token going forward and 4 going backward. Multiply by N weights and D tokens and you have the compute of a training run.