Artificial Intelligence • Generative AI and Language Models • 12 min read

Attention, Self-Attention, and Multi-Head Attention

Attention is a mechanism that computes how strongly one representation should draw information from a set of other representations. It converts learned relevance scores into weights and uses those weights to combine information. Attention is especially important in Transformers, where tokens exchange contextual information without relying on a recurrent hidden-state chain.

The central distinction is between attention, the general weighted-information mechanism; self-attention, where queries, keys, and values come from the same sequence; and multi-head attention, where several attention computations learn different projections of the representations.

Start with a simple example

Consider the sentence “The animal didn’t cross the road because it was tired.” To interpret it, a model benefits from drawing on information about the animal, rather than treating every earlier word as equally relevant. Attention provides a trainable way to combine information from other positions with different weights.

A useful first mental model is a weighted average. Suppose a query attends to three value vectors with weights 0.60.6, 0.30.3, and 0.10.1. If their (one-dimensional) values are 22, 44, and 1010, the resulting output is:

0.6(2)+0.3(4)+0.1(10)=3.40.6(2)+0.3(4)+0.1(10)=3.4

The weights sum to one because they can be produced by softmax over learned relevance scores. This arithmetic illustrates how information is combined; real attention usually operates on multidimensional vectors.

  • Query: what information a position is looking for.
  • Key: a representation used to judge whether another position is relevant.
  • Value: the information to combine when that position receives weight.

In self-attention, queries, keys, and values are computed from the same sequence (possibly using different learned projections). Multi-head attention performs several such computations in parallel and combines their outputs. These learned weights are not dependable, stand-alone explanations of a model’s reasoning.

1. Why attention is useful

Consider the sentence:

The student submitted the assignment because she had finished it.

To form a contextual representation of she, a model can use information from other positions, including student. A fixed representation of a token cannot capture every meaning across contexts. Attention provides a learned way to combine contextual information from relevant positions.

Attention does not explicitly understand grammar or identify referents by a guaranteed rule. It learns numerical relationships during training, and its outputs can be wrong or difficult to interpret.

2. Queries, keys, and values

Each position participating in attention has three conceptual roles:

  • Query (Q): What information the receiving position is looking for.
  • Key (K): A representation used to evaluate whether a source position is relevant to that query.
  • Value (V): The information contributed by a source position if it receives attention weight.

In neural networks, these are usually vectors obtained through learned linear projections. For an input matrix XX, a self-attention layer computes:

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\qquad K=XW_K,\qquad V=XW_V

Here WQW_Q, WKW_K, and WVW_V are trainable weight matrices. They are not predefined semantic labels. The model learns useful projections by minimizing its training objective.

If XX contains nn token representations of dimension dmodeld_{\text{model}}, then typically:

  • QQ has shape n×dkn\times d_k.
  • KK has shape n×dkn\times d_k.
  • VV has shape n×dvn\times d_v.

The matching query and key dimensions allow their dot products to be calculated. The value dimension can differ.

3. Scaled dot-product attention

The standard scaled dot-product attention expression is:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q,K,V) =\operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

It consists of four operations:

  1. Similarity scoring: Multiply QK⊤QK^\top to score every allowed query-key pair.
  2. Scaling: Divide scores by dk\sqrt{d_k} to control how their magnitude tends to grow with vector dimension.
  3. Normalization: Apply a row-wise softmax so each query’s attention weights are nonnegative and sum to one.
  4. Weighted aggregation: Multiply the attention weights by VV to create contextual output vectors.

For a single query vector qq and source positions jj, the calculation is:

sj=q⋅kjdk,αj=esj∑resr,z=∑jαjvjs_j=\frac{q\cdot k_j}{\sqrt{d_k}},\qquad \alpha_j=\frac{e^{s_j}}{\sum_r e^{s_r}},\qquad z=\sum_j\alpha_jv_j

The dot product is a learned compatibility score, not an independently verified measure of meaning. The output zz is a weighted combination of value vectors, not a selection of one token.

Why scale by the square root of the key dimension?

When query and key vector components have roughly zero mean, unit variance, and suitable independence assumptions, dot-product variance grows with dkd_k. Very large score magnitudes can cause softmax to become sharply concentrated, which can make optimization difficult. Scaling by dk\sqrt{d_k} helps moderate that effect; it does not guarantee good training by itself.

4. Worked attention calculation

Suppose a query and two keys have two components:

q=[1,0],k1=[1,0],k2=[0,1]q=[1,0],\quad k_1=[1,0],\quad k_2=[0,1]

Let the associated value vectors be:

v1=[2,0],v2=[0,4]v_1=[2,0],\qquad v_2=[0,4]

