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.
Each row is one token. It spreads a weight of 1 over itself and the tokens before it. The mask hides the future.
thecatsatonthemat
the1.00
cat0.440.56
sat0.500.170.32
on0.370.230.240.17
the0.240.230.150.210.16
mat0.120.170.140.140.310.12
Contents in reading order
Tokens, attention, training, scaling, serving and alignment. Each part builds on the one before it, and every code block was run before this page was built.
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 inzip(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)-1and(w[i], w[i +1])==(a, b):
new.append(a + b); i +=2else:
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')
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 tokenreturnfloat(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.
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
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 isnotNone:
s = s + mask
return softmax(s)@ V
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))/6for _ inrange(4)]print(multi_head(X,*W, h=4).shape)# (6, 32)
4.7Online softmax (the trick inside FlashAttention)
m′=max(m,x),ℓ′=ℓem−m′+ex−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.0for 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.
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):return0.5* x *(1+ np.vectorize(erf)(x / sqrt(2)))def gelu_tanh(x):return0.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
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):return12* L * d **2print(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.
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.
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
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
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 what serving costs
Inference cost and the KV cache
Generating a token reuses the keys and values of every earlier token. Their storage usually sets the limit.
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))
V(p)=smallest set with v∈V(p)∑p(v)≥p,p′(v)∝p(v)1[v∈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()returnint(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 fewer bits per weight
Quantization
Weights stored in 16 bits can usually be stored in 8 or 4 with a small loss. Fewer bytes means less memory and faster decoding.
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 <=8else 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())
overhead bits per weight=block sizebits per scale
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.
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
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.
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()returnsum(gi * experts[i](x)for gi, i inzip(g, top))
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
accept x∼q with probability min(1,q(x)p(x)),else resample from ∑max(0,p−q)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)returnint(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 _ inrange(100_000)]print(np.bincount(draws)/len(draws))# about 0.6 0.3 0.1
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.