← Back to Technical Library

Transformers Architecture Explained

A Technical Deep-Dive into the Architecture That Revolutionized AI

Category: Core AI Concepts Read time: ~25 min Updated: June 2026 Level: Intermediate-Advanced
The Transformer architecture, introduced in the 2017 paper "Attention Is All You Need" by Vaswani et al., replaced recurrent neural networks with a purely attention-based mechanism that processes sequences in parallel. This article provides a comprehensive technical walkthrough of every core component: self-attention, multi-head attention, positional encoding, feed-forward layers, residual connections, and layer normalization. We compare encoder-only, decoder-only, and encoder-decoder variants; trace token flow step-by-step; survey landmark models (GPT, BERT, T5); examine scaling relationships; and explore advanced architectures including Mixture of Experts (MoE). Whether you are building fine-tuning pipelines or simply seeking a deeper understanding of modern LLMs, this reference covers the mechanics from first principles.
Transformers Attention Encoder-Decoder Positional Encoding GPT BERT MoE RoPE

Table of Contents

1. What Are Transformers?

A Transformer is a neural network architecture that processes sequential data -- most commonly text -- using a mechanism called self-attention rather than recurrence or convolution. Unlike RNNs that read tokens one at a time and carry a hidden state forward, transformers look at all positions in a sequence simultaneously, computing weighted relationships between every pair of tokens in a single matrix operation.

The architecture was introduced by Ashish Vaswani and colleagues at Google in the landmark 2017 paper "Attention Is All You Need." The title was provocative: it declared that attention alone -- without recurrence, convolution, or gating -- was sufficient for state-of-the-art sequence modeling. The claim proved correct, and transformers now underpin virtually every major natural language processing system, from search ranking to machine translation to the large language models (LLMs) that power conversational AI.

At the highest level, a transformer takes a sequence of tokens, converts each into a dense vector embedding, adds positional information, and then passes those vectors through a stack of identical layers. Each layer refines the representations by allowing tokens to attend to one another, then applies a position-wise feed-forward network. After many such layers, the output representations encode rich contextual meaning that can be used for classification, generation, translation, or any downstream task.

Key Insight: The core innovation is not attention itself (attention existed in RNN encoder-decoder models before 2017), but the removal of recurrence entirely. By computing all pairwise token interactions in parallel via matrix multiplication, transformers exploit GPU hardware far more efficiently than sequential RNNs.

Core Properties

2. Why Transformers Revolutionized NLP

Before 2017, the dominant sequence modeling architectures were LSTMs (Long Short-Term Memory networks) and GRUs (Gated Recurrent Units). These models achieved strong results but suffered from fundamental limitations that transformers overcame:

Transformers solved all of these problems simultaneously. The attention mechanism provides direct access between any two positions, eliminating the information bottleneck. Matrix-based computation parallelizes perfectly on GPUs and TPUs, enabling training on datasets orders of magnitude larger. And the architecture scales smoothly: adding more layers, heads, or parameters reliably improves performance, a property that enabled the era of large language models.

The Scaling Revolution: Transformers enabled a paradigm shift -- from carefully designing architectures for specific tasks to training a single general architecture on massive data and scaling it up. This gave rise to GPT-3, GPT-4, Claude, Gemini, and the entire modern LLM ecosystem.

Timeline of Impact

Year Milestone Significance
2017 "Attention Is All You Need" Transformer architecture introduced; SOTA on WMT translation
2018 BERT (Google) Encoder-only transformer; 11 NLP benchmarks surpassed
2018 GPT-1 (OpenAI) Decoder-only transformer; generative pre-training paradigm
2019 GPT-2 (OpenAI) 1.5B parameters; coherent multi-paragraph text generation
2019 T5 (Google) Encoder-decoder; unified text-to-text framework
2020 GPT-3 (OpenAI) 175B parameters; in-context learning / few-shot emerges
2021 Switch Transformer (Google) Mixture of Experts at trillion-parameter scale
2022 Chinchilla (DeepMind) Scaling laws refined: data matters as much as parameters
2023+ GPT-4, Claude, Gemini, Llama Multimodal, MoE, and open-weight ecosystems mature

3. Encoder vs Decoder vs Encoder-Decoder

The original transformer was an encoder-decoder architecture designed for sequence-to-sequence tasks like machine translation. The encoder maps an input sequence into a sequence of contextualized representations; the decoder then generates an output sequence auto-regressively, attending both to its own previous outputs (causal self-attention) and to the encoder's representations (cross-attention).

