Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Multi-Head Attention Computation

Recommended resources

Introduction

In our last lesson, we focused on the fundamental building block of the Transformer: scaled dot-product attention. We delved into the mathematics to understand not just how it works, but precisely why the scaling factor is essential for stable training. Now, we will build directly on that knowledge to construct a more powerful and expressive mechanism: multi-head attention.

Your goal for this lesson is to compute multi-head attention given the query, key, and value matrices. We will explore how the Transformer architecture runs multiple attention mechanisms in parallel, allowing it to capture a richer variety of relationships within the input data. Conceptually, this is like moving from a single, fixed spotlight of attention to a bank of independently steerable spotlights, each capable of focusing on a different feature or relationship. For your work in computer vision, you can think of this as analogous to how a CNN uses multiple filters to detect different kinds of features (edges, textures, colors) in parallel. In multi-head attention, each "head" learns to focus on different types of conceptual relationships within the sequence data.


The Architecture of Multi-Head Attention

The core idea of multi-head attention, as proposed in the "Attention Is All You Need" paper, is that performing a single, large attention calculation is less effective than performing several smaller attention calculations in parallel. Each parallel instance is called an "attention head".

Each head learns a different projection of the original query, key, and value vectors. This means each head operates in its own "representational subspace," allowing it to specialize in capturing a specific type of relationship. For example, in a sentence, one head might learn to track syntactic dependencies, while another might focus on semantic similarity.

The overall process can be summarized by the following formulas:

This diagram shows the formulas for both Scaled Dot-Product Attention (top) and Multi-Head Attention (bottom). The multi-head mechanism is composed of several individual attention heads whose results are concatenated and then linearly projected.

As you can see, the multi-head attention is defined as:

where each individual head is calculated as:

Let's break down this computation into four main steps.

  1. Linear Projections: Before anything else, for each of the attention heads, we create three unique, learnable weight matrices: , , and . These matrices project the full-dimensional input queries, keys, and values () into a lower-dimensional subspace specific to head .
  2. Parallel Attention Calculation: For each head , we apply the scaled dot-product attention function we learned in the previous lesson to its projected queries, keys, and values (). These calculations are completely independent of one another and can be performed in parallel.
  3. Concatenation: The output matrices from all heads are concatenated along their feature dimension to form a single, wide matrix.
  4. Final Projection: This large, concatenated matrix is multiplied by one final learnable weight matrix, , which projects it back to the model's original embedding dimension (). This final projection allows information from the different heads to be mixed and combined.

The following diagram provides an excellent high-level overview of this entire data flow for a model with 8 attention heads.

A visual summary of the multi-head self-attention mechanism. From the input embeddings (X), separate Q, K, and V matrices are generated for each of the 8 heads using unique weight matrices. Attention is calculated for each head, producing an output matrix Z_i. These are then concatenated and projected through a final weight matrix W^O to produce the final output Z.

A Walkthrough of the Dimensions

Understanding how the dimensions of the matrices change at each step is crucial. Your background in linear algebra and experience with tensor manipulations in ML frameworks will make this analysis straightforward. Let's trace the dimensions for a typical Transformer configuration:

  • Input sequence length: (e.g., number of words or image patches)
  • Model embedding dimension:
  • Number of attention heads:

This means the input embedding matrix (from which Q, K, and V are initially derived) has a shape of .

  1. Projections: Each head will work with a smaller dimension, .

    • The weight matrices for each head , , will have a shape of .
    • The projected queries, keys, and values for each head, e.g., , will have a shape of .
  2. Attention Calculation: Inside each head, the scaled dot-product attention is calculated: .

    • results in a attention score matrix.
    • Multiplying the attention weights by (shape ) gives the head's output, , which has a shape of .
  3. Concatenation: The outputs of all 8 heads, , are concatenated.

    • results in a matrix of shape .
  4. Final Projection: This concatenated matrix is multiplied by .

    • The final projection matrix must map the concatenated output back to the model's dimension, so it has a shape of .
    • The final output has a shape of .

Notice that the final output dimension, , is identical to the input dimension. This property makes the multi-head attention block a residual component that can be stacked multiple times without changing the dimensionality of the data flowing through the network.

To see this entire process animated with a clear, step-by-step example, please watch the following video. It does an exceptional job of visualizing the matrix operations and dimensionality changes.

Introduction to Multi head attention

This video from the Vizuara channel provides a detailed visual explanation of multi-head attention, building from the concepts of single-head attention. It is particularly strong in its visualization of the concatenation step.

Please watch the following segments to solidify your understanding of the computation: This section introduces the core concept of parallel, independent heads, each with its own set of learnable weight matrices. This part details the scaled dot-product attention calculation that occurs within each head, resulting in separate context vector matrices. Pay close attention to the concatenation step, which is visualized with a concrete numerical example, showing how the outputs of the heads are combined. Finally, watch this segment, which generalizes the calculation of the final output dimensionality based on the number of heads and the QKV space dimension.


From Theory to Efficient Implementation

While it's useful to think of the heads operating in parallel and then being concatenated, modern deep learning frameworks perform this entire calculation much more efficiently. Instead of creating separate sets of weight matrices and running separate attention calculations (which would be inefficient, especially on a GPU), the process is vectorized.

In practice, a single large weight matrix is used for each of Q, K, and V (e.g., of size ). The input is multiplied by this matrix once. The resulting large matrix is then reshaped and transposed to create the view of separate heads. After the vectorized attention calculation, the output is reshaped back to its concatenated form.

The following article provides a from-scratch NumPy implementation that demonstrates this efficient approach. While we won't go through every line of code, examining the tensor manipulation functions gives a clear picture of how this is achieved in practice.

The Math Behind Multi-Head Attention in Transformers

This article from Towards Data Science provides a Python implementation that reveals the efficient, vectorized approach to multi-head attention.

Please focus on the transpose_qkv and transpose_output methods. Read the explanations for these methods to understand how reshape and transpose operations are used to create the "multi-head" view of the Q, K, and V tensors without using a loop. Then, see how these functions are used within the main computation by reading the explanation of the forward pass method. This shows the full sequence: project, reshape for heads, apply attention, and reshape back.


Conclusion

In this lesson, we have extended the single scaled dot-product attention mechanism into the full multi-head attention block used in Transformers. By projecting the queries, keys, and values into different subspaces, the model can learn to capture a more diverse and robust set of relationships from the input data.

Here are the key takeaways:

  • Multi-head attention consists of multiple scaled dot-product attention "heads" that operate in parallel.
  • Each head has its own set of learnable projection matrices () that map the input Q, K, and V into a specific subspace.
  • The outputs of all heads are concatenated and passed through a final output projection matrix () to produce the final result.
  • The entire block is designed to be dimension-preserving, meaning the shape of the output tensor matches the shape of the input tensor, allowing it to be easily stacked.

So far, our attention mechanism can find relationships between tokens, but it has no inherent sense of their order. A sentence like "The dog chased the cat" would produce the same attention scores as "The cat chased the dog" if we only consider the token embeddings. In our next lesson, we will address this critical gap by exploring positional embeddings, the mechanism Transformers use to incorporate sequence order.