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 , , and . If their (one-dimensional) values are , , and , the resulting output is:
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 , a self-attention layer computes:
Here , , and are trainable weight matrices. They are not predefined semantic labels. The model learns useful projections by minimizing its training objective.
If contains token representations of dimension , then typically:
- has shape .
- has shape .
- has shape .
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:
It consists of four operations:
- Similarity scoring: Multiply to score every allowed query-key pair.
- Scaling: Divide scores by to control how their magnitude tends to grow with vector dimension.
- Normalization: Apply a row-wise softmax so each query’s attention weights are nonnegative and sum to one.
- Weighted aggregation: Multiply the attention weights by to create contextual output vectors.
For a single query vector and source positions , the calculation is:
The dot product is a learned compatibility score, not an independently verified measure of meaning. The output 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 . Very large score magnitudes can cause softmax to become sharply concentrated, which can make optimization difficult. Scaling by 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:
Let the associated value vectors be:
Because , the scaled scores are:
Softmax converts these scores to weights:
The output is:
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.
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 ) 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
Trueto 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 :
Their outputs are concatenated and projected:
For example, with a model width and equal-sized heads, a common choice is 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.
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 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 positions, the attention score matrix has entries per head. Storing those scores or weights directly can require quadratic memory in sequence length. The main attention multiplication work is proportional to for a head width , 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
| Misconception | More 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
- Why must queries and keys have matching inner dimensions?
- What does softmax accomplish after the score calculation?
- Why is attention output based on values rather than keys?
- How do self-attention and cross-attention differ?
- Why does an autoregressive decoder use a causal mask?
- What does the final projection in multi-head attention combine?
- Why can attention become costly for long sequences?
Show short answers
- Their dot product requires compatible dimensions.
- It produces nonnegative weights that sum to one for each query.
- Keys are used to score relevance; values carry the information being combined.
- Self-attention draws from the same sequence; cross-attention uses queries from a different stream than keys and values.
- It prevents access to future token positions during next-token prediction.
- It mixes the concatenated outputs of the parallel heads.
- Dense score computation has quadratic dependence on sequence length.
13. Related PlainCS articles
- Vectors and Matrices: Vector representations and matrix shapes.
- Vector and Matrix Operations: Dot products, multiplication, and transposes.
- Entropy, Cross-Entropy, and KL Divergence: Probability distributions and training objectives.
- Neural Networks: Neurons, Layers, Weights, and Biases: Learned projections and hidden representations.
- Text Processing, Tokenization, and Embeddings: How text becomes input vectors.
- The Transformer Architecture: Attention inside complete encoder and decoder blocks.
- Large Language Models: Foundations and Capabilities: How attention-based architectures support modern language models.
14. References and further reading
- Vaswani, A., et al. (2017). Attention Is All You Need. Introduces the original Transformer and scaled dot-product multi-head attention.
- Bahdanau, D., Cho, K., and Bengio, Y. (2014). Neural Machine Translation by Jointly Learning to Align and Translate. An influential earlier neural attention mechanism.
- PyTorch: Scaled Dot Product Attention. Reference API and implementation behavior.
- The Annotated Transformer. An educational walkthrough of Transformer components.
Related articles in
- AI Agents and Tool-Using Workflows — Learn agent goals, tool invocation, planning, state, permissions, and how to evaluate multi-step AI workflows.
- AI Development Tools: Git, Jupyter, and APIs — Learn how Git, Jupyter notebooks, Python environments, and APIs fit together in reproducible, secure artificial intelligence workflows.
- How AI Is Changing Theoretical Computer Science — AI is beginning to help researchers explore algorithms, mathematical structures, and formal proofs. Here is what it can do, what still needs human judgment, and why verification matters.