Over time, researchers found that each half of the architecture is useful independently, leading to three major families:

3.1 Encoder-Only (e.g., BERT)

Uses only the encoder stack. Every token attends to every other token (bidirectional / full self-attention). Produces a contextualized embedding for each position. Best suited for understanding tasks: classification, named entity recognition, question answering, sentence embeddings.

3.2 Decoder-Only (e.g., GPT family, Llama, Claude)

Uses only the decoder stack with causal (masked) self-attention. Each token can only attend to itself and previous tokens, never to future ones. This auto-regressive structure is ideal for generation tasks: given a prefix, predict the next token, then the next, and so on.

3.3 Encoder-Decoder (e.g., T5, BART, original Transformer)

Uses both stacks. The encoder processes the full input sequence with bidirectional attention; the decoder generates output auto-regressively, using causal self-attention for its own outputs and cross-attention to attend over encoder outputs. Ideal for sequence-to-sequence tasks: translation, summarization, and any task framed as input-to-output mapping.

Trend: The modern LLM ecosystem has overwhelmingly converged on decoder-only architectures. GPT-4, Claude, Gemini, Llama, Mistral, and DeepSeek are all decoder-only (or decoder-only with MoE). The simplicity of next-token prediction and the scalability of a single stack have proven decisive.

Architecture Comparison Summary

Property Encoder-Only Decoder-Only Encoder-Decoder
Example BERT, RoBERTa GPT, Llama, Claude T5, BART, original
Attention Full (bidirectional) Causal (masked) Full + Causal + Cross
Training objective Masked LM Next-token prediction Denoising / Seq2Seq
Best for Understanding / classification Generation / chat Translation / summarization
Generation capable? No (needs adaptation) Yes (natively) Yes (natively)
Dominant today? Niche (embeddings, classification) Yes -- most LLMs Niche (T5 family)

4. The Self-Attention Mechanism

Self-attention is the heart of the transformer. Given a sequence of token embeddings, self-attention computes a new representation for each token by taking a weighted average of all other token representations, where the weights reflect how relevant each other token is to the current one.

4.1 Query, Key, and Value Matrices

The mechanism borrows terminology from information retrieval. For each token, the model produces three vectors via learned linear projections:

For an input matrix X of shape (sequence_length × d_model), three learned weight matrices W_Q, W_K, and W_V (each of shape d_model × d_k) produce:

Q = X · W_Q (shape: n × d_k) K = X · W_K (shape: n × d_k) V = X · W_V (shape: n × d_v)

Here, n is the sequence length, d_model is the embedding dimension, and d_k / d_v are the per-head attention dimensions (typically d_model / num_heads).

4.2 Scaled Dot-Product Attention

The attention output for the entire sequence is computed in a single matrix operation:

Attention(Q, K, V) = softmax( Q · K^T / sqrt(d_k) ) · V

Breaking this down step by step:

  1. Dot product Q · KT: Compute the similarity (dot product) between every query and every key. This produces an n × n matrix of raw attention scores, where entry (i, j) measures how much token i should attend to token j.
  2. Scaling by 1/sqrt(d_k): Divide each score by the square root of the key dimension. This prevents the dot products from growing large in high dimensions, which would push the softmax into regions with extremely small gradients.
  3. Softmax: Apply softmax along each row (over the key dimension) to convert raw scores into a probability distribution. Each row now sums to 1, representing how the current token distributes its attention across all positions.
  4. Multiply by V: Multiply the n × n attention weight matrix by the n × d_v value matrix to produce the final n × d_v output. Each output token is a weighted sum of all value vectors.
Why scale by 1/sqrt(d_k)? When d_k is large, the dot products Q·KT can have large variance, pushing the softmax function into saturation where gradients vanish. Dividing by sqrt(d_k) keeps the variance of the dot products at approximately 1, ensuring stable gradients. This is a critical implementation detail -- omitting it degrades training, especially for large models.

4.3 Causal Masking

In decoder models, we must prevent tokens from attending to future positions. This is achieved by adding a causal mask to the attention scores before softmax. The mask sets all entries above the diagonal to negative infinity (or a very large negative number), so that after softmax, those positions receive exactly zero attention weight:

Mask (lower triangular): [[ 0, -inf, -inf, -inf], [ 0, 0, -inf, -inf], [ 0, 0, 0, -inf], [ 0, 0, 0, 0 ]] After softmax, upper-triangular entries become 0, ensuring token i only attends to tokens 0..i.

