Transformers Architecture Explained in Depth
1. Historical Context and Motivation for Transformers
1.1 Historical Context and Motivation for Transformers
Prior to the introduction of transformers in 2017, sequence modeling and transduction tasks were dominated by recurrent neural networks (RNNs) and convolutional neural networks (CNNs). While effective, these architectures suffered from fundamental limitations in handling long-range dependencies and parallelization. RNNs, including Long Short-Term Memory (LSTM) and Gated Recurrent Unit (GRU) variants, process sequences sequentially, making them inherently slow to train due to their temporal dependency. The vanishing gradient problem further restricted their ability to capture relationships between distant tokens in long sequences.
CNNs, when applied to sequence tasks, could process inputs in parallel through dilated convolutions. However, they required increasingly large receptive fields to model long-range dependencies, leading to computational inefficiency. The number of operations needed to relate two positions grew linearly or logarithmically with distance, making it difficult to learn direct relationships between arbitrary positions in the input and output sequences.
The Attention Mechanism Breakthrough
The key innovation that enabled transformers was the attention mechanism, first introduced for neural machine translation in 2014. The original formulation computed a weighted sum of encoder hidden states at each decoder step, allowing the model to dynamically focus on relevant parts of the input sequence. This proved more effective than fixed-length vector representations used in earlier encoder-decoder architectures.
The 2017 paper Attention Is All You Need by Vaswani et al. took this concept further by eliminating recurrence entirely. The transformer architecture replaced sequential processing with self-attention mechanisms that could directly model relationships between all positions in the input and output sequences with a constant number of operations. This was achieved through three key mathematical operations:
Where Q (queries), K (keys), and V (values) are learned linear transformations of the input embeddings, and dk is the dimension of the keys. The scaling factor 1/√dk prevents dot products from growing too large in magnitude, which would push the softmax into regions with extremely small gradients.
Parallelization and Computational Efficiency
The transformer's architecture enabled unprecedented parallelization during training. Unlike RNNs that require sequential computation of hidden states, self-attention layers can process all positions simultaneously. This property, combined with modern GPU/TPU architectures, reduced training times from weeks to days for comparable model sizes. The computational complexity of self-attention is:
Where n is the sequence length and d is the representation dimension. While quadratic in sequence length, this proved more efficient in practice than the O(n) sequential operations of RNNs due to massive parallelization and optimized matrix multiplication routines.
Positional Encoding and Sequence Modeling
Since transformers lack inherent notion of sequence order, they incorporate positional encodings to inject information about token positions. The original paper used sinusoidal functions of varying frequencies:
Where pos is the position and i is the dimension. This choice allows the model to learn to attend by relative positions, as any fixed offset k, PEpos+k can be represented as a linear function of PEpos.
Impact on Modern AI Systems
The transformer architecture's scalability led to rapid adoption across natural language processing, with models like BERT, GPT, and T5 achieving state-of-the-art results on numerous benchmarks. Its success subsequently extended to computer vision (Vision Transformers), speech processing, and multimodal systems. The attention mechanism's ability to model arbitrary dependencies between input and output positions, regardless of distance, fundamentally changed the approach to sequence modeling across AI domains.

1.2 Key Innovations: Self-Attention and Positional Encoding
Self-Attention Mechanism
The self-attention mechanism is the cornerstone of the Transformer architecture, enabling the model to weigh the importance of different input tokens dynamically. Unlike traditional recurrent or convolutional approaches, self-attention computes pairwise interactions between all tokens in a sequence, capturing long-range dependencies without sequential processing.
Given an input sequence of embeddings X ∈ ℝn×d, where n is the sequence length and d is the embedding dimension, self-attention projects X into three matrices:
where WQ, WK, WV ∈ ℝd×dk are learnable weight matrices. The attention scores are computed as scaled dot-products between queries Q and keys K:
The scaling factor √dk prevents gradient vanishing issues caused by large dot-product magnitudes. Multi-head attention extends this by running h parallel attention heads, concatenating their outputs:
where each head performs independent attention computations with different learned projections.
Positional Encoding
Since self-attention is permutation-invariant, positional encodings are added to input embeddings to inject information about token order. The original Transformer uses sinusoidal positional encodings defined as:
where pos is the position and i is the dimension index. This encoding scheme allows the model to attend to relative positions through linear transformations, as shown by the trigonometric identity:
where Tk is a linear transformation matrix dependent on k. Recent variants like learned positional embeddings or relative position representations (e.g., Shaw et al., 2018) have shown improved performance in certain tasks.
Practical Implications
The combination of self-attention and positional encoding enables three key advantages:
- Parallelization: Unlike RNNs, all attention scores can be computed simultaneously.
- Long-range dependency capture: Direct token-to-token interactions mitigate vanishing gradients in long sequences.
- Interpretability: Attention weights often reveal linguistically meaningful patterns (e.g., coreference resolution).
In practice, modern implementations optimize memory usage through techniques like memory-efficient attention (Rabe and Staats, 2021) or flash attention (Dao et al., 2022) to handle sequences exceeding 32K tokens.