Because dk=2d_k=2, the scaled scores are:

s1=12≈0.7071,s2=02=0s_1=\frac{1}{\sqrt{2}}\approx0.7071,\qquad s_2=\frac{0}{\sqrt{2}}=0

Softmax converts these scores to weights:

α1=e0.7071e0.7071+e0≈0.6698,α2≈0.3302\alpha_1=\frac{e^{0.7071}}{e^{0.7071}+e^0}\approx0.6698, \qquad \alpha_2\approx0.3302

The output is:

z=0.6698[2,0]+0.3302[0,4]≈[1.3396,1.3208]z=0.6698[2,0]+0.3302[0,4] \approx[1.3396,1.3208]

The query assigns more weight to the first key, but both values contribute. Notice that a high attention weight does not mean that the corresponding value dominates every output component; value magnitudes also matter.

One query compares with two keys, softmax produces attention weights, and the weighted values combine into one output
Attention weights determine how value vectors are mixed for a particular query.

5. What makes attention self-attention?

In self-attention, a sequence supplies its own queries, keys, and values through separate learned projections. Every output position can aggregate information from other permitted positions in that same sequence.

For example, a token’s representation may attend to words earlier or later in a sentence, depending on the model’s attention mask. After aggregation, its output represents the token in context, rather than as an isolated symbol.

This distinction matters:

  • Self-attention: Query and key/value sequences originate from the same input sequence or representation stream.
  • Cross-attention: Queries originate from one stream, while keys and values come from another, such as decoder states attending to encoder outputs.

These terms describe where the inputs originate, not whether attention is causal or bidirectional.

6. Attention masks

Not every query should be able to use every key. A mask prevents or limits particular query-key connections, usually by adding a very large negative number (conceptually −∞-\infty) to forbidden logits before softmax.

Padding mask

A batch may contain sequences padded to equal length. Padding positions are not meaningful source tokens and should not contribute to attention outputs. A padding mask excludes them as keys.

Causal mask

An autoregressive language model predicts tokens using only available earlier positions and the current position. A causal mask prevents a position from attending to future positions.

For a four-token sequence, allowed connections are lower triangular:

              Key position
              1  2  3  4
Query 1       ✓  ·  ·  ·
Query 2       ✓  ✓  ·  ·
Query 3       ✓  ✓  ✓  ·
Query 4       ✓  ✓  ✓  ✓

This mask prevents future-token leakage during autoregressive training. It does not automatically prevent every other form of data leakage or guarantee that generated answers are accurate.

Implementation note: Mask semantics vary by library. Some APIs use True to mean “allowed,” while others use it to mean “blocked.” Check the specific function’s documentation rather than assuming one convention.

7. Multi-head attention

A single attention computation produces one learned pattern of weighted information exchange. Multi-head attention runs several attention computations in parallel, typically using distinct learned projection matrices.

For head ii:

headi=Attention⁡(XWQ(i),XWK(i),XWV(i))\mathrm{head}_i =\operatorname{Attention}(XW_Q^{(i)},XW_K^{(i)},XW_V^{(i)})

Their outputs are concatenated and projected:

MultiHead⁡(X)=Concat⁡(head1,…,headh)WO\operatorname{MultiHead}(X) =\operatorname{Concat}(\mathrm{head}_1,\ldots,\mathrm{head}_h)W_O

For example, with a model width dmodel=512d_{\text{model}}=512 and h=8h=8 equal-sized heads, a common choice is dk=dv=64d_k=d_v=64 per head. Concatenating eight 64-dimensional head outputs recovers 512 dimensions before the output projection.

What multiple heads accomplish

Distinct projections let the model learn different patterns of association and information aggregation. Some heads may correlate with positional or syntactic patterns, but assigning a stable human-readable purpose to each head is generally unreliable. Heads can also be redundant.

Multi-head attention is therefore not equivalent to eight independent reasoning agents. It is one trainable layer with multiple projection subspaces.

Input representations flow through three parallel attention heads, are concatenated and passed to an output projection
Multi-head attention combines information from multiple learned projection spaces.

8. Self-attention in a Transformer block

Attention is one component of a Transformer block, not the entire network. A typical block also contains residual connections, normalization, and a position-wise feed-forward network. Its precise ordering depends on the architecture.

Attention mixes information between positions. The feed-forward network transforms representations within each position. Residual pathways and normalization support stable learning and information flow.

Positional information is needed because attention alone does not encode token order simply from the set of input vectors. Models may use absolute positional embeddings, relative position biases, rotary position embeddings, or other schemes.

See The Transformer Architecture for a full discussion of how these pieces fit together.

9. Implementing scaled dot-product attention in NumPy