4.4 Complexity Analysis

Operation Time Complexity Space Complexity Notes
Q, K, V projections O(n · d_model · d_k) O(n · d_k) Linear in sequence length
Q · KT O(n2 · d_k) O(n2) Quadratic -- the attention bottleneck
Softmax over rows O(n2) O(n2) Per-row normalization
Attn · V O(n2 · d_v) O(n · d_v) Weighted sum of values
Total self-attention O(n2 · d) O(n2) Quadratic in sequence length

The O(n2) memory for the attention matrix is the primary bottleneck for long sequences. A 128K-token context window requires storing a 128K × 128K attention matrix, which is why techniques like FlashAttention, sliding window attention, and linear attention variants have become critical at scale.

5. Multi-Head Attention

Instead of performing a single attention function with d_model-dimensional keys and values, the transformer runs h attention functions (heads) in parallel, each with reduced dimension d_k = d_model / h. The outputs are concatenated and projected back to d_model.

For each head i (i = 1..h): Q_i = X · W_Q_i (n × d_k) K_i = X · W_K_i (n × d_k) V_i = X · W_V_i (n × d_v) head_i = Attention(Q_i, K_i, V_i) Concatenate: MultiHead = [head_1; head_2; ...; head_h] Output: Z = MultiHead · W_O (n × d_model)

5.1 Why Multiple Heads?

Different heads learn to attend to different types of relationships. Research on attention head analysis has shown that individual heads specialize:

By running multiple heads in parallel and concatenating, the model captures a richer set of relationships than any single attention function could.

Dimension sharing: Each head operates on d_k = d_model / h dimensions. The total computation across all heads is approximately the same as a single head with full d_model dimension. The multi-head design therefore adds representational richness without significantly increasing compute -- it is a "free" improvement in expressiveness.

5.2 Typical Head Counts

Model d_model Num Heads d_k per head
Transformer (base) 512 8 64
BERT-Large 1024 16 64
GPT-2 (1.5B) 1600 25 64
GPT-3 (175B) 12288 96 128
Llama-2 70B 8192 64 128
Llama-3 70B 8192 64 128

6. Positional Encoding

Self-attention is permutation-invariant -- it computes the same result regardless of the order of tokens, because the attention weights depend only on the content of Q, K, V, not on position. This is a problem: "the dog chased the cat" and "the cat chased the dog" would produce identical representations without positional information.

Positional encoding solves this by injecting position-dependent signals into the input embeddings so that the attention mechanism can distinguish token order. Several approaches have been developed:

6.1 Sinusoidal Positional Encoding (Original)

The original transformer uses fixed sine and cosine functions of different frequencies:

PE(pos, 2i) = sin(pos / 10000^(2i / d_model)) PE(pos, 2i+1) = cos(pos / 10000^(2i / d_model))

Where pos is the position (0, 1, 2, ...) and i is the dimension index. The resulting positional encoding vector is added to the token embedding before the first layer.

6.2 Learned Positional Embeddings

Instead of a fixed formula, the model learns a lookup table of position embeddings -- one vector per position, up to a maximum sequence length. BERT and GPT-2 use this approach.

6.3 Rotary Position Embedding (RoPE)

RoPE, introduced by Su et al. in 2021, encodes position by rotating the query and key vectors in a multi-dimensional space. The rotation angle depends on position, and the relative position between two tokens is implicitly encoded in the angle difference of their rotations.

For a 2D sub-space (x, y), position p applies rotation: [x'] [cos(pθ) -sin(pθ)] [x] [y'] = [sin(pθ) cos(pθ)] [y] Applied independently to each pair of dimensions with different frequencies θ. Key property: <q_m, k_n> depends only on (m - n), the relative position, not absolute positions.
RoPE Scaling: To extend context length, methods like Linear Scaling (divide positions by a scale factor s), NTK-aware Scaling (adjust RoPE frequencies), and YaRN (yet another RoPE extensioN) have been developed. These allow models trained at 4K context to operate at 32K-128K context with minimal fine-tuning.

6.4 ALiBi (Attention with Linear Biases)

ALiBi, introduced by Press et al. in 2021, takes a radically different approach: it does not add positional embeddings to the input at all. Instead, it adds a static, non-learned bias to the attention scores that penalizes attention to distant tokens:

Attention_score(i, j) += -m · |i - j| where m is a per-head slope (geometric sequence: m_h = 1 / 2^(2h-8) for h heads) This makes attention to nearby tokens slightly cheaper than attention to distant tokens, encoding position directly in the attention computation.

