liveBook · Manning

Multi-head attention

As explained in Deep Learning with PyTorch, Second Edition

An attention mechanism that runs several attention heads in parallel, each learning different projections and relationships.

Multi-head attention runs several attention mechanisms in parallel instead of relying on one. Each head learns its own query, key, and value projections, so different heads can focus on different relationships in the same sequence. section 9.6.1

For example, one head might learn syntactic relationships while another captures semantic associations. The head outputs are concatenated and passed through a linear layer to form the final representation. section 9.6.1

A transformer block uses multi-head attention alongside:

  • Residual connections, which let gradients flow directly through deeper networks. section 9.6.1
  • Positional embeddings, which add token-order information to otherwise parallel processing. section 9.6.1
  • Layer normalization and a feed-forward MLP, which complete the surrounding transformer block. section 9.6.1

A PyTorch transformer block

A block can set num_heads=4, require n_embd to be divisible by that number, and create separate linear query, key, and value projections. A larger Transformer then adds character and positional embeddings, stacks these blocks, and projects the result to vocabulary logits.

Figure 9.13 Diagram of the Transformer architecture from the original paper “Attention Is All You Need.” The encoder is on the left, and the decoder is on the right. The encoder output is fed into the decoder as the key and value for the multi-head attention mechanism.
figure

Use the architecture diagram to trace how encoder outputs become the keys and values for decoder cross-attention, supporting sequence generation such as translation. section 9.7.2

How Deep Learning with PyTorch, Second Edition covers it

How deep it goes
Explains learned projections, head specialization, concatenation, and surrounding components, while stopping short of detailed attention-score mathematics.
Examples
Demonstrates a PyTorch TransformerBlock and a stacked character-level Transformer that generates sample names.
What it assumes
Assumes basic attention, embeddings, neural-network modules, and transformer-block components such as residual connections and normalization.
What you can do after
Builds it from scratch in PyTorch as part of a transformer block and connects it to sequence generation.
How it connects
Connects attention heads to query, key, and value projections, residual connections, positional embeddings, layer normalization, and encoder-decoder attention.

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 PyTorch, Second Edition. The section links point to the parts of the book it draws on.