Transformer Architecture Internals & Variants

Transformer Architecture Internals & Variants

Every modern LLM (Llama 3, DeepSeek-V3, Qwen 3, Mistral, Gemma 2) is a stack of near-identical decoder blocks. This reference is the anatomy of one block and the menu of variants the frontier labs swap in. It answers: what is actually inside the box, why is it shaped that way, and which knob did DeepSeek/Llama/Mistral turn?

The one mental model that unlocks everything here: the residual stream. A decoder-only transformer is a residual stream of width d_model that every layer reads from and writes back to additively: x = x + Attention(Norm(x)) then x = x + FFN(Norm(x)). Attention moves information between token positions; the FFN processes each position independently. Normalization keeps the stream numerically sane; positional encoding tells attention where tokens sit. Almost every “variant” below is a cheaper/longer/sparser way to compute one of those two sublayers (attention or FFN) without changing the residual-stream contract. Hold that and the whole zoo becomes legible.

Scope guard: this file is the architecture. For serving it (vLLM, paged KV cache, continuous batching, speculative decoding) see llm-inference-serving.md, which explicitly defers attention math here. For shrinking it (GPTQ/AWQ/GGUF/FP8 algorithms) see llm-compression.md. For training/aligning it see llm-alignment-post-training.md. For which model to pick see llm-models.md.

The canonical block, modern (pre-norm, decoder-only) form:

                 ┌─────────────────────── residual stream (width d_model) ───────────────────────┐
   tokens → embed │→(+)→[ Norm → Self-Attention (+ pos. enc.) ]→(+)→[ Norm → FFN (gated) ]→ … ×L │→ Norm → unembed → logits
                  └──────↑──────────────────────────────────────↑─────────────────────────────────┘
                       residual add                          residual add

1. Self-attention & multi-head attention (the core mechanic)

Core idea. Attention lets each token build a query, compare it against every token’s key, and pull a weighted blend of every token’s value. It is the only sublayer that mixes information across positions. “Self”-attention means Q, K, V are all projections of the same sequence.

The mechanism — scaled dot-product attention (Vaswani et al. 2017, “Attention Is All You Need”, arXiv:1706.03762):

Attention(Q, K, V) = softmax( Q Kᵀ / √d_k ) V

Multi-head attention (MHA). Run h attention computations in parallel on d_model/h-sized slices, concatenate, project back: MHA = Concat(head₁…head_h) W_O. Each head can specialize (one tracks syntax, another tracks a referent). Cost: O(seq² · d_model) compute and an O(seq²) attention matrix, the quadratic wall that drives every efficiency variant below.

The KV cache (why inference memory explodes). During autoregressive decode, the K and V for past tokens never change, so they are cached and reused, turning per-step attention from quadratic into linear compute. But the cache itself grows as 2 · n_layers · n_kv_heads · d_head · seq · batch · dtype_bytes, and at long context / large batch it becomes the dominant memory consumer and the thing that caps throughput. Shrinking the KV cache is the single biggest motivation for MQA/GQA/MLA (§3). (The serving-side management of this cache, via PagedAttention and offload, is llm-inference-serving.md’s job; here it explains why the variants exist.)


2. Positional encoding (telling attention where tokens are)

Attention is permutation-invariant: softmax(QKᵀ)V doesn’t know token order. Positional encoding injects order. This is one of the most consequential architecture choices because it governs how far the model can extrapolate beyond its training context.

Scheme Mechanism Relative? Extrapolates? Used by
Sinusoidal absolute (Vaswani 2017) Add fixed sin/cos vectors of geometric frequencies to embeddings No Poorly Original Transformer, early models
Learned absolute A trainable embedding per position index No No (caps at trained length) GPT-2, BERT, early GPT-3
RoPE (Su et al. 2021, RoFormer, arXiv:2104.09864) Rotate Q and K in 2-D subspaces by an angle m·θ_i proportional to position; θ_i = base^(−2i/d), base usually 10000 Yes (dot product depends on m−n) Moderately (and the basis for YaRN, §7) Llama 1/2/3, DeepSeek, Qwen, Mistral, Gemma — the de-facto standard
ALiBi (Press et al. 2022, arXiv:2108.12409) Add a linear bias −slope·(m−n) directly to attention scores; no embeddings at all Yes (bias is on distance) Strongly (train short, test long) BLOOM, MPT, some long-context models
NoPE (no positional encoding) Causal mask alone leaks enough order for decoder-only LMs to learn position implicitly n/a Surprisingly well at length generalization Research finding; used selectively / in hybrids

RoPE — the one to understand. It applies a rotation matrix to each 2-D pair of Q/K dimensions:

R(m,θ_i) = [ cos(m·θ_i)  −sin(m·θ_i) ;  sin(m·θ_i)  cos(m·θ_i) ]
⟨R(m)·q,  R(n)·k⟩  ∝  ⟨q,k⟩ · cos((m−n)·θ)

Because the inner product collapses to a function of (m−n), RoPE encodes relative position while only ever rotating absolute-position-indexed vectors: cheap, no extra parameters, and it composes with the KV cache. It also has a long-term decay property (distant tokens attend less). The base/θ value is the knob long-context extension turns (§7). Adoption: essentially every open-weight frontier model in 2025-2026.


3. Attention-efficiency variants (shrinking the KV cache: MQA → GQA → MLA)

These keep the same attention math but reduce how many distinct K/V projections exist, directly shrinking the KV cache and the memory-bandwidth bottleneck during decode. This is a spectrum:

Why this lives here, not in serving: GQA/MLA change the model’s parameter structure and what gets cached. The serving engine’s PagedAttention then manages that cache in GPU memory. Architecture decides the cache shape; serving decides its placement. See llm-inference-serving.md §KV-cache.


4. FlashAttention — IO-aware exact attention

Core idea. FlashAttention is not an approximation and not a new attention formula; it is the same softmax(QKᵀ/√d)V, computed in an order that never writes the giant seq × seq attention matrix to slow memory. It is the reason long-context training/inference is affordable.

Why “IO-aware” is the whole point. A GPU has a memory hierarchy: huge-but-slow HBM (high-bandwidth memory) and tiny-but-fast on-chip SRAM. Naive attention is memory-bound, not compute-bound: it materializes the N×N scores in HBM, reads them back for softmax, reads again for the ×V; the bottleneck is HBM traffic, not FLOPs. FlashAttention (Dao et al. 2022, arXiv:2205.14135, NeurIPS 2022):

Net effect: memory drops from O(N²) to O(N), with a ~7.6× attention speedup reported originally.

The version progression (architecture-relevant differences):

Boundary: the kernel implementation and how a serving engine integrates it is llm-inference-serving.md. Here the takeaway is conceptual: FlashAttention is exact attention reordered to respect the GPU memory hierarchy, which is why context windows grew without the quadratic memory wall.


5. Normalization & its placement (RMSNorm, pre-norm vs post-norm)

What normalization does. It rescales activations to keep the residual stream numerically stable as it passes through dozens of layers; without it, deep transformers diverge.

Placement — pre-norm vs post-norm (Xiong et al. 2020, “On Layer Normalization in the Transformer Architecture”):

Modern default: pre-RMSNorm. DeepSeek-V3 adds an extra norm after the compressed-attention/MoE paths for stability.


6. Feed-forward network & gated activations (SwiGLU)

What the FFN does. After attention mixes positions, the FFN (a.k.a. MLP) processes each position independently through an expand-then-contract MLP. It holds the bulk of a dense model’s parameters (~2/3) and is where most “knowledge” is stored.

SwiGLU-FFN(x) = ( Swish(x W_gate) ⊙ (x W_up) ) W_down

Adoption: SwiGLU is the modern default — PaLM, Llama 1/2/3, Mistral, DeepSeek, Qwen, Gemma.


7. Long-context extension (stretching a trained context window)

Models are pretrained at a fixed context (e.g. 4K-8K) but deployed at 128K-1M+. Because RoPE (§2) is a function of position, you can rescale its frequencies to cover positions never seen in training, usually with a short fine-tune, sometimes zero-shot.


8. Mixture-of-Experts (sparse FFN: scale parameters, not compute-per-token)

Core idea. Replace the single dense FFN (§6) with many expert FFNs and a router that sends each token to only a few. Total parameters (capacity) grow huge while compute per token stays fixed: you “activate” only a sparse slice. MoE is applied to the FFN sublayer; attention stays dense.

Mechanics:

DeepSeek-V3-style MoE — the 2024-2026 frontier design (arXiv:2412.19437):

Adoption: DeepSeek-V3/R1, Mixtral, Qwen-MoE, Llama 4, GPT-class frontier models — MoE is the dominant way to scale frontier capacity in 2025-2026.


9. Alternative & hybrid architectures (beyond quadratic attention)

Attention is O(seq²). A parallel research line replaces or dilutes it with sub-quadratic sequence mixers that keep a fixed-size recurrent state.


10. Tokenization (overview — how text becomes token IDs)

Before any of the above runs, text is split into tokens. The choice affects vocabulary size, sequence length, and multilingual/code coverage, but it’s upstream of the architecture.

Rule of thumb: GPT family → byte-level BPE via tiktoken; Llama/Gemma → SentencePiece (Llama 3 moved to a tiktoken-style 128K byte-level BPE). Tokenizer choice is a data/efficiency decision, not part of the transformer block.


Putting it together — how a 2025-2026 frontier model is configured

