From Transformer to LLM: The Mathematics of Training and Generation
The original Transformer learned to translate one sequence into another. GPT used causal self-attention to learn the probability of text itself. This change made ordinary text a source of training targets: each token supplies the answer for the preceding context.
The central transition is between two probability distributions:
and
The first describes translation conditioned on a source sequence. The second describes an autoregressive language model. Both can use the same basic attention equation.
This article follows that transition through explicit computations, then examines Adam, AdamW, attention optimizations, and KV caching. Original papers and technical reports support the historical claims and named methods. Numerical examples and algebraic derivations are worked examples for this article.
1. Notation: what each matrix contains
A token is an integer index into a vocabulary. It can represent a word, part of a word, punctuation, or another unit chosen by the tokenizer.
| Symbol | Meaning |
|---|---|
| Number of tokens in a sequence | |
| Width of a token representation | |
| Width of the intermediate nonlinear representation | |
| Number of repeated transformations | |
| Number of query heads | |
| Number of key/value heads | |
| Widths of one key and one value | |
| Vocabulary size | |
| Batch size | |
| All trainable parameters |
Use row vectors throughout. Stack one row per token:
Here is a representation, while in a probability expression denotes the token sequence. Context distinguishes these two uses.
Matrix multiplication uses juxtaposition. The symbol means elementwise multiplication. Softmax acts across the keys in each query row. Normalization acts across the coordinates of each token independently.
Batch dimensions are omitted until the memory calculations. Each depth and each attention operation has its own parameters, even when subscripts are omitted. Unless stated otherwise, equations omit dropout and attention-projection biases to expose the main computation.
2. The original Transformer, expressed as equations
The 2017 Transformer uses an encoder and an autoregressive decoder. Its base configuration has transformations on each side, , , , and . It uses sinusoidal positions, ReLU, and normalization after residual addition. These choices belong to the original architecture; later sections introduce different choices. See Attention Is All You Need.
2.1 Token indices become vectors with positions
Let be the embedding matrix. For token index , the initial representation is
For coordinate pairs indexed by , the original position encoding is
The embedding supplies learned token coordinates. The position vector supplies a fixed function of the token’s location. The sum has the same width .
2.2 Attention is a normalized, input-dependent weighted sum
For one head, compute three projections:
where
Thus and . Each query row is compared with each key row :
The mask determines which comparisons are allowed. Convert scores into weights, then combine values:
In matrix form:
The intermediate shapes explain the computation:
Before dropout, each valid row satisfies and . A single head therefore returns a convex combination of its projected values. The weights depend on the input through and .
For example, take one query whose three scores are . Then
With , , and , the output is
If the third position is masked, its weight becomes zero and the other weights must be renormalized. They become .
2.3 Why divide by the square root of the key width?
Assume, for a scale estimate, that the coordinates of and are mutually independent, have zero mean, and have variance one. Then
Consequently,
This controls the initial score scale as changes. It does not require trained coordinates to remain independent.
The softmax derivative shows why score scale matters:
When one probability is almost one, many of these derivatives approach zero. Scaling reduces the tendency of large dot products to create this saturation at initialization.
2.4 Multiple heads use different learned projections
For head , let
Concatenate the results across feature coordinates and project back to width :
The heads can learn different comparisons. No equation assigns a fixed role such as syntax or factual knowledge to a particular head.
For cross-attention, use two sequences with potentially different lengths:
where and . Its score matrix has shape . Denote the concatenated, output-projected result by .
Self-attention and cross-attention differ in the source of . Multiple heads can be used in either computation.
2.5 What the two “Linear” operations actually compute
For each token row , the original nonlinear transformation is
with
For the original base configuration, this gives
An operation called “Linear” in a library is usually affine when it includes a bias. The intermediate nonlinearity is essential. Without it,
which is just one affine transformation.
The same apply to every token position. This calculation mixes features within a row. Attention supplies direct mixing between rows.
2.6 Residual addition and LayerNorm
For a row , define
Both are trainable. The scalar prevents division by zero.
Write one original encoder transformation as
Here assumes no padding. Padding keys must be masked in a padded batch. The original training computation also applies dropout to each residual branch before addition.
The order is . This is called Post-LN. Normalization before the residual branch, called Pre-LN, is a later choice discussed in Section 5.1.
2.7 The original decoder has two distinct attention calculations
Let be the final encoder representations. Initialize the decoder from the shifted target sequence
The representation at position predicts . Its causal mask is
One decoder transformation is
The first attention uses target-prefix representations for . The second uses target representations for and encoder outputs for . All non-padding source positions can be available in this second calculation.
Finally,
where . The basic training loss is the sum of negative log probabilities of the correct targets. The original paper additionally uses label smoothing, so its training target distribution is not exactly one-hot.
3. GPT: make the prefix itself the conditioning sequence
GPT removes the separate source encoding and its cross-attention calculation. Causal self-attention remains. Learned absolute positions and GELU are used in the original GPT. Its pretraining objective is the likelihood of the next token. See Improving Language Understanding by Generative Pre-Training.
With token indices , use the input and targets . A GPT-style prediction has the form
The recurrence for retains causal self-attention, residual additions, normalization, and a nonlinear feature transformation. There is no cross-attention term dependent on .
“Decoder-only” therefore describes the causal computation and absence of a separate source encoder. It does not mean that the model stops computing useful representations of its input. It also does not mean that every decoder-only model is a GPT model.
3.1 Parallel training, sequential generation
During training, all target tokens are known. A triangular mask makes it possible to evaluate every next-token loss in one sequence pass. There is no need to run each growing prefix separately.
During generation, the next token is unknown until it is selected:
This dependence across output tokens remains even when all computations within one step use parallel hardware.
3.2 Why this supports general language pretraining
Translation requires paired source and target text. Autoregressive training obtains targets by shifting ordinary text. A task can then be expressed as part of the prefix:
GPT-3 demonstrated task performance from prompts and examples without a separate gradient update for each prompted task. This is an empirical result, not a theorem that scale must produce any particular capability. See Language Models are Few-Shot Learners.
Instruction tuning changes the training distribution to examples of desired responses:
Preference-based training can further change which responses receive higher probability. It does not replace next-token probabilities as the generation interface. InstructGPT is an early example of supervised fine-tuning followed by reinforcement learning from human feedback. See Training language models to follow instructions with human feedback.
4. From prediction error to Adam and AdamW
Attention specifies how to calculate predictions. The loss specifies what counts as an error. An optimizer specifies how gradients change the parameters.
For one token with one-hot target vector ,
Backpropagation applies the chain rule from this error to every trainable matrix.
4.1 Attention also receives gradients
For , , and , write . Then
For example, gives . Masked entries have zero attention weight and zero score gradient. These equations assume no attention dropout; its derivative must be included when it is active.
4.2 Adam estimates gradient direction and scale
Use for optimizer steps to distinguish them from token positions. Starting with , compute
Correct the zero-initialization bias:
The update is
All vector operations in this update are elementwise. The numerator estimates recent gradient direction. The denominator adjusts the step for each coordinate’s recent squared-gradient scale. The quantity estimates a second raw moment, not a centered variance or a Hessian. See Adam: A Method for Stochastic Optimization.
For a constant gradient , the recurrence gives . Bias correction recovers . The same argument gives .
4.3 AdamW separates weight decay from gradient adaptation
An L2 penalty changes the objective to
If this combined gradient enters Adam, the penalty also enters both moment estimates. Its effect therefore depends on gradient history.
AdamW instead forms moments from the data-loss gradient and applies decay separately:
Here uses the convention in which decay is scaled by the learning rate. A schedule can equivalently specify the decay coefficient directly. For plain SGD, an L2 gradient gives this multiplicative decay. For Adam, the gradient transformation breaks that equivalence. See Decoupled Weight Decay Regularization.
Parameter groups can use different , including zero. Thus decay need not apply to biases or normalization parameters. Adam and AdamW are training algorithms; ordinary generation does not run these updates.
4.4 Learning-rate schedules are a separate choice
The original Transformer uses an Adam learning-rate schedule of the form
where is the warmup duration in optimizer steps. The rate first rises linearly, then decreases as . This schedule is a training choice from the original Transformer paper, not part of Adam’s definition.
5. Change the equations to train deeper models
The next changes concern representations and gradient flow. Their usefulness is empirical; none is a universal requirement for an LLM.
5.1 Pre-LN moves normalization before each residual branch
Compare
Using column-style Jacobian notation for this derivative only, the second form gives
The identity term is a direct gradient path through the residual addition. In the first form, the derivative is . This difference helps explain the training behavior studied in On Layer Normalization in the Transformer Architecture. It does not guarantee that gradients remain bounded at arbitrary depth.
GPT-2 moved normalization to the inputs of its residual branches and added final normalization. See Language Models are Unsupervised Multitask Learners. A Pre-LN recurrence should therefore not be labeled as the original 2017 ordering.
5.2 RMSNorm removes centering
RMSNorm uses
It scales the row without subtracting its mean. The standard form above has a learned scale and no additive bias. See Root Mean Square Layer Normalization.
For , with , , and ignored,
RMSNorm does not force a zero mean. It also does not directly bound the magnitude of the unnormalized residual stream.
5.3 SwiGLU introduces multiplication between learned features
GELU can be written as , where is the standard normal cumulative distribution function. A GELU transformation is
A common bias-free SwiGLU form is
Here and . This form adds a second input projection and an elementwise product. See GLU Variants Improve Transformer.
The SiLU output can be negative or greater than one. The word “gate” therefore does not imply a probability restricted to .
Ignoring biases, a two-projection transformation has parameters. SwiGLU has . To match the parameter count of a two-projection transformation with width , choose approximately
then adjust the width for hardware requirements. Comparing both forms at the same changes their parameter budgets.
6. Optimize attention from projections to weighted sums
The attention calculation has several costs: projections, pairwise scores, normalization, weighted sums, and memory traffic. Changes at these points solve different problems.
6.1 Fuse projections without changing their result
The three projection matrices can be concatenated:
This identity allows one larger matrix multiplication in place of three separate calls. It preserves the real-arithmetic result. Speed depends on implementation and hardware. Floating-point operation ordering can produce small numerical differences.
For , query heads, and key/value heads, the combined projection width is .
6.2 RoPE puts position differences into query-key products
For a two-coordinate row vector, define
Use the transpose when applying this conventional rotation matrix to row vectors:
Their dot product is
The explicit rotation depends on the relative offset . In higher dimensions, apply separate rotations to coordinate pairs, for example with frequencies
This is the central construction in RoFormer. The remaining content dependence still comes from . Standard RoPE rotates queries and keys; values remain unrotated. The relative-position identity does not guarantee useful behavior beyond the model’s trained context length.
6.3 MHA, GQA, and MQA differ in which heads share keys and values
Assume divides . Map query head to key/value head
Then
MHA has . Multi-query attention, or MQA, has . Grouped-query attention, or GQA, uses an intermediate number of key/value heads. See the MQA paper and GQA paper.
For , these choices might use , , and . All retain 32 query heads. Each query head still produces its own attention weights. Sharing does not make the score matrices identical.
Key/value projection width and cache size scale with . Pairwise score and value-aggregation arithmetic still scales with for a direct implementation. GQA therefore does not reduce every attention cost by .
These choices change parameter sharing. They usually require appropriate training or adaptation; they are not exact replacements for an arbitrary trained MHA checkpoint.
6.4 Stable softmax subtracts a row maximum
For finite scores , choose . Then
Subtracting preserves the result and prevents overflow in the exponentials. An implementation must handle a fully masked row separately: subtracting from is undefined.
6.5 FlashAttention avoids storing the full score and probability matrices
For one query, attention can be expressed as a ratio:
For a set of valid keys , define a maximum, a scalar sum, and a vector sum:
For a disjoint set , merge the statistics using
After all valid keys have been processed, . Empty or fully masked sets are skipped or handled explicitly.
This derivation permits an exact attention result in real arithmetic while processing scores in tiles. FlashAttention uses this principle with fast on-chip memory and reduced transfers to GPU high-bandwidth memory. It also uses recomputation during the backward pass. See FlashAttention.
A conventional materialized attention matrix requires elements. FlashAttention avoids keeping that full matrix in high-bandwidth memory. Dense pairwise arithmetic remains . It improves memory use and data movement without turning dense attention into a linear-time calculation.
6.6 A local mask changes the attention function
If attention is restricted to a causal window of tokens, define
The allowed pair count becomes instead of . To realize the saving, the implementation must skip disallowed pairs. This restriction removes direct access to older positions within that attention calculation. It changes the function, whereas FlashAttention preserves the chosen dense or masked function.
7. KV cache: derive the reusable state
Consider generation in a causal decoder with fixed parameters and dropout disabled. A representation at position depends only on tokens at positions . Appending future tokens does not change that prefix.
This statement holds by induction over depth. It is true for token and fixed-position embeddings. Causal attention only reads earlier or current positions. Per-token normalization and feature transformations do not introduce a dependence on future positions.
Thus, for an unchanged prefix and position convention,
7.1 Compute one new row and reuse the previous rows
For one head at one depth, let be the current input to its projections:
Append the new key and value:
The new attention result is
The score shape is now . Each depth has its own cache. The new token must pass through every depth before the next-token probabilities are available.
For RoPE, cache the rotated keys using their correct positions. Rotate the new query and key at the new position. A change in position indexing or position-scaling rules can invalidate a cache.
7.2 Why cache K and V, but not old Q?
The expression for needs the current query , all keys , and all values . It does not contain .
Old queries were needed to calculate old outputs. They are not needed to calculate the next output. This is why standard autoregressive inference retains K and V. Training has different requirements because backward computation needs additional activations or their recomputation.
Caching is exact for the same causal model under these assumptions, up to numerical effects. Quantized or truncated caches introduce additional approximations.
7.3 Prefill and decode have different cost shapes
Prefill processes a prompt of length and creates its caches. Dense attention has query-key pairs. The final prompt position supplies probabilities for the first generated token.
Each subsequent decode step processes one newly selected token. With cached positions, its attention work is per depth. Its projections and per-token nonlinear transformations also have a cost, independent of when model widths are fixed.
For generation from a short initial prefix to length , a naive method that repeatedly recomputes the full prefix incurs pairwise attention work proportional to
With cached keys and values, the pairwise work is proportional to
These are attention-only totals for that comparison. KV caching does not make a full dense-attention generation run linear in output length. Each new query still reads the retained context.
7.4 Calculate the cache size
With equal key and value widths and bytes per stored element, an unsharded cache for equal-length sequences uses
The factor two counts keys and values. More generally, the per-depth factor is . This formula excludes weights, activations, allocator overhead, and quantization metadata.
Take , , , , , and :
| Attention choice | KV heads | Cache calculation | Cache size |
|---|---|---|---|
| MHA | 32 | 4 GiB | |
| GQA | 8 | 1 GiB | |
| MQA | 1 | 128 MiB |
These are worked examples, not measurements of named models. For a batch of eight equal-length sequences, multiply each value by eight. Lower cache size can reduce memory traffic, but it does not imply the same factor of end-to-end speedup.
8. MLA: cache a latent representation instead of expanded K and V
DeepSeek-V2 introduces multi-head latent attention, or MLA, and DeepSeek-V3 retains it. The following discussion concerns those documented architectures. See the DeepSeek-V2 report and DeepSeek-V3 report.
8.1 A low-rank factorization exposes a smaller state
First omit positional rotations to isolate the algebra. Compress a token representation into a latent row:
For head , define
where and . The superscript denotes the content part of a key.
Associativity gives
The value sum also factors:
These identities let an implementation attend over cached latent rows without repeatedly expanding historical keys and values. They are exact for the specified factorized weights. They do not prove that an arbitrary MHA model can be compressed to any chosen rank without error.
8.2 Separate the positional key contribution
If a position-dependent rotation acts on the full expanded content key, the score contains
The query-side expression now depends on key position . A single fixed absorbed query projection cannot remove that dependence.
A simplified expression for the decoupled position treatment is
where the terms carry RoPE and the positional key is shared across heads. The cache stores both and . The V2 equations also include query compression; it is omitted here because it does not add historical KV state.
The resulting idealized cache size is
This is a different storage strategy from choosing fewer KV heads. Its benefit depends on compared with the expanded key/value widths. Actual speed also depends on the kernels and memory layout.
9. Store the cache efficiently: paging and quantization
9.1 Paging changes allocation, not attention weights
For page capacity tokens and sequence length , the required number of pages is
Logical position maps to
A page table maps logical pages to physical storage. This allows cache growth without one large contiguous allocation. The unused capacity in the final page is less than tokens per sequence. Additional allocator and page-table costs still exist. PagedAttention applies this principle to LLM serving. See Efficient Memory Management for Large Language Model Serving with PagedAttention.
Prefix sharing can reuse pages only when tokens, model parameters, positional treatment, and other computation-affecting settings match. A common textual suffix with different earlier context does not generally produce the same keys and values.
9.2 Quantization changes the numerical representation
A simple symmetric quantizer for a cache group is
where is a scale and is the largest positive integer magnitude. With bits per element, the idealized payload size becomes
Scales, packing, and other metadata add storage. Quantization errors in K change the scores; errors in V change the weighted sums. Their effect on output quality must be measured. Paging preserves the stored values; quantization generally changes them.
10. Put a modern causal decoder into one recurrence
A representative dense decoder using Pre-RMSNorm, RoPE, GQA, and SwiGLU can be written as follows. This is a worked composition of the preceding equations, not a specification for every GPT or every LLM. Related choices appear in the LLaMA paper, although individual model versions use different head-sharing choices.
Start from token embeddings . At depth , let
For each query head and KV head , compute
Then apply the two residual additions:
The final row predicts the next token:
During training, shifted targets supply cross-entropy gradients and AdamW can update the parameters. During generation, fixed parameters and causal dependence permit KV reuse. FlashAttention determines how the attention sums are evaluated. Paging determines where the cache lives. Each choice acts on a specific equation or its execution.
| Change | Mathematical or execution effect |
|---|---|
| Translation objective to causal language modeling | Learn from text |
| Adam to AdamW | Separate multiplicative parameter decay from gradient moments |
| Post-LN to Pre-LN | Move normalization inside the residual branch |
| LayerNorm to RMSNorm | Remove mean subtraction |
| ReLU/GELU transformation to SwiGLU | Add a learned projection and featurewise multiplication |
| Absolute additive positions to RoPE | Rotate Q and K so their product contains position differences |
| MHA to GQA/MQA | Share K and V across query heads |
| Materialized attention to FlashAttention | Evaluate the same attention through tiled sums and less memory traffic |
| Full-prefix recomputation to KV caching | Reuse unchanged historical K and V |
| Expanded KV storage to MLA latent storage | Exploit a trained factorization and retain a separate positional key |
| Contiguous allocation to paging | Change the address mapping of retained cache values |
| Full-precision cache to quantized cache | Reduce bytes per element while introducing numerical error |
The connection from Transformer to LLM is visible in these equations: causal probabilities define the task, learned matrix products and nonlinear functions define the model, gradient updates define learning, and reusable prefix state makes sequential generation practical.
References
The following original papers and technical reports are cited in the text. Years identify their first public release; conference or journal publication can be later.
- Vaswani, A., et al. (2017). Attention Is All You Need. arXiv:1706.03762. Original encoder–decoder Transformer, scaled dot-product attention, sinusoidal positions, and training schedule.
- Radford, A., et al. (2018). Improving Language Understanding by Generative Pre-Training. GPT and causal language pretraining.
- Radford, A., et al. (2019). Language Models are Unsupervised Multitask Learners. GPT-2 and its normalization placement.
- Brown, T. B., et al. (2020). Language Models are Few-Shot Learners. arXiv:2005.14165. GPT-3 and learning tasks from examples in the prompt.
- Ouyang, L., et al. (2022). Training language models to follow instructions with human feedback. arXiv:2203.02155. InstructGPT, supervised fine-tuning, and reinforcement learning from human feedback.
- Kingma, D. P., and Ba, J. (2014). Adam: A Method for Stochastic Optimization. arXiv:1412.6980. Gradient moment estimates, bias correction, and adaptive parameter updates.
- Loshchilov, I., and Hutter, F. (2017). Decoupled Weight Decay Regularization. arXiv:1711.05101. AdamW and the distinction between L2 regularization and weight decay.
- Xiong, R., et al. (2020). On Layer Normalization in the Transformer Architecture. arXiv:2002.04745. Post-LN, Pre-LN, and gradient behavior at initialization.
- Zhang, B., and Sennrich, R. (2019). Root Mean Square Layer Normalization. arXiv:1910.07467. RMSNorm and normalization without mean subtraction.
- Shazeer, N. (2020). GLU Variants Improve Transformer. arXiv:2002.05202. Gated nonlinear transformations, including SwiGLU.
- Su, J., et al. (2021). RoFormer: Enhanced Transformer with Rotary Position Embedding. arXiv:2104.09864. RoPE and relative position in query-key products.
- Shazeer, N. (2019). Fast Transformer Decoding: One Write-Head is All You Need. arXiv:1911.02150. Multi-query attention and reduced key/value memory traffic during decoding.
- Ainslie, J., et al. (2023). GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints. arXiv:2305.13245. Grouped-query attention and adaptation from MHA checkpoints.
- Dao, T., et al. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. arXiv:2205.14135. Tiled exact attention, online softmax, and reduced memory traffic.
- DeepSeek-AI, et al. (2024). DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model. arXiv:2405.04434. MLA, latent KV compression, and decoupled RoPE.
- DeepSeek-AI, et al. (2024). DeepSeek-V3 Technical Report. arXiv:2412.19437. Use of MLA in DeepSeek-V3.
- Kwon, W., et al. (2023). Efficient Memory Management for Large Language Model Serving with PagedAttention. arXiv:2309.06180. Paged KV allocation and cache sharing in vLLM.
- Touvron, H., et al. (2023). LLaMA: Open and Efficient Foundation Language Models. arXiv:2302.13971. A causal language model combining pre-normalization, RMSNorm, SwiGLU, and RoPE.