Octonote AI
Make your own →

Self-attention in one page

Sunil Tiwari · Oct 12, 2026 · 6 min read

Queries, keys and values, scaled dot-product attention, and why the √d scaling matters — with NumPy code.

Self-attention lets every token in a sequence look at every other token and decide how much each one matters for its own new representation. It is the operation at the heart of every Transformer, from BERT to the largest language models. The whole idea fits in one equation, and this page walks through it piece by piece.

The problem it solves

Take the sentence "the animal didn't cross the street because it was too tired". To understand it, a model has to connect it back to animal, six words earlier. Recurrent networks pass information along one step at a time, so long-range links fade. Self-attention connects every pair of positions directly, in a single step, and lets the model learn which connections are useful.

Queries, keys and values

Each token arrives as an embedding xix_i, a vector of dmodeld_{\text{model}} numbers. Self-attention projects it three ways with learned matrices:

qi=xiWQ,ki=xiWK,vi=xiWVq_i = x_i W_Q, \qquad k_i = x_i W_K, \qquad v_i = x_i W_V

Each projection plays a different role:

  • Query qiq_i: what this token is looking for.
  • Key kik_i: what this token offers to others who are looking.
  • Value viv_i: the information this token hands over if it is chosen.

The split matters. A token can advertise one thing (its key) while passing on something richer (its value). Search engines work the same way: your query is matched against page titles, but what you read is the page.

The whole computation

Stack the token vectors into matrices QQ, KK and VV (one row per token) and the entire layer is:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V
Scaled dot-product self-attention
Scaled dot-product self-attention

Read it from the inside out:

  1. Scores. QK⊤QK^{\top} is an n×nn \times n matrix. Entry (i,j)(i, j) is the dot product qi⋅kjq_i \cdot k_j: how well token jj's key matches token ii's query.
  2. Scale. Divide every score by dk\sqrt{d_k}, where dkd_k is the length of the key vectors. The next section explains why.
  3. Mask (decoders only). Set scores for future positions to −∞-\infty.
  4. Softmax. Apply softmax to each row, so row ii becomes a probability distribution Pi,⋅P_{i,\cdot} over all tokens.
  5. Mix. Multiply by VV. Token ii's output is a weighted average of every value vector: zi=∑jPij vjz_i = \sum_j P_{ij}\, v_j.

One query, worked through

Follow a single token. In "the cat sat", suppose the query for sat produces scaled scores of 0.3, 2.5 and 2.6 against the keys of the, cat and sat. Softmax turns them into weights:

softmax⁡(0.3, 2.5, 2.6)=(e0.3, e2.5, e2.6)e0.3+e2.5+e2.6≈(0.05, 0.45, 0.50)\operatorname{softmax}(0.3,\ 2.5,\ 2.6) = \frac{(e^{0.3},\ e^{2.5},\ e^{2.6})}{e^{0.3} + e^{2.5} + e^{2.6}} \approx (0.05,\ 0.45,\ 0.50)
One query: how "sat" reads "the cat sat"
One query: how "sat" reads "the cat sat"

The new representation of sat is 0.05 vthe+0.45 vcat+0.50 vsat0.05\,v_{\text{the}} + 0.45\,v_{\text{cat}} + 0.50\,v_{\text{sat}}. It is mostly about itself and its subject, with almost nothing from the article. Nothing in the code says "verbs should look at their subjects". The model learns WQW_Q and WKW_K so that such patterns produce high scores.

Why divide by √dₖ?

Suppose the components of qq and kk are independent, with mean 0 and variance 1. Each product qjkjq_j k_j then has variance 1, and the dot product sums dkd_k of them:

Var⁡(q⋅k)=∑j=1dkVar⁡(qjkj)=dk\operatorname{Var}(q \cdot k) = \sum_{j=1}^{d_k} \operatorname{Var}(q_j k_j) = d_k