Component Legacy (GPT-2 era) Modern default (Llama 3 / Qwen) Frontier MoE (DeepSeek-V3)
Norm LayerNorm, post-norm RMSNorm, pre-norm RMSNorm, pre-norm (+ extra norms)
Positional Learned absolute RoPE RoPE with decoupled dims (for MLA)
Attention MHA GQA MLA (low-rank latent KV)
Attention kernel naive FlashAttention-2/3 FlashAttention-3
FFN ReLU/GELU MLP SwiGLU SwiGLU experts
Capacity dense dense fine-grained + shared MoE, aux-loss-free LB
Long context RoPE + YaRN YaRN-style + context parallel
Tokenizer BPE byte-level BPE / SentencePiece byte-level BPE

The throughline: every modern choice (RMSNorm, pre-norm, RoPE, GQA/MLA, SwiGLU, FlashAttention, MoE) is the cheaper or longer-context substitute for an original-Transformer component, chosen to push more capability through the same FLOP and memory budget.


Anti-patterns & gotchas


References (primary sources & reference implementations)

Attention & efficiency

  1. Vaswani et al. (2017), Attention Is All You Need — arXiv:1706.03762 (scaled dot-product + MHA, the origin).
  2. Shazeer (2019), Fast Transformer Decoding: One Write-Head is All You Need (MQA) — arXiv:1911.02150.
  3. Ainslie et al. (2023), GQA: Training Generalized Multi-Query Transformer Models from Multi-Head Checkpoints — arXiv:2305.13245 (EMNLP 2023).
  4. DeepSeek-AI (2024), DeepSeek-V3 Technical Report — arXiv:2412.19437 (MLA + DeepSeekMoE primary source).
  5. Dao et al. (2022), FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness — arXiv:2205.14135 (NeurIPS 2022).
  6. Dao (2023), FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning — arXiv:2307.08691.
  7. Shah, Dao et al. (2024), FlashAttention-3: Fast and Accurate Attention with Asynchrony and Low-precision — arXiv:2407.08608; tridao.me/blog/2024/flash3/.
  8. Beltagy et al. (2020), Longformer: The Long-Document Transformer — arXiv:2004.05150 (sliding-window + global/sparse attention).

Positional & long context 9. Su et al. (2021), RoFormer: Enhanced Transformer with Rotary Position Embedding (RoPE) — arXiv:2104.09864. 10. Press et al. (2022), Train Short, Test Long: Attention with Linear Biases (ALiBi) — arXiv:2108.12409. 11. Chen et al. (2023), Extending Context Window via Position Interpolation — arXiv:2306.15595. 12. Peng et al. (2023), YaRN: Efficient Context Window Extension of Large Language Models — arXiv:2309.00071 (ICLR 2024).

Normalization, FFN, residual 13. Zhang & Sennrich (2019), Root Mean Square Layer Normalization (RMSNorm) — arXiv:1910.07467. 14. Xiong et al. (2020), On Layer Normalization in the Transformer Architecture (pre vs post-norm) — arXiv:2002.04745. 15. Shazeer (2020), GLU Variants Improve Transformer (SwiGLU/GeGLU) — arXiv:2002.05202. 16. Jiang/Halverson et al. (2023), Pre-RMSNorm and Pre-CRMSNorm Transformers — arXiv:2305.14858.

MoE & alternative architectures 17. Fedus et al. (2021), Switch Transformers (top-1 routing, aux load-balancing loss) — arXiv:2101.03961. 18. Dai et al. (2024), DeepSeekMoE: Towards Ultimate Expert Specialization (fine-grained + shared experts) — arXiv:2401.06066. 19. Wang et al. (2024), Auxiliary-Loss-Free Load Balancing Strategy for MoE — arXiv:2408.15664. 20. Gu & Dao (2023), Mamba: Linear-Time Sequence Modeling with Selective State Spaces — arXiv:2312.00752. 21. Dao & Gu (2024), Transformers are SSMs: Generalized Models and Efficient Algorithms (Mamba-2 / SSD) — arXiv:2405.21060. 22. Peng et al. (2023→2025), RWKV: Reinventing RNNs for the Transformer Era (and RWKV-7) — arXiv:2305.13048. 23. Lieber et al. (2024), Jamba: A Hybrid Transformer-Mamba Language Model — arXiv:2403.19887.

Tokenization 24. Sennrich et al. (2016), Neural Machine Translation of Rare Words with Subword Units (BPE) — arXiv:1508.07909. 25. Kudo & Richardson (2018), SentencePiece — arXiv:1808.06226. OpenAI tiktoken (github.com/openai/tiktoken).

Compiled via /dr deep-research, 2026-05-31. Treat any model IDs / context-window numbers as fast-moving — defer to the model’s own technical report / model card for exact current specs.