Comparison with RNNs and CNNs: Why Transformers?
Recurrent Neural Networks (RNNs) and Their Limitations
RNNs process sequential data through recurrent connections, maintaining a hidden state that theoretically captures information from all previous time steps. The core recurrence relation is:
where ht is the hidden state at time t, xt is the input, and Wh, Wx are learnable weights. While elegant in theory, RNNs suffer from two critical weaknesses:
- Vanishing/exploding gradients: The repeated multiplication of Wh makes learning long-range dependencies practically impossible without careful initialization or architectural modifications.
- Sequential computation: The inherently sequential nature prevents parallelization during training, making RNNs prohibitively slow for long sequences.
Convolutional Neural Networks (CNNs) for Sequences
CNNs apply learned filters across temporal or spatial dimensions, with the 1D temporal convolution operation defined as:
where wk are the filter weights and K is the kernel size. While CNNs offer:
- Parallel computation: Unlike RNNs, convolutions can be computed simultaneously across all positions.
- Local feature extraction: Effective for capturing local patterns through hierarchical layers.
They still struggle with:
- Fixed receptive fields: Capturing long-range dependencies requires either very large kernels or many stacked layers, increasing computational cost.
- Positional invariance: Standard convolutions are translation-equivariant, which may not be ideal for tasks where absolute position matters.
The Transformer Advantage
Transformers address these limitations through two key innovations:
1. Self-Attention Mechanism
The scaled dot-product attention computes pairwise relationships between all positions in constant time:
where Q, K, V are learned query, key, and value matrices. This provides:
- Global receptive field: Any two positions can directly interact, regardless of distance.
- Dynamic feature weighting: Attention weights adaptively highlight relevant relationships.
2. Parallel Sequence Processing
Unlike RNNs, Transformers process all positions simultaneously through:
- Positional encodings: Injected sinusoidal or learned vectors preserve sequence order:
- Layer normalization and residual connections: Enable stable training of deep architectures.
Empirical Performance Comparison
On the WMT 2014 English-to-German translation task:
| Model | BLEU | Training Time |
|---|---|---|
| LSTM (RNN) | 24.6 | 5.8 days |
| CNN | 26.4 | 3.5 days |
| Transformer (Base) | 27.3 | 1.2 days |
The Transformer achieves superior performance with significantly faster training, demonstrating the architectural advantages in both quality and computational efficiency.

2. Self-Attention Mechanism: Scaled Dot-Product Attention
Self-Attention Mechanism: Scaled Dot-Product Attention
The scaled dot-product attention mechanism forms the core of transformer architectures, enabling dynamic weighting of input tokens based on their contextual relationships. Given an input sequence of embeddings X ∈ ℝn×d, where n is sequence length and d is embedding dimension, the mechanism first projects X into three learned matrices:
Here WQ, WK ∈ ℝd×dk and WV ∈ ℝd×dv are projection matrices for queries, keys, and values respectively. The attention scores are computed as scaled dot-products between queries and keys:
Mathematical Derivation
The scaling factor 1/√dk is critical for stable gradient propagation. For high-dimensional keys, the dot product QKT grows large in magnitude, pushing softmax outputs into saturated regions. The scaling preserves gradient flow:
where qi and kj are random vectors with unit variance components. This maintains stable gradients regardless of dk.
Parallel Computation
The mechanism computes attention scores for all positions simultaneously via batched matrix multiplication. For a sequence of length n, the attention pattern forms an n×n matrix where each row sums to 1 after softmax normalization. This allows modeling arbitrary token-to-token dependencies.
Multi-Head Extension
Multi-head attention splits the projections into h parallel heads:
Each head applies independent attention in reduced dimension spaces (typically dk = dv = d/h), enabling specialized attention patterns across different representation subspaces.
Computational Complexity
The dominant term is the QKT multiplication with O(n2d) complexity. While effective for moderate sequence lengths, this quadratic scaling motivates research into sparse attention variants for long sequences.

