Treatise
Irreducible
The mathematics of the autoregressive Transformer
A complete, notation-stable treatise on building, training, and running an LLM: tokens, residual stream, attention, SwiGLU, cross-entropy, Jacobians, AdamW, and inference. Every symbol defined where it is used. Loss is driven toward zero. It never arrives.
00 · Object
The object of study
An LLM is a map from token IDs to logits. Training only ever sees next-token conditionals.
What is being built
An LLM, in the sense used throughout this treatise, is a single differentiable function from a sequence of discrete token IDs to a matrix of logits — one row per position, one column per vocabulary item.
- vocabulary size (number of distinct tokens)
- sequence length of this forward pass
- model / residual-stream width
- number of Transformer layers
- every learnable number in the network
- token IDs, each x_t \in \{1,\dots,V\}
Why it mattersTraining never “understands a paragraph as a whole” as a primitive. It only learns next-token conditionals. Every later capability is a side effect of making those conditionals accurate.
The probabilistic model is autoregressive. The joint over a sequence factorizes into a product of next-token conditionals. There is no separate “sentence model.”
- (x_1,\dots,x_{t-1}); empty when t = 1
- the model’s categorical over V tokens at step t
Two modes of the same network
The same function is used in two incompatible ways. Training has a correct next token sitting in a dataset, so a loss exists, so a gradient exists, so moves. Inference has no such token. The weights freeze. Only the forward map runs.
Forward map. Training attaches CE → Jacobians → AdamW after p. Inference samples from p.
Notation that does not change
Every later chapter uses the same letters. Residuals are with rows . Attention is the only mixer. Everything else is applied positionwise. The unembedding produces logits , and softmax turns a row into .
01 · A · Data
Tokenization and targets
Text becomes integers. Loss, perplexity, and “zero” are defined on this vocabulary, not on English words.
Raw text becomes integers
A tokenizer — almost always BPE, SentencePiece, or Unigram — cuts raw bytes into a finite vocabulary. The model never sees characters as characters. From this point on, every quantity that can go to zero is defined on those integers.
Byte-pair encoding (Sennrich, Haddow, and Birch, 2016) is the usual algorithm. Start with a vocabulary of bytes. Count adjacent pairs in the corpus. Merge the most frequent pair into a new token. Repeat until the vocabulary has size . Encoding a new string is the greedy application of those merges, left to right.
- adjacent tokens in the current segmentation
- final vocabulary size: bytes plus the learned merges
Why it mattersThe tokenizer is not part of θ. It is a frozen preprocessing map. Changing it changes the units of every later number — loss, perplexity, the fitted floor E — which is why bits-per-byte is the fair comparison.
A training example is one sequence . The supervision target at position is the next token . Position either has no target, or sequences are packed so every position has a successor.
- one-hot target at position t
- the true next token in the document
- vocabulary size, typically 32k–256k
Why it mattersLoss, perplexity, and “what zero loss would mean” live on this discrete vocabulary, not on English words. A larger vocabulary usually raises per-token loss even if the model is a better compressor.
The causal shift
In code this is a one-position shift: logits at index predict token . The first token has no predecessor; the last logit is either unused or predicts the first token of the next packed span.
02 · B · Embed
Embeddings and position
Tokens enter a vector space. RoPE injects order by rotating query/key pairs.
Token embedding
A learned matrix stores one row per token. Looking up token is a gather; equivalently, a one-hot times .
- token embedding matrix, V×d
- the d-vector for token x_t
- one-hot sequence, T×V
Absolute position (GPT-2 style)
Without a position signal the Transformer is a bag of tokens. Absolute embeddings add a learned vector per index.
- learned positions, T_max × d
- residual-stream vector at layer 0
RoPE (Llama-style default)
Rotary position embeddings (Su et al., 2021) add no extra vector to the residual stream. After Q and K are formed, each even/odd pair of coordinates is rotated by an angle that depends on position. Inner products then depend on the difference , not on absolute and separately.
- head dimension (even)
- pair index 0, 1, …, d_h/2 − 1
- base frequency, usually 10,000 (or a long-context variant)
Write for the block-diagonal matrix of all pair rotations at position . Rotations compose, and :
Why it mattersThe rotation is orthogonal, so it preserves norms. The backward pass is the inverse rotation (the transpose). Relative position is baked into the attention score, which is why RoPE extrapolates farther than absolute embeddings.
03 · C · Block
The pre-norm Transformer block
Residual highways, RMSNorm, and the two sublayers that every modern decoder stacks.
Pre-norm residual block
Modern decoder LLMs stack identical pre-norm blocks. Each block writes a residual delta into the stream, twice: once from attention, once from the MLP.
- layer index, 1 … n
- residual stream after layer ℓ, T×d
- stream after the attention residual
Why it mattersResiduals are the highway that lets gradients travel through dozens of layers (He et al., 2016). The skip has Jacobian I, so there is always a path that does not vanish.
RMSNorm
RMSNorm scales a vector by its root-mean-square and a learned gain (Zhang and Sennrich, 2019). It does not subtract the mean and has no bias. Llama-style models use it.
- one residual-stream vector
- small constant, e.g. 10^{-6}
- learned scale
- elementwise multiply
Why it mattersNorms keep residual-stream scale stable so attention scores and MLP activations do not explode as depth grows.
LayerNorm
LayerNorm also subtracts the mean and usually has a bias. GPT-2 uses it. The extra projection orthogonal to is the only structural difference.
- mean of u
- variance of u
- learned bias
04 · C · Mix
Causal attention
The only place tokens mix. Scale, mask, softmax, GQA, and the softmax Jacobian.
Queries, keys, values
From normalized input , three linear maps produce Q, K, V. They are then split into heads of width . If RoPE is used, Q and K are rotated now.
- projections in R^{d × d} (or d × H d_h)
- head h, each T × d_h
Scores, scale, causal mask, softmax
Why it mattersA typical coordinate of q and k is O(1), so a typical dot product is O(√dₕ). The √dₕ scale (Vaswani et al., 2017) puts scores back at O(1). Without it, softmax saturates as dₕ grows and the Jacobian vanishes.
Future tokens must be invisible. The causal mask writes above the diagonal so those entries become zero after softmax.
- a probability distribution over past-and-present positions
Why it mattersAttention is the only place tokens mix. Everything else is applied positionwise. The causal mask is what makes the model a next-token predictor rather than a bidirectional encoder.
- output projection, d × d
- Attn(U), written back into the residual stream
Softmax Jacobian
For one row :
Why it mattersThis Jacobian is symmetric, has null space along 1 (softmax is shift-invariant), and is positive semidefinite on the simplex tangent space. You will meet it again in the p − y collapse.
Grouped-query and multi-query attention
Multi-head attention uses query and key/value heads. Multi-query (Shazeer, 2019) uses one KV head. Grouped-query (Ainslie et al., 2023) sits in between: Llama-3-class models share each KV head across a group of query heads. The score math is the same; the cache is smaller.
- number of query heads
- number of key/value heads, 1 ≤ H_kv ≤ H_q
- group size; g = 1 is MHA, H_kv = 1 is MQA
Why it mattersThe KV cache at inference is O(T · n · H_kv · d_h), not O(T · n · H_q · d_h). That memory, not the matmul, is what bounds generation length.
05 · C · Compute
MLP and SwiGLU
Per-token computation and the wide matrices that store features.
Two-layer GELU FFN (GPT-2)
Attention moves information between positions. The MLP is the per-token computation: feature mixing, and a large fraction of stored knowledge in the wide matrices.
- GELU
- up-projection, typically to 4d
- down-projection, back to d
- standard Gaussian CDF; Hendrycks and Gimpel, 2016
SwiGLU (Llama)
Gated linear units (Shazeer, 2020) replace the single nonlinearity with a product of a SiLU-gated branch and a linear “up” branch. There is no bias in the usual Llama formulation. The up-projection is written so it is never confused with the unembedding .
- gate and up, d × d_ff
- down, d_ff × d
- inner width, often ~ 8d/3 so parameter count matches 4d GELU
Why it mattersYou need this derivative in the backward pass. The extra σ(z)(1−σ(z)) term is the sigmoid Jacobian.
06 · D · Readout
Unembedding to probabilities
A final norm, a linear map into V dimensions, and a categorical distribution per position.
Final norm and unembedding
After blocks we have . A last norm, then a linear map into the vocabulary, produces logits.
- unembedding matrix, d × V — never the SwiGLU up-projection
- row t of Z: logits at position t
Some models tie (Press and Wolf, 2017; Inan, Khosravi, and Socher, 2017). Tied embeddings save parameters and couple the geometry of “looking up a token” with “predicting a token.” Untied is the Llama default.
From logits to a categorical
- a probability distribution over the vocabulary
- probability assigned to the true next token
Why it mattersThis is the model’s entire prediction: one categorical distribution per position. Everything before this was geometry in R^d. This is the interface to discrete text.
07 · E · Signal
Loss, entropy, and scaling
Cross-entropy is maximum likelihood. It decomposes into entropy plus KL. The floor is E, not zero.
Cross-entropy is maximum likelihood
The autoregressive model is a probability distribution over sequences. Maximizing the likelihood of the training documents is exactly minimizing next-token cross-entropy.
Why it mattersThere is no extra objective hiding behind the loss. Pretraining is MLE of the next-token categorical. Every later capability is a side effect of making that likelihood large.
Token-level cross-entropy
PyTorch CrossEntropyLoss on logits is exactly this, in nats.
- NLL of the true next token, in nats
- positions that are not padding / not masked
Why it mattersThis scalar is the only training signal in pretraining. Backprop exists solely to make L smaller.
Entropy plus KL
If is the true next-token distribution of the data, the expected loss splits into two terms (Cover and Thomas). Training can only shrink the second.
- entropy of language: irreducible uncertainty
- extra loss from the model being wrong
for open language, so is not achievable on a general corpus. Fitted irreducible floors on web-scale English tokenizers are often around nats/token.
Perplexity and bits-per-byte
Loss 2.0 nats/token is perplexity . Loss 1.69 is about 5.4. Read it as: “as uncertain as choosing among about 5–7 equally likely tokens,” on average.
Loss is not comparable across tokenizers. Bits-per-byte is the fairer comparison. If a document of bytes is tokenized into tokens:
- loss in bits per token
- tokens per byte for this tokenizer and document
Classic estimates of English entropy are roughly 0.6–1.3 bits per character (Shannon, 1951); frontier models are often cited around ~0.7 bits per character on diverse English — already near those old bounds on many corpora.
Scaling-law shape
This is a forecast of pretraining loss, not a training step. DeepMind’s Chinchilla fit (Hoffmann et al., 2022):
- parameter count
- training tokens
- estimated irreducible loss
- penalty for finite model size
- penalty for finite data
Their original fit put , , , , . A later replication (Besiroglu, Erdil, Barnett, 2024) put closer to and a larger data coefficient. Those numbers are estimates for a data mix and a tokenizer, not a universal constant.
Training compute is, to a standard approximation (Kaplan et al., 2020),
- ≈ 2 FLOPs/param/token for the forward pass, 4 for the backward
Minimize (7.5) along the budget line . The compute-optimal allocation is
- ≈ 0.46 on the printed Chinchilla fit
- ≈ 0.54
- (\alpha A / \beta B)^{1/(\alpha+\beta)}
Why it mattersThe IsoFLOP experiments, which do not depend on the parametric constants, said something simpler: scale N and D equally, about twenty tokens per parameter. Chinchilla-70B was trained that way (70B × 1.4T). Kaplan had recommended many fewer tokens; that is the disagreement the floor does not care about.
| Stage | Loss (nats) | Meaning |
|---|---|---|
| Random initialization | ln V ≈ 10.8–11.8 | Uniform over 50k–128k tokens |
| Early training | ~4–6 | Crude word and syntax statistics |
| Small modern pretrain | ~2.0–2.5 | Competent next-token model |
| Strong large pretrain | ~1.7–2.1 | Near fitted irreducible floors |
| Narrow SFT, regular data | ~0.2–0.8 | The task is less uncertain than web text |
| Overfit a tiny set | → 0 | Memorization, not general language |
08 · E · Floor
Why loss is not zero
Context collapses meaning. It does not collapse the next token. The floor is entropy, not tautology.
Context kills branching. It does not kill the string.
Conditional entropy falls as context grows. That is not controversial.
If the prompt is only “After tomorrow is”, the calendar is unpinned. Supply “Today is Sunday” and Tuesday is the unique calendar answer. Ambiguity was unfinished context. Semantic collapse is real.
What does not follow is: therefore the next token becomes unique. All of these can be true on Sunday:
- After tomorrow is Tuesday.
- After tomorrow’s Tuesday.
- After tomorrow it will be Tuesday.
- After tomorrow is the 16th.
- After tomorrow? Tuesday.
Same fact. Different tokens. The training objective is not “recover the unique true proposition.” It is “assign probability to the exact next token that happened to be in this document.”
Two layers, easy to mix
Semantic collapse. Given enough context, the intended meaning often becomes unique. “After tomorrow,” plus “today is Sunday,” plus “we are talking about weekdays,” leaves one date.
Realizational leftover. How that meaning gets worded, whether the speaker continues the sentence at all, what they mention next, in what register — that usually stays open.
A Born-rule picture is a fair analogy for sense: many readings exist while the sentence is incomplete; context makes one reading definite. It is a weaker analogy for the next token, because the “measurement” here is “whatever this particular writer typed,” and many typings are compatible with the same collapsed meaning.
Why the floor is not mystical
A huge fraction of remaining loss is missing context, not linguistic randomness. The data-generating process is many speakers, not one oracle with one lawful continuation. The model is not given the full world: it gets a window of text, not “it is Sunday and the speaker intends to name the weekday.”
Shannon already measured this with humans (1951). People who had seen the preceding text still could not guess the next character with certainty. Human conditional entropy of English is low, not zero. An LLM is trying to match that same process.
09 · F · Reverse
Backpropagation and Jacobians
Reverse-mode AD, the p − y collapse, RMSNorm, attention, SwiGLU, and the skip whose Jacobian is I.
Chain rule and Jacobians
Training is gradient descent on . Backprop is reverse-mode automatic differentiation: one backward sweep computes . If , , and is scalar:
- Jacobian of the local map
- vector-Jacobian product (VJP) — what is actually computed
In practice nobody materializes giant Jacobians. Frameworks compute VJPs. For a matrix multiply , with incoming gradient :
Why it mattersThose two identities run through almost the entire Transformer. Every linear map is this pair.
Softmax + cross-entropy collapses
This is the most important gradient in the whole system. Start from the definitions:
The upstream vector is . One-hot at makes that . The VJP through softmax is
Here and , so
Why it mattersYou do not backprop through softmax and log separately. The error signal is “probability assigned minus truth.” Overconfident wrong tokens get a large push; already-correct peaked predictions get a small one.
Into the residual stream and W_U
Then the final Norm Jacobian maps back to .
RMSNorm Jacobian (one vector)
Let , , .
Then follows by the product rule with . LayerNorm is the same idea after projecting orthogonal to (mean removal).
Attention backward
Fix one head. Forward: , , . Given :
RoPE’s backward pass is the inverse rotation. Then etc. give
The same for K, V. Multi-head: sum the contributions.
Residual Jacobian
Why it mattersThe first term is the skip connection. That is why deep Transformers train: there is always a path whose Jacobian is I.
SwiGLU backward
Let , , , , .
Then ordinary matmul rules for .
Embedding backward
is scattered back into the rows of (and if used):
10 · G · Step
AdamW, clip, and the schedule
Turning a gradient into a new θ without destroying a billion-parameter run.
Vanilla SGD is not what runs
Raw gradients in a Transformer have wild scale differences across layers. LLMs use AdamW: per-parameter adaptive steps, decoupled weight decay, a warmup-cosine schedule, and global-norm clipping.
AdamW
Let at optimizer step .
- scheduled learning rate
- first-moment decay, typically 0.9
- second-moment decay, 0.95 or 0.999
- weight decay, applied to θ directly (the “W”)
- 10^{-8}, avoid divide-by-zero
- elementwise square
Warmup then cosine decay
Gradient clipping
Before AdamW:
- clip threshold, often 1.0
- global L2 norm of the concatenated gradient
Why it mattersAdam normalizes per-parameter. Weight decay stops ‖θ‖ drifting. Clipping stops rare batches from destroying the run. The schedule starts gentle, then anneals so the model settles.
11 · H · Train
The training loop
Batch, forward, loss, backward, accumulate, clip, step. Train loss is not validation loss.
What actually runs
Repeat millions of steps:
- Sample a batch of sequences. Shape: token IDs.
- Forward: embeddings → blocks → logits .
- Compute on next-token targets (ignore pad / masked positions).
- Backward: reverse-mode AD gives .
- Optionally accumulate g over several micro-batches to fake a larger batch.
- Clip g, AdamW update, zero grads.
- Periodically evaluate validation loss on held-out data (no parameter update).
- number of micro-batches
- mean token loss on micro-batch k
Initialization
Embeddings and most projections start as small Gaussians. Residual-output projections are often scaled so the untrained skip path dominates at depth (GPT-2):
Why it mattersThe skip Jacobian still starts at I. Scaling the branch keeps H^{(ℓ)} from exploding before the first useful gradient. μP (Yang et al.) is the width-aware version: change d without retuning η.
Train loss is not the target
Batch loss is the mean of per-token losses. Mixed precision (BF16/FP16 forward, FP32 master weights and loss) is an implementation detail; the math above is the same. The loss itself is computed in FP32 so the log-sum-exp is not wrecked by underflow.
Training loss can keep falling by memorization. Validation loss estimates generalization. The entropy floor applies to both; validation is the one that tells you the model is not just reciting.
12 · I · Use
Inference and the KV cache
Frozen θ. Temperature, top-k, nucleus. Prefill once, then decode with cached keys and values.
Weights freeze. Only the forward map runs.
Once training is finished, is frozen. There is no “correct” next token sitting in a dataset, so there is nothing to compute a loss on and therefore nothing to back-propagate. Autoregressive generation:
- Start with prompt tokens .
- Forward → logits .
- Form a sampling distribution from .
- Draw , append, repeat.
Decoding math
- temperature. τ → 0 is greedy: argmax_k z_{t,k}
Top-k. Keep the largest logits, set the rest to , then softmax.
Nucleus / top-p (Holtzman et al., 2020). Keep the smallest set of tokens whose cumulative probability is at least , then renormalize.
No . No Jacobian. No Adam.
KV cache
Attention at step only needs and all past . Store (K, V) per layer:
New token: compute new , append , attend. Cost per new token is attention, not from scratch.
Prefill
O(T²)
One forward over the whole prompt. Every position attends to the past. Cache is filled.
Decode
O(t) / token
New q attends to cached K, V. Append one row. No Jacobian. No optimizer.
This is the entire user-facing model: frozen , forward pass, sample. Training was the process that carved . Inference only reads it.
13 · Map
End-to-end map and catalogue
The stacked forward equation, the train path, the infer path, Jacobians, and what each piece is for.
Stacked forward map
Forward map. Training attaches CE → Jacobians → AdamW after p. Inference samples from p.
Train path
Infer path
Jacobian catalogue
Reverse-mode AD never materializes most of these as matrices. It computes the vector-Jacobian products. Written out, they are the whole backward pass.
| Map | Jacobian / VJP |
|---|---|
| softmax | diag(a) − aaᵀ |
| CE + softmax | p − y |
| Y = XW | ∂L/∂X = G Wᵀ, ∂L/∂W = Xᵀ G |
| RMSNorm | r⁻¹ (I − uuᵀ / (d r²)) |
| LayerNorm | same, after P = I − 11ᵀ/d |
| residual H ↦ H + F(H) | I + J_Fᵀ |
| RoPE | Rᵀ = R⁻¹ |
| SiLU | σ(z) + z σ(z)(1 − σ(z)) |
| embedding lookup | scatter into row x_t |
What each piece is for
The whole machine is one differentiable map from token IDs to next-token distributions. Training differentiates that map and walks θ downhill on cross-entropy. Use-time throws the derivative away and only evaluates the map.
| Piece | Job |
|---|---|
| Tokenizer / BPE | Discrete interface to text. Frozen. Defines the units of loss. |
| Embedding + position | Put tokens into a space where order exists |
| Residual stream | Common currency every layer reads and writes |
| Norm | Control scale so depth does not explode |
| Causal attention | Move information from past tokens to the current one |
| √dₕ scale | Keep scores O(1) so softmax does not saturate |
| GQA / MQA | Share KV heads so the cache, not the matmul, stays small |
| MLP / SwiGLU | Per-token computation and stored features |
| Unembed + softmax | Turn vectors into a distribution over V |
| Cross-entropy = MLE | Scalar “how wrong was the next-token guess” |
| Entropy + KL | Floor versus avoidable error |
| Softmax–CE gradient p − y | Error signal into logits |
| Jacobians / backprop | Route that scalar error to every weight |
| Skip-connection Jacobian I | Make deep nets trainable |
| AdamW + schedule + clip | Stable updates at billion-parameter scale |
| C ≈ 6ND / Chinchilla E | Compute unit and the fitted floor |
| Validation loss | Measure generalization; zero is not the target |
| Sampling + KV cache | Use the trained pθ without changing it |
14 · Sources
Literature, in the order of the lesson
The papers that justify each step. Named where they earn a place. The Papers tab is the reading copy.
How to read this list
These are the papers that justify a step in the stack, in the order the treatise uses them. A citation earns its place by naming a map, a Jacobian, a floor, or a default this site actually writes. Broader surveys, systems papers, and post-training are out of scope on purpose.
The interactive archive — filter by step, open an arXiv HTML copy, follow a DOI — lives in the Papers tab. This chapter is the print bibliography.
00 · The object of study
Shannon, C. E. (1948). A mathematical theory of communication. Bell System Technical Journal 27.
Entropy as the irreducible uncertainty of a discrete source. Every later claim that loss cannot hit zero on language is this paper, applied to tokens.
doi:10.1002/j.1538-7305.1948.tb01338.x
Shannon, C. E. (1951). Prediction and entropy of printed English. Bell System Technical Journal 30.
The floor is a measurement. Humans who have seen the preceding text still cannot guess the next character with certainty. Conditional entropy of English is low, not zero.
doi:10.1002/j.1538-7305.1951.tb01366.x
Radford, A., Wu, J., Child, R., Luan, D., Amodei, D., and Sutskever, I. (2019). Language models are unsupervised multitask learners. OpenAI technical report.
The decoder-only language model this treatise writes: causal mask, next-token MLE, GELU FFN. Capabilities as a side effect of the conditionals.
official
01 · Tokenization and targets
Gage, P. (1994). A new algorithm for data compression. C Users Journal 12(2).
Byte-pair encoding as a compression algorithm: repeatedly merge the most frequent adjacent pair. The tokenizer is this idea, frozen, pointed at text.
closed
Sennrich, R., Haddow, B., and Birch, A. (2016). Neural machine translation of rare words with subword units. ACL 2016.
BPE as the frozen map from bytes to the integers the treatise trains on. Loss, perplexity, and ‘what zero would mean’ are defined on this vocabulary.
arXiv:1508.07909
Kudo, T., and Richardson, J. (2018). SentencePiece: a simple and language independent subword tokenizer and detokenizer. EMNLP 2018 (system demonstrations).
The other common tokenizer: unigram LM / BPE trained from raw bytes, language-agnostic, the Llama-class default alongside BPE.
arXiv:1808.06226
02 · Embeddings and position
Su, J., Lu, Y., Pan, S., Murtadha, A., Wen, B., and Liu, Y. (2021). RoFormer: enhanced Transformer with rotary position embedding. Neurocomputing / arXiv.
RoPE. Inner products depend on t − s, not on absolute t and s. No extra residual vector. The rotation the embeddings chapter writes.
arXiv:2104.09864
03 · The pre-norm Transformer block
He, K., Zhang, X., Ren, S., and Sun, J. (2016). Deep residual learning for image recognition. CVPR 2016.
The skip whose Jacobian is I. Why a 32-layer Transformer trains: there is always a path that does not multiply by a layer Jacobian.
arXiv:1512.03385
Ba, J. L., Kiros, J. R., and Hinton, G. E. (2016). Layer normalization. arXiv preprint.
Per-token mean and variance. GPT-2’s norm. The RMSNorm Jacobian in the treatise is this operator with the mean step removed.
arXiv:1607.06450
Zhang, B., and Sennrich, R. (2019). Root mean square layer normalization. NeurIPS 2019.
RMSNorm: scale without mean-centering. The Llama default, and the Jacobian the backprop chapter writes.
arXiv:1910.07467
Xiong, R., Yang, Y., He, D., Zheng, K., Zheng, S., Xing, C., Zhang, H., Lan, Y., Wang, L., and Liu, T. (2020). On layer normalization in the Transformer architecture. ICML 2020.
Pre-norm trains at depth; post-norm was the original and is harder. The block equation in the treatise is the pre-norm form this paper recommends.
arXiv:2002.04745
Touvron, H., Lavril, T., Izacard, G., et al. (2023). LLaMA: open and efficient foundation language models. arXiv preprint.
The modern stack this treatise writes in one notation: RoPE, RMSNorm, SwiGLU, no biases, pre-norm, decoder-only.
arXiv:2302.13971
04 · Causal attention
Bahdanau, D., Cho, K., and Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. ICLR 2015.
Attention as a content-based weighted sum over source states. Vaswani replaces the scoring function; the mixing primitive is already here.
arXiv:1409.0473
Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., and Polosukhin, I. (2017). Attention is all you need. NeurIPS 2017.
Scaled dot-product attention, the √d_h factor, multi-head, sinusoidal position, the original post-norm stack. The mixing equation the treatise writes is this one.
arXiv:1706.03762
Shazeer, N. (2019). Fast Transformer decoding: one write-head is all you need. arXiv preprint.
Multi-query attention. The KV cache, not the matmul, bounds generation. One K/V head shared across all query heads.
arXiv:1911.02150
Dao, T., Fu, D. Y., Ermon, S., Rudra, A., and Ré, C. (2022). FlashAttention: fast and memory-efficient exact attention with IO-awareness. NeurIPS 2022.
Same softmax Jacobian, different IO. The T×T matrix does not have to live in HBM. Exact attention, not an approximation.
arXiv:2205.14135
Dao, T. (2023). FlashAttention-2: faster attention with better parallelism and work partitioning. arXiv preprint.
The production kernel. Still exact. Still the same Jacobian. Parallelism and work partitioning, not a new formula.
arXiv:2307.08691
Ainslie, J., Lee-Thorp, J., de Jong, M., Zemlyanskiy, Y., Lebrón, F., and Sanghai, S. (2023). GQA: training generalized multi-query Transformer models from multi-head checkpoints. EMNLP 2023.
Grouped-query attention: H_kv between 1 and H_q. The Llama-3-class default. Interpolates MHA and MQA.
arXiv:2305.13245
05 · MLP and SwiGLU
Hendrycks, D., and Gimpel, K. (2016). Gaussian error linear units (GELUs). arXiv preprint.
GPT-2’s nonlinearity. Smooth, not a hard gate. The older MLP in the treatise before SwiGLU.
arXiv:1606.08415
Shazeer, N. (2020). GLU variants improve Transformer. arXiv preprint.
SwiGLU: the gated MLP Llama uses. Gate, up, down — three matrices, no bias. The forward and backward the treatise writes.
arXiv:2002.05202
06 · Unembedding to probabilities
Bridle, J. S. (1990). Probabilistic interpretation of feedforward classification network outputs, with relationships to statistical pattern recognition. Neurocomputing (Springer).
Softmax as a categorical distribution, and the collapse of softmax-plus-cross-entropy to p − y. The treatise’s most important gradient is this identification.
closed
Press, O., and Wolf, L. (2017). Using the output embedding to improve language models. EACL 2017.
Weight tying: W_U = W_E^⊤. Two uses, one parameter. The unembedding chapter’s optional identification.
arXiv:1608.05859
07 · Loss, entropy, and scaling
Cover, T. M., and Thomas, J. A. (2006). Elements of information theory (2nd ed.). Wiley.
The identity the loss chapter writes without apology: cross-entropy = entropy + KL. Training is KL minimization in disguise.
closed
Kaplan, J., et al. (2020). Scaling laws for neural language models. arXiv preprint.
C ≈ 6ND. The compute unit. Power-law loss in N and D. Their N-versus-D allocation is the one Chinchilla later revised.
arXiv:2001.08361
Hoffmann, J., Borgeaud, S., Mensch, A., et al. (2022). Training compute-optimal large language models. NeurIPS 2022.
The Chinchilla law. E is the fitted irreducible loss — the floor the treatise refuses to call zero. IsoFLOP said roughly 20 tokens per parameter.
arXiv:2203.15556
Besiroglu, T., Erdil, E., and Barnett, M. (2024). Chinchilla Scaling: a replication attempt. arXiv preprint.
The printed Approach-3 constants do not recover the 20:1 policy. E is closer to 1.82 on their refit. The floor is an estimate, not a constant of nature.
arXiv:2404.10102
09 · Backpropagation and Jacobians
Rumelhart, D. E., Hinton, G. E., and Williams, R. J. (1986). Learning representations by back-propagating errors. Nature 323.
The public statement that a scalar loss can be routed to every weight by the chain rule, layer by layer, in reverse.
doi:10.1038/323533a0
Baydin, A. G., Pearlmutter, B. A., Radul, A. A., and Siskind, J. M. (2018). Automatic differentiation in machine learning: a survey. Journal of Machine Learning Research 18.
Backprop as reverse-mode automatic differentiation: vector–Jacobian products, not materialized Jacobians. The treatise’s ‘nobody forms J’ is this paper’s point.
arXiv:1502.05767
10 · AdamW, clip, and the schedule
Loshchilov, I., and Hutter, F. (2017). SGDR: stochastic gradient descent with warm restarts. ICLR 2017.
Cosine annealing of the learning rate. The schedule the treatise writes (warmup, then cosine to η_min) is this shape, usually without the restarts.
arXiv:1608.03983
Kingma, D. P., and Ba, J. (2015). Adam: a method for stochastic optimization. ICLR 2015.
Per-parameter first and second moments. The adaptive step the treatise starts from before the ‘W’.
arXiv:1412.6980
Loshchilov, I., and Hutter, F. (2019). Decoupled weight decay regularization. ICLR 2019.
AdamW: λθ sits outside the second-moment rescaling. That is the entire difference, and it is the LLM default.
arXiv:1711.05101
11 · The training loop
Micikevicius, P., et al. (2018). Mixed precision training. ICLR 2018.
BF16/FP16 forward, FP32 master weights. An implementation detail the training loop names so the math is not confused with the storage format.
arXiv:1710.03740
12 · Inference and the KV cache
Holtzman, A., Buys, J., Du, L., Forbes, M., and Choi, Y. (2020). The curious case of neural text degeneration. ICLR 2020.
Nucleus / top-p. Inference carves a sampling set from the leftover mass, then renormalizes. No gradient. Also: typical human text is not the mode.
arXiv:1904.09751
Pope, R., Douglas, S., Chowdhery, A., Devlin, J., Bradbury, J., Heek, J., Xiao, K., Agrawal, S., and Dean, J. (2023). Efficiently scaling Transformer inference. MLSys 2023.
Prefill versus decode, and why the KV cache is the resource that bounds serving. The inference chapter’s operational picture.
arXiv:2211.05102
13 · End-to-end map and catalogue
Dubey, A., et al. (Llama Team) (2024). The Llama 3 herd of models. arXiv preprint.
The current default: GQA, RoPE, RMSNorm, SwiGLU, document mask, a much larger data mix. Confirmation that the treatise’s stack is the one in production, not a 2017 museum piece.
arXiv:2407.21783
End matter
| Piece | Job |
|---|---|
| Tokenizer / BPE | Discrete interface to text. Frozen. Defines the units of loss. |
| Embedding + position | Put tokens into a space where order exists |
| Residual stream | Common currency every layer reads and writes |
| Norm | Control scale so depth does not explode |
| Causal attention | Move information from past tokens to the current one |
| √dₕ scale | Keep scores O(1) so softmax does not saturate |
| GQA / MQA | Share KV heads so the cache, not the matmul, stays small |
| MLP / SwiGLU | Per-token computation and stored features |
| Unembed + softmax | Turn vectors into a distribution over V |
| Cross-entropy = MLE | Scalar “how wrong was the next-token guess” |
| Entropy + KL | Floor versus avoidable error |
| Softmax–CE gradient p − y | Error signal into logits |
| Jacobians / backprop | Route that scalar error to every weight |
| Skip-connection Jacobian I | Make deep nets trainable |
| AdamW + schedule + clip | Stable updates at billion-parameter scale |
| C ≈ 6ND / Chinchilla E | Compute unit and the fitted floor |
| Validation loss | Measure generalization; zero is not the target |
| Sampling + KV cache | Use the trained pθ without changing it |