Skip to main content
Open In Colab The single-head self-attention 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 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 HH is the number of heads, indexed by hh, each head computes headh=Attention(Qh,Kh,Vh),\mathrm{head}_h = \mathtt{Attention}(Q_h, K_h, V_h), where Qh,Kh,VhQ_h, K_h, V_h are the query, key and value matrices of head hh: Qh=XWhqKh=XWhkVh=XWhv\begin{aligned} Q_h &= X W_h^q \\ K_h &= X W_h^k \\ V_h &= X W_h^v \end{aligned} Here Whq,Whk,WhvW_h^q, W_h^k, W_h^v are the weight matrices of head hh. The output of multi-head attention is X^=concat(head1,…,headH) Wo,\hat X = \mathtt{concat}(\mathrm{head}_1, \ldots, \mathrm{head}_H)\, W^o, where WoW^o is the output weight matrix with dimensions Hdv×dH d_v \times d. Usually dv=d/Hd_v = d/H, so Hdv=dH 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 Multi-head attention. Each head computes its own attention, the outputs of all heads are concatenated, and the weight matrix WoW^o combines them. WoW^o is called the mixing matrix for this reason. The code below implements one head and the multi-head layer. Each head projects the dd-dimensional input to queries, keys and values of dimension d/Hd/H.
The matrices WoW^o and Whq,Whk,WhvW_h^q, W_h^k, W_h^v are learned during training. Using HH heads does not increase the number of parameters, because each head works in d/Hd/H dimensions. The next cell counts the parameters for several values of HH and compares them with PyTorch’s nn.MultiheadAttention.
The count is the same for every HH: four d×dd \times d weight matrices and their biases, 4d2+4d4d^2 + 4d. What grows with HH is the number of T×TT \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 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.
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 UU 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: Z=LayerNorm(U)Z^=MHSA(Z)+U\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).
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 section.

PyTorch reference

Key references: (Vaswani et al., 2017); Ba et al., Layer Normalization, 2016, arXiv: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

Found an error on this page? Report an issue.