From Tokens to Transformers

The mathematics of LLMs

Kempelen’s “The Turk” · Wikimedia

Tokenization

I am Locutus, of Borg

I40 ·am1097 ·Loc13914 ut332 us355 ,11 ·of315 ·Borg65582

\[ \operatorname{enc}:\mathcal S\longrightarrow\mathcal V^{*}, \qquad \underbrace{\mathcal V}_{\text{vocabulary}} =\{\,\underbrace{v_1,\ldots,v_{V}}_{\text{tokens}}\,\},\qquad |\mathcal V|=V \]

Vocabulary

start from small unitsl · o · w · e · r
count frequent adjacent pairs
merge one pairl · o · w · er
repeat under a vocabulary budget
learn reusable pieceslow · er

Next-token prediction

The theorem follows from

\[ P:\;\Theta\times\mathcal V^{*}\longrightarrow\Delta(\mathcal V) \]

\[ \bigl(\underset{\substack{\uparrow\\ \text{parameters}}}{\theta}\,,\; \underset{\substack{\uparrow\\ \text{context}}}{c}\bigr) \longmapsto p_\theta(\cdot\mid c) \]

\[ \Delta(\mathcal V):=\Bigl\{q\in\mathbb R^{\mathcal V}_{\ge 0}:\textstyle\sum_{a\in\mathcal V}q_a=1\Bigr\} \]