The following example uses explicit query, key, and value matrices rather than learned projections. It illustrates the mathematical computation, not training a Transformer.

import numpy as np


def softmax(x, axis=-1):
    shifted = x - np.max(x, axis=axis, keepdims=True)
    exponents = np.exp(shifted)
    return exponents / np.sum(exponents, axis=axis, keepdims=True)


def scaled_dot_product_attention(q, k, v, allowed=None):
    """Return outputs and attention weights for arrays of token vectors."""
    if q.shape[-1] != k.shape[-1]:
        raise ValueError("Query and key dimensions must agree")
    if k.shape[0] != v.shape[0]:
        raise ValueError("Keys and values must have the same sequence length")

    scores = (q @ k.T) / np.sqrt(q.shape[-1])

    if allowed is not None:
        if allowed.shape != scores.shape:
            raise ValueError("Mask shape must match attention scores")
        if not np.all(allowed.any(axis=-1)):
            raise ValueError("Each query must have an allowed key")
        scores = np.where(allowed, scores, -np.inf)

    weights = softmax(scores, axis=-1)
    return weights @ v, weights


q = np.array([[1.0, 0.0]])
k = np.array([[1.0, 0.0], [0.0, 1.0]])
v = np.array([[2.0, 0.0], [0.0, 4.0]])

output, weights = scaled_dot_product_attention(q, k, v)
print("Weights:", np.round(weights, 4))
print("Output:", np.round(output, 4))

Expected output:

Weights: [[0.6698 0.3302]]
Output: [[1.3395 1.3210]]

Slight differences in the last decimal place can arise from rounding. In production, frameworks such as PyTorch implement optimized attention operations, often using kernels that avoid materializing every intermediate attention matrix.

Applying a causal mask

For nn input positions, a lower-triangular Boolean mask represents allowed keys for each query:

n = 4
allowed = np.tril(np.ones((n, n), dtype=bool))

x = np.eye(n)
causal_output, causal_weights = scaled_dot_product_attention(
    x, x, x, allowed=allowed
)
print(causal_weights.round(3))

Each row has zero weight at future key positions. This toy computation uses the input vectors directly as queries, keys, and values; real neural attention layers learn projections.

10. Computational cost and limitations

For standard dense self-attention on a sequence of nn positions, the attention score matrix has n2n^2 entries per head. Storing those scores or weights directly can require quadratic memory in sequence length. The main attention multiplication work is proportional to n2dn^2d for a head width dd, apart from projection and other network costs.

This is why long-context processing can be expensive. Techniques such as optimized exact attention kernels, sparse attention, sliding-window attention, and other variants can reduce memory use or restrict the number of interactions. Their computational trade-offs differ, and not every efficient implementation changes the underlying exact attention result.

Other limitations include:

  • Learned scores are not proofs: High attention does not establish a causal or logically correct relationship.
  • Interpretability is limited: Attention weights alone do not fully explain a model’s behavior.
  • Context is bounded: A model can use only information available in its input and accessible state.
  • Positional handling matters: Different position-encoding schemes influence how order and distance are represented.
  • Generation constraints matter: Incorrect masking can leak future tokens in a causal training setup.

11. Common misconceptions

MisconceptionMore accurate explanation
Attention selects one important word.Standard softmax attention forms a weighted combination of value vectors.
Self-attention and multi-head attention are alternatives.Multi-head attention often consists of several self-attention heads.
The query, key, and value vectors have fixed linguistic meanings.They are learned projections optimized for the model’s task.
Every Transformer is bidirectional.Causal decoders restrict access to future token positions.
Attention weights explain all model decisions.They describe one computation and are not a complete explanation of model behavior.
More heads always produce better results.Head count is an architectural choice with capacity, redundancy, and efficiency trade-offs.

12. Check your understanding

  1. Why must queries and keys have matching inner dimensions?
  2. What does softmax accomplish after the score calculation?
  3. Why is attention output based on values rather than keys?
  4. How do self-attention and cross-attention differ?
  5. Why does an autoregressive decoder use a causal mask?
  6. What does the final projection in multi-head attention combine?
  7. Why can attention become costly for long sequences?
Show short answers
  1. Their dot product requires compatible dimensions.
  2. It produces nonnegative weights that sum to one for each query.
  3. Keys are used to score relevance; values carry the information being combined.
  4. Self-attention draws from the same sequence; cross-attention uses queries from a different stream than keys and values.
  5. It prevents access to future token positions during next-token prediction.
  6. It mixes the concatenated outputs of the parallel heads.
  7. Dense score computation has quadratic dependence on sequence length.

14. References and further reading

Related articles in

Image preview

Fit