LLM Algorithms · 6 of 10

Multi-Head Attention tutorial

Runs several attention projections in parallel so different relationships can be learned. Learn the concept, implement it from scratch, and apply it with PyTorch.

Category
Attention
Core idea
MHA(X) = Concat(head₁,…,headₕ)Wᴼ
Typical use
Learning several kinds of contextual relationship at once.
Practical tool
PyTorch

What is Multi-Head Attention?

Multi-Head Attention is a attention technique. Runs several attention projections in parallel so different relationships can be learned. Its central idea is summarized by MHA(X) = Concat(head₁,…,headₕ)Wᴼ.

This guide connects theory to practice. You will trace the input, intermediate process, and output; decode the notation; run a dependency-light implementation; then repeat the workflow with PyTorch and evaluate the result.

By the end of this tutorial, you will be able to

  • Explain when Multi-Head Attention is appropriate and what assumptions it makes.
  • Read its mathematical notation or complexity statement without guessing what the symbols mean.
  • Follow and modify a from-scratch Python implementation.
  • Build a practical workflow with PyTorch and choose useful evaluation checks.

Prerequisites and tools

You do not need an advanced software stack. Start with a recent Python environment and the fundamentals below, then install only the packages used by the practical example.

  • Comfort with Python, tensor shapes, matrix multiplication, and probability distributions.
  • A working understanding of token sequences, embeddings, batches, and attention masks.
  • Enough memory to run the small tensor example; pretrained-model tutorials may also download model weights.
LanguagePython 3
Primary libraryPyTorch
Learning modeFrom scratch + library

How Multi-Head Attention works

  1. 1

    Input

    Token representations shared across multiple attention heads.

  2. 2

    Prepare and configure

    Check shapes, value ranges, ordering assumptions, missing values, and the parameters that control the algorithm’s behavior.

  3. 3

    Algorithm process

    Attend independently in each projected subspace, concatenate, and mix.

  4. 4

    Output

    A representation combining syntactic, semantic, and positional relationships.

  5. 5

    Validate

    Validate shapes, padding behavior, and gradients before integrating the layer into a larger model.

Formula and intuition

MHA(X) = Concat(head₁,…,headₕ)Wᴼ

Each head performs attention with its own learned projections; h is the head count and Wᴼ mixes the concatenated outputs.

The notation captures the main operation or complexity statement behind Multi-Head Attention. Read it together with the symbol key above and the step-by-step process in this guide.

When to use Multi-Head Attention

Learning several kinds of contextual relationship at once.

Learning tip

Change one parameter at a time in the interactive lesson, replay the animation, and connect the visible change to the input, process, and output described above.

Multi-Head Attention from scratch in Python

This dependency-light example emphasizes the algorithm’s mechanics so each important step remains visible.

PythonEducational implementation
import numpy as np

heads = []
for Wq, Wk, Wv in projections:
    Q, K, V = X @ Wq, X @ Wk, X @ Wv
    scores = Q @ K.T / np.sqrt(Q.shape[-1])
    weights = np.exp(scores - scores.max(axis=-1, keepdims=True))
    weights /= weights.sum(axis=-1, keepdims=True)
    heads.append(weights @ V)

multi_head_output = np.concatenate(heads, axis=-1) @ W_output
How to use this example

Run it once unchanged, inspect the output, and then alter one input or parameter. The compact implementation is designed for learning; use the tested library workflow below for real projects.

Build Multi-Head Attention with PyTorch

nn.MultiheadAttention owns the Q/K/V projections, head splitting, output projection, masks, and optional attention weights.

Recommended environment

JupyterLab, Google Colab, or VS Code

Create an isolated virtual environment for a local project, or paste the cells into a hosted notebook. Pin package versions before deploying a reproducible application.

Install the required package python -m pip install torch
  1. Prepare the data.Token representations shared across multiple attention heads. Validate its shape, type, range, and ordering before training or execution.
  2. Configure the algorithm.Begin with explicit, conservative parameters and a fixed random seed whenever the library supports one.
  3. Fit or execute.Attend independently in each projected subspace, concatenate, and mix.
  4. Inspect the result.A representation combining syntactic, semantic, and positional relationships. Then apply the evaluation checks in the next section.
PythonPyTorch workflow
import torch
from torch import nn

torch.manual_seed(7)
attention = nn.MultiheadAttention(
    embed_dim=128, num_heads=8, dropout=0.1, batch_first=True
)
tokens = torch.randn(3, 20, 128)
padding_mask = torch.zeros(3, 20, dtype=torch.bool)
padding_mask[0, -3:] = True

output, weights = attention(
    tokens, tokens, tokens,
    key_padding_mask=padding_mask,
    need_weights=True,
)
print("output:", output.shape)
print("averaged attention weights:", weights.shape)

API details and version-specific options: official PyTorch reference →

How to evaluate the result

A successful run is not enough. Evaluate the output against the intended use, compare it with a simple baseline, and preserve a genuinely unseen test case whenever the task involves learned parameters.

  • Validate shapes, padding behavior, and gradients before integrating the layer into a larger model.
  • Profile multiple head counts because smaller per-head dimensions can change quality and throughput.
Reproducibility check

Record the data version, package versions, parameters, random seeds, and evaluation procedure. Re-run the same workflow before publishing a benchmark or deploying a model.

Pitfalls and how to avoid them

These failure modes are common in tutorials and production systems. Treat them as review questions, not just after-the-fact debugging advice.

  • embed_dim must be divisible by num_heads.
  • Sequence-first and batch-first layouts are easy to confuse.
  • Averaged attention weights hide differences between individual heads.

Before using Multi-Head Attention in a project

  • Write down every tensor shape and mask convention before composing layers.
  • Test a tiny deterministic case against a simple reference implementation.
  • Separate training behavior from autoregressive inference and disable dropout for evaluation.
  • Measure quality, latency, peak memory, and sequence-length scaling together.
  • Pin model, tokenizer, framework, and generation-configuration versions.

Official documentation and next steps

Primary software reference PyTorch

Use the official documentation to confirm supported parameters, current defaults, input requirements, and version changes.

Read official documentation →

This guide is an educational introduction, not a substitute for domain validation. For consequential applications, review the source documentation, test against representative data, and involve a subject-matter expert.

See Multi-Head Attention in motion

Open the interactive lesson to adjust parameters, scrub through the process, replay the animation, and compare the explanation with the Python code.

Launch visualization →