Hello! Welcome to the third lesson in our module on Transformer Architectures.
In our last lesson, we dove deep into the core of the Transformer: the self-attention mechanism. You learned how it uses Query, Key, and Value vectors to compute attention scores, allowing the model to create context-aware word representations. We ended with the compact formula that makes this process efficient:
This formula, however, has two significant limitations. First, it forces the model to average different kinds of linguistic relationships (e.g., grammatical vs. semantic) into a single attention representation. Second, the mechanism itself is "order-agnostic"—it treats a sentence like a bag of words, with no inherent sense of sequence.
Today, we'll tackle both of these problems. You will learn about Multi-Head Attention, which allows the model to focus on different aspects of the input simultaneously, and Positional Encoding, which injects crucial information about word order into the model.
1. Beyond Single Attention: Multi-Head Attention
A single self-attention mechanism can be limiting. When processing the word "it" in the sentence "The cat chased the mouse because it was fast," one attention calculation must decide whether "it" refers to the "cat" (the subject) or the "mouse" (the object). But what if other relationships are also important?
Multi-head attention addresses this by running the self-attention process multiple times in parallel, allowing the model to capture a richer set of relationships.
The "Why": Limitations of Single-Head Attention
A single attention head has to learn a "blended" or "averaged" representation of all the different ways words can relate to each other. This is like asking a single developer to be an expert in backend logic, database optimization, and frontend UX all at once. While possible, it's more effective to have specialists focus on each area.
Multi-Head Attention Explained
This article provides a very clear, high-level motivation for why multi-head attention is necessary. Let's start there.
Please read the short section titled 'Why Single-Head Attention Is Limited'. This will set the stage for the solution that multi-head attention provides.
The "How": Parallel Attention Mechanisms
The core idea of multi-head attention is to have multiple "heads," where each head is a complete self-attention mechanism that learns to focus on a different aspect of the input.
You can think of it as assembling a team to analyze a sentence.
- Head 1 might be the "syntax expert," figuring out subject-verb-object relationships.
- Head 2 could be the "semantic expert," tracking which words have similar meanings.
- Head 3 might focus on long-range dependencies, connecting pronouns to nouns far away in the text.
Each head operates in its own "representation subspace," meaning it has its own learned weight matrices (). The model then combines the insights from all these specialists to form a much richer, more nuanced understanding.

The process works as follows:
- Projection: The input embedding matrix is projected into different sets of Queries, Keys, and Values using separate weight matrices for each ( for head ).
- Parallel Attention: Each head independently calculates its attention output, , using the same scaled dot-product attention formula we learned in the last lesson.
- Concatenation: The output vectors from all heads are concatenated into a single large vector.
- Final Projection: This concatenated vector is passed through one more linear layer (with weight matrix ) to produce the final output of the multi-head attention block.
Let's dive into a more formal description of this process.
Tutorial 6: Transformers and Multi-Head Attention
The UvA Deep Learning course notes provide a concise, technical explanation of multi-head attention, complete with the mathematical formulation and a PyTorch implementation.
Please read the section 'Multi-Head Attention'. Pay close attention to the mathematical formula and look at the MultiheadAttention class implementation. Note how the Q, K, and V projections are done efficiently in a single linear layer (self.qkv_proj) and then reshaped for the different heads.
From Theory to Code: Tensor Manipulations
As a software engineer, seeing how the tensors are manipulated can make this abstract process much more concrete. Let's walk through the shapes. Assume we have a batch of 2 sentences, each with 4 tokens, and an embedding dimension of 8. We want to use 2 attention heads.
batch_size = 2,seq_len = 4,embed_dim = 8,num_heads = 2- This means each head will work with a dimension of
head_dim = embed_dim / num_heads = 4.
The following resource provides a step-by-step walkthrough of these tensor transformations in PyTorch.
Multi-Head Attention Explained
The DigitalOcean article we looked at earlier has an excellent, practical walkthrough of the tensor manipulations inside multi-head attention.
Please read the section 'Multi-Head Attention in PyTorch (With Tensor Shapes)'. Follow the tensor shapes as they change from step 1 to step 5. This is key to understanding the implementation.
Here is a summary of that tensor flow:
- Input:
xhas shape(2, 4, 8).[batch, seq_len, embed_dim] - Projection: After projecting through the layers,
q,k, andvalso have shape(2, 4, 8). - Split Heads: The tensors are reshaped to
(2, 4, 2, 4).[batch, seq_len, num_heads, head_dim] - Transpose: They are transposed to
(2, 2, 4, 4).[batch, num_heads, seq_len, head_dim]. This gets all data for a single head contiguous for the parallel matrix multiplies. - Attention: The attention calculation
softmax(q @ k.T) @ vis done. The outputvalueshas shape(2, 2, 4, 4).[batch, num_heads, seq_len, head_dim] - Concatenate: The
transposeandreshapeoperations are reversed, bringing the tensor back to(2, 4, 8).[batch, seq_len, embed_dim] - Final Projection: This is passed through the final linear layer, resulting in an output of shape
(2, 4, 8).
This sequence of reshape and transpose operations is a highly efficient way to perform the "parallel" computations on a GPU.
Test your understanding!
Suppose you have an input with embed_dim = 512 and you configure your multi-head attention layer with num_heads = 8. What will be the dimension of the Q, K, and V vectors within each attention head?
Show answer
The dimension for each head will be embed_dim / num_heads = 512 / 8 = 64. Each of the 8 heads will perform self-attention on vectors of dimension 64.
2. Solving for Order: Positional Encoding
The attention mechanism we've discussed, whether single- or multi-headed, has a fundamental property: it is permutation-invariant. This means if you shuffle the words in the input sentence, the attention output will be identical (just shuffled in the same way). The model has no built-in sense of word order.
For language, order is critical. "The cat chased the mouse" and "The mouse chased the cat" have the same words but entirely different meanings. We need a way to tell the model where each word is in the sequence. This is the job of positional encoding.

