AI Wiki中文/EN

Attention mechanisms

注意力机制

Compute query-dependent weighted averages, track query/key/value shapes, and distinguish attention weights from causal explanations.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The question determines which stored information matters

Two stored records carry values 2 and 10. A query gives them scores 0 and log⁡3\log3. Softmax turns those scores into weights 1/41/4 and 3/43/4, so the retrieved value is 2/4+30/4=82/4+30/4=8. Changing the query can change the weights without changing either stored value.

This is the core of soft attention: score candidate information, normalize the scores, and combine the values. The output is usually a mixture, not a single selected item. In translation, different output positions can retrieve different mixtures of source representations. Bahdanau, Cho, and Bengio developed this learned alignment approach in their 2014 preprint, accepted at ICLR 2015. Original paper, Section 3.1

Keys decide relevance; values carry the payload

For a query qq, keys kjk_j, values vjv_j, and score function ss, define:

ej=s(q,kj),αj=exp⁡(ej)∑rexp⁡(er),o=∑jαjvj.e_j=s(q,k_j),\qquad \alpha_j=\frac{\exp(e_j)}{\sum_r\exp(e_r)},\qquad o=\sum_j\alpha_jv_j.

Queries and keys must be compatible with the score function. Values can have another dimension. In exact arithmetic, the nonnegative weights sum to one, so the pooled output lies in the convex hull of the values. Later projections, residual additions, or nonlinear layers need not preserve that property.

A learned additive score can use u⊤tanh⁡(Wqq+Wkkj+b)u^\top\tanh(W_q q+W_k k_j+b). A scaled dot-product score uses q⊤kj/dkq^\top k_j/\sqrt{d_k}. The latter can be computed for all queries as:

Q∈Rm×dk,K∈Rn×dk,V∈Rn×dv,O=softmax⁡rows(QK⊤dk)V.Q\in\mathbb R^{m\times d_k},\quad K\in\mathbb R^{n\times d_k},\quad V\in\mathbb R^{n\times d_v},\qquad O=\operatorname{softmax}_{\mathrm{rows}}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V.

The score matrix has shape m×nm\times n, and the output has shape m×dvm\times d_v. Each row normalizes over keys for one query. Under an illustrative assumption of independent zero-mean unit-variance query and key components, the dot product has variance dkd_k; division by dk\sqrt{d_k} keeps that scale from growing with dimension. Real learned vectors need not satisfy those assumptions exactly. Vaswani et al., Section 3.2

A mask removes forbidden query–key pairs before normalization. A padded key should receive zero weight; the remaining permitted weights must renormalize. Multiplying probabilities by a mask after softmax without renormalization generally changes their sum and the meaning of the output.

A single query is enough to verify the arithmetic

This complete example computes scaled dot-product attention for one query, with explicit shape and mask checks. It uses only permitted scores in the normalizer and returns both output and weights. The opening calculation uses key dimension one, so its scaling factor is one.

import math

def attend(query, keys, values, allowed=None):
    n, dk = len(keys), len(query)
    if not n or not dk or len(values) != n or not values[0]:
        raise ValueError("nonempty matching query/key/value shapes required")
    dv = len(values[0])
    if any(len(k) != dk for k in keys) or any(len(v) != dv for v in values):
        raise ValueError("ragged or incompatible dimensions")
    if any(not math.isfinite(x) for row in [query]+keys+values for x in row):
        raise ValueError("finite inputs required")
    if allowed is None:
        allowed = [True]*n
    if len(allowed) != n or any(type(a) is not bool for a in allowed) or not any(allowed):
        raise ValueError("Boolean mask needs at least one permitted key")
    scores = [sum(q*k for q,k in zip(query,key))/math.sqrt(dk) for key in keys]
    if not all(math.isfinite(s) for s in scores):
        raise ArithmeticError("nonfinite score")
    maximum = max(s for s,a in zip(scores,allowed) if a)
    raw = [math.exp(s-maximum) if a else 0.0 for s,a in zip(scores,allowed)]
    normalizer = sum(raw)
    weights = [r/normalizer for r in raw]
    output = [sum(w*v[d] for w,v in zip(weights,values)) for d in range(dv)]
    if not all(math.isfinite(v) for v in output):
        raise ArithmeticError("nonfinite output")
    return output, weights

