> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Multi-Head Self-Attention

> Multi-head self-attention.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/nlp/transformers/multihead-self-attention/index.ipynb)

The [single-head self-attention](https://aegean.ai/aiml-common/lectures/nlp/transformers/singlehead-self-attention/index.md) section showed how token representations can depend on context, including the noun compound "bear country". A single head computes one set of attention weights per token, so it has to serve all of these patterns at once. Multiple heads provide separate compatibility functions and value projections. They may learn different patterns, but specialization is not guaranteed.

![Three attention heads, each drawn as its own query-key space: head 1 matches the verb love with its subject I, head 2 matches love with its object bears, and head 3 matches the noun country with its modifier bear](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/multihead-self-attention/images/attention-heads.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=7baa0b8e8059bcfcf942ba7ee26ba4c4)

*Three heads, each with its own query-key space. The orange arrow is the query of one token and the green arrows are the keys of the tokens in the sentence. The key closest to the query gets the largest weight. This is an analogy: what a head learns is not labeled, and interpretable patterns may occur at different depths.*

The heads play a role similar to the multiple filters of a CNN layer: each one looks at the same input for a different kind of structure.

If $H$ is the number of heads, indexed by $h$, each head computes

$$
\mathrm{head}_h = \mathtt{Attention}(Q_h, K_h, V_h),
$$

where $Q_h, K_h, V_h$ are the query, key and value matrices of head $h$:

$$
\begin{aligned}
Q_h &= X W_h^q \\
K_h &= X W_h^k \\
V_h &= X W_h^v
\end{aligned}
$$

Here $W_h^q, W_h^k, W_h^v$ are the weight matrices of head $h$. The output of multi-head attention is

$$
\hat X = \mathtt{concat}(\mathrm{head}_1, \ldots, \mathrm{head}_H)\, W^o,
$$

where $W^o$ is the output weight matrix with dimensions $H d_v \times d$. Usually $d_v = d/H$, so $H d_v = d$.

![Multi-head attention with three heads: X is projected by each head's own W^q, W^k and W^v, each head runs scaled dot-product attention, the three head outputs are concatenated and multiplied by W^o](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/multihead-self-attention/images/multi-head-attention.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=ce2083352a1a10dd15b01e49f025f25b)

*Multi-head attention. Each head computes its own attention, the outputs of all heads are concatenated, and the weight matrix $W^o$ combines them. $W^o$ is called the mixing matrix for this reason.*

The code below implements one head and the multi-head layer. Each head projects the $d$-dimensional input to queries, keys and values of dimension $d/H$.

> [accordion] Code
>
> ```python theme={null}
> import math
> from types import SimpleNamespace
>
> import torch
> import torch.nn as nn
> import torch.nn.functional as F
>
> torch.manual_seed(0)
>
>
> def scaled_dot_product_attention(query, key, value):
>     dim_k = query.size(-1)
>     scores = torch.bmm(query, key.transpose(1, 2)) / math.sqrt(dim_k)
>     weights = F.softmax(scores, dim=-1)
>     return torch.bmm(weights, value)
>
>
> class AttentionHead(nn.Module):
>     def __init__(self, embed_dim, head_dim):
>         super().__init__()
>         self.q = nn.Linear(embed_dim, head_dim)
>         self.k = nn.Linear(embed_dim, head_dim)
>         self.v = nn.Linear(embed_dim, head_dim)
>
>     def forward(self, hidden_state):
>         return scaled_dot_product_attention(
>             self.q(hidden_state), self.k(hidden_state), self.v(hidden_state)
>         )
>
>
> class MultiHeadAttention(nn.Module):
>     def __init__(self, config):
>         super().__init__()
>         embed_dim = config.hidden_size
>         num_heads = config.num_attention_heads
>         if num_heads <= 0 or embed_dim % num_heads != 0:
>             raise ValueError("hidden_size must be divisible by positive num_heads")
>         head_dim = embed_dim // num_heads
>         self.heads = nn.ModuleList(
>             [AttentionHead(embed_dim, head_dim) for _ in range(num_heads)]
>         )
>         self.output_linear = nn.Linear(embed_dim, embed_dim)
>
>     def forward(self, hidden_state):
>         x = torch.cat([h(hidden_state) for h in self.heads], dim=-1)
>         x = self.output_linear(x)
>         return x
>
>
> config = SimpleNamespace(hidden_size=768, num_attention_heads=12)
> mha = MultiHeadAttention(config)
> x = torch.randn(2, 10, config.hidden_size)  # batch of 2 sequences of 10 tokens
> print("input:", tuple(x.shape), " output:", tuple(mha(x).shape))
> ```

```output theme={null}
input: (2, 10, 768)  output: (2, 10, 768)
```

The matrices $W^o$ and $W_h^q, W_h^k, W_h^v$ are learned during training. Using $H$ heads does not increase the number of parameters, because each head works in $d/H$ dimensions. The next cell counts the parameters for several values of $H$ and compares them with PyTorch's `nn.MultiheadAttention`.

> [accordion] Code
>
> ```python theme={null}
> def count(module):
>     return sum(p.numel() for p in module.parameters())
>
>
> d = config.hidden_size
> for num_heads in (1, 4, 12):
>     ours = count(MultiHeadAttention(SimpleNamespace(hidden_size=d, num_attention_heads=num_heads)))
>     torch_mha = count(nn.MultiheadAttention(d, num_heads))
>     print(f"H={num_heads:2d}: ours {ours:,}  nn.MultiheadAttention {torch_mha:,}")
> print(f"4d^2 + 4d = {4 * d * d + 4 * d:,}")
> ```

```output theme={null}
H= 1: ours 2,362,368  nn.MultiheadAttention 2,362,368
H= 4: ours 2,362,368  nn.MultiheadAttention 2,362,368
H=12: ours 2,362,368  nn.MultiheadAttention 2,362,368
4d^2 + 4d = 2,362,368
```

The count is the same for every $H$: four $d \times d$ weight matrices and their biases, $4d^2 + 4d$. What grows with $H$ is the number of $T \times T$ attention weight matrices, one per head, and with them the memory needed by a naive implementation that materializes every matrix; fused attention can avoid storing them explicitly.

## Attention blocks with skip connections

![Post-LN and pre-LN placement of layer normalization around the attention and MLP sublayers](https://mintcdn.com/aegeanaiinc/Yrt_S4TWwKs8h38s/aiml-common/lectures/nlp/transformers/multihead-self-attention/images/layer-norm-placement.svg?fit=max\&auto=format\&n=Yrt_S4TWwKs8h38s\&q=85\&s=77b50e1b9a44111b2bb2e48f0f096f6b)

*Where layer normalization sits in a transformer layer. Post-LN normalizes after each residual addition. Pre-LN normalizes the input of each sublayer and leaves the residual path untouched.*

Layer normalization normalizes the inputs across the features of each individual token. Batch normalization, by contrast, normalizes each feature across the batch. Normalization stabilizes training and can make it converge faster. The next cell shows the difference on a small tensor.

> [accordion] Code
>
> ```python theme={null}
> tokens = 3 * torch.randn(4, 6) + 5  # 4 tokens with 6 features each
> ln = nn.LayerNorm(6, elementwise_affine=False)(tokens)
> bn = nn.BatchNorm1d(6, affine=False)(tokens)
>
> torch.set_printoptions(precision=2, sci_mode=False)
> print("LayerNorm, mean of each token:  ", ln.mean(dim=1))
> print("LayerNorm, mean of each feature:", ln.mean(dim=0))
> print("BatchNorm, mean of each feature:", bn.mean(dim=0))
> ```

```output theme={null}
LayerNorm, mean of each token:   tensor([-0.00,  0.00, -0.00,  0.00])
LayerNorm, mean of each feature: tensor([-0.43, -0.03, -0.24,  0.48, -0.19,  0.42])
BatchNorm, mean of each feature: tensor([-0.00,  0.00,  0.00,  0.00, -0.00,  0.00])
```

In this example, with affine parameters disabled, every token has approximately mean 0 and variance 1 across its features, while the feature means across tokens are not 0. Batch normalization here normalizes each feature across the four rows. Learned affine parameters and numerical epsilon modify these statements in general. Layer normalization does not depend on the other examples in the batch, which suits sequences of different lengths.

We apply layer normalization to the input of the multi-head self-attention (MHSA). Here $U$ denotes the input to the block, to distinguish it from the attention output above. As in ResNet, a skip connection adds the input to the output of the MHSA:

$$
\begin{aligned}
Z &= \mathtt{LayerNorm}(U) \\
\hat Z &= \mathtt{MHSA}(Z) + U
\end{aligned}
$$

Normalizing before the attention layer, as here, is called *pre-LN*, and GPT-2 and most later models use it. The original transformer normalized after the residual addition instead (*post-LN*), which can require more careful optimization in deep stacks ([Xiong et al., 2020](https://arxiv.org/abs/2002.04745)).

> [accordion] Code
>
> ```python theme={null}
> class AttentionBlock(nn.Module):
>     def __init__(self, config):
>         super().__init__()
>         self.norm = nn.LayerNorm(config.hidden_size)
>         self.attention = MultiHeadAttention(config)
>
>     def forward(self, x):
>         return x + self.attention(self.norm(x))  # pre-LN with a skip connection
>
>
> block = AttentionBlock(config)
> print("attention block output:", tuple(block(x).shape))
> ```

```output theme={null}
attention block output: (2, 10, 768)
```

We call this an *attention block*. Depth helps representation learning, so we want to stack several attention blocks. Before stacking them, each attention block is followed by a feed-forward layer, for the reasons given in the [MLP](https://aegean.ai/aiml-common/lectures/nlp/transformers/mlp/index.md) section.

## PyTorch reference

| PyTorch class | Description |
| - | - |
| [`nn.Linear`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Linear.html) | Affine map of the input: $y = xA^T + b$. |
| [`nn.MultiheadAttention`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.MultiheadAttention.html) | Attention with several heads in parallel. |
| [`nn.LayerNorm`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.LayerNorm.html) | Layer normalization over the last dimensions of the input. |
| [`nn.Softmax`](https://docs.pytorch.org/docs/2.12/generated/torch.nn.Softmax.html) | Softmax over one dimension of a tensor. |

Key references: (Vaswani et al., 2017); Ba et al., Layer Normalization, 2016, [arXiv:1607.06450](https://arxiv.org/abs/1607.06450).

## References

* Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., et al. (2017). *Attention Is All You Need*. arXiv \[cs.CL]. [Link](http://arxiv.org/abs/1706.03762)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/nlp/transformers/multihead-self-attention).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.