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.

(0.1)
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.”

(0.2)
(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.

x₁:Ttokens
H⁽⁰⁾embed + RoPE
H⁽ⁿ⁾n blocks
Zlogits
p₁:Tsoftmax

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.

(1.0)
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.

(1.1)
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.

(1.2)

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 .

(2.1)
token embedding matrix, V×d
the d-vector for token x_t
(2.2)
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.

(2.3)
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.

(2.4)
head dimension (even)
pair index 0, 1, …, d_h/2 − 1
base frequency, usually 10,000 (or a long-context variant)
(2.5)
(2.6)

Write for the block-diagonal matrix of all pair rotations at position . Rotations compose, and :

(2.7)

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.

ONE RoPE PAIRR_s kR_t q⟨R_t q, R_s k⟩ = ⟨q, R_{s−t} k⟩Inner product depends only on t − s.Backward pass: apply Rᵀ, which equals R⁻¹.

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.

(3.1)
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.

PRE-NORM BLOCKH⁽ℓ−1⁾RMSNormthen Attn+ → Zskip J = IRMSNormthen MLPH⁽ℓ⁾Two residual adds. Each skip contributes a Jacobian of I, which is why depth trains.

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.

(3.2)
one residual-stream vector
small constant, e.g. 10^{-6}
(3.3)
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.

(3.4)
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.

(4.1)
projections in R^{d × d} (or d × H d_h)
head h, each T × d_h

Scores, scale, causal mask, softmax

(4.2)

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.

(4.3)
(4.4)
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.

CAUSAL MASK · T = 8Steel: visible (M = 0). Paper: future (M = −∞).
(4.5)
output projection, d × d
Attn(U), written back into the residual stream

Softmax Jacobian

For one row :

(4.6)
(4.7)

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.

(4.8)
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.

(5.1)
GELU
up-projection, typically to 4d
down-projection, back to d
(5.2)
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 .

(5.3)
gate and up, d × d_ff
down, d_ff × d
inner width, often ~ 8d/3 so parameter count matches 4d GELU
(5.4)
(5.5)

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.

(6.1)
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

(6.2)
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.

(7.0)

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.

(7.1)
NLL of the true next token, in nats
(7.2)
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.

(7.3)
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

(7.4)

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:

(7.4b)
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):

(7.5)
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),

(7.6)
≈ 2 FLOPs/param/token for the forward pass, 4 for the backward

Minimize (7.5) along the budget line . The compute-optimal allocation is

(7.7)
≈ 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.

StageLoss (nats)Meaning
Random initializationln V ≈ 10.8–11.8Uniform over 50k–128k tokens
Early training~4–6Crude word and syntax statistics
Small modern pretrain~2.0–2.5Competent next-token model
Strong large pretrain~1.7–2.1Near fitted irreducible floors
Narrow SFT, regular data~0.2–0.8The task is less uncertain than web text
Overfit a tiny set→ 0Memorization, 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.

(8.1)

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:

(9.1)
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 :

(9.2)

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:

(9.3)

The upstream vector is . One-hot at makes that . The VJP through softmax is

(9.3b)

Here and , so

(9.4)
(9.5)

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

(9.6)

Then the final Norm Jacobian maps back to .

RMSNorm Jacobian (one vector)

Let , , .

(9.7)

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 :

(9.8)
(9.9)
(9.10)

RoPE’s backward pass is the inverse rotation. Then etc. give

(9.11)

The same for K, V. Multi-head: sum the contributions.

Residual Jacobian

(9.12)

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 , , , , .

(9.13)

Then ordinary matmul rules for .

Embedding backward

is scattered back into the rows of (and if used):

(9.14)

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

(10.1)

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 .

(10.2)
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

(10.3)

Gradient clipping

Before AdamW:

(10.4)
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:

  1. Sample a batch of sequences. Shape: token IDs.
  2. Forward: embeddings → blocks → logits .
  3. Compute on next-token targets (ignore pad / masked positions).
  4. Backward: reverse-mode AD gives .
  5. Optionally accumulate g over several micro-batches to fake a larger batch.
  6. Clip g, AdamW update, zero grads.
  7. Periodically evaluate validation loss on held-out data (no parameter update).
(11.1)
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):

(11.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:

  1. Start with prompt tokens .
  2. Forward → logits .
  3. Form a sampling distribution from .
  4. Draw , append, repeat.

Decoding math

(12.1)
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.

(12.2)

No . No Jacobian. No Adam.

KV cache

Attention at step only needs and all past . Store (K, V) per layer:

(12.3)

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

x₁:Ttokens
H⁽⁰⁾embed + RoPE
H⁽ⁿ⁾n blocks
Zlogits
p₁:Tsoftmax

Forward map. Training attaches CE → Jacobians → AdamW after p. Inference samples from p.

(13.1)

Train path

(13.2)

Infer path

(13.3)

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.

MapJacobian / VJP
softmaxdiag(a) − aaᵀ
CE + softmaxp − y
Y = XW∂L/∂X = G Wᵀ, ∂L/∂W = Xᵀ G
RMSNormr⁻¹ (I − uuᵀ / (d r²))
LayerNormsame, after P = I − 11ᵀ/d
residual H ↦ H + F(H)I + J_Fᵀ
RoPERᵀ = R⁻¹
SiLUσ(z) + z σ(z)(1 − σ(z))
embedding lookupscatter 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.

PieceJob
Tokenizer / BPEDiscrete interface to text. Frozen. Defines the units of loss.
Embedding + positionPut tokens into a space where order exists
Residual streamCommon currency every layer reads and writes
NormControl scale so depth does not explode
Causal attentionMove information from past tokens to the current one
√dₕ scaleKeep scores O(1) so softmax does not saturate
GQA / MQAShare KV heads so the cache, not the matmul, stays small
MLP / SwiGLUPer-token computation and stored features
Unembed + softmaxTurn vectors into a distribution over V
Cross-entropy = MLEScalar “how wrong was the next-token guess”
Entropy + KLFloor versus avoidable error
Softmax–CE gradient p − yError signal into logits
Jacobians / backpropRoute that scalar error to every weight
Skip-connection Jacobian IMake deep nets trainable
AdamW + schedule + clipStable updates at billion-parameter scale
C ≈ 6ND / Chinchilla ECompute unit and the fitted floor
Validation lossMeasure generalization; zero is not the target
Sampling + KV cacheUse 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

  1. 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

  2. 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

  3. 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

  1. 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

  2. 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

  3. 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

  1. 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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  1. 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

  2. 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

  3. 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

  4. 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

  5. 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

  6. 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

  1. 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

  2. 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

  1. 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

  2. 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

  1. 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

  2. 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

  3. 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

  4. 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

  1. 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

  2. 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

  1. 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

  2. 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

  3. 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

  1. 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

  1. 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

  2. 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

  1. 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

PieceJob
Tokenizer / BPEDiscrete interface to text. Frozen. Defines the units of loss.
Embedding + positionPut tokens into a space where order exists
Residual streamCommon currency every layer reads and writes
NormControl scale so depth does not explode
Causal attentionMove information from past tokens to the current one
√dₕ scaleKeep scores O(1) so softmax does not saturate
GQA / MQAShare KV heads so the cache, not the matmul, stays small
MLP / SwiGLUPer-token computation and stored features
Unembed + softmaxTurn vectors into a distribution over V
Cross-entropy = MLEScalar “how wrong was the next-token guess”
Entropy + KLFloor versus avoidable error
Softmax–CE gradient p − yError signal into logits
Jacobians / backpropRoute that scalar error to every weight
Skip-connection Jacobian IMake deep nets trainable
AdamW + schedule + clipStable updates at billion-parameter scale
C ≈ 6ND / Chinchilla ECompute unit and the fitted floor
Validation lossMeasure generalization; zero is not the target
Sampling + KV cacheUse the trained pθ without changing it