AI Wiki中文/EN

Transformer

Attention Is All You Need

Build contextual relationships with attention. Understand matrix shapes, information flow, position, and generation constraints.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Why attention?

The word bank can mean a financial institution or land beside a river. Other words in the sentence help distinguish the two. Attention lets each position use its current representation to assign different weights to other positions, then combine the information they carry. “Attention” names a computation, not evidence of human-like consciousness or subjective attention.

The original 2017 Transformer was an encoder–decoder architecture for sequence transduction. It used attention to handle sequence relationships and was evaluated on machine translation. Many current language models use decoder-only variants, so the original architecture should not be equated with every modern implementation. Original paper

Observe connections between tokensIllustrative values

Each row distributes one query token’s attention across the keys. Every row sums to one.

Open the interactive lab →
These are teaching examples, not measured model outputs or causal explanations.

From intuition to matrix operations

Let X∈Rn×dX\in\mathbb{R}^{n\times d} represent a sequence: nn tokens, each with dimension dd. Three learned projections form queries, keys, and values: Q=XWQQ=XW_Q, K=XWKK=XW_K, and V=XWVV=XW_V. One attention head computes:

A=softmax⁡(QK⊤dk+M),O=AV.A=\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}+M\right),\qquad O=AV.

QK⊤QK^\top has shape n×nn\times n. Row ii compares query ii with every key. Softmax normalizes each row, so its entries sum to one; columns need not sum to one. The optional mask MM adds zero at allowed positions and negative infinity at forbidden positions. During autoregressive training, a position cannot read future tokens without leaking information about prediction targets.

Multi-head attention computes relationships using different projections, concatenates the results, and projects them back to the model dimension. A complete block also uses a feed-forward network, residual connections, and normalization. Attention has no inherent sequence order, so positional encodings or relative-position structures are needed. Models can differ in normalization order, activation functions, and block arrangement.

Standard dense attention takes O(n2dk)O(n^2d_k) computation to construct attention scores, with O(n2)O(n^2) space if the full matrix is stored. Longer context can therefore be expensive. Implementation improvements can reduce memory traffic or avoid materializing the matrix, but that does not establish linear computational complexity for every standard attention operation.

The original architecture has two stacks with different information boundaries:

ComponentInputs it may readWhat it contributes
Encoder self-attentionAll valid source positionsContextual source representations
Decoder self-attentionEarlier target inputs and the current shifted inputAutoregressive target context
Decoder cross-attentionDecoder queries and encoder keys/valuesAccess to source information
Position-wise feed-forward networkOne position at a timeA nonlinear transformation shared across positions

For model width dd, an original-style feed-forward sublayer expands to width dffd_{ff} and returns to dd:

FFN⁡(x)=ReLU⁡(xW1+b1)W2+b2,W1∈Rd×dff,W2∈Rdff×d.\operatorname{FFN}(x)=\operatorname{ReLU}(xW_1+b_1)W_2+b_2,\qquad W_1\in\mathbb R^{d\times d_{ff}},\quad W_2\in\mathbb R^{d_{ff}\times d}.

The 2017 model applies residual addition and layer normalization around each sublayer. Later variants can change their order. The residual requires matching widths; the feed-forward operation does not itself mix token positions. During teacher forcing, a target sequence A, B, EOS is predicted from BOS, A, B. A causal mask alone would not fix an unshifted input that already contains the answer. Original paper, Sections 3.1–3.5

Encoder-only, decoder-only, and encoder–decoder models retain different parts of this structure. Thus a Transformer is more than its attention formula. The encoder–decoder chapter separates the source representation, target conditioning, and stopping rule; the self-attention chapter isolates the masking and permutation properties.

A runnable minimal attention function

This standard-library Python example implements a single attention head and an optional causal mask. It is not a complete Transformer and has no parameter training. For a step-by-step model implementation, see LLMs from Scratch.

import math

