Skip to content

By John Martin

  • ai
  • attention
Cover illustration: three matrices meeting at a softmax curve

Attention, from vectors to probabilities

Every transformer article assumes you already know scaled dot-product attention. This one does not. We build the equation from three plain vectors, watch each symbol earn its place, and end at the exact form used in the original paper.

Three vectors walk into a layer

For a single query, attention compares:

  • a query vector q∈Rdkq \in \mathbb{R}^{d_k} - what this position is looking for;
  • a key vector k∈Rdkk \in \mathbb{R}^{d_k} - what each position offers;
  • a value vector v∈Rdvv \in \mathbb{R}^{d_v} - what each position contributes.

The raw match score is a dot product, which is just a similarity meter:

score(q,k)=q⋅k=∑i=1dkqiki\text{score}(q, k) = q \cdot k = \sum_{i=1}^{d_k} q_i k_i

Dividing by dk\sqrt{d_k} keeps the variance of the score stable as vectors grow

  • without it, long vectors push the softmax into regions with vanishing gradients.

From scores to a probability distribution

The softmax turns raw scores into weights that sum to one:

Attention(q,K,V)=∑jsoftmaxj ⁣(qkj⊤dk)vj\text{Attention}(q, K, V) = \sum_j \text{softmax}_j\!\left(\frac{q k_j^\top}{\sqrt{d_k}}\right) v_j

In matrix form for a whole sequence at once:

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V

That is the entire operation. Multi-head attention runs it hh times in parallel subspaces and concatenates the results.

The natural follow-up is why sequences need positional information once attention is permutation-invariant - that article lands later in this series.

Series: LLM foundations

← All posts

Related posts