Multi-Head Attention: Parallel Processing of Attention Heads
The multi-head attention mechanism extends single-head attention by computing multiple attention operations in parallel, allowing the model to jointly attend to information from different representation subspaces. Each attention head operates independently with its own set of learnable parameters, enabling the model to capture diverse relationships in the input sequence.
Mathematical Formulation
Given an input sequence X of dimension n × dmodel, multi-head attention first projects X into h different sets of queries, keys, and values using learned linear transformations:
where WiQ ∈ ℝdmodel × dk, WiK ∈ ℝdmodel × dk, and WiV ∈ ℝdmodel × dv are the projection matrices for head i, with dk = dv = dmodel/h.
Parallel Attention Computation
Each head computes scaled dot-product attention independently:
The outputs of all heads are concatenated and linearly transformed to produce the final multi-head attention output:
where WO ∈ ℝhdv × dmodel is the output projection matrix.
Advantages of Multi-Head Attention
- Diverse Representation Learning: Different heads can learn to attend to different aspects of the input (e.g., syntactic vs. semantic relationships).
- Improved Gradient Flow: Parallel computation allows for more efficient backpropagation through multiple attention pathways.
- Scalability: The computational complexity remains O(n2d) while providing h times more representational capacity.
Implementation Considerations
In practice, multi-head attention is implemented efficiently using batch matrix operations. For h heads, the projections can be computed as a single large matrix multiplication:
The resulting tensor is then split into h heads along the feature dimension. This approach maximizes GPU utilization by avoiding sequential computation of individual heads.
Empirical Observations
Research has shown that different heads often specialize in distinct patterns:
- Some heads attend to local syntactic patterns (e.g., verb-object relationships)
- Others capture long-range dependencies or positional relationships
- A subset of heads may act as "noise" filters or redundancy handlers
The number of heads h is typically chosen such that dk = dv = dmodel/h remains large enough to maintain meaningful representations (common values are 8-16 heads for dmodel=512).

Position-wise Feed-Forward Networks
Each position in the Transformer's self-attention output undergoes an identical transformation through a position-wise feed-forward network (FFN). Despite its name, the FFN is applied independently and identically to each position, making it position-wise rather than sequential. This design allows parallel processing across all positions while introducing non-linearity and increased model capacity.
Mathematical Formulation
The FFN consists of two linear transformations with a ReLU activation in between:
Where:
- x ∈ ℝdmodel is the input vector (dmodel = 512 in the original Transformer)
- W1 ∈ ℝdmodel × dff and W2 ∈ ℝdff × dmodel are learnable weights
- dff is the inner layer dimensionality (typically 2048 or 4096)
- The ReLU activation (max(0,·)) introduces non-linearity
Architectural Properties
The FFN serves several critical functions:
- Dimensionality expansion: The hidden layer (dff) is typically 4× wider than dmodel, enabling richer representations
- Non-linear transformation: The ReLU activation allows modeling complex interactions that the attention mechanism alone cannot capture
- Position independence: Unlike RNNs, the same weights are applied to all positions, making the operation fully parallelizable
Variants and Improvements
Several modifications to the original FFN have been proposed:
Gated Linear Units (GLU)
Used in models like PaLM and GPT-3, replacing ReLU with a gating mechanism:
where σ is the sigmoid function and ⊗ denotes element-wise multiplication.
SwiGLU Activation
Combining Swish activation with GLU, as used in LLaMA and GPT-4:
Computational Considerations
The FFN typically accounts for about 2/3 of the Transformer's total parameters and FLOPs. For a model with dmodel = 1024 and dff = 4096:
Modern implementations often fuse the two linear transformations into a single optimized kernel for efficiency.
Layer Normalization and Residual Connections
Layer Normalization in Transformers
Layer normalization (LayerNorm) is a critical component in Transformer architectures, stabilizing training by normalizing activations across the feature dimension. Unlike batch normalization, which operates over the batch dimension, LayerNorm computes statistics independently for each sample, making it suitable for variable-length sequences common in NLP tasks. Given an input vector x of dimension d, LayerNorm applies:
where μ and σ² are the mean and variance of x, γ and β are learnable scale and shift parameters, and ϵ is a small constant for numerical stability. This operation ensures that gradients remain well-conditioned during backpropagation, mitigating the vanishing gradient problem in deep networks.
Residual Connections
Residual connections, introduced in ResNet, are employed in Transformers to enable training of very deep networks. They allow gradients to flow directly through the network via identity mappings, preserving information across layers. For a sublayer F (e.g., attention or feed-forward), the output is computed as:
This additive skip connection ensures that even if F(x) becomes small during initialization, the network can still propagate meaningful signals. Combined with LayerNorm, the standard Transformer layer implements this as:
Pre-LN vs. Post-LN Architectures
Recent variants of Transformers debate the placement of LayerNorm. In the original Post-LN architecture, LayerNorm is applied after the residual connection:
In Pre-LN architectures, LayerNorm is applied before the sublayer:
Pre-LN tends to enable more stable training for very deep networks, as gradients flow more smoothly through the normalization layers. Empirical studies show Pre-LN achieves faster convergence but may sacrifice peak performance in some tasks.
Gradient Flow Analysis
The effectiveness of residual connections can be analyzed through gradient propagation. Let L be the loss function. The gradient of L with respect to the input x of a residual block is:
This decomposition shows that the identity term I ensures gradients can propagate directly, even when the Jacobian ∂F(x)/∂x becomes small. LayerNorm further stabilizes this by bounding the magnitude of activations entering F.
Practical Implications
In modern implementations like GPT-3 and BERT, LayerNorm and residual connections are applied per transformer block. Key design choices include:
- Initialization: Scale parameters γ in LayerNorm are initialized to 1, while β is initialized to 0.
- Precision: LayerNorm is sensitive to numerical precision, often requiring float32 in practice.
- Parallelism: Residual connections enable model parallelism by allowing independent computation of F(x) across devices.

