From Encoder Bottleneck to Multi-Head Attention: Principles and Implementation
This article explains why attention mechanisms were introduced to overcome the information bottleneck of early encoder-decoder architectures, walks through the scaled dot-product self-attention computation step by step, details the structure of multi-head attention with a NumPy reference implementation, and covers masking mechanisms and the computational complexity of attention in practice.
1. Why Attention Was Invented
Early sequence-to-sequence tasks, such as machine translation, typically used an encoder-decoder architecture. The encoder, built with a recurrent neural network, read source tokens one by one and compressed the entire sentence into a single fixed-length hidden state. The decoder then generated the target sentence word by word based on that state.
This design works for short sentences, but it creates an obvious information bottleneck for two reasons:
- A fixed-length vector has limited capacity. The longer the sentence, the more likely earlier information gets overwritten by later inputs.
- When decoding a particular output word, the truly relevant source information may sit anywhere in the sentence, and a single summary vector cannot extract it on demand.
The core idea of attention is that at every decoding step, the model looks back at the entire input sequence, assigns different weights to each position, and aggregates information accordingly. Instead of compressing everything into one vector, the model queries the relevant fragments when needed.
2. The Basic Self-Attention Computation
Self-attention relates tokens within the same sequence to one another. Each token’s input vector x is projected into three vectors via three learnable matrices:
- Query vector Q: what information the current token is looking for.
- Key vector K: what kind of matching features each token can offer.
- Value vector V: the actual content each token carries.
The computation proceeds in three steps:
- Similarity scoring: dot Q with all K vectors to produce an n × n score matrix.
- Scaling and normalization: divide the scores by sqrt(d_k). The variance of dot products grows with dimension; scaling prevents softmax from entering its saturation region and keeps gradients in a reasonable range. A row-wise softmax then converts scores into weights that sum to 1.
- Weighted sum: take the weighted average of the V vectors to obtain the new representation for each position.
Each output vector fuses information from other positions in the sequence, so it is called a context-dependent representation. The same word produces different output vectors in different sentences. This is the key difference between attention and static word embeddings.
3. The Structure of Multi-Head Attention
A single attention operation can only form one weighting pattern. Multi-head attention (MHA) runs h independent attention operations in parallel, each with its own projection matrices. The outputs of all heads are concatenated and passed through one final linear transformation.
The flow looks like this:
Input X (shape n × d_model)→ Linear projections to get Q, K, V (each n × d_model)→ Split along the feature dimension into h heads (each n × d_head, d_head = d_model / h)→ Each head computes scaled dot-product attention independently→ Concatenate head outputs (n × d_model)→ Output projection W_O
Two design points are worth noting. First, each head’s dimension is reduced to d_model / h, so the total computation is comparable to single-head attention. Second, different heads can learn different relationships in different subspaces. When analyzing trained models, it is common to observe some heads focusing on adjacent positions and others on syntactic or coreference relations. However, the exact division of labor is determined by the training data and cannot be specified in advance.
Below is a reference implementation that relies only on generic array operations. It illustrates how tensor shapes change at each step:
import numpy as npdef softmax(x, axis=-1):x = x - np.max(x, axis=axis, keepdims=True) # subtract the max to avoid exponent overflowe = np.exp(x)return e / np.sum(e, axis=axis, keepdims=True)def multi_head_attention(x, W_q, W_k, W_v, W_o, num_heads, causal=False):# x: (seq_len, d_model)seq_len, d_model = x.shapeassert d_model % num_heads == 0d_head = d_model // num_headsq = x @ W_q # (seq_len, d_model)k = x @ W_kv = x @ W_v# Split into multiple heads: (num_heads, seq_len, d_head)def split_heads(t):return t.reshape(seq_len, num_heads, d_head).transpose(1, 0, 2)q, k, v = split_heads(q), split_heads(k), split_heads(v)# Scaled dot product: (num_heads, seq_len, seq_len)scores = q @ k.transpose(0, 2, 1) / np.sqrt(d_head)if causal:# Upper triangle marks future positions; set to a very small value so# their weights approach zero after softmaxmask = np.triu(np.ones((seq_len, seq_len), dtype=bool), k=1)scores = np.where(mask, -1e9, scores)weights = softmax(scores, axis=-1)out = weights @ v # (num_heads, seq_len, d_head)# Merge heads: (seq_len, d_model)out = out.transpose(1, 0, 2).reshape(seq_len, d_model)return out @ W_o, weights
A few points to keep in mind when implementing this:
- The reshape and transpose operations that split and merge heads are the most error-prone parts. Print tensor shapes at every step while debugging.
- The causal mask ensures that position i can only attend to tokens at or before position i, which guarantees the correctness of autoregressive generation.
- Production systems typically use fused kernels or built-in framework operators. The implementation here prioritizes clarity over performance.
4. Masking Mechanisms
Masking is the most common source of bugs in attention engineering. There are two main types:
- Padding mask: during batch processing, short sentences must be padded to a uniform length. Real tokens should not attend to padding tokens, so the corresponding columns are set to a very small value before softmax.
- Causal mask: used in autoregressive generation to ensure the model cannot see future tokens during training. If the mask is missing, the training loss may drop abnormally while generation quality is poor. This phenomenon is usually called information leakage.
The two mask types can be combined. A practical verification method is to modify the last token of the input sequence and check whether the outputs at all preceding positions remain unchanged. If earlier outputs change, the mask has a problem.
5. Inference and Engineering Practice
5.1 Computational and Memory Complexity
The computation of standard self-attention scales quadratically with sequence length n, giving a time complexity of O(n² · d…