The solution is to add a vector representing the position to each input embedding before it enters the first encoder block.
The "How": Sine and Cosine Functions
We could learn an embedding for each position, but this approach doesn't generalize well to sentences longer than those seen during training. Instead, the original Transformer paper introduced a clever scheme using sine and cosine functions of different frequencies:
Where:
posis the position of the word in the sequence (0, 1, 2, ...).iis the index of the dimension within the embedding vector.d_modelis the embedding dimension.
You don't need to memorize this formula, but the intuition is important. By using periodic sin and cos functions with different wavelengths for each dimension, it creates a unique positional signature for each token. A key property is that the encoding for a position pos+k can be represented as a linear function of the encoding for pos. This makes it easy for the model to learn to attend to relative positions.
Let's read a more detailed explanation and see how it's implemented.
Tutorial 6: Transformers and Multi-Head Attention
The UvA notebook provides another excellent section on positional encoding, complete with the formula, visualizations, and a PyTorch implementation.
Please read the section 'Positional encoding'. Focus on the intuition behind the formula and examine the visualizations. In the PositionalEncoding code, notice how the encoding matrix pe is created and then simply added to the input x. Also, note the use of register_buffer, a common PyTorch pattern for fixed tensors within a module.
The key takeaway is that this is a fixed, non-learned component. It's a clever feature engineering step that injects the necessary positional information directly into the input vectors, which the attention mechanism can then utilize.
Conclusion
In this lesson, you've learned about two critical components that augment the self-attention mechanism to make it truly powerful.
Key Takeaways:
- Multi-Head Attention addresses the limitation of single-head attention by running multiple attention mechanisms in parallel. Each head learns to focus on different types of relationships from different representation subspaces.
- The outputs of the heads are concatenated and passed through a final linear layer to combine their insights into a single, rich representation.
- Positional Encoding solves the problem of order-invariance in self-attention. It uses a fixed set of
sinandcosfunctions to generate unique positional vectors that are added to the input embeddings, injecting information about token sequence.
We now have all the pieces needed to construct a full Transformer block. We have a way to understand context (Multi-Head Attention) and a way to understand order (Positional Encoding).
Next up:
In our next lesson, we will assemble these components. You will see how Multi-Head Attention and Positional Encodings are combined with other layers—specifically, Feed-Forward Networks and Residual Connections with Layer Normalization—to build a complete Transformer encoder block.