Find a concept

Search Notes and Discovery

Enter a term to search published Notes and Discovery.

    In this topic

    Structured note

    Multi-head attention

    How parallel attention projections create complementary views and recombine them into one representation.

    TransformersIntermediate
    Published
    Reviewed
    Reading time
    3 min

    Prerequisites

    On this page

    Direct answer

    Multi-head attention runs several attention operations in parallel after applying different learned projections. Each head can form a different score matrix and value mixture. Their outputs are concatenated and projected back into the model width.

    This expands the set of relationships a layer can represent, but it does not guarantee that every head learns a human-readable specialization.

    Equation and shapes

    For head (i):

    headi=Attention(QWiQ,KWiK,VWiV)\operatorname{head}_i=\operatorname{Attention}(QW_i^Q,KW_i^K,VW_i^V)

    The heads are recombined as:

    MultiHead(Q,K,V)=Concat(head1,,headh)WO\operatorname{MultiHead}(Q,K,V)=\operatorname{Concat}(\operatorname{head}_1,\ldots,\operatorname{head}_h)W^O

    In the original Transformer configuration, model width dmodeld_{model} is divided across hh heads. With 512 model dimensions and 8 heads, each query and key head uses 64 dimensions. Concatenation restores the combined width before the output projection.

    One-head shape walkthrough

    Assume a batch of 2 sequences, 10 tokens per sequence, model width 512, and 8 heads.

    StageShapeMeaning
    Input2 × 10 × 512One vector per token
    Split Q/K/V2 × 8 × 10 × 64Eight projected views
    Scores2 × 8 × 10 × 10Every query-key comparison per head
    Concatenate2 × 10 × 512Heads reunited before output projection

    The head dimension affects the scaling term. Each head divides its score by 64\sqrt{64}, not 512\sqrt{512} in this example.

    A transparent shape check

    head_shapes.pyPython
    batch, tokens, model_width, heads = 2, 10, 512, 8
    
    if model_width % heads != 0:
        raise ValueError("model width must divide evenly across heads")
    
    head_width = model_width // heads
    score_elements = batch * heads * tokens * tokens
    
    print(f"head width: {head_width}")
    print(f"score tensor: ({batch}, {heads}, {tokens}, {tokens})")
    print(f"score elements: {score_elements}")

    This example checks dimensions; it is not a neural-network implementation. Production kernels typically fuse projection and attention steps and may avoid materializing the full score matrix.

    Why multiple heads help

    A single attention distribution supplies one weighted mixture per query. Multiple learned projections allow a layer to preserve several mixtures before recombination. One head may emphasize nearby syntax while another uses a longer-range association, but such interpretations must be verified rather than assumed.

    Increasing head count is not free. At fixed model width, more heads make each head narrower. The score tensor still scales with sequence length, and extra heads introduce projection and memory-layout costs. Head count, width, hardware kernels, and task behavior should be evaluated together.

    Common mistakes

    • Applying softmax across the head dimension instead of the key positions.
    • Forgetting to transpose tokens and heads before matrix multiplication.
    • Scaling by the full model width rather than the per-head key width.
    • Assuming every head is necessary or semantically distinct.
    • Comparing INT8 and floating-point implementations without checking the accumulator and scale strategy.

    Interview takeaway

    Multi-head attention creates several learned query-key-value subspaces, performs attention independently in each, concatenates the results, and uses an output projection to mix them.

    Sources

    1. Attention Is All You Need