Attention

Attention · node type · MatMul, Softmax

Each position builds its output as a weighted average of other positions, weighted by how well they match.

Also called Scaled dot-product attention, Self-attention, SDPA

Each token's query is compared with every key; softmax turns the scaled dot products into weights that mix the values. Pick a row to read one token's attention. The vectors here are hand-made, not from a trained model.
thefoxsawahenthe0.380.080.110.310.12fox0.040.050.830.040.04saw0.020.520.030.020.40a0.380.080.110.310.12hen0.060.070.750.060.06

“fox” attends to

the4%
fox5%
saw83%
a4%
hen4%

score = q · k / √3 × 1.0

Figure 1. Try it: every number is computed in your browser from the formula below.

What it does

Attention compares a query vector from one position with a key vector from every position, using dot products. The scores are scaled, passed through a softmax to become weights that sum to one, and used to average the value vectors. A position can therefore pull in information from anywhere in the sequence in a single step, and which positions it listens to depends on the content, not on fixed distances. In self-attention, queries, keys and values all come from the same sequence; in cross-attention, queries come from one sequence and keys and values from another. In an exported graph it shows up as MatMul, a scale (Div or Mul), an optional mask Add, Softmax, and a second MatMul.

Formula

Attention(Q, K, V) = softmax(Q KT / √d) Vaij = eqi · kj / √d / Σl eqi · kl / √dyi = Σj aij vj

Shapes and parameters

Shapes
Queries [N, Tq, d], keys [N, Tk, d], values [N, Tk, dv]; the weight matrix is [N, Tq, Tk]; output [N, Tq, dv].
Parameters
None in the attention step itself. The learned parameters live in the dense projections that produce Q, K and V (see multi-head attention).
Used for
Every transformer, cross-attention in translation decoders, the point-prompt decoder of SlimSAM, and the tracker in VitTrack.

Figure 2. The typed ports of Attention, in the same format as every model drawing. Letters such as N or C stand for any size.

In WeightSpace

Read-only in WeightSpace today. Transformer models in the catalog are edited at their output heads or at a final normalization; the effect of those edits does not change which positions attend to which.

Where it appears

No model in WeightSpace uses Attention yet; it is here as a reference for how the others work.