Multi-head attention

Attention · node type · Attention, MultiHeadAttention

Runs several attention patterns in parallel on projected slices of the input, then merges them.

Also called MHA, Multi-head self-attention, MultiHeadAttention

Each token's query is compared with every key; softmax turns the scaled dot products into weights that mix the values. Pick a row to read one token's attention. The vectors here are hand-made, not from a trained model.
thefoxsawahenthe0.380.080.110.310.12fox0.040.050.830.040.04saw0.020.520.030.020.40a0.380.080.110.310.12hen0.060.070.750.060.06

“fox” attends to

the4%
fox5%
saw83%
a4%
hen4%

score = q · k / √3 × 1.0

Figure 1. Try it: every number is computed in your browser from the formula below.

What it does

Multi-head attention projects the input into h smaller sets of queries, keys and values with learned dense layers, runs scaled dot-product attention on each set independently, concatenates the h results and mixes them with a final dense projection. Each head can specialize: one may track the previous word, another the subject of a sentence, another a matching image patch. In ONNX exports from PyTorch it usually appears as three MatMul + Add projections, Reshape and Transpose to split heads, the attention MatMul–Softmax–MatMul core, a Transpose and Reshape to merge heads, and the output MatMul + Add.

Formula

headi = Attention(X WiQ, X WiK, X WiV)MHA(X) = Concat(head1, …, headh) WOWiQ, WiK, WiV ∈ RD × D/h, WO ∈ RD × D

Shapes and parameters

Shapes
Query input [N, T, D], key and value input [N, S, D]; per-head tensors [N, h, T, D/h]; output [N, T, D].
Parameters
Four D × D projections plus four bias vectors: 4D² + 4D. With D = 256: 262,144 + 1,024 = 263,168, independent of the number of heads and of sequence length.
Used for
Every layer of BERT, ALBERT, DistilBERT, MiniLM, TAPAS, Marian translation, ViT, CLIP, Depth Anything and the Kokoro speech model.

Figure 2. Multi-head attention inside Ask a question about a table, a real model in WeightSpace. The 2 outlined nodes are Multi-head attention; select any node for its shapes and parameters.

Figure 3. The typed ports of Multi-head attention, in the same format as every model drawing. Letters such as N or C stand for any size.

In WeightSpace

Read-only in WeightSpace today. In the catalog’s transformers the editable parameters sit in the output head or the final LayerNorm, so the attention patterns stay as shipped.