What Is the Attention Mechanism in a Transformer?
The attention mechanism lets a model build a context-aware representation for each token by scoring other available tokens and combining their information. In a Transformer, each query is compared with keys, the scores are converted into weights, and those weights determine how much each value vector contributes to the output.
Consider the sentence The keys to the cabinet near the stairs are missing. To predict the verb after stairs, the model can use information from the earlier noun keys, even though several other nouns intervene. In a causal language model, the hidden state at the final visible position helps predict the next token. Attention can bring information about the subject into that hidden state. A single attention head need not perform the whole task: several heads, layers and feed-forward blocks may contribute to the prediction.
In the Transformer architecture, attention provides a direct route between any two positions that the mask allows to interact in a layer. A standard recurrent neural network processes its inputs in sequence, passing information from one recurrent state to the next. A Transformer can compute attention for all positions in a known input together using matrix operations. A causal mask restricts which positions share information, but it does not force those matrix operations to run one row at a time.
That parallelism applies during training and when processing an already available prompt. When an autoregressive model generates new tokens, it still predicts them one at a time: the token selected at one step becomes part of the input for the next. Also, attention weights are separate from next-token probabilities. The former distribute weight across eligible input positions inside a head; the latter distribute probability across vocabulary entries at the model output.
What Are Query, Key and Value in Attention?
Query key value attention separates the job of choosing where to read from the job of carrying the information being read. Take a matrix X with shape [n, d_model], where each row represents one of n tokens. At the first layer, these rows start from token embeddings, with position information handled according to the architecture. In deeper layers, the rows come from earlier blocks and already contain contextual information.

For one self attention head, use three learned projection matrices: Q = XW_Q, K = XW_K and V = XW_V. This notation omits optional biases and any separate position operation. The same projection matrices are applied to every row. A token's query, key and value can differ because each projection learns a different mapping from the same input.
| Matrix | Projection shape | Result shape | Role |
|---|---|---|---|
Q, queries | [d_model, d_k] | [n, d_k] | One vector per position requesting information |
K, keys | [d_model, d_k] | [n, d_k] | One vector per source position used to score a match |
V, values | [d_model, d_v] | [n, d_v] | One vector per source position available for aggregation |
For query position i and key position j, the raw score is q_i · k_j. If q_i = [1, 0, 1] and k_j = [1, 1, 0], the score is 1×1 + 0×1 + 1×0 = 1. Computing all dot products at once gives QKᵀ: row i belongs to query i, and column j belongs to key j.
A higher score gives a key more weight than a lower-scoring key in the same row, provided both keys are allowed. The score is a learned compatibility measure, without the vector normalisation used in cosine similarity, so vector magnitude can affect it. Even in self attention, the score from token A to token B can differ from the reverse score because queries and keys generally use different projections. The value does not participate in the scoring step. Key k_j affects how much the query reads from position j; value v_j supplies the content of that read.
How Does Scaled Dot Product Attention Work?
The calculation is Z = softmax(QKᵀ / sqrt(d_k) + M) V, where M is an optional additive mask and softmax runs across the key columns of each row. In the unmasked case, omit M. For general inputs with n_q queries and n_k key and value positions, the logit and weight matrices both have shape [n_q, n_k]. Multiplying by V, whose shape is [n_k, d_v], produces Z with shape [n_q, d_v].
- Score and scale. Compute each query and key dot product, then divide by
sqrt(d_k). The resulting numbers are the attention logits before masking. - Apply the mask. In a hard additive mask, add zero for an allowed connection and negative infinity for a blocked connection. Apply the mask before softmax so that blocked positions do not receive probability mass.
- Normalise over keys. For a logit row
s, usea_j = exp(s_j - m) / sum_l exp(s_l - m), wheremis the row maximum. Subtracting the maximum preserves the ratios and prevents overflow in the exponential for finite, allowed logits. This formula assumes at least one finite logit in the row. - Mix the values. Compute
z_i = sum_j a_ij v_j. A valid weight row sums to one before any training-time attention dropout, and a blocked value contributes zero to that row.
Why divide by the square root? As a simple model, assume all query and key components are independent, have mean zero and have variance one. Each product q_r k_r then has variance one, so the sum of d_k such products has variance d_k and standard deviation sqrt(d_k). Dividing by that standard deviation keeps the scaled logits at roughly unit variance under this model. Learned activations need not satisfy these assumptions. The argument explains the scale factor, rather than predicting the actual variance of every head.
Large differences between logits can make softmax nearly one-hot. In that regime, changes to many logits have little effect on the weights, which can weaken gradients. Scaling reduces the tendency for larger head dimensions alone to cause this saturation. The divisor is based on the number of components in a single query or key vector. Sequence length changes the number of competing scores in a row, but it does not change the divisor.
What Is Self Attention? Bidirectional, Causal and Cross Attention
Self attention derives queries, keys and values from the same sequence of hidden states. Every input position produces an output, but a mask determines which source positions it can use. In bidirectional self attention, a query may read positions on either side. In causal self attention, query position i may read positions j ≤ i, including itself, subject to any further restrictions such as padding or a local window.