6.5 Comparison of Positional Encoding Methods

Method Type Learned? Extrapolation Used By
Sinusoidal Absolute, additive No Poor Original Transformer
Learned embeddings Absolute, additive Yes None (hard limit) BERT, GPT-2
RoPE Relative, rotational No Good (with scaling) Llama, Mistral, Qwen
ALiBi Relative, attention bias No Excellent BLOOM, MPT

7. Feed-Forward Networks, Layer Normalization & Residual Connections

Self-attention is only one of two sub-layers in each transformer block. The second is a position-wise feed-forward network (FFN). Additionally, residual connections and layer normalization are applied around both sub-layers. These components are essential for training deep transformer stacks.

7.1 Position-Wise Feed-Forward Network

After multi-head attention, each position's vector is independently passed through a two-layer MLP with a non-linear activation:

FFN(x) = max(0, x · W_1 + b_1) · W_2 + b_2 Input: x (n × d_model) Hidden: (n × d_ff) where d_ff = 4 · d_model (typical) Output: (n × d_model)

The hidden dimension d_ff is typically 4× the model dimension (e.g., d_model=4096 → d_ff=16384). This makes the FFN the most parameter-heavy component of a standard transformer -- approximately 2/3 of the total parameters are in the FFN layers.

Activation functions have evolved:

7.2 Residual Connections

Each sub-layer (attention and FFN) is wrapped with a residual connection:

output = x + Sublayer(x) For attention: output = x + MultiHeadAttention(x) For FFN: output = x + FFN(x)

Residual connections (from the ResNet architecture) allow gradients to flow directly through the network during backpropagation, mitigating the vanishing gradient problem in deep stacks. Without them, training transformers beyond a few layers is extremely difficult.

7.3 Layer Normalization

Layer normalization normalizes the activations across the feature dimension (d_model) for each token independently, stabilizing training:

LayerNorm(x) = γ · (x - μ) / sqrt(σ2 + ε) + β where μ and σ2 are computed over the feature dimension d_model for each position, and γ, β are learned scale/shift parameters.

Two placement strategies exist:

RMSNorm: Many modern models (Llama, Mistral) use Root Mean Square Normalization instead of LayerNorm. RMSNorm removes the mean-centering step and only scales by the RMS of activations, reducing computation by ~10-30% with comparable performance. Formula: RMSNorm(x) = x / RMS(x) · γ where RMS(x) = sqrt(mean(x2) + ε).

7.4 Complete Transformer Layer Formula

-- Pre-LN Transformer Layer -- z1 = LayerNorm(x) z2 = x + MultiHeadAttention(z1) z3 = LayerNorm(z2) output = z2 + FeedForward(z3) -- Or with RMSNorm (Llama-style) -- z1 = RMSNorm(x) z2 = x + MultiHeadAttention(z1) z3 = RMSNorm(z2) output = z2 + SwiGLU_FFN(z3)

8. The Transformer Block Diagram

Below is a text-based diagram of the complete encoder-decoder transformer architecture from the original paper, showing how data flows through the layers.

===================================================================== FULL ENCODER-DECODER TRANSFORMER (Original 2017) ===================================================================== OUTPUT EMBEDDINGS | +------+-------+ | Positional | | Encoding | +------+-------+ | ===================== DECODER STACK (N layers) ===================== | +---------------+---------------+ | | +------+-------+ +------+-------+ | Masked MHA | | Cross-Attn | | (Causal) | | K,V from | +------+-------+ | Encoder | | +------+-------+ +------+-------+ | | Add & Norm | +------+-------+ +------+-------+ | Add & Norm | | +------+-------+ +------+-------+ | | Feed-Forward | +------+-------+ +------+-------+ | Add & Norm | | +------+-------+ +------+-------+ | | Add & Norm | | +------+-------+ | +---------------+-------------+ | [Next Layer...] | +--------+--------+ | Linear Layer | | (d_model -> V) | +--------+--------+ | +--------+--------+ | Softmax | +--------+--------+ | OUTPUT PROBS | [Next Token Prediction] ===================================================================== INPUT EMBEDDINGS | +------+-------+ | Positional | | Encoding | +------+-------+ | ===================== ENCODER STACK (N layers) ===================== | +---------------+---------------+ | | +------+-------+ +------+-------+ | Multi-Head | | Add | | Attention |<-------------+| & Norm | +------+-------+ +------+-------+ | +------+-------+ | Add & Norm | +------+-------+ | +------+-------+ | Feed-Forward | +------+-------+ | +------+-------+ | Add & Norm | +------+-------+ | [Next Layer...] | ENCODER OUTPUTS -----> (fed to Decoder Cross-Attention) =====================================================================

