GNGiseldo Neo and Alana NeoBooks
Language Models with Python7 / 16

Multi-Head Attention and Linear Projections

An extension of the attention mechanism to multiple heads, allowing the model to focus on different parts of the sequence simultaneously.

7.1 Introduction

In the previous chapter, we explored the self-attention mechanism, which allows the model to weigh the importance of different words in a sequence. However, a single attention operation limits the model’s ability to focus on different types of relationships at the same time (for example, grammatical agreement versus semantic context).

Multi-Head Attention (MHA) solves this limitation by running multiple self-attention mechanisms in parallel. Each “head” learns to focus on a different representation subspace, allowing the model to capture complex and varied nuances of language at the same time.

7.2 The Concept of Linear Projections

Before splitting the processing into multiple heads, the input vectors (embeddings) go through linear projections.

Mathematically, a linear projection is a matrix multiplication that transforms the original input vector into a new vector space. In the context of the Transformer, for each head ii, we train three independent weight matrices:

  1. WiQW_i^Q (Query weights)
  2. WiKW_i^K (Key weights)
  3. WiVW_i^V (Value weights)

If the model dimension is dmodeld_{model} and we want hh heads, the dimension of each head will typically be dk=dmodel/hd_k = d_{model} / h. The projections reduce the dimensionality for each head, keeping the total computational cost similar to that of a single head with the full dimension.

7.3 Multi-Head Attention Architecture

The process takes place in four main steps:

  1. Projection: The input vectors (queries, keys, values) are linearly projected hh times with different, learned weight matrices.
  2. Scaled Dot-Product Attention: The attention mechanism is applied in parallel to each of these projections.
  3. Concatenation: The outputs of all heads are concatenated.
  4. Final projection: The concatenation passes through a last linear layer (WOW^O) to restore the original dimension and mix the information learned by the different heads.

7.3.1 Mathematical Formulation

Given a set of input matrices Q,K,VQ, K, V:

MultiHead(Q,K,V)=Concat(head1,…,headh)WO\text{MultiHead}(Q, K, V) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)W^O

Where each head is computed as:

headi=Attention(QWiQ,KWiK,VWiV)\text{head}_i = \text{Attention}(QW_i^Q, KW_i^K, VW_i^V)

And the attention function is the standard one:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

7.4 Data Flow Diagram

The diagram below illustrates how the data flow is split, processed, and reunified.

Diagram

7.5 Technical Implementation (PyTorch)

In practice, we do not create hh separate linear layers because that is inefficient. Instead, we project to the full dimension (dmodeld_{model}) and use reshape and transpose operations to logically separate the heads.

Below is a robust, annotated implementation:

import torch
import torch.nn as nn
import math

class MultiHeadAttention(nn.Module):
    def __init__(self, d_model, num_heads):
        super(MultiHeadAttention, self).__init__()
        assert d_model % num_heads == 0, "d_model must be divisible by num_heads"

        self.d_model = d_model
        self.num_heads = num_heads
        self.d_k = d_model // num_heads

        # Linear projections (W_q, W_k, W_v)
        # Note that we use a single large matrix for efficiency
        self.w_q = nn.Linear(d_model, d_model)
        self.w_k = nn.Linear(d_model, d_model)
        self.w_v = nn.Linear(d_model, d_model)

        # Final projection (W_o)
        self.w_o = nn.Linear(d_model, d_model)

    def scaled_dot_product_attention(self, Q, K, V, mask=None):
        # Q, K, V shape: [batch_size, num_heads, seq_len, d_k]

        # 1. Matmul of Q and transposed K
        scores = torch.matmul(Q, K.transpose(-2, -1)) / math.sqrt(self.d_k)

        # 2. Apply the mask (optional, used in the decoder)
        if mask is not None:
            scores = scores.masked_fill(mask == 0, -1e9)

        # 3. Softmax
        attn_weights = torch.softmax(scores, dim=-1)

        # 4. Multiply by the Values
        output = torch.matmul(attn_weights, V)
        return output, attn_weights

    def forward(self, q, k, v, mask=None):
        batch_size = q.size(0)

        # 1. Linear projections and reshape to separate the heads
        # Transformation: [batch, seq_len, d_model] -> [batch, seq_len, num_heads, d_k]
        # Transpose: -> [batch, num_heads, seq_len, d_k] to ease matmul
        Q = self.w_q(q).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        K = self.w_k(k).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)
        V = self.w_v(v).view(batch_size, -1, self.num_heads, self.d_k).transpose(1, 2)

        # 2. Apply attention to all heads simultaneously
        attn_output, _ = self.scaled_dot_product_attention(Q, K, V, mask)

        # 3. Concatenation
        # Reverse transpose: [batch, num_heads, seq_len, d_k] -> [batch, seq_len, num_heads, d_k]
        # Contiguous + View: -> [batch, seq_len, d_model]
        attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, -1, self.d_model)

        # 4. Final linear projection
        output = self.w_o(attn_output)

        return output