With dk=64d_k = 64, raw scores have a standard deviation of 8. Softmax over numbers that far apart is nearly one-hot: one weight close to 1, the rest close to 0. In that regime the gradients of softmax are tiny and learning stalls. Dividing by dk\sqrt{d_k} brings the variance back to 1 and keeps the softmax in its responsive range.

Multi-head attention

One attention pattern per layer is limiting. A token may need to track its syntactic head, the entity it refers to and its neighbours, all at once. Multi-head attention runs hh attentions in parallel, each with its own projections into a smaller space of size dk=dmodel/hd_k = d_{\text{model}} / h:

headi=Attention⁡(XWQ(i), XWK(i), XWV(i))\text{head}_i = \operatorname{Attention}(X W_Q^{(i)},\ X W_K^{(i)},\ X W_V^{(i)})
MultiHead⁡(X)=Concat⁡(head1,…,headh) WO\operatorname{MultiHead}(X) = \operatorname{Concat}(\text{head}_1, \dots, \text{head}_h)\, W_O
Multi-head attention
Multi-head attention

Because each head works in dmodel/hd_{\text{model}}/h dimensions, eight heads cost about the same as one full-width head. The output projection WOW_O mixes what the heads found back into a single vector per token.

Causal masking

A language model that predicts the next token must not peek at it. Decoders add a mask MM before the softmax, with Mij=0M_{ij} = 0 when j≤ij \le i and Mij=−∞M_{ij} = -\infty when j>ij > i:

softmax⁡ ⁣(QK⊤dk+M)V\operatorname{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}} + M\right) V

Since e−∞=0e^{-\infty} = 0, masked positions get exactly zero weight. Each token attends only to itself and the tokens before it.

Causal mask: each token sees only the past
Causal mask: each token sees only the past

Encoders such as BERT skip the mask and let every token see the whole sequence.

Where it sits in a Transformer

Self-attention is one of two sublayers in each Transformer block. Attention moves information between tokens. A feed-forward network then processes each token on its own. Both are wrapped in a residual connection and layer normalisation, so a block can refine its input without having to rebuild it.

Where attention sits in a Transformer block
Where attention sits in a Transformer block

The figure shows the pre-norm arrangement used by most modern models. The original 2017 Transformer applied LayerNorm after each residual addition instead.

In NumPy

The whole layer, including the optional causal mask, is a dozen lines:

import numpy as np

def softmax(x, axis=-1):
    x = x - x.max(axis=axis, keepdims=True)   # numerical stability
    e = np.exp(x)
    return e / e.sum(axis=axis, keepdims=True)

def self_attention(X, Wq, Wk, Wv, causal=False):
    Q, K, V = X @ Wq, X @ Wk, X @ Wv
    scores = Q @ K.T / np.sqrt(K.shape[-1])   # (n, n)
    if causal:
        n = scores.shape[0]
        future = np.triu(np.ones((n, n), dtype=bool), k=1)
        scores = np.where(future, -np.inf, scores)
    weights = softmax(scores)                 # each row sums to 1
    return weights @ V, weights

The cost

Every token compares itself with every other token, so the score matrix has n2n^2 entries. Time is O(n2d)O(n^2 d) and memory for the weights is O(n2)O(n^2) per head. Doubling the context length quadruples the work, which is why long contexts are expensive and why techniques such as FlashAttention (exact attention computed in tiles, never storing the full matrix) and sparse or sliding-window attention exist.

Key takeaways

IdeaIn one line
Queries, keys, valuesThree learned views of each token: what it seeks, offers and gives.
ScoresQK⊤QK^{\top} compares every query with every key.
ScalingDividing by dk\sqrt{d_k} keeps softmax out of its flat, low-gradient regions.
SoftmaxTurns each row of scores into weights that sum to 1.
OutputEach token becomes a weighted average of all value vectors.
Multi-headSeveral smaller attentions in parallel, each free to learn its own pattern.
Causal mask−∞-\infty on future positions so decoders cannot look ahead.
Make a page like this. Free.Notes and diagrams side by side, written by you or by Claude Code and Codex. Publish it in one click.
Make your own, free