4. The Transformer Encoder
Architecture Layout and Self-Attention
The Transformer encoder is a stack of N identical layers. Each layer is composed of two primary sub-layers: a multi-head self-attention mechanism and a position-wise fully connected feed-forward network. The encoder's primary responsibility is to transform input embeddings into a richer, context-aware representation space.
By utilizing self-attention, each token in the input sequence attends to all other tokens, allowing the model to capture long-range dependencies regardless of the distance between tokens. This parallel processing capability is what distinguishes the architecture from sequential models like RNNs.
import torch import torch.nn as nn class SimpleEncoderLayer(nn.Module): def __init__(self, d_model, nhead): super().__init__() self.self_attn = nn.MultiheadAttention(d_model, nhead) self.norm = nn.LayerNorm(d_model) def forward(self, x): # Standard attention mechanism: Query, Key, Value are the same attn_output, _ = self.self_attn(x, x, x) return self.norm(x + attn_output)
Feed-Forward Neural Networks (FFN)
After the attention sub-layer, the output is passed through a position-wise feed-forward network. This network is identical for every position in the sequence and consists of two linear transformations with an activation function in between, typically ReLU or GeLU.
The first linear layer projects the embedding into a higher dimension (often 4x the d_model), while the second projects it back to the original d_model. This bottleneck architecture is crucial for expanding the representation space to learn more complex feature interactions before compressing it back for the next layer.
class FFN(nn.Module): def __init__(self, d_model, d_ff=2048): super().__init__() self.linear1 = nn.Linear(d_model, d_ff) self.activation = nn.GELU() self.linear2 = nn.Linear(d_ff, d_model) def forward(self, x): return self.linear2(self.activation(self.linear1(x)))
Pre-LN vs Post-LN Configurations
The placement of Layer Normalization is critical for training stability. The original Transformer used 'Post-LN', applying normalization after the residual connection (Add & Norm). While effective, it often requires a warm-up phase to prevent early training divergence due to large gradients.
'Pre-LN' places the normalization inside the residual block, before the attention/FFN layer. This allows for more stable gradient flow throughout the stack, often eliminating the need for a long learning rate warm-up and allowing for training of significantly deeper models.
class PreLNBlock(nn.Module): def __init__(self, d_model): super().__init__() self.norm = nn.LayerNorm(d_model) self.sublayer = nn.Linear(d_model, d_model) def forward(self, x): # Pre-LN: Norm is applied before the sub-layer computation return x + self.sublayer(self.norm(x))
Knowledge Check
Ready to test your understanding of 4. The Transformer Encoder?