3. Encoder-Decoder Structure: Roles and Responsibilities
Encoder-Decoder Structure: Roles and Responsibilities
The encoder-decoder architecture forms the backbone of the original Transformer model, as introduced in Attention Is All You Need (Vaswani et al., 2017). This structure is particularly effective for sequence-to-sequence (seq2seq) tasks such as machine translation, text summarization, and dialogue generation, where an input sequence is transformed into an output sequence of potentially different length.
Encoder: Feature Extraction and Contextual Representation
The encoder processes the input sequence $$X = (x_1, x_2, ..., x_n)$$ through a stack of N identical layers (typically N = 6 in the original paper). Each layer consists of two sub-layers:
- Multi-Head Self-Attention: Computes attention scores between all pairs of tokens in the input sequence, enabling the model to weigh the importance of each token relative to others. The output is a weighted sum of value vectors, where weights are determined by the compatibility of queries and keys.
- Position-wise Feed-Forward Network: A two-layer MLP with ReLU activation, applied independently to each token position. This introduces non-linearity and allows the model to transform features in a position-specific manner.
Both sub-layers employ residual connections followed by layer normalization, formalized as:
The encoder's output is a sequence of continuous representations $$Z = (z_1, z_2, ..., z_n)$$, where each $$z_i$$ encodes contextual information from the entire input sequence.
Decoder: Autoregressive Generation with Masked Attention
The decoder generates the output sequence $$Y = (y_1, y_2, ..., y_m)$$ one token at a time in an autoregressive manner. Each decoder layer includes three sub-layers:
- Masked Multi-Head Self-Attention: Similar to the encoder's self-attention but with a masking mechanism to prevent positions from attending to subsequent tokens, ensuring the model only uses information from previously generated outputs during training.
- Multi-Head Cross-Attention: Queries from the decoder attend to keys and values from the encoder's output $$Z$$, aligning decoder states with relevant input context.
- Position-wise Feed-Forward Network: Identical in structure to the encoder's FFN, enabling non-linear feature transformation.
Like the encoder, residual connections and layer normalization are applied after each sub-layer. The decoder's autoregressive nature is mathematically enforced by masking future positions in the attention computation:
where $$M$$ is a lower-triangular matrix with $$M_{ij} = -\infty$$ for $$i < j$$ to enforce causality.
Interplay Between Encoder and Decoder
The encoder's contextual representations $$Z$$ serve as the memory for the decoder. During cross-attention, the decoder dynamically retrieves information from $$Z$$ at each generation step, allowing the model to focus on different parts of the input sequence as needed. This mechanism is particularly powerful for tasks requiring alignment between input and output sequences, such as translating a sentence while preserving semantic meaning across languages.
In practice, the encoder-decoder structure is trained end-to-end using teacher forcing, where the decoder receives the ground truth output sequence (shifted right) as input during training, and maximizes the likelihood of the next token at each step:

Encoder Stack: Multi-Layer Processing
The encoder stack in the Transformer architecture consists of multiple identical layers, each performing a series of operations to transform input representations into higher-level abstractions. Each encoder layer contains two primary sub-layers: a multi-head self-attention mechanism and a position-wise feed-forward neural network, both followed by residual connections and layer normalization.
Layer Normalization and Residual Connections
Before processing by either sub-layer, the input undergoes layer normalization, which stabilizes training by normalizing activations across the feature dimension. The normalized input is then passed through the sub-layer, and the result is added to the original input via a residual connection:
This residual connection ensures gradient flow during backpropagation, mitigating the vanishing gradient problem in deep networks. Layer normalization operates independently on each sequence element, computing statistics over the feature dimension:
where μ and σ² are the mean and variance of features, γ and β are learnable parameters, and ϵ is a small constant for numerical stability.
Multi-Head Self-Attention Mechanism
Each encoder layer employs multi-head self-attention to capture diverse relationships between input tokens. The input is projected into h separate sets of queries, keys, and values, allowing the model to attend to information from different representation subspaces. For each head i:
The outputs of all heads are concatenated and linearly projected:
where WiQ, WiK, WiV are learned projection matrices for head i, and WO is the output projection matrix.
Position-wise Feed-Forward Networks
Following self-attention, each encoder layer applies a position-wise feed-forward network (FFN) to every token independently. The FFN consists of two linear transformations with a ReLU activation in between:
Despite operating identically on each position, the FFN introduces non-linearity and enables interactions between different dimensions of the representation space. The hidden layer typically has a larger dimensionality (e.g., 2048) than the input/output (e.g., 512), acting as a bottleneck that encourages information compression.
Stacking Encoder Layers
Multiple encoder layers are stacked to form a deep representation hierarchy. Lower layers capture local patterns and syntactic relationships, while higher layers model more abstract semantic features. The number of layers varies across architectures:
- Base Transformer: 6 encoder layers
- BERT-base: 12 encoder layers
- BERT-large: 24 encoder layers
- GPT-3: Up to 96 encoder-like layers (in decoder-only configuration)
As information propagates through the stack, gradient flow is maintained through residual connections, while layer normalization prevents exploding activations. The combination of self-attention and FFNs allows each layer to refine representations by incorporating both global context and localized feature transformations.

Decoder Stack: Masked Attention and Output Generation
Masked Multi-Head Attention Mechanism
The decoder's first sub-layer employs masked multi-head attention to ensure autoregressive properties during sequence generation. Unlike the encoder, which processes all tokens simultaneously, the decoder restricts attention to preceding tokens only. This is achieved by applying a causal mask to the attention scores before the softmax operation:
where i and j represent target and source positions, respectively. The masking ensures that during training, predictions for position i depend only on known outputs at positions less than i.
Mathematical Derivation of Masked Attention
Given input embeddings X ∈ ℝn×d, the masked attention computation proceeds as:
- Project X into queries, keys, and values:
$$ Q = XW_Q, \quad K = XW_K, \quad V = XW_V $$
- Compute scaled dot-product attention scores:
$$ A = \frac{QK^T}{\sqrt{d_k}} $$
- Apply causal mask element-wise:
$$ A_{masked} = A + M \quad \text{where } M_{ij} = \text{Mask}(i,j) $$
- Compute softmax and weighted sum:
$$ \text{Attention}(Q,K,V) = \text{softmax}(A_{masked})V $$
Encoder-Decoder Attention Layer
The second sub-layer performs cross-attention between decoder queries and encoder memory. The keys and values are derived from the encoder's output, while queries come from the previous decoder layer:
This allows each decoding step to dynamically attend to the most relevant parts of the input sequence, a critical feature for tasks like machine translation where alignment between source and target is non-monotonic.
Position-wise Feed-Forward Networks
Each decoder layer contains a position-wise FFN identical to the encoder's:
The FFN provides additional nonlinear transformations while maintaining positional independence, allowing each token to be processed separately after attention aggregation.
Output Generation Process
During inference, the decoder operates autoregressively:
- Step 1: Initialize with start token 〈sos〉
- Step 2: For each position i:
- Compute decoder states up to position i
- Generate logits via final linear projection:
$$ z_i = h_iW_{vocab} $$
- Sample next token from distribution pi = softmax(zi)
- Termination: Repeat until end token 〈eos〉 is generated
Teacher Forcing During Training
When ground truth targets are available, training uses teacher forcing - feeding correct previous tokens regardless of model predictions. This is implemented by:
- Right-shifting the target sequence
- Using the shifted sequence as decoder input
- Computing loss against original targets
The parallel processing capability is maintained through masking, while still enforcing the autoregressive constraint.
Beam Search Decoding
For improved generation quality, inference often employs beam search:
where k maintains the top-B partial sequences at each step. Practical implementations include length normalization to prevent bias toward shorter outputs:
with α typically between 0.6 and 1.0.