| Attention type | Query source | Key and value source | Typical visibility |
|---|---|---|---|
| Bidirectional self attention | Current sequence | Current sequence | All valid positions in that sequence |
| Causal self attention | Current sequence | Current sequence | Current and earlier valid positions |
| Cross attention | One sequence or stream | A separate source sequence or stream | Valid source positions, subject to any source mask |
For example, in an encoder-decoder translation model, a decoder state can query keys and values from the encoder output. The score matrix can be rectangular because the source and target lengths need not match. The decoder can use causal self attention over the target prefix while still using cross attention over the full valid source sentence.
Within a Transformer block, multi-head attention and positional encoding address two different needs. Multiple heads apply separate learned projections and compute separate weight matrices. Their outputs are concatenated and passed through a learned output projection that mixes information from the heads. Position methods provide order information. For instance, rotary position embeddings rotate queries and keys according to their positions before scoring. Unmasked self attention without any position signal rearranges its outputs when the input rows are rearranged; it cannot distinguish order independently of that rearrangement.
Full attention gives distant positions a direct connection inside the context window, even when many tokens separate them. That connection makes a dependency possible, rather than ensuring that the model uses it correctly. Also, a high weight shows that a head read strongly from a position relative to the other eligible positions. It does not establish how important that token was to the final prediction, which depends on the value vectors and subsequent computation.
Worked Example: Calculate Attention for Three Tokens
Use the tokens The, cat and sits with a toy input matrix X = [[1, 0], [0, 1], [1, 1]]. Set W_Q and W_K to the two-dimensional identity matrix, and set W_V = [[1, 2], [2, 0]]. Then Q = K = X and V = [[1, 2], [2, 0], [3, 2]]. The third value is the sum of the first two because the third input is the sum of the first two and the projection is linear. Use an unmasked head first so that all three queries can read all three values.
QKᵀ =
[[1, 0, 1],
[0, 1, 1],
[1, 1, 2]]
QKᵀ / sqrt(2) ≈
[[0.7071, 0.0000, 0.7071],
[0.0000, 0.7071, 0.7071],
[0.7071, 0.7071, 1.4142]]
A = row_softmax(QKᵀ / sqrt(2)) ≈
[[0.4011, 0.1978, 0.4011],
[0.1978, 0.4011, 0.4011],
[0.2483, 0.2483, 0.5035]]
Z = AV ≈
[[2.0000, 1.6044],
[2.2033, 1.1978],
[2.2552, 1.5035]]
For The, subtract the row maximum from the three logits to get [0, -1/sqrt(2), 0]. Their exponentials are approximately [1, 0.4931, 1]. Dividing by their sum gives the first weight row. The zero raw score for cat still produces a nonzero weight: a finite logit remains in the softmax denominator and contributes its own positive exponential.
Now multiply the first weight row by the value vectors. The first coordinate is approximately 0.4011×1 + 0.1978×2 + 0.4011×3 = 2.0000. The second is 0.4011×2 + 0.1978×0 + 0.4011×2 = 1.6044. The output has two features because the values have two features. It has one row per query, and each row is computed independently from its own weights.
Now turn on the causal mask. The first query may read only The, so its weight row becomes [1, 0, 0] and its output becomes [1, 2]. The second query keeps its logits for The and cat, giving weights of about [0.3302, 0.6698, 0]. The third query can still see every position in this three-token example, so its result is unchanged. Removing a key changes the weights of the remaining keys because the denominator is recomputed over the permitted positions.
How to Implement Attention in PyTorch and Estimate Its Cost
The code below exposes the scores and weights for inspection. It then checks the output against PyTorch's scaled_dot_product_attention. Using the same projections for both calls isolates any discrepancy to the attention calculation. The first printed matrix shows how the causal mask changes the weights; the second contains the mixed value vectors.
import math
import torch
import torch.nn.functional as F
x = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
w_q = torch.eye(2)
w_k = torch.eye(2)
w_v = torch.tensor([[1., 2.], [2., 0.]])
q, k, v = x @ w_q, x @ w_k, x @ w_v
logits = (q @ k.transpose(-2, -1)) / math.sqrt(q.size(-1))
n = x.size(0)
allowed = torch.ones(n, n, dtype=torch.bool).tril()
masked_logits = logits.masked_fill(~allowed, float("-inf"))
weights = torch.softmax(masked_logits, dim=-1)
z = weights @ v
# Add batch and head axes: [batch, heads, tokens, features].
reference = F.scaled_dot_product_attention(
q[None, None], k[None, None], v[None, None],
is_causal=True, dropout_p=0.0,
)
torch.testing.assert_close(z, reference[0, 0], rtol=1e-5, atol=1e-6)
torch.testing.assert_close(weights.sum(dim=-1), torch.ones(n))
assert torch.all(weights[~allowed] == 0)
print(weights)
print(z)
In batches, a common projected tensor layout is [batch, heads, tokens, features]. Transpose only the last two axes of K when computing scores. Softmax then runs over the last axis of the resulting tensor, which holds the key positions. When combining padding and causal masks, check their broadcasting and boolean conventions. For example, a boolean mask passed as attn_mask to PyTorch's scaled dot product attention uses True for allowed entries, while a boolean key_padding_mask in MultiheadAttention uses True for ignored keys. A manual softmax over a row containing only negative infinity is undefined and yields NaNs. Skip that query or explicitly handle its output.
For dense self attention with n positions, score computation costs O(n²d_k) per head, and mixing values costs O(n²d_v), excluding the input and output projections. A straightforward implementation materialises O(n²) scores or weights per head. Doubling the sequence length at fixed head width quadruples the number of entries in a dense score matrix. Fused implementations can process blocks of scores and avoid storing the entire matrix, which reduces intermediate memory use without eliminating the quadratic arithmetic of dense full-sequence attention.
During generation in large language models, a key-value cache stores earlier keys and values per layer. For a new token, the model computes its projections, adds the new key and value to the cache, and scores the new query against the available keys. It avoids recomputing all earlier projections, but the new query's dense attention work still grows with the number of cached positions it reads. Cache memory also grows with the number of positions retained.
Key Takeaways
- Queries and keys determine the attention scores. Values carry the vectors that the weights combine.
- Divide the logits by
sqrt(d_k)and apply softmax across the keys for each query. - Self attention gets all three projections from one sequence. Cross attention uses a separate source for keys and values.
- A causal mask blocks future positions before softmax, including when all training positions are processed together.
- Multi-head attention computes separate mixtures, then combines the head outputs with a learned projection.
- Dense full-sequence attention has quadratic arithmetic in sequence length. Fused kernels and key-value caching address different costs.
Frequently Asked Questions
Why do queries and keys have the same dimension?
A dot product pairs each query component with the corresponding key component and sums the products. The projected vectors therefore need the same width. Values can use a different width because scoring does not use their components. The value width determines the number of features in the output of a single head.
Is self attention parallel during generation?
Attention can process many known prompt positions in parallel during the initial prompt pass. Once the model begins autoregressive decoding, each new input token depends on the token selected at the preceding step. The matrix operations within a step can still run in parallel, but the model cannot compute the ordinary decoding steps for unknown future tokens all at once.
Can a token attend to itself in causal self attention?
Yes. The standard causal mask includes the diagonal, so the query at a position can read the key and value at that same position. This does not reveal the future token being predicted. In next-token training, the prediction from the current position is evaluated against the token at the next position.
Does a zero attention logit mean a token is ignored?
No. A finite zero logit contributes an exponential of one before normalisation if you write softmax without subtracting the row maximum. Its final weight depends on the other logits in the row. To exclude a position, use a mask that makes its logit effectively negative infinity before softmax, with at least one valid key left in the row.
Does a high attention weight explain the final prediction?
A high weight indicates that a head gave a particular value vector a large coefficient for that query. The final effect also depends on what the vector contains, how the head output is projected, and what later layers do. Use attention weights to inspect a head's mixing pattern, rather than treating them alone as a causal explanation of the model's answer.