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.
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













