Skip to main content

Welcome to a Grasp lesson

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

Lesson 13

Multi-Head Attention: Computation, Concatenation, and Projection

Recommended resources

Introduction

In our previous lesson, we established the crucial motivation for multi-head attention. We saw that relying on a single attention mechanism creates a representational bottleneck, forcing the model to average diverse linguistic relationships into a single, compromised view. The solution, we discovered, is to run multiple attention "heads" in parallel, allowing each to specialize in detecting different patterns.

Having understood the "why," we now turn to the "how." This lesson will dissect the precise mechanics of the multi-head attention layer. We will trace the flow of data step-by-step, detailing how the input is projected into multiple subspaces, how attention is computed in parallel for each head, and how the results are concatenated and projected to form the final, enriched output. This is a cornerstone of the Transformer architecture, and mastering its mechanism is essential to understanding how models like GPT work.


The Multi-Head Attention Pipeline

At its core, multi-head attention consists of four main steps, which we will explore in detail:

  1. Initial Linear Projections: Create distinct Query, Key, and Value sets for each head.
  2. Parallel Attention Computation: Apply scaled dot-product attention independently to each head.
  3. Concatenation: Combine the outputs of all heads.
  4. Final Linear Projection: Mix the combined outputs to produce the final result.

The entire process is visualized in the diagram below. We start with the input token embeddings (represented as Q, K, and V for simplicity, as they are all derived from the same source in self-attention) and end with the final Multi-Head Attention Output.

This diagram illustrates the complete multi-head attention mechanism. The input is split and projected for multiple heads, each undergoing a self-attention calculation. The results are then concatenated and passed through a final linear layer.

Let's break down each stage.

1. Initial Linear Projections

In the last lesson, we mentioned that each head operates in a separate "representation subspace." This is achieved through linear projections.

Let's say our input is a matrix of token embeddings, with dimensions , where is the embedding dimension (e.g., 512). If we have attention heads, we don't just use one set of weight matrices . Instead, we create independent sets of them:

  • , , for each head .

A crucial architectural detail is that the output dimension of these projections is smaller than . Typically, the dimension for each head's keys, queries, and values is set to . For example, with a model dimension of 512 and 8 heads, each head would work with vectors of dimension 64.

For each head , we compute its query, key, and value matrices:


Because each matrix is initialized randomly and updated independently during training, each head learns a unique projection, effectively focusing on a different subspace of the original embedding. This is the foundation of the specialization we discussed previously.

2. Parallel Attention Computation

With the projected for each head, we can now perform scaled dot-product attention in parallel. The calculation for each head is exactly what you learned in the previous module:

Since these computations are independent of one another, they are perfectly suited for parallelization on modern hardware like GPUs. The output of each head, , is a matrix of size .

3. Concatenation

After each of the heads has produced its output matrix, we need to combine them back into a single matrix. This is done by simple concatenation along the feature dimension:

The resulting matrix has dimensions . Since we chose , the dimension of this concatenated matrix becomes . We have successfully returned to the original embedding dimension of our model, but now the representation for each token is a composite of information from all the specialized heads.

4. Final Linear Projection

The concatenated output contains rich information, but the outputs from each head are still segregated in their own "lanes." To allow these specialized representations to be integrated and mixed, we apply one final linear projection using another learned weight matrix, :

This final layer allows the model to learn how to best combine the outputs of the different heads. It can choose to weigh some heads' outputs more heavily than others, creating a powerful, unified representation. The output of this operation is the final output of the multi-head attention sub-layer, and it has the dimensions , ready to be passed to the next layer in the Transformer block.


A Guided Walkthrough of the Mechanism

To solidify your understanding, we will now walk through this process using a combination of video explanations, formal definitions, and code implementations.

First, let's watch a clear, step-by-step visual explanation of the entire pipeline we just discussed.

Attention is all you need (Transformer) - Model explanation (including math), Inference and Training

This segment from Umar Jamil's "Attention is all you need" video provides an excellent visual walkthrough of the multi-head attention mechanism, detailing the projections, splitting into heads, parallel attention, concatenation, and the final output projection.

Please watch from this section. Pay close attention to how the dimensions of the matrices change at each step, particularly the splitting of the d_model dimension across the heads and its reassembly via concatenation.

Next, let's ground this visual intuition in a more formal mathematical description and a concrete PyTorch implementation. The following tutorial provides a concise and comprehensive look at the subject.

Tutorial 6: Transformers and Multi-Head Attention

This tutorial from the UvA Deep Learning course notebooks presents the mathematical formulation of multi-head attention and provides a clean PyTorch implementation. It's a perfect resource for bridging theory and practice.

Please read the section on Multi-Head Attention. Focus on understanding the mathematical formula that defines the MultiHead function and then carefully study the MultiheadAttention nn.Module class. Notice how the qkv_proj linear layer efficiently creates the Q, K, and V projections for all heads at once, and how the reshape and permute operations are used to prepare the tensors for parallel computation.

The approach of using a single large qkv_proj matrix and then reshaping is a common and efficient implementation trick. It's computationally equivalent to having separate matrices for each head but can be faster in practice.

Finally, to see this from a "from-scratch" perspective that deeply aligns with your goals, let's watch how Andrej Karpathy implements multi-head attention.

Let's build GPT: from scratch, in code, spelled out.

In this segment from "Let's build GPT," Andrej Karpathy implements multi-head attention by literally running multiple single-head modules in parallel and concatenating their results. This provides a very intuitive, code-first understanding.

Watch the clip from this point. He explains that multi-head attention is "just applying multiple attentions in parallel and concatenating their results." Observe how his MultiHeadAttention class uses a nn.ModuleList to hold several Head instances and then uses torch.cat to combine their outputs. This directly mirrors the conceptual model we've been building.


Conclusion

In this lesson, we have demystified the inner workings of multi-head attention. We moved from the high-level motivation of "why" to the detailed mechanics of "how." By breaking down the process, we can see it's a sequence of logical, well-motivated steps rather than a single monolithic black box.

Here are the key takeaways on the mechanics of multi-head attention:

  • Projection into Subspaces: The process begins by projecting the input embeddings into lower-dimensional query, key, and value representations for each of the heads using independent weight matrices ().
  • Parallel Computation: Scaled dot-product attention is performed independently and in parallel for each head, allowing for specialization.
  • Concatenation and Projection: The outputs of all heads are concatenated back into a single, full-dimension tensor. A final linear projection () is then applied to integrate the information from all the specialized heads into a unified output.
  • Dimensionality: The dimensions are carefully managed throughout. By setting , the total computational cost of multi-head attention is roughly equivalent to that of a single attention head operating on the full dimension.

You have now mastered the first major component of a Transformer block. However, the multi-head attention sub-layer does not work in isolation. In the next lesson, we will explore the second key component: the Position-wise Feed-Forward Network, and see how it works in tandem with attention to process the information for each token.