Transformer Architecture and Its Variants
Chapter 7 ended with a stable mapping from text to token ids. This chapter follows those ids through a decoder-only transformer: embedding, a stack of residual blocks, a final normalization, and a vocabulary projection. The 2017 Transformer introduced the attention-and-feed-forward block in an encoder-decoder system (Vaswani et al. 2017). Modern causal language models reuse that basic pattern, but differ in normalization, position handling, feed-forward design, attention heads, and cache representation.
Those choices are not cosmetic. They determine which positions can exchange information, how gradients travel through depth, how many parameters sit in each block, and how much state a serving process retains for every active sequence. A useful architecture description therefore needs tensor shapes, mask semantics, and memory units, not only a box labeled “Transformer.”
Scope: a causal decoder
Here a batch contains sequences of length , and the model width is . The tokenizer emits integer ids for a vocabulary of size . An embedding table maps them to the initial residual stream . After blocks and a final normalization, an output matrix produces logits over the vocabulary:
Here is the last block's output, is the final normalization, is the output or unembedding matrix, contains the logits at position , and is a candidate next-token id. The causal condition means that position may depend only on tokens at positions up to . Encoder-only models use bidirectional masks; encoder-decoder models also add cross-attention. Those architectures share components with this one, but they do not share its exact information-flow contract.
The input embedding and may share parameters, a design called weight tying (Press and Wolf 2017). Tying removes one matrix, but also forces the input and output roles to use the same rows. It is an architecture choice, not a rule for large or small models.
A block updates one residual stream twice
A common pre-normalized decoder block has two residual updates:
Here is the block index; is the block input; is the state after self-attention; and is the block output. Attention mixes information across allowed positions. The feed-forward network (FFN) transforms each position independently. Both return a tensor with the same shape as the residual stream so that addition is defined.
The residual stream is the width- state carried through the stack. Calling it a stream is helpful, but it is not a separate memory module. It is the sequence of hidden vectors that every sublayer reads and updates.
This diagram specifies pre-normalization. The original Transformer instead normalized after each residual addition (Vaswani et al. 2017):
Here the symbols have the same shapes as in the pre-normalized block, but the normalizers now act after each addition. Xiong et al. showed why pre-normalization has better-behaved gradients at initialization and can reduce reliance on learning-rate warmup (Xiong et al. 2020). That evidence does not make post-normalization invalid: initialization, residual scaling, depth, and optimizer settings change the comparison. Record the exact block equation rather than relying on the labels “pre-norm” or “post-norm.”
Normalization controls scale
LayerNorm centers a hidden vector and divides by its standard deviation (Ba et al. 2016). root mean square layer normalization (RMSNorm), introduced by Zhang and Sennrich in 2019, omits mean subtraction and normalizes by root mean square (Zhang and Sennrich 2019):
Here is one token's hidden vector; is its -th component; is a learned element-wise scale; prevents division by zero; and denotes element-wise multiplication. Implementations must pin , accumulation precision, and whether a learned bias is present. These details can affect checkpoint compatibility and low-precision stability.
Some architectures also normalize queries and keys before their dot product. That QK normalization solves a different problem from normalizing the residual stream: it bounds attention-score scale. A model manifest should state both locations independently.
The feed-forward network supplies per-position capacity
The original block used two matrices with a ReLU between them. A common gated alternative is Swish-gated linear unit (SwiGLU) (Shazeer 2020):
Here is one residual vector; are the gate and value projections; projects back to model width; is the FFN hidden width; and is applied element-wise. Ignoring biases, this gated FFN has parameters. A plain two-matrix FFN has .
That count explains the often-quoted “two-thirds” adjustment. A plain FFN with hidden width has parameters. Matching it with a three-matrix gated FFN requires , before rounding to a hardware-friendly multiple. The ratio is a budgeting rule, not an intrinsic property of SwiGLU. Actual models choose different expansion ratios, and equal matrix counts do not guarantee equal wall-clock time across kernels or hardware.
Attention and the FFN play different roles, but claims that one stores “knowledge” while the other only “routes” it are interpretations, not tensor invariants. Ablations can localize behavior; the forward equations alone do not assign semantic ownership.
Causal self-attention with explicit shapes
Here, for one sequence, let . Assume equal query, key, and value head widths. Let be the number of query heads, the number of distinct key-value heads, and the width of one head. Learned projections produce
Each query head is assigned to a key-value head . For query position , its output is
Here is the query for head at position ; and are the selected key and value at position ; is their normalized attention weight; and is the mask. For ordinary causal attention, when and when . The entries become zero probability after softmax. Padding, packed documents, sliding windows, and prefix-language models require different masks.
The divisor keeps score variance from growing with head width under common initialization assumptions (Vaswani et al. 2017). Concatenating the head outputs and applying an output projection returns a width- update for the residual addition.
When and biases are omitted, the query and output projections hold parameters. The key and value projections hold . Standard MHA with therefore uses projection parameters. GQA and MQA reduce the K/V term as well as the cache, while dense query-key interaction still scales with .
A dense attention layer forms query-key relationships across a full sequence. The arithmetic is therefore quadratic in . A naive implementation also materializes an score matrix, but that temporary storage is not required by the mathematical definition.
Position enters through queries and keys
Unmasked content-only self-attention is permutation-equivariant: permuting the input positions permutes its outputs. A causal mask already imposes a direction, but it does not give equal content vectors an explicit distance representation. rotary position embedding (RoPE) applies a position-dependent rotation to pairs of query and key coordinates (Su et al. 2024). For an even rotated width , define
Here is the frequency base; indexes a pair of rotated coordinates; is that pair's angular frequency; and is token position. Let be the block-diagonal matrix made from all . Then
Here and are unrotated query and key vectors; and use the configured frequency schedule; and the last identity shows that the positional part of their dot product depends on relative offset . RoPE does not make the complete attention score a function of distance alone; the content vectors still matter.
The frequency base, the fraction of dimensions rotated, and any scaling used for context extension belong in the checkpoint contract. Changing them after training is an adaptation experiment, not a metadata edit. RoPE is common, but it is not the only valid scheme. ALiBi instead adds a head-specific linear distance penalty to each causally valid score (Press et al. 2022):
Here is a fixed slope for head ; is non-negative for an allowed past position; and is the causal mask defined earlier. ALiBi introduces no learned position vectors. Long-context behavior under either method depends on training length, frequency or slope configuration, later adaptation, and the evaluation distribution.
Prefill creates the cache; decode reuses it
Autoregressive serving exposes a distinction that a full-sequence training diagram hides. The first pass is prefill: it reads the entire prompt under the causal mask, produces logits at its positions, and populates keys and values for the prompt. The logits at the last prompt position predict the first generated token. The positions can run in parallel, although serving systems may split a long prefill into chunks. The second phase is decode: it processes one new position per sequence, attends from that new query to stored past keys and values, selects or samples a token, appends that position's keys and values, and repeats.
In standard causal self-attention with a fixed prefix, a past position's key and value at a given layer do not change during later decode steps. Reusing them avoids projecting the whole prefix again. A dense decode step still reads the retained cache, making it a bandwidth cost as well as a capacity cost. For a ragged batch, the persistent key-value (KV) tensor payload is
Here is the number of resident sequences; is the cached length of sequence ; is the number of attention layers; is the number of distinct KV heads in layer ; and are the key and value elements per head; and is bytes per cached element. For uniform length and equal , this reduces to . Real servers also have allocation blocks, metadata, padding or fragmentation, quantization scales, speculative or beam state, prefix sharing, and possible offload. The formula is the dense tensor payload, not total process memory.
With cache reuse, dense attention for one new token is linear in retained length per layer, omitting head and dimension factors. Generating new tokens after a prompt of length therefore performs attention work proportional to across decode. Cache reuse prevents repeated prefix projection; it does not make long decode constant-time.
The cache scales linearly with resident tokens. Whether it exceeds model weights depends on all the quantities above, plus weight and cache precision. It is therefore incorrect to present one crossover as a property of Transformers in general.
Figure 8.4 uses explicit assumptions: 32 layers, 128-wide heads, two bytes per KV element, batch size one, and 7 billion two-byte weight parameters. The plotted MHA, GQA, and MQA lines differ only in , so every value follows directly from the cache equation.
The runnable cell prints the cache payload per token and the context length at which that payload equals the stated weight bytes. Change batch size, precision, or KV-head count to test a different deployment.
layers = 32
head_width = 128
bytes_per_kv_element = 2
batch_size = 1
parameter_count = 7_000_000_000
bytes_per_weight = 2
weight_bytes = parameter_count * bytes_per_weight
def kv_payload_bytes(sequence_length, kv_heads):
return (
2
* layers
* batch_size
* sequence_length
* kv_heads
* head_width
* bytes_per_kv_element
)
for name, kv_heads in [("MHA", 32), ("GQA", 8), ("MQA", 1)]:
bytes_per_token = kv_payload_bytes(1, kv_heads)
crossover_tokens = weight_bytes / bytes_per_token
cache_at_128k_gib = kv_payload_bytes(128_000, kv_heads) / 2**30
print(
f"{name}: {bytes_per_token / 1024:.0f} KiB/token; "
f"128k cache={cache_at_128k_gib:.2f} GiB; "
f"equals weight bytes at {crossover_tokens:,.0f} tokens"
)
MHA, GQA, and MQA change KV-head sharing
Multi-head attention (MHA) uses : every query head has its own key and value head (Vaswani et al. 2017). Multi-query attention (MQA) uses , so all query heads share one key and value head (Shazeer 2019). Grouped-query attention (GQA) chooses an intermediate and assigns several query heads to each KV head (Ainslie et al. 2023).
Under the dense-payload formula, changing MHA to GQA reduces cache bytes by when all other dimensions stay fixed. Changing MHA to MQA reduces them by . These are exact storage ratios, not quality claims. Ainslie et al. reported that an MHA checkpoint could be uptrained into GQA using 5% of its original pretraining compute, with quality close to MHA and speed comparable to MQA in their experiments (Ainslie et al. 2023). The result supports GQA as a useful design point; it does not prove one KV-head count is optimal for every model and context length.
MLA changes the cached representation
Multi-head latent attention (MLA), introduced in DeepSeek-V2, does not obtain its main saving by sharing a conventional KV head (DeepSeek-AI 2024). It projects each residual vector into a low-dimensional latent , from which content keys and values are derived. A separate small RoPE key component is retained because applying a position-dependent rotation prevents the full key projection from being absorbed into later matrix multiplications.
In the DeepSeek-V2 construction, the per-position payload is
Here is the joint KV latent width; is the decoupled RoPE-key width; and , , , and have the meanings defined for the dense cache. DeepSeek-V2 sets and , or cached elements per position and layer. A conventional equal-width MQA cache stores elements, so MLA is not generically “smaller than MQA.” During optimized decode, the up-projection matrices can be absorbed into the query and output projections; full per-head K and V need not be explicitly reconstructed.
DeepSeek reported lower cache requirements than its MHA baseline and better results on most listed metrics in its controlled ablations. That is evidence for the reported architecture and training recipe, not a general theorem that latent attention dominates GQA.
Separate arithmetic, temporary memory, and persistent state
Several techniques called “efficient attention” act on different resources:
| Technique | Changes attention result? | Main resource changed | What remains |
|---|---|---|---|
| FlashAttention | No; exact dense attention up to numerical ordering | HBM traffic and temporary score storage | Dense quadratic attention arithmetic and the persistent KV cache |
| MQA / GQA | Yes; query heads share K and V projections | KV parameters, cache payload, and decode bandwidth | Every query still attends to every allowed cached position |
| MLA | Yes; K/V content uses a latent factorization | Cached representation and associated bandwidth | Dense position coverage unless combined with sparsity |
| Trained sparse attention | Yes; only selected positions or blocks enter the main attention | Main score/value arithmetic and memory traffic | Selector work and cache footprint depend on the design |
FlashAttention tiles exact attention so the full score matrix need not be written to high-bandwidth memory (Dao et al. 2022). It reduces IO and temporary activation memory during training and prefill. It does not by itself change the number of past key/value elements retained for decode.
Sparse attention changes the mathematical connectivity. Native sparse attention jointly trains three gated branches: compressed coarse-grained tokens, selected fine-grained blocks, and a local sliding window (Yuan et al. 2025). DeepSeek Sparse Attention (DSA) is a distinct later design. Its low-dimensional lightning indexer ranks past tokens, after which the main MLA path attends to a selected top- subset (DeepSeek-AI 2025). The main attention work moves from all past positions toward , but the indexer reported for DeepSeek-V3.2 still scores all query-key pairs and remains quadratic at a smaller dimension. Selector error, continued-training cost, and retained cache state also count. Sparse selection does not automatically delete the full cache.
There is no single efficiency frontier independent of workload. GQA has a simple dense computation and an exact head-count storage formula. MLA changes the factorization and may reduce cache further under a matched recipe. Learned sparsity attacks position coverage, but adds a selector whose recall and hardware efficiency must be measured. Training loss, long-context task quality, prefill throughput, decode latency, resident batch size, and implementation maturity can rank the same candidates differently.
The tokenizer fixes vocabulary size and the sequence lengths presented to this architecture. This chapter then fixes model width, block count, head dimensions, mask semantics, position scheme, and cache representation. Those choices become tensor shapes and memory demand for Chapter 10 and Chapter 31. A serving kernel may implement the equations more efficiently, but it cannot silently change their mask, head mapping, or checkpoint row meanings.
Record the architecture as a contract
A reproducible decoder specification should name at least:
- vocabulary size, embedding width, output projection shape, and weight tying;
- block count, model width, FFN width, activation, and all bias settings;
- residual ordering, normalization locations, type, epsilon, and precision;
- query-head count, KV-head count, head width, and query-to-KV mapping;
- attention mask, document-boundary behavior, and any local or sparse pattern;
- position mechanism, RoPE base and rotated dimensions, plus scaling rules;
- cache representation, element type, quantization scale granularity, and payload bytes per token;
- final normalization and any logit scaling or clipping.
Names such as “LLaMA-like” or “GQA” leave several of these fields undefined. The serialized model configuration, checkpoint tensors, training code, and serving engine must agree on the same contract.
Validate before the full training run
- Check shapes and parameter counts. Derive every projection shape and reconcile the total with serialized tensors, including tied parameters.
- Test causality. Perturb future tokens and confirm earlier logits do not change. Include padding, packed documents, and prefix masks where used.
- Compare a reference attention path. On small tensors, compare the optimized kernel with a straightforward high-precision implementation and declare numerical tolerances.
- Test cached equivalence. Confirm token-by-token decode logits match a full-prefix forward pass within tolerance at every position.
- Measure cache bytes. Compare allocated and payload memory against the declared formula across batch sizes and sequence lengths.
- Exercise position boundaries. Test the trained length, the deployed maximum, and offsets used by prefix caching or sequence packing.
- Ablate architecture choices. Compare normalization, FFN, head sharing, and position candidates under matched parameter, token, and compute budgets.
- Benchmark end to end. Report training throughput, prefill latency, decode latency, maximum resident batch, and quality on the target workload.
The block is compact enough to draw on one page, but its contract reaches from token ids to serving memory. Precision comes from keeping the mathematical operation, its tensor layout, and its runtime representation distinct.
Further reading
- Vaswani et al., “Attention Is All You Need,” 2017. arXiv:1706.03762The Transformer replaces recurrence with multi-head attention and position-wise feed-forward blocks, enabling substantially more parallel sequence training.
- Ba et al., “Layer Normalization,” 2016. arXiv:1607.06450Layer normalization computes normalization statistics across all hidden units within a single layer and training case, eliminating batch-size constraints and stabilizing recurrent neural network training.
- Zhang & Sennrich, “Root Mean Square Layer Normalization” (RMSNorm), 2019. arXiv:1910.07467RMSNorm replaces LayerNorm's mean-and-variance normalization with RMS-only scaling, achieving comparable accuracy while reducing per-step runtime by 7 to 64 percent.
- Xiong et al., “On Layer Normalization in the Transformer Architecture,” 2020. arXiv:2002.04745This paper uses mean field theory to show that placing layer normalization inside residual blocks (Pre-LN) yields well-behaved gradients at initialization, allowing Transformer training without learning rate warm-up.
- Hendrycks & Gimpel, “Gaussian Error Linear Units (GELUs),” 2016. arXiv:1606.08415This paper introduces GELU, an activation function defined as x times the Gaussian CDF, which outperforms ReLU and ELU across vision, NLP, and speech tasks.
- Shazeer, “GLU Variants Improve Transformer” (SwiGLU), 2020. arXiv:2002.05202This paper proposes GLU variants such as SwiGLU and GEGLU as replacements for the ReLU activation in the Transformer FFN sublayer, finding they improve perplexity and downstream task quality.
- Su et al., “RoFormer: Enhanced Transformer with Rotary Position Embedding” (RoPE), 2024. arXiv:2104.09864RoFormer introduces RoPE, which encodes token positions as rotation matrices in self-attention, giving sequence-length flexibility and decaying inter-token dependency with distance.
- Press et al., “Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation” (ALiBi), 2022. arXiv:2108.12409ALiBi replaces positional embeddings with per-head linear distance penalties on attention scores, enabling transformers trained on short sequences to extrapolate to longer ones at inference time with no added runtime cost.
- Press & Wolf, “Using the Output Embedding to Improve Language Models” (weight tying), 2017. arXiv:1608.05859Tying the input and output embedding matrices in neural language models reduces perplexity and can cut translation model parameter count to less than half with no performance loss.
- Shazeer, “Fast Transformer Decoding: One Write-Head is All You Need” (MQA), 2019. arXiv:1911.02150Multi-query attention (MQA) shares keys and values across all attention heads, cutting memory bandwidth for incremental decoding with only minor quality loss.
- Ainslie et al., “GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints,” 2023. arXiv:2305.13245Grouped-query attention uses an intermediate number of KV heads; in the paper's uptraining experiments it approaches MHA quality with MQA-like speed using 5 percent of original pretraining compute.
- Dao et al., “FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness,” 2022. arXiv:2205.14135Dense FlashAttention computes exact attention with IO-aware tiling, reducing HBM traffic and avoiding materialization of the full score and probability matrices.
- DeepSeek-AI, “DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model” (introduces multi-head latent attention (MLA)), 2024. arXiv:2405.04434DeepSeek-V2 introduces multi-head latent attention, which caches a compressed joint KV latent plus a decoupled positional key component.
- Yuan et al., “Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse Attention” (NSA, trainable sparse attention), 2025. arXiv:2502.11089NSA trains a gated combination of compressed-token, selected-block, and local-window attention branches end to end, with hardware-aligned kernels for long contexts.
- DeepSeek-AI, “DeepSeek-V3.2: Pushing the Frontier of Open Large Language Models” (DeepSeek sparse attention (DSA) in production), 2025. arXiv:2512.02556DeepSeek-V3.2 introduces DSA: a low-dimensional lightning indexer selects top-k latent entries for the main MLA path, while the indexer itself still performs lower-cost quadratic scoring.
- Touvron et al., “LLaMA: Open and Efficient Foundation Language Models,” 2023. arXiv:2302.13971LLaMA introduces a family of open foundation language models (7B to 65B parameters) trained exclusively on public data, where smaller models trained on more tokens match or outperform larger proprietary models at inference.
- Bai et al., “Qwen Technical Report,” 2023. arXiv:2309.16609Qwen is a family of large language models trained on up to 3 trillion tokens, covering base pretrained models, RLHF-aligned chat models, and specialized coding and mathematics variants.
- Yang et al., “Qwen2 Technical Report,” 2024. arXiv:2407.10671Qwen2 is a series of open-weight LLMs (0.5B to 72B, plus a 57B-A14B MoE) trained on 7T tokens with GQA, RoPE, SwiGLU, DPO, and strong multilingual coverage across 30 languages.
- Yang et al., “Qwen2.5 Technical Report,” 2024. arXiv:2412.15115Qwen2.5 is a family of LLMs trained on 18 trillion tokens with SFT, DPO, and GRPO post-training, spanning dense models from 0.5B to 72B and MoE variants Qwen2.5-Turbo and Qwen2.5-Plus.
Comments
Log in to comment