liveBook · Manning

Multi-head attention

As explained in Inside Deep Learning: Math, Algorithms, Models

An attention mechanism that uses multiple attention heads to attend to different contexts or aspects of the input in parallel.

Multi-head attention (MHA) extends attention by learning several contexts in parallel. Each head can focus on a different pattern, then the model mixes their answers into one output. section 12.5.1

Represent the mechanism as queries over paired keys and values:

  • Use key and value tensors K and V with shape (T, D), where each key has a corresponding value. section 12.5.1
  • Use a query tensor Q with its own length T′; each query receives one D-dimensional response. section 12.5.1
  • Apply softmax and learned nn.Linear layers so each head selectively focuses on parts of the input. section 12.5.1
  • Concatenate the head outputs and project them through a final linear layer; increasing the head count does not increase output width. section 12.5.1

A PyTorch implementation pattern

Create one query, key, and value projection per head, compute Attention(wq(Q), wk(K), wv(V)) for every head, concatenate the results, and apply wo to return D features. A useful intuition is the contrast with a Python dictionary: MHA lets every key contribute according to similarity instead of requiring an exact match. section 12.5.1

Figure 12.5 Outline of the multiheaded attention block. There are three sequences as inputs: the queries Q and the keys and values K, V, which are paired together. The MHA returns a D-dimensional vector that answers each query qi ∈ Q.

Shows Q, K, and V as three input sequences and the D-dimensional response returned for each query. section 12.5.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Explains tensor roles, shapes, head behavior, and PyTorch construction, while deferring detailed transformer additions.
Examples
Uses negation detection, a key-value dictionary analogy, tensor shapes, and nn.ModuleList projection code.
What it assumes
Assumes familiarity with attention, softmax, nn.Linear, and tensor dimensions while clarifying queries, keys, and values.
What you can do after
Apply it via PyTorch by projecting Q, K, and V per head, combining head outputs, and returning fixed-width representations.
How it connects
Connects attention mechanisms, transformers, positional encoding, recurrent neural networks, and convolutional layers.

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 Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.