Skip to content
MAMasterAI Now

Deep Learning4 Min. Lesezeit

What Is Self-Attention in Transformers?

Diese Antwort wurde noch nicht ins Deutsch übersetzt; du liest daher das englische Original.

Die kurze Antwort

Self-attention is the operation that lets each token in a sequence look at the other tokens and build a new representation from them. Every token produces a query, a key and a value; the query is compared with all keys to score relevance, those scores become weights via softmax, and the weights average the values. The result is a context-aware vector for each position.

The intuition: every token asks a question

Read “The animal did not cross the street because it was too tired.” What does “it” refer to? You resolve it by looking back at the other words and weighting the evidence. Self-attention is a learned, differentiable version of that lookup.

Each token emits three vectors. The query encodes what this token is looking for. The key encodes what a token offers as a match. The value carries the content passed along if the match is good. A token compares its query with every key, turns the similarities into weights, and mixes the values accordingly.

NoteSelf-attention is within one sequence

“Self” means queries, keys and values all come from the same sequence. Cross-attention, used in encoder–decoder models, takes queries from one sequence and keys/values from another.

The scaled dot-product formula

Stack the token vectors into matrices Q, K and V. The attention output is:

Attention(Q, K, V) = softmax(QKᵀ / √dₖ) V
dₖ is the dimension of each query/key. Dividing by √dₖ stops dot products from growing with dimension, which would push softmax into saturation.

The product QKᵀ holds raw relevance scores: one row per token, one column per token it can see. Softmax is applied per row, so each token’s weights sum to one. Multiplying by V then produces a weighted average of value vectors — the new representation for that position.

MatrixShapeMeaning
Qsequence × dₖWhat each token is looking for
Kᵀdₖ × sequenceWhat each token offers
QKᵀsequence × sequenceRaw pairwise relevance scores
softmax(…)Vsequence × dᵥMixed context per token

Causal masks and multiple heads

A language model that generates left to right must not see future tokens during training. A causal mask sets the scores above the diagonal to negative infinity before the softmax, so position 4 can attend to positions 1–4 but never to 5. Encoder models such as BERT omit that mask and attend in both directions.

One attention pattern is limiting, so transformers run several heads in parallel with separate projections. Each head can specialise — one may track nearby syntax, another may link pronouns to nouns — and their outputs are concatenated and projected back to the model width. The heads are not assigned roles by hand; the specialisation emerges from training.

A toy row of attention weights might be [0.10, 0.70, 0.20]: the current token puts 70% of its read on one earlier token. The demonstration below recomputes a full matrix as you toggle the causal mask and change the softmax temperature.

What it costs, and what it does not do

The score matrix has one entry per pair of tokens, so attention scales quadratically with sequence length. Doubling the context window roughly quadruples that part of the compute, and the KV cache grows linearly with the number of tokens. This is the practical reason long-context inference is expensive rather than free.

Attention weights are not a complete explanation. A high weight means a value vector was mixed in heavily; it does not prove that the model’s decision was caused by that token, because later layers, residual streams and MLPs all transform the representation again. Treat attention maps as a useful diagnostic, not a receipt.

Self-attention also has no memory between requests. Everything a model “remembers” about your conversation is text placed back into the prompt, which is why context limits and prompt structure matter so much. For how those vectors are first produced, see “What is an embedding in AI?”

Inspect a small attention matrix

A deterministic toy attention computation over a short sentence. Pick a row, toggle the causal mask, and change the temperature to see the weights sharpen or blur.

Masking
Tokens
12
Peak attention weight
1.000
Head
h0 · layer 1
Masked cells
66
Attention weights — rows query, columns key
thetiranididnotcrothestrbecitwastoo
Where “animal” looks
the
0.270
tired
0.358
animal
0.372
did
0.000
not
0.000
cross
0.000
the
0.000
street
0.000
because
0.000
it
0.000
was
0.000
too
0.000

Toggle the causal mask and note the black triangle in the top-right: those are the future positions a decoder must never see. Now raise the softmax temperature above 2 and watch the row collapse into a near-uniform blur — that is attention losing its focus.

Runs entirely in your browser — nothing you change here is sent anywhere.

Im Kurs tiefer einsteigen

Diese Stufen vermitteln dieselbe Idee mit einem vollständigen Lesetext und einer Live-Simulation.