def attention(q, k, v, causal=False):
    if not q or not k or not v or not q[0] or not v[0] or len(k) != len(v):
        raise ValueError("nonempty compatible matrices required")
    d, dv = len(q[0]), len(v[0])
    if any(len(row) != d for row in q+k) or any(len(row) != dv for row in v):
        raise ValueError("ragged or incompatible dimensions")
    if any(not math.isfinite(x) for row in q+k+v for x in row):
        raise ValueError("finite matrix entries required")
    if causal and len(q) != len(k):
        raise ValueError("this causal example assumes aligned query/key positions")
    output, weights = [], []
    for i, query in enumerate(q):
        scores = [sum(x*y for x,y in zip(query,key))/math.sqrt(d) for key in k]
        if not all(math.isfinite(s) for s in scores):
            raise ArithmeticError("nonfinite score")
        allowed = [j <= i or not causal for j in range(len(k))]
        peak = max(s for s,ok in zip(scores,allowed) if ok)
        exps = [math.exp(s-peak) if ok else 0.0 for s,ok in zip(scores,allowed)]
        normalizer = sum(exps)
        row = [e/normalizer for e in exps]
        result = [sum(row[j]*v[j][c] for j in range(len(v))) for c in range(dv)]
        if not all(math.isfinite(x) for x in result):
            raise ArithmeticError("nonfinite pooled value")
        weights.append(row)
        output.append(result)
    return output, weights

x = [[1.,0.], [0.,1.], [1.,1.]]
out, weights = attention(x,x,x,causal=True)
assert weights[0] == [1.,0.,0.]
assert all(abs(sum(row)-1) < 1e-12 for row in weights)
changed = x[:2]+[[8.,-3.]]
assert attention(changed,changed,changed,True)[0][:2] == out[:2]
cross,_ = attention([[1.,0.]]*5,[[0.,1.]]*7,[[2.,3.,4.]]*7)
assert len(cross) == 5 and all(len(row) == 3 for row in cross)
assert all(abs(a-b) < 1e-12 for a,b in zip(cross[0],[2,3,4]))
for invalid in [([],x,x), ([[1.]],x,x), (x,x,[[1.],[2.]])]:
    try:
        attention(*invalid)
    except ValueError:
        pass
    else:
        raise AssertionError("invalid shapes accepted")

The example validates nonempty compatible matrices and finite inputs. Its causal mode assumes aligned query/key positions and includes the diagonal; rectangular cross-attention is supported without that mask. For m queries and n keys, pooling and scoring cost O(mn(d_k+d_v)); each softmax denominator is computed once per row. The returned weights occupy O(mn) space. Batches, padding masks, dropout, gradients, and complete Transformer blocks remain outside this teaching function.

Limitations and common misconceptions

Attention weights describe an intermediate computation, not automatically a faithful causal explanation. Values, residual pathways, later layers, and training all influence the output. A large weight on a token alone does not prove that the prediction was caused by that token.

An architecture organizes computation; it does not guarantee factuality, generalization, or safety. Training data, objectives, inference settings, and surrounding tools all matter. A large context capacity also does not guarantee effective use of every part of the context.

Experiments and exercises

  1. If QQ is 5×45\times4, KK is 7×47\times4, and VV is 7×37\times3, what is the output shape? Answer: 5×35\times3.
  2. Why use a causal mask during autoregressive training? Answer: to prevent future tokens from revealing information about prediction targets.
  3. What happens when you lower the experiment’s temperature? Answer: with a unique maximum score, the distribution generally concentrates; equal scores still receive equal probabilities.
  4. Remove positional information and the causal mask, then consistently permute all tokens. What changes? Answer: without other ordering information, self-attention is equivariant to a consistent input permutation and cannot identify the original order by itself.

Research connections

Position representations govern how a model uses order. KV caching and FlashAttention address efficiency, while long-context evaluation tests whether a model actually uses additional input. Distinguish executing the same mathematical operation more efficiently from changing or approximating the operation. Transformer Explainer can expose internal computations of a real model, but a visualization is not by itself a rigorous interpretability conclusion.

Make a prediction, then check

Along which direction is attention normally normalized?

Choose one answer

Learning objectives

  • Track matrix shapes for Q, K, V, attention weights, and outputs.
  • Explain positions, masks, and encoder/decoder variants.

Prerequisites & connections

Explore related knowledge →

References

  1. Attention Is All You Need
    Ashish Vaswani and coauthors · 2017
  2. Build a Large Language Model (From Scratch): code
    Sebastian Raschka · 2024
  3. Transformer Explainer
    Polo Club, Georgia Tech
  4. Dive into Deep Learning — Self-Attention and Positional Encoding
    Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023

Version2 · 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.

  • Moved the softmax denominator outside each row loop to avoid extra cubic work; checked 5×7 cross-attention, future-token intervention, unmasked permutation, and independent softmax values.
  • Checked the original full architecture, feed-forward dimensions, and shifted training; inspected all nine figure values, row sums, and bilingual accessible names.
  • Compared the main claims, assumptions, examples, exercises, and citations across languages; structural checks additionally compare display equations, code, and source IDs. This is an AI technical check, not 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.