Decoder-Only Block (GPT / Llama style)

=================== DECODER-ONLY BLOCK =================== Token Embeddings + RoPE Positional Info | +--------------+--------------+ | | +--+--+ +---+---+ |RMSNorm| | Res | +--+--+ | id. | | +---+---+ +--+--+ | |Masked| +---+---+ | MHA |<---------------------+| | |(RoPE)| | | +--+--+ | | | | | +--+--+ | | | x | (residual add) | | +--+--+ | | | | | +-----------+---------------+ | +------+------+ | RMSNorm | +------+------+ | +------+------+ | SwiGLU FFN | +------+------+ | +------+------+ | Residual | +------+------+ | [Output to next layer...] ===========================================================

9. How Tokens Flow Through a Transformer (Step by Step)

Let us trace exactly what happens when the input sentence "The cat sat" is processed by a decoder-only transformer (the most common modern architecture). We assume a model with d_model=512, 8 heads, 12 layers.

Step 1: Tokenization

The input string is split into tokens using a subword tokenizer (BPE, WordPiece, or SentencePiece). Each token maps to an integer ID from the vocabulary.

Input: "The cat sat" Tokens: ["The", " cat", " sat"] IDs: [464, 3797, 3290] (example GPT-2 IDs) Vocab size V = 50257

Step 2: Token Embedding

Each integer ID is looked up in an embedding matrix of shape (V × d_model), producing a d_model-dimensional vector for each token.

Embedding matrix E: (50257 × 512) Token ID 464 -> E[464] = [0.12, -0.34, 0.56, ...] (512-dim) Token ID 3797 -> E[3797] = [0.78, 0.01, -0.45, ...] (512-dim) Token ID 3290 -> E[3290] = [-0.22, 0.67, 0.33, ...] (512-dim) Input tensor X: (3 × 512) [seq_len × d_model]

Step 3: Positional Encoding

Positional information is added. For RoPE (used in modern models), this is applied inside the attention computation by rotating Q and K vectors. For learned or sinusoidal embeddings, a position vector is added to the embedding here.

X = X + PE[0..2] (if using additive PE) or: RoPE applied later in attention (rotating Q, K)

Step 4: Layer 1 -- Multi-Head Self-Attention

The input passes through the first transformer layer. First, RMSNorm/LayerNorm is applied, then the normalized output is projected into Q, K, V for each of the 8 attention heads.

h = LayerNorm(X) (3 × 512) For head i (i=0..7): Q_i = h · W_Q_i (3 × 64) K_i = h · W_K_i (3 × 64) V_i = h · W_V_i (3 × 64) Apply RoPE rotation to Q_i, K_i scores = Q_i · K_i^T / sqrt(64) (3 × 3) Apply causal mask (upper triangle = -inf) weights = softmax(scores) (3 × 3) head_i = weights · V_i (3 × 64) Concat all heads: (3 × 512) Project: Z = concat · W_O (3 × 512) Residual: X' = X + Z (3 × 512)

Step 5: Layer 1 -- Feed-Forward Network