·the0.525
·a0.062
·The0.040
·Lemma0.018
·Proposition0.012
·an0.011
·Cor0.010
·[0.009
·this0.008
·(0.007
all 151,926 others0.298

actual next-token distribution, Qwen2.5-0.5B · \(V=151{,}936\)

Token prediction vs. language modelling

A language distribution

\[ p:\mathcal V^{*}\longrightarrow[0,1], \qquad \sum_{x\in\mathcal V^{*}}p(x)=1 \]

\[ q_\theta(x_1,\ldots,x_T) = \prod_{t=1}^{T} p_\theta(x_t\mid x_{<t}) \]

The space of models

Context is bounded: a window \(C\)  (\(C=32{,}768\) for Qwen2.5-0.5B; \(C\approx 10^{6}\) at the frontier)

\[ P(\theta,\cdot):\ \mathcal V^{\le C}\longrightarrow\Delta(\mathcal V) \]

So the models form a product of simplices — of absurd dimension

\[ \Delta(\mathcal V)^{\mathcal V^{\le C}}, \qquad \bigl|\mathcal V^{\le C}\bigr|=\frac{V^{C+1}-1}{V-1}\;>\;10^{5\,000\,000} \quad\text{contexts at } C=10^{6} \]

A lookup table — one row per context — is out. A transformer architecture realizes a subset of these models with only \(\sim\!10^{12}\) parameters.

The game: make that subset flexible enough to pass close to the model you want.

Learning

Parametrized family of functions

\[ f_\theta:\mathbb R^{2}\longrightarrow[0,1], \qquad \theta\in\Theta \]

Training samples

\[ (\mathbf x_i,y_i)_{i=1}^{N}, \qquad \mathbf x_i\in\mathbb R^{2}, \quad y_i\in\{0,1\} \]

Neural network

Gradient Descent

Likelihood

\[ L(\theta)=\prod_{i=1}^{N} f_\theta(\mathbf x_i)^{\,y_i}\, \bigl(1-f_\theta(\mathbf x_i)\bigr)^{1-y_i} \]

Average negative log likelihood, or cross-entropy loss

\[ \mathcal L(\theta) :=-\frac1N\log L(\theta) \]

Gradient descent, with learning rate \(\eta>0\)

\[ \theta^{(t+1)}:=\theta^{(t)}-\eta\,\nabla\mathcal L\bigl(\theta^{(t)}\bigr), \qquad t\ge 0 \]

Translate the toy problem to language

Playground Language model
point \(\mathbf x\in\mathbb R^2\) token context \(c\in\mathcal V^{*}\)
gold label \(y_i\) observed next token
\(f_\theta(\mathbf x)\in[0,1]\) \(p_\theta(\cdot\mid c)\in\Delta(\mathcal V)\)
classification loss next-token cross-entropy loss
small neural network causal transformer

Latent (embedding) space

\[ E\in\mathbb R^{V\times d}, \qquad x_t\longmapsto E_{x_t}\in\mathbb R^{d}. \]

The[  .2   −.7   ···   .1  ]

theorem[ −.4   .3   ···   .8  ]

follows[  .6   −.1   ···   −.3  ]

\(d\) is the model width. In a modern LLM it is a few thousand: \(d=4096\) at 7B parameters, \(d=8192\) at 72B.

Embedding map is learned.

Embedding geometry

Nearest neighbours in \(E\) (cosine)

·theorem theorem .68  ·lemma .46  orem .45  ·proposition .32
·seven ·six .77  ·eight .75  ·nine .74  ·five .73
·Paris Paris .80  巴黎 .65  ·France .46  ·London .39
·Borg borg .35  𝘉 .31  🕉 .30  𐌰 .30 rare token: stray glyphs

measured in Qwen2.5-0.5B’s embedding matrix \(E\); the mark · is a leading space

Linear structure

\[ E_{\texttt{king}}-E_{\texttt{man}}+E_{\texttt{woman}} \;\approx\; E_{\texttt{queen}} \]

Cyclic structure

the twelve months on the top two principal components of their own span — real coordinates from Qwen2.5-0.5B’s \(E\)

The Residual Stream

\[ X^{(0)}\longrightarrow X^{(1)}\longrightarrow\cdots\longrightarrow X^{(L)}, \qquad X^{(\ell)}\in\mathbb R^{T\times d} \]

The Residual Stream Initial Values

\[ X_t^{(0)}=E_{x_t}+P_t. \]

Modern LLMs: positional mechanism elsewhere

Layers  →

Streams  →

X(0)token embedding X(1)after block 1 X(2)after block 2 X(24)after block 24
The
theorem
follows
from

Every tile is one real residual stream: all \(896\) coordinates, one pixel each, \(32\times 28\). Qwen2.5-0.5B  ·  \(T=4\), \(d=896\), \(L=24\).

Query, Key, Value

QUERYwhat this position seeks
KEYwhat this position advertises
VALUEwhat this position can send

\[ Q=XW_Q, \quad W_Q\in\mathbb R^{d\times d_k} \]

\[ K=XW_K, \quad W_K\in\mathbb R^{d\times d_k} \]

\[ V=XW_V, \quad W_V\in\mathbb R^{d\times d_v} \]

\(W_Q,\ W_K,\ W_V\) are learned — part of \(\theta\).

Attention

\[ S=\frac{QK^{\top}}{\sqrt{d_k}}\in\mathbb R^{T\times T}, \qquad S_{ij}=\frac{\langle q_i,k_j\rangle}{\sqrt{d_k}} \]

keys  →

queries  →

Open the pod bay doors , Hal
Open 11.5 4.3 -1.4 -0.2 5.8 8.9 3.6
the 11.5 12.3 3.2 -2.3 0.8 7.2 6.0
pod 13.3 15.5 11.0 1.6 -0.8 3.0 1.4
bay 13.4 12.2 16.2 12.0 6.3 2.9 -4.5
doors 14.2 5.4 14.1 17.7 13.3 5.9 -9.3
, 13.7 0.2 5.0 13.5 16.2 12.0 -1.8
Hal 12.2 2.2 0.8 5.3 12.6 14.4 10.5

Qwen2.5-0.5B, layer 8 head 7  ·  actual values

Attention (with masking)

\[ S+M, \qquad M_{ij}=\begin{cases}0,&j\le i\\ -\infty,&j>i\end{cases} \]

keys  →

queries  →

Open the pod bay doors , Hal
Open 11.5 −∞ −∞ −∞ −∞ −∞ −∞
the 11.5 12.3 −∞ −∞ −∞ −∞ −∞
pod 13.3 15.5 11.0 −∞ −∞ −∞ −∞
bay 13.4 12.2 16.2 12.0 −∞ −∞ −∞
doors 14.2 5.4 14.1 17.7 13.3 −∞ −∞
, 13.7 0.2 5.0 13.5 16.2 12.0 −∞
Hal 12.2 2.2 0.8 5.3 12.6 14.4 10.5

Qwen2.5-0.5B, layer 8 head 7  ·  actual values

Attention (with masking and softmax)

\[ A=\operatorname{softmax}_{\mathrm{row}}(S+M), \qquad A_{ij}\ge 0,\quad \sum_j A_{ij}=1 \]

keys  →

queries  →

Open the pod bay doors , Hal
Open 1.00 0 0 0 0 0 0
the 0.31 0.69 0 0 0 0 0
pod 0.10 0.89 0.01 0 0 0 0
bay 0.05 0.02 0.92 0.01 0 0 0
doors 0.03 0.00 0.03 0.93 0.01 0 0
, 0.07 0.00 0.00 0.06 0.86 0.01 0
Hal 0.09 0.00 0.00 0.00 0.12 0.78 0.01

Qwen2.5-0.5B, layer 8 head 7  ·  actual values

Mixing the values

\[ AV\in\mathbb R^{T\times d_v}, \qquad (AV)W_O\in\mathbb R^{T\times d} \]

\(W_O\) is learned — the head’s fourth and last parameter matrix. \(A\) is not: it is recomputed for every input.

All 336 attention heads at once

Layers  →

Heads  →

Every head’s matrix \(A\) on the HAL sentence — actual values. Gold frame: the head we dissected.

A transformer LLM

embedding  ·  Q, K, V  ·  the attention matrix  ·  the MLP  ·  residual  ·  softmax over the vocabulary

Transformer Explainer, Polo Club of Data Science, Georgia Tech  ·  GPT-2 small, running in the browser

Pretraining

Gradient descent, over next tokens of corpus

\[ \mathcal L(\theta) =-\frac1M\sum_{s}\sum_{t} \log p_\theta\!\left(x^{(s)}_t\mid x^{(s)}_{<t}\right) \]

One sequence supplies many targets

\[ x_{<2}\mapsto x_2, \qquad x_{<3}\mapsto x_3, \qquad\ldots\qquad x_{<T}\mapsto x_T \]

Result: a continuation machine, fitted on roughly \(10^{13}\) tokens.

Supervised Fine-Tuning

on the scene ≈ 2021–22  ·  FLAN, InstructGPT

Demonstrations — prompts \(c\) with replies \(y\) written by annotators, or by a stronger model

\[ \left(c^{(i)},\,y^{(i)}\right)_{i=1}^{N}, \qquad \mathcal L_{\mathrm{SFT}}(\theta) =-\sum_{i}\sum_{t} \log p_\theta\!\left(y^{(i)}_t\mid c^{(i)},\,y^{(i)}_{<t}\right) \]

Thousands to millions of curated examples, totalling roughly \(10^{6}\)\(10^{9}\) tokens. The model now answers instead of continuing.

Chain of thought

a prompting trick 2022 (“think step by step”)  ·  trained-in 2024–  ·  now woven through all post-training

The answer token, two ways

\[ p_\theta(\text{answer}\mid q) \qquad\text{vs.}\qquad p_\theta(\text{answer}\mid q,\ \underbrace{w_1,\ldots,w_k}_{\text{its own written working}}) \]

17 × 24 = ? 17×20 = 340,  17×4 = 68,  340+68 = 408

A fixed network does bounded computation per token.

Reinforcement Learning from Human Feedback

preferences 2017 (Christiano et al.)  ·  at LLM scale 2022 (InstructGPT → ChatGPT)  ·  direct preference optimization (DPO) 2023

The data are comparisons, not targets

\[ \left(c,\;y^{+}\succ y^{-}\right) \]

Fit a reward model \(r\) to the comparisons, by a type of logistic regression

\[ \Pr\left[\,y^{+}\succ y^{-}\mid c\,\right] =\sigma\!\left(r(c,y^{+})-r(c,y^{-})\right) \]

Then maximize judged quality while staying near a reference model

\[ \max_\theta\; \mathbb E_{y\sim p_\theta(\cdot\mid c)}\!\left[r(c,y)\right] \;-\; \beta\,\mathrm{KL}\!\left(p_\theta(\cdot\mid c)\,\middle\|\,p_{\mathrm{ref}}(\cdot\mid c)\right) \]

Learning on its own output — typically \(10^{5}\)\(10^{6}\) human comparisons (Llama 2: \(1.4\)M).

Reward hacking

A simulated claw hovering on the camera-ball sightline, appearing to grasp
Paid to grasp, it hovers on the camera–ball line — the human judge sees a grasp. (Christiano et al., 2017)
The CoastRunners boat circling respawning bonuses instead of racing
Paid for score, it circles respawning bonuses, on fire, never finishing — and outscores the racers. (CoastRunners, 2016)

Raters favour agreement and length, so chatbots learn to flatter and to pad.

Reinforcement Learning with Verifiable Rewards

on the scene 2024–  ·  o1, DeepSeek-R1

Some domains contain their own judge

\[ r(c,y)= \begin{cases} 1,&\text{the answer verifies — the tests pass, the value matches}\\ 0,&\text{otherwise} \end{cases} \]

The same objective as RLHF — but \(r\) is ground truth, not a fit

\[ \max_\theta\; \mathbb E_{y\sim p_\theta(\cdot\mid c)}\!\left[r(c,y)\right] \;-\; \beta\,\mathrm{KL}\!\left(p_\theta\,\middle\|\,p_{\mathrm{ref}}\right) \]

Math and code (where we have Lean and compilers, code tests).

Scaffolding

The system surrounding the model writes tokens into the context (memory, tools).

The raw context

<|im_start|>system
You are a helpful assistant.

# Tools

You may call one or more functions to assist with the user query.

You are provided with function signatures within <tools></tools> XML tags:
<tools>
{"type": "function", "function": {"name": "web_search", "description": "Search the web", "parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}}
{"type": "function", "function": {"name": "memory", "description": "Store a note about the user that persists across conversations", "parameters": {"type": "object", "properties": {"note": {"type": "string"}}, "required": ["note"]}}}
</tools>

For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:
<tool_call>
{"name": <function-name>, "arguments": <args-json-object>}
</tool_call><|im_end|>
<|im_start|>user
Who is Locutus of Borg? (I'm a Star Trek fan, by the way.)<|im_end|>
<|im_start|>assistant
<think>Two things: a factual question I should search, and a durable fact about the user worth remembering.</think>
<tool_call>
{"name": "web_search", "arguments": {"query": "Locutus of Borg"}}
</tool_call>
<tool_call>
{"name": "memory", "arguments": {"note": "The user is a Star Trek fan."}}
</tool_call><|im_end|>
<|im_start|>user
<tool_response>
Locutus of Borg: the Borg identity imposed on Captain Jean-Luc Picard after his assimilation (TNG, "The Best of Both Worlds", 1990).
</tool_response>
<tool_response>
Saved.
</tool_response><|im_end|>
<|im_start|>assistant
Locutus of Borg is the name the Borg gave Captain Picard after assimilating him in "The Best of Both Worlds" (1990). And noted - I'll remember you're a fan.<|im_end|>

Shaded gold: what the model emits. Everything else is supplied to it — user, tools, template. The format is real (rendered verbatim by Qwen2.5’s chat template, \(416\) tokens); the conversation is staged, <think> per DeepSeek-R1 / QwQ.