liveBook · Manning

Multi-head attention

As explained in Deep Learning with R, Third Edition

MultiHeadAttention is a Keras layer that computes attention through multiple parallel attention heads and combines their outputs.

Multi-head attention runs attention several times in parallel with different learned projections, then concatenates the head outputs. Separate heads can focus on different relationships, such as sentence subjects or punctuation, instead of washing all source information into one softmax sum. section 15.3.1

A reusable Keras layer

A multi-head attention layer can replace the explicit per-head implementation: multi_head_attention <- layer_multi_head_attention(num_heads = num_heads, head_dim = head_dim); multi_head_attention(query = target, key = source, value = source). Each head projects queries, keys, and values, computes scaled dot-product attention, and contributes a partition of the final output. section 15.3.1

With self-attention, query, key, and value all come from the same sequence, allowing every token to incorporate contextual information from every other token. Transformer encoder blocks combine this layer with residual connections, layer normalization, and a two-layer feed-forward network. section 15.3.2 section 15.3.2

Figure 15.7 Multiheaded attention allows each target word to attend to different parts of the source sequence in separate partitions of the eventual output vector.
figure

Shows how separate attention heads let each target token attend to different source regions within separate output partitions. section 15.3.1

How Deep Learning with R, Third Edition covers it

How deep it goes
Explains projections, scaled scores, softmax weighting, concatenation, and encoder integration, without deriving the underlying mathematics.
Examples
Uses R/Keras listings, source-target sequence attention, and the contextual example of “station” attending to “train.”
What it assumes
Assumes sequence representations and attention basics while motivating the transition from RNN-based translation models to self-attention.
What you can do after
Build it from scratch or operate a Keras layer for cross-sequence attention, self-attention, and Transformer encoder blocks.
How it connects
Connects multi-head attention to dot-product attention, self-attention, RNNs, layer normalization, and Transformer encoder blocks.

Also explained in

Compare how 14 books explain multi-head attention →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with R, Third Edition. The section links point to the parts of the book it draws on.