7.6 Why Multiple Heads? (Intuition)

Imagine the sentence: “The bank denied the loan because it was out of funds.”

To understand the word “it”, the model needs to relate it to other words. * Head 1 (syntactic): It may focus on the grammatical structure, linking “it” to the subject of the main clause. * Head 2 (semantic): It may focus on the financial context (“bank”, “loan”, “funds”) to disambiguate whether “it” refers to the bank or to the applicant (in this case, the context suggests the bank).

If we had only one attention head, the model would have to take a weighted average of all these relationships, potentially diluting crucial information. With Multi-Head Attention, each head specializes in a different aspect of language, resulting in a much richer and more robust representation.

7.7 Summary

  • Multi-Head Attention allows parallel processing of different representation subspaces.
  • Linear projections (WQ,WK,WVW^Q, W^K, W^V) are used to transform the input into specific dimensions for each head.
  • The output is a linear combination (concatenation + WOW^O) of the views of all heads, giving the rest of the network a complete contextual view of the sequence.

7.8 Dimension Accounting

With dmodel=512d_{model}=512 and H=8H=8, each head typically uses dk=64d_k=64. After the projections, we reorganize (B,T,512)(B,T,512) into (B,8,T,64)(B,8,T,64). Attention operates independently per head; then transpose and reshape rebuild (B,T,512)(B,T,512) before WOW^O.

This rearrangement does not create information or change the number of elements. It only changes the interpretation of the axes. In PyTorch, a transposition can produce non-contiguous memory; therefore, reshape or contiguous().view(...) should be used consciously.

Specialization is an observable hypothesis

Saying a head is “syntactic” is a useful intuition, not a rule imposed by the architecture. The function of each head emerges from training and may be redundant, distributed, or vary across inputs.

7.9 MHA, MQA, and GQA

In conventional multi-head attention (MHA), each head has its own keys and values. During generation, these tensors for all previous tokens are kept in the cache, which can consume a lot of memory. Multi-query attention (MQA) shares a single set of keys and values across all query heads. Grouped-query attention (GQA) takes the middle ground: several query heads share each group of KK and VV.

If there are Hq=8H_q=8 query heads and Hkv=2H_{kv}=2 groups of keys and values, four queries share each group. The output still contains eight query perspectives, but the cache stores only two versions of KK and VV per layer. This reduces memory and bandwidth during decoding.

Diagram

Sharing too much can reduce capacity; sharing too little saves less. The number of groups is therefore an architectural hyperparameter evaluated together with quality and speed.

7.10 Approximate Parameter Count

With dense projections and dmodel=dd_{model}=d, the usual MHA has approximately 4d24d^2 parameters: three projections for QQ, KK, VV and one output projection. Splitting into heads does not automatically multiply this total when the concatenated dimensions still add up to dd. The cost changes when the key and value dimensions or the number of groups are altered.