h2 = LayerNorm(X') (3 × 512) FFN (SwiGLU example): gate = h2 · W_gate (3 × 2048) [d_ff = 4 × d_model] up = h2 · W_up (3 × 2048) act = Swish(gate) · up (3 × 2048) down = act · W_down (3 × 512) Residual: X'' = X' + down (3 × 512) This is the output of Layer 1.

Step 6: Layers 2 through N

The same process repeats for each of the remaining 11 layers. Each layer refines the representations:

Layer 2: X2 = TransformerLayer(X'') Layer 3: X3 = TransformerLayer(X2) ... Layer 12: X12 = TransformerLayer(X11) Final hidden states: (3 × 512)

Early layers tend to capture syntactic and local patterns; middle layers capture semantic relationships; later layers produce task-relevant representations. This hierarchical feature emergence is a well-documented phenomenon in transformer interpretability research.

Step 7: Output Projection & Softmax

The final hidden states are projected back to vocabulary size via the output (unembedding) matrix, then softmax converts to probabilities:

logits = X12 · W_out^T (3 × 50257) [W_out = embedding matrix, weight-tied in many models] probs = softmax(logits, dim=-1) (3 × 50257) Position 0: predicts token after "The" Position 1: predicts token after "The cat" Position 2: predicts token after "The cat sat" For generation: sample from probs[2, :] e.g., argmax -> " on" (ID 318) Append to sequence, repeat from Step 1
Weight Tying: Most modern LLMs tie the input embedding matrix and the output projection matrix (they share the same weights). This reduces parameters by V×d_model and often improves performance because the input and output representations live in the same semantic space.

11. Model Scaling: Parameters, Layers, Hidden Size & Heads

One of the most important properties of transformers is that they scale predictably. The Kaplan et al. (2020) and Hoffmann et al. (2022, "Chinchilla") scaling laws established that model performance (loss) follows a power-law relationship with model size, dataset size, and compute. This predictability is what enabled the LLM era: you can estimate how good a 100B model will be by measuring a 1B model.

11.1 Parameter Count Breakdown

For a decoder-only transformer with L layers, d_model hidden size, h heads, d_ff = 4·d_model, and vocabulary V:

Embedding: V · d_model Per layer: Attention (Q,K,V,O): 4 · d_model² FFN (2 layers): 2 · d_model · d_ff = 8 · d_model² (With SwiGLU: 3 · d_model · d_ff_factor · d_model) LayerNorm/RMSNorm: ~2 · d_model (negligible) Total per layer: ~12 · d_model² Total (L layers): ~L · 12 · d_model² + V · d_model Approximate total: P ≈ 12 · L · d_model² (embedding is small relative to body for large models)

11.2 Scaling Relationships

The Kaplan scaling law states that the loss L scales as a power law with parameters N, data D, and compute C:

L(N) = (N_c / N)^α_N + L_inf L(D) = (D_c / D)^α_D + L_inf L(C) = (C_c / C)^α_C + L_inf Typical exponents (Kaplan 2020): α_N ≈ 0.076, α_D ≈ 0.095, α_C ≈ 0.050 Chinchilla correction (Hoffmann 2022): Models should be trained on ~20 tokens per parameter. Previous models were undertrained (too many params, too little data).
The Chinchilla Lesson: Before 2022, the common practice was to scale parameters aggressively while using relatively less data. Chinchilla showed that a 70B model trained on 1.4T tokens outperforms a 175B model (GPT-3) trained on 300B tokens. The optimal ratio is approximately 20 tokens per parameter. This finding reshaped the entire LLM training landscape.

11.3 Scaling Configurations of Major Models

Model Params Layers d_model Heads d_ff Vocab Context
GPT-2 Small 124M 12 768 12 3072 50,257 1,024
BERT-Base 110M 12 768 12 3072 30,522 512
BERT-Large 340M 24 1024 16 4096 30,522 512
T5-3B 3B 24+24 1024 32 16384 32,128 512
GPT-3 175B 96 12,288 96 49,152 50,257 2,048
Llama-2 7B 7B 32 4096 32 11,008 32,000 4,096
Llama-2 70B 70B 80 8192 64 28,672 32,000 4,096
Llama-3 8B 8B 32 4096 32 14,336 128,256 8,192
Llama-3 70B 70B 80 8192 64 28,672 128,256 8,192
Mistral 7B 7B 32 4096 32 14,336 32,000 8,192
Chinchilla 70B 80 8192 64 28,672 32,000 2,048

11.4 Depth vs Width

When scaling, there is a choice between increasing depth (more layers) and increasing width (larger d_model). Empirical research suggests:

12. Mixture of Experts (MoE) Architecture

A Mixture of Experts (MoE) model replaces the standard feed-forward network in (some or all) transformer layers with a set of multiple expert FFNs and a router (gate) that dynamically selects which expert(s) to use for each token. This dramatically increases total parameter count while keeping active compute per token roughly constant.

12.1 How MoE Works

Standard FFN (dense): output = FFN(x) -- all parameters used MoE FFN: Router: gate_logits = x · W_gate (1 × num_experts) top_k = topk(gate_logits, k) -- select k experts weights = softmax(top_k) For each selected expert e: expert_output_e = FFN_e(x) output = sum(weights_e · expert_output_e) for e in top_k Key: only k experts are activated per token, but all experts' parameters exist in memory.

Typical configurations use k=2 (top-2 routing) with 8-64 experts. This means each token uses 2 expert FFNs, but the model has 8-64 FFNs worth of parameters available. A 67B MoE model might have only ~13B active parameters per token, making it as fast as a 13B dense model but with the capacity of a much larger model.

12.2 Benefits of MoE

12.3 Challenges

12.4 Notable MoE Models

Model Total Params Active Params Experts Top-k Notes
Switch Transformer 1.6T ~13B 2048 1 Google; top-1 routing
GLaM 1.2T ~97B 64 2 Google; encoder-decoder MoE
Mixtral 8x7B 46.7B ~12.9B 8 2 Mistral; open weights; very popular
DeepSeek-V2 236B ~21B 160 6 Shared + routed experts; MLA attention
DeepSeek-V3 671B ~37B 256 8 Free auxiliary-loss balancing
GPT-4 (rumored) ~1.8T ~220B ~16 2 Architecture not officially confirmed
Claude 3 (estimated) ~200B+ Unknown Unknown Unknown Details not public; likely MoE
DeepSeek's Innovation: DeepSeek-V2/V3 introduced Multi-head Latent Attention (MLA), which compresses the KV cache into a low-rank latent space, drastically reducing memory for long contexts. Combined with fine-grained expert segmentation (shared + routed experts), DeepSeek models achieve frontier-level performance at a fraction of the inference cost of dense models of comparable capability.

12.5 MoE vs Dense: Trade-off Summary

Metric Dense Model MoE Model
Params vs compute 1:1 (all params active) Total >> active (sparse)
Inference speed Slower (more FLOPs/token) Faster (fewer active FLOPs)
Memory requirement Proportional to params Must load all experts (high VRAM)
Training complexity Simpler Router, load balancing, all-to-all
Performance at same compute Baseline Generally better (more capacity)
Fine-tuning Stable Can be unstable; expert collapse

13. Why Transformers Replaced RNNs / LSTMs

The replacement of RNNs by transformers was not merely incremental -- it was a paradigm shift. Here is a detailed comparison of the fundamental limitations of RNNs and how transformers address each one.

13.1 Parallelism

RNNs: Process tokens sequentially. For a sequence of length n, n sequential matrix multiplications are required. This cannot be parallelized across the time dimension, making training on long sequences extremely slow on GPUs/TPUs.

Transformers: Process all tokens in parallel within each layer. The attention computation is a single batched matrix multiplication. This achieves near-peak hardware utilization and enables training on datasets orders of magnitude larger.

Training time comparison (illustrative): LSTM on 1B tokens: ~weeks (sequential) Transformer on 1B: ~hours (parallelized) Transformer on 300B: ~days (distributed) The parallelism advantage is the single most important factor -- it made large-scale pretraining economically feasible.

13.2 Long-Range Dependencies

RNNs: Information from token 1 must pass through every intermediate hidden state to reach token 100. Despite LSTM gating, the effective path length is O(n), and distant information degrades.

Transformers: Any token can directly attend to any other token in a single attention operation. The path length between any two positions is O(1) within a layer. This fundamentally changes the model's ability to capture long-range dependencies.

13.3 Gradient Flow

RNNs: Backpropagation through time (BPTT) requires unrolling the network over the full sequence. Gradients must traverse every time step, making vanishing/exploding gradients a persistent challenge.

Transformers: Gradients flow through residual connections directly across layers. The architecture is effectively a deep feed-forward network (not recurrent), so standard backpropagation applies without time-unrolling.

13.4 Context Length

RNNs: Practical context is limited to a few hundred tokens. Beyond that, the hidden state becomes an information bottleneck, and training becomes unstable.

Transformers: Context is limited by the O(n2) attention cost and memory, but modern techniques (FlashAttention, ring attention, sparse attention) have extended practical context to 128K-1M+ tokens -- orders of magnitude beyond what RNNs could achieve.

13.5 Transfer Learning

RNNs: Transfer learning was limited. Pre-trained RNN embeddings existed (ELMo, ULMFiT), but the architecture did not scale well enough for massive pre-training to produce general-purpose capabilities.

Transformers: Scale beautifully with data and parameters. Pre-training a transformer on web-scale text produces general-purpose capabilities (reasoning, translation, coding) that transfer to virtually any text task through prompting or light fine-tuning.

13.6 Direct Comparison Table

Property RNN / LSTM Transformer
Processing Sequential (one token at a time) Parallel (all tokens at once)
Max path length between tokens O(n) O(1) per layer
Complexity per layer O(n · d2) O(n2 · d)
Sequential operations O(n) O(1)
Parallelizable No (across time) Yes (fully)
Long-range capture Poor (degrades with distance) Excellent (direct attention)
Practical context length ~200-500 tokens 128K - 1M+ tokens
Scalability Poor (compute-bound) Excellent (power-law scaling)
Transfer learning Limited (ELMo, ULMFiT) Foundation model paradigm
GPU utilization Low (sequential ops) High (batched matrix ops)
The Decisive Factor: While attention provides better long-range modeling, the parallelism of transformers was the decisive advantage. It enabled training on datasets 1000x larger than what RNNs could practically consume, and this data scale -- combined with parameter scale -- is what produced the emergent capabilities of modern LLMs. Without parallelism, the LLM era could not have happened, regardless of architectural elegance.

14. Comparison Table of Major Transformer Models

The following table provides a comprehensive comparison of the most influential transformer models, their architectures, training data, and key characteristics.

Model Architecture Params Training Data Key Innovation Year Open?
Transformer Encoder-Decoder ~65M WMT (~4.5M pairs) Attention-only architecture 2017 Yes
GPT-1 Decoder-only 117M ~7,000 books Generative pre-training + fine-tuning 2018 Yes
BERT Encoder-only 340M 3.3B words (Books + Wiki) Bidirectional MLM; 11 NLP SOTAs 2018 Yes
GPT-2 Decoder-only 1.5B 40GB WebText Zero-shot generation; scale 2019 Yes (staged)
T5 Encoder-Decoder 11B C4 (~750GB) Unified text-to-text framework 2019 Yes
GPT-3 Decoder-only 175B ~500B tokens (Common Crawl) In-context / few-shot learning 2020 No (API only)
Switch Transformer Encoder-Decoder MoE 1.6T C4 (~1T tokens) Trillion-param MoE; top-1 routing 2021 Yes
Chinchilla Decoder-only 70B 1.4T tokens Scaling laws: 20 tokens/param 2022 No
PaLM Decoder-only 540B 780B tokens Pathways; multilingual training 2022 No
Llama-2 Decoder-only 7-70B 2T tokens Open weights; RoPE; RMSNorm 2023 Yes
Mixtral 8x7B Decoder-only MoE 46.7B (12.9B active) Unknown Open-weight MoE; top-2 routing 2023 Yes
Llama-3 Decoder-only 8-405B 15T+ tokens Massive data scale; 128K context 2024 Yes
DeepSeek-V3 Decoder-only MoE 671B (37B active) 14.8T tokens MLA attention; aux-loss-free MoE 2024 Yes
GPT-4 Decoder-only MoE? ~1.8T (est.) Unknown (multimodal) RLHF; multimodal; reasoning 2023 No
Claude 3.5 Decoder-only (MoE?) Unknown Unknown Constitutional AI; long context 2024 No
Gemini 1.5 Decoder-only MoE Unknown Unknown (multimodal) 1M+ token context; native multimodal 2024 No

Key Architectural Trends Over Time

Where We Are Now (2026): The transformer architecture has been remarkably stable for 9 years. The core components -- self-attention, FFN, residual connections, normalization -- are unchanged from 2017. What has changed is scale (parameters, data, context), efficiency techniques (FlashAttention, KV cache compression), and sparsity (MoE). Alternative architectures (Mamba/SSMs, RWKV, hybrid models) show promise but have not yet displaced transformers at the frontier.

Summary & Key Takeaways

The transformer architecture, now nearly a decade old, remains the foundation of modern AI. Its key design principles are:

  1. Self-attention enables direct, O(1)-path interactions between any two tokens, replacing the sequential bottleneck of RNNs.
  2. Parallelism across the sequence dimension enables efficient GPU/TPU utilization and training on web-scale data.
  3. Multi-head attention allows the model to capture multiple types of relationships simultaneously.
  4. Positional encoding injects order information, with RoPE being the modern standard for its extrapolation properties.
  5. Residual connections and normalization (Pre-LN or RMSNorm) enable training of deep stacks (80-120+ layers).
  6. Scaling laws provide predictable performance improvements with more parameters, data, and compute -- with the Chinchilla ratio of ~20 tokens/parameter being the key calibration.
  7. Mixture of Experts decouples parameter count from compute, enabling trillion-parameter-class models with efficient inference.
  8. Decoder-only has won the architecture war for general-purpose LLMs, due to simplicity, scalability, and the power of next-token prediction as a universal training objective.

Understanding these mechanisms is essential for anyone working with LLMs -- whether fine-tuning, building retrieval pipelines, optimizing inference, or developing new architectures. The transformer is not just a model; it is the scaffolding upon which the entire modern AI ecosystem is built.

Further Reading