output, weights = attend([math.log(3)],[[0],[1]],[[2],[10]])
assert math.isclose(output[0],8)
assert all(math.isclose(a,b) for a,b in zip(weights,[0.25,0.75]))
assert attend([0],[[0],[1]],[[2],[10]])[0] == [6]
assert attend([1],[[0],[1]],[[2],[10]],[True,False]) == ([2.0],[1.0,0.0])
try:
    attend([1],[[0],[1]],[[2],[10]],[False,False])
except ValueError:
    pass
else:
    raise AssertionError("all-masked query accepted")

For mm queries and nn keys, scoring and pooling cost O(mn(dk+dv))O(mn(d_k+d_v)) before any projection costs. Explicitly storing all weights takes O(mn)O(mn) space. This single-query implementation stores O(n+dv)O(n+d_v) additional values beyond its inputs. Implementations that stream blocks or recompute intermediates can change memory usage without changing the mathematical result.

High weight does not establish a cause

A large attention weight says that a value contributes strongly to this particular weighted sum. It does not by itself prove that the corresponding input token caused the final decision. Values can already mix information from many tokens, and other layers and residual paths also affect the output. A causal claim needs an appropriate intervention or analysis, not just a heatmap.

Soft attention can average incompatible values. In the opening example, 8 is neither stored value. That is useful for continuous representations, but a task requiring a discrete record may need a separate decision or retrieval operation. Attention is not automatically an exact database lookup.

Every query must have at least one permitted key. An all-masked row has no categorical distribution; this implementation rejects it. Extremely large input products can overflow even though softmax itself subtracts the maximum. The program checks scores and output for nonfinite values; stable normalization cannot repair an earlier overflow.

Predict the weighted result

  1. If both opening scores are zero, what is the output? Answer: equal weights give 6.
  2. If the second record is masked, what is the output? Answer: 2, with weights [1,0][1,0].
  3. For five queries, seven keys, and value width three, what is the output shape? Answer: 5×35\times3; the weight matrix is 5×75\times7.
  4. Must keys and values have the same width? Answer: no. Keys match queries for scoring; values determine the output width.

A computation used in several architectures

Self-attention draws queries, keys, and values from the same sequence. Cross-attention draws queries from one stream and keys and values from another. Multi-head attention learns several projected versions of the computation and combines their outputs. These choices build on the pooling operation but do not replace the need to specify masks, tensor dimensions, and the role of each stream.

Make a prediction, then check

Values are 2 and 10 with weights 1/4 and 3/4. What is the pooled output?

Choose one answer

Learning objectives

  • Calculate query/key/value scores, normalization, and weighted outputs by hand.
  • Check dimensions and masks, and explain why attention weights do not directly establish causation.

Prerequisites & connections

Explore related knowledge →

References

  1. Neural Machine Translation by Jointly Learning to Align and Translate (v7; first preprint 2014, ICLR 2015)
    Dzmitry Bahdanau; Kyunghyun Cho; Yoshua Bengio · 2014
  2. Attention Is All You Need
    Ashish Vaswani and coauthors · 2017

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Recalculated outputs 8, 6, and 2; checked 30 log-integer score sets against exact rational weights for three-dimensional pooling and masks.
  • Checked Q/K/V dimensions, the independent unit-variance scaling illustration, normalization order, and all-masked rejection; moved the denominator outside the weight loop to preserve linear normalization cost.
  • Compared bilingual arguments, conditions, examples, and exercise answers; structural checks separately compare formulas, code, sections, and references. No independent human peer review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.