QuiddityML

By · 10 November 2026 · 15 min read

Self-attention explained step by step: queries, keys, and values

How to compute self-attention by hand on a three-token sentence, why the scores are divided by the square root of the key size, and how to write it in PyTorch.

Self-attention is the operation that lets each token in a sequence build a new representation of itself as a weighted blend of the tokens in the same sequence. It is the main operation inside a transformer, the architecture behind GPT-style language models. Models read tokens, which can be whole words or pieces of words, and the example here uses three short words as its tokens.

Where self-attention comes from

Attention first appeared inside RNN encoder-decoder models. The encoder reads the input and produces one state vector per input token. The decoder writes the output one token at a time. At each step it scores every encoder state against its own current state, turns the scores into weights with softmax, and adds up the encoder states using those weights. The result is one context vector for that step, and what is attention in deep learning works through that version with numbers.

Self-attention keeps the same three steps and changes who runs them. Every position in a sequence runs the recipe over the sequence it belongs to, so the sequence attends to itself. The vectors that get added up in the last step are called value vectors, and they are defined further down.

Top: the recipe of score token representations, softmax weights and weighted sum of value vectors. Middle: in RNN attention one decoder state runs the recipe over the encoder states e1 to e4 to build one context vector. Bottom: now every position of the, cute, axolotl runs the recipe over the same sequence, which is why it is called self-attention.

What self-attention does

Take the sentence the cute axolotl. Each position asks the same question about the others: which token representations in this same sequence are useful for updating me? The answer comes back as one weight per position, and the position's new vector is the blend those weights describe.

The token the, highlighted as the asking position, points to itself, to cute and to axolotl. Every position looks at the positions it is allowed to see in the sequence, including itself, and asks which token representations are useful for updating it.

A model that generates text adds a mask that hides later tokens from earlier ones, which is why the picture says "allowed to see". This post leaves the mask out, so all three positions see each other.

From words to vectors

Attention works on vectors, so the text has to become numbers first. A tokenizer turns text into integer ids. With a tiny made-up tokenizer that maps the to 4, cute to 7 and axolotl to 9, the sentence becomes:

$$[\text{the},\ \text{cute},\ \text{axolotl}] \mapsto [4, 7, 9]$$

An embedding table then maps each id to a vector of numbers, called its features. The vector can have any length, and 768 is a common size. This example uses 6 features so the arithmetic fits on the page:

$$\begin{aligned} 4\ (\text{the}) &\mapsto [1, -1, 2, 0, 1, -2] \\ 7\ (\text{cute}) &\mapsto [0, 2, -1, 1, -3, 1] \\ 9\ (\text{axolotl}) &\mapsto [2, 1, 0, -1, 1, 3] \end{aligned}$$

Stacking the three vectors in sentence order gives the input matrix $X$:

$$X = \begin{bmatrix} 1 & -1 & 2 & 0 & 1 & -2 \\ 0 & 2 & -1 & 1 & -3 & 1 \\ 2 & 1 & 0 & -1 & 1 & 3 \end{bmatrix}$$

$X$ has one row per token and one column per feature. Its shape is $T \times d_{model} = 3 \times 6$, where $T$ is the number of tokens and $d_{model}$ is the number of features per token.

The tokens the, cute and axolotl map to ids 4, 7 and 9. The embedding grid gives each id its 6-number vector, a table lists each token with its id and its position 0, 1 or 2, and the three rows stack into X with shape 3 × 6.

The formula in three lines

Self-attention is usually written in three stages:

$$S = \frac{QK^\top}{\sqrt{d_k}}$$

$$A = \operatorname{softmax}(S)$$

$$\operatorname{Attention}(Q, K, V) = AV$$

Here $Q$, $K$ and $V$ are three matrices computed from $X$. They are called the queries, the keys and the values. $QK^\top$ makes the raw scores and dividing by $\sqrt{d_k}$ scales them. Softmax turns each row of scores into probabilities: it raises $e$ to the power of each score and divides by the total, so the results are positive and add up to 1. Multiplying by $V$ then blends the value vectors. The sections below build each piece with numbers.

The full equation Attention(Q, K, V) = softmax(QK transpose over the square root of d_k) V, followed by its parts: QK transpose makes raw scores, the square root of d_k scales the scores, softmax turns scores into probabilities and V blends value vectors.

Queries, keys and values

From the same input vectors the model makes three new versions. Each comes from multiplying $X$ by its own matrix:

$$Q = XW_Q \qquad K = XW_K \qquad V = XW_V$$

$W_Q$, $W_K$ and $W_V$ are weight matrices the model learns. They start as random numbers and training adjusts them. $Q$, $K$ and $V$ are computed from $X$ on every forward pass.

The same starting vectors X go through W_Q, W_K and W_V to give Q (queries), K (keys) and V (values), three learned projections of the same input vectors.

Their shapes

The sizes of the outputs are separate choices. $d_k$ is the number of features in each query and key vector, and $d_v$ is the number in each value vector. Neither has to equal $d_{model}$, and this example sets both to 5 to make that visible. Each projection matrix then has shape $6 \times 5$, and each of $Q$, $K$ and $V$ has shape $3 \times 5$.

The number of rows stays 3 because there are still three tokens. Only the number of features per token changes, from 6 to 5. Queries and keys need the same number of features because they get multiplied together feature by feature. Values can use a different size.

X with shape 3 × 6 is multiplied by W_Q, W_K and W_V, each 6 × 5, to give Q, K and V, each 3 × 5. A side card lists T = 3, d_model = 6, d_k = 5 and d_v = 5, and notes that W_Q, W_K and W_V are trainable while Q, K and V are computed.

Computing them

Matrix multiplication works one row at a time. The query for the is its row of $X$ times $W_Q$:

$$q_{the} = x_{the}W_Q \qquad x_{the} = [1, -1, 2, 0, 1, -2]$$

Each of the five numbers in $q_{the}$ is the dot product of $x_{the}$ with one column of $W_Q$, which means multiplying matching entries and adding them up. In this example the first column of $W_Q$ is $[-1.2, 1.1, 0.4, -1.5, 1.1, -0.5]$, so:

$$\begin{aligned} q_{the,1} &= 1(-1.2) + (-1)(1.1) + 2(0.4) \\ &\quad + 0(-1.5) + 1(1.1) + (-2)(-0.5) \\ &= 0.6 \end{aligned}$$

The other four columns give the other four numbers, so $q_{the} = [0.6, 1.7, 1.3, -3.2, 4.2]$. Doing the same for cute and axolotl fills in $Q$, and $W_K$ and $W_V$ produce $K$ and $V$ the same way:

$$Q = \begin{bmatrix} 0.6 & 1.7 & 1.3 & -3.2 & 4.2 \\ -3.5 & -2.7 & -7.0 & 3.2 & -2.9 \\ -0.2 & 0.1 & 5.7 & 1.4 & -0.4 \end{bmatrix}$$

$$K = \begin{bmatrix} -1.2 & -6.8 & 2.2 & -3.6 & -0.6 \\ -2.2 & 3.4 & -0.6 & 3.4 & 1.7 \\ 3.3 & 2.0 & -1.8 & 6.2 & 4.6 \end{bmatrix}$$

$$V = \begin{bmatrix} 3.8 & -0.1 & -0.9 & -2.2 & 4.6 \\ 0.7 & 4.6 & 2.9 & 3.0 & -8.2 \\ -1.8 & 3.7 & -8.6 & -0.8 & -4.5 \end{bmatrix}$$

The rows are in sentence order, so the first row of each matrix belongs to the, the second to cute and the third to axolotl.

q_the = x_the W_Q with x_the = [1, -1, 2, 0, 1, -2]. One coordinate is one dot product: the first gives 0.6 and the second gives 1.7. The full q_the is [0.6, 1.7, 1.3, -3.2, 4.2], and Q has shape 3 × 5. K and V come from the same kind of multiplication with different learned matrices.

Scores: every query against every key

A score is one number that says how much one token should attend to another. It is the dot product of the asking token's query with the other token's key, and a larger score means a stronger match. All the scores at once are a single matrix product:

$$\text{scores} = QK^\top$$

$K^\top$ is $K$ transposed, with rows turned into columns, so its shape is $5 \times 3$. A $3 \times 5$ matrix times a $5 \times 3$ matrix gives a $3 \times 3$ matrix, one score for each pair of positions.

Q with shape 3 × 5 times K transpose with shape 5 × 3 gives scores with shape 3 × 3. Each of the 3 positions gets one score for each of the 3 positions it can attend to.

Take the row for the. Its query is compared with each of the three keys:

$$\begin{aligned} q_{the} \cdot k_{the} &= 0.6(-1.2) + 1.7(-6.8) + 1.3(2.2) \\ &\quad + (-3.2)(-3.6) + 4.2(-0.6) = -0.42 \end{aligned}$$

The same arithmetic with the keys of cute and axolotl gives $-0.06$ and $2.52$. So the score row for the is $[-0.42, -0.06, 2.52]$, and its query matches the key of axolotl far more than the other two.

The query for the, [0.6, 1.7, 1.3, -3.2, 4.2], dotted with the keys of the, cute and axolotl gives -0.42, -0.06 and 2.52. The first score is expanded term by term. The score row for the is [-0.42, -0.06, 2.52], raw match scores before softmax.

Doing the same for every query gives the full score matrix. Row 1 holds the scores for updating the, row 2 for cute and row 3 for axolotl:

$$\text{scores} = \begin{bmatrix} -0.42 & -0.06 & 2.52 \\ -2.62 & 8.67 & 2.15 \\ 7.30 & 1.44 & -3.88 \end{bmatrix}$$

These are match numbers. They can be negative and their rows do not add up to anything in particular, so they are not probabilities yet.

The 3 × 3 score matrix with rows and columns labelled the, cute and axolotl. Each row is read as the scores for updating that token, and the scores are only match numbers, not probabilities yet.

Scaling by the square root of $d_k$

Before softmax, every score is divided by $\sqrt{d_k}$. Here $d_k = 5$ and $\sqrt{5} \approx 2.24$, so the row for the changes from $[-0.42, -0.06, 2.52]$ to:

$$[-0.19, -0.03, 1.13]$$

The shape stays $3 \times 3$. Only the size of the numbers changes.

QK transpose over the square root of d_k. The shape stays 3 × 3 before and after scaling. With d_k = 5 the square root is about 2.24, and the score row for the changes from [-0.42, -0.06, 2.52] to [-0.19, -0.03, 1.13].

Why the square root

A dot product of two vectors with $d_k$ features adds up $d_k$ products. Variance measures how far numbers spread from their mean. If every query and key feature has mean 0 and variance 1, each product $q_i k_i$ also has mean 0 and variance 1. Adding $d_k$ of them gives a variance of about $d_k$:

$$\mathrm{Var}(q \cdot k) \approx d_k$$

The typical size of a score is the square root of that, about $\sqrt{d_k}$. With $d_k = 64$, raw scores are about 8 times larger than with a single feature. Dividing by $\sqrt{d_k}$ brings the variance back to 1:

$$\mathrm{Var}\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = \frac{d_k}{d_k} = 1$$

Dividing by $d_k$ itself would push the variance down to $1/d_k$ and flatten every row of scores. A quick check with random vectors:

1import torch
2 
3torch.manual_seed(0)
4for d_k in (5, 64):
5    q = torch.randn(10000, d_k)
6    k = torch.randn(10000, d_k)
7    dots = (q * k).sum(dim=-1)
8    scaled = dots / d_k ** 0.5
9    print(d_k, round(dots.var().item(), 1), round(scaled.var().item(), 2))
15 5.1 1.01
264 63.6 0.99

The raw variance comes out close to $d_k$ and the scaled variance close to 1.

Large scores are a problem because of what they do to softmax. Take $d_k = 4$ and the raw scores $s = [-2, 0, 4]$. Softmax gives $[0.002, 0.018, 0.980]$, which puts almost all the probability on one position. Dividing by $\sqrt{4} = 2$ first gives $[-1, 0, 2]$ and a softmax of $[0.042, 0.114, 0.844]$, where the top position still leads and the other two keep some weight. A softmax that close to all-or-nothing passes almost no gradient back, and the gradient is the signal training uses to adjust the weights. The attention pattern then stops improving.

Four panels. A dot product adds one product per feature, 5 products with d_k = 5 and 64 with d_k = 64. The variance grows with d_k. Dividing by the square root brings the standard deviation back to 1. With d_k = 4 the unscaled scores [-2, 0, 4] give softmax [0.002, 0.018, 0.980], and the scaled scores [-1, 0, 2] give [0.042, 0.114, 0.844], drawn as bar charts.

Softmax: from scores to attention weights

Softmax runs on each row of scaled scores separately. For the row of the:

$$e^{-0.19} \approx 0.83 \qquad e^{-0.03} \approx 0.97 \qquad e^{1.13} \approx 3.10$$

These add up to about 4.89. Dividing each by 4.89 gives the attention weights for the:

$$[0.17,\ 0.20,\ 0.63]$$

They say how much the uses each position's value vector: 17% from the, 20% from cute and 63% from axolotl.

softmax of QK transpose over the square root of d_k keeps the 3 × 3 shape. The scaled score row for the, [-0.19, -0.03, 1.13], becomes the attention weights [0.17, 0.20, 0.63]: 17% the, 20% cute and 63% axolotl.

Every row gets its own weights, so the weights form a $3 \times 3$ matrix $A$. Rows are the positions being updated and columns are the positions whose values get used:

$$A = \begin{bmatrix} 0.17 & 0.20 & 0.63 \\ 0.01 & 0.94 & 0.05 \\ 0.93 & 0.07 & 0.01 \end{bmatrix}$$

Each row adds up to 1, up to rounding. cute puts almost all its weight on itself, and axolotl puts almost all of its weight on the.

The attention weight matrix A, with query positions the, cute and axolotl as rows and value positions as columns, also shown as a heatmap. Each row sums to about 1 and tells one token position how to blend the sequence's value vectors.

Blending the value vectors

The weights are not the output. They say how to blend the value vectors, and the blend is the output:

$$\operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$

$A$ is $3 \times 3$ and $V$ is $3 \times 5$, so $AV$ is $3 \times 5$. For the, the output is its three weights times the three rows of $V$:

$$\begin{aligned} &0.17\,[3.8, -0.1, -0.9, -2.2, 4.6] \\ +\ &0.20\,[0.7, 4.6, 2.9, 3.0, -8.2] \\ +\ &0.63\,[-1.8, 3.7, -8.6, -0.8, -4.5] \end{aligned}$$

Using the unrounded weights 0.1695, 0.1991 and 0.6313, the sum is:

$$[-0.35,\ 3.24,\ -5.00,\ -0.28,\ -3.69]$$

That is the new representation of the, with 5 features. It is mostly the value vector of axolotl, because axolotl got 63% of the weight. cute and axolotl get their own outputs from their own rows of $A$, and together the three rows form the $3 \times 5$ output.

Each unrounded weight, 0.1695, 0.1991 and 0.6313, multiplies one value vector. The three weighted parts add up to the output vector for the, [-0.35, 3.24, -5.00, -0.28, -3.69], with shape (5,).

Why they are called query, key and value

The names come from the job each vector does in the formula. The query is the vector a position asks with. For the that is $q_{the}$, the vector that produced the score row $[-0.42, -0.06, 2.52]$. The key is the vector each position is compared against, so $q_{the}$ was scored against $k_{the}$, $k_{cute}$ and $k_{axolotl}$. The value is the content that gets carried into the output. Once the weights were known, only the rows of $V$ went into the blend.

All three are computed from the same $X$. What separates them is where they enter the equation.

Query, the vector that asks: q_the produces the scores -0.42, -0.06 and 2.52. Key, what gets matched: q_the is compared against k_the, k_cute and k_axolotl. Value, what gets carried: the weights 0.17, 0.20 and 0.63 blend the value rows into [-0.35, 3.24, -5.00, -0.28, -3.69].

The full formula

Putting the pieces together:

$$Q = XW_Q \qquad K = XW_K \qquad V = XW_V$$

$$\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V$$

Read from the inside out: $QK^\top$ gives the scores, dividing by $\sqrt{d_k}$ scales them, softmax turns them into weights and the weights blend the rows of $V$. In the running example $X$ is $3 \times 6$, then $Q$, $K$ and $V$ are $3 \times 5$, then the scores and $A$ are $3 \times 3$ and the output $AV$ is $3 \times 5$. This is also called scaled dot-product attention.

The projections Q = XW_Q, K = XW_K and V = XW_V, then Attention(Q, K, V) = softmax(QK transpose over the square root of d_k) V. Read slowly: QK transpose gives scores, then scale, then probabilities, then a weighted sum of V. Shape summary: X is 3 × 6, Q, K and V are 3 × 5, QK transpose and A are 3 × 3 and AV is 3 × 5.

Where the learning happens

Nothing in the formula itself is learned. The trainable parameters are $W_Q$, $W_K$ and $W_V$. They start as random weights like the embedding table and the output layer, the layer that turns the model's final vectors into next-token predictions. During training, backpropagation works out how each weight should change to reduce the loss, and it updates the embedding table and the three projection matrices together.

An untrained model might give the almost flat raw scores such as $[0.02, 0.00, -0.01]$. After scaling and softmax those become almost even weights, $[0.34, 0.33, 0.33]$, and the output is close to a plain average of the three value vectors. The projections in the running example gave $[-0.42, -0.06, 2.52]$ and weights of $[0.17, 0.20, 0.63]$ instead. Training changes the vectors, the changed vectors give changed scores, and the changed scores give changed weights.

The embedding table, W_Q, W_K and W_V are marked trainable. The token ids look up X, and Q = XW_Q, K = XW_K and V = XW_V are computed from X. Backpropagation from the loss updates the embedding table and all three projection matrices together.

Self-attention in PyTorch

The code has two pieces. A projection layer holds $W_Q$, $W_K$ and $W_V$ and uses them to make the queries, keys and values from x. A function then takes those three tensors and runs the formula. In equations they are written $Q$, $K$ and $V$, and in PyTorch code the same tensors are usually named q, k and v.

Piece 1, the projection layer: the same x enters three lanes through W_Q, W_K and W_V to give q, k and v, which are passed into piece 2, the reusable function scaled_dot_product_attention(q, k, v).

The function first, checked against the numbers worked out above:

1import torch
2 
3Q = torch.tensor([[ 0.6,  1.7,  1.3, -3.2,  4.2],
4                  [-3.5, -2.7, -7.0,  3.2, -2.9],
5                  [-0.2,  0.1,  5.7,  1.4, -0.4]])
6K = torch.tensor([[-1.2, -6.8,  2.2, -3.6, -0.6],
7                  [-2.2,  3.4, -0.6,  3.4,  1.7],
8                  [ 3.3,  2.0, -1.8,  6.2,  4.6]])
9V = torch.tensor([[ 3.8, -0.1, -0.9, -2.2,  4.6],
10                  [ 0.7,  4.6,  2.9,  3.0, -8.2],
11                  [-1.8,  3.7, -8.6, -0.8, -4.5]])
12 
13 
14def scaled_dot_product_attention(q, k, v):
15    d_k = q.size(-1)
16    scores = q @ k.transpose(-2, -1)
17    scores = scores / (d_k ** 0.5)
18    weights = torch.softmax(scores, dim=-1)
19    out = weights @ v
20    return out, weights
21 
22 
23out, weights = scaled_dot_product_attention(Q, K, V)
24print(weights.round(decimals=2))
25print(out[0].round(decimals=2))
1tensor([[0.1700, 0.2000, 0.6300],
2        [0.0100, 0.9400, 0.0500],
3        [0.9300, 0.0700, 0.0100]])
4tensor([-0.3500,  3.2400, -5.0000, -0.2800, -3.6900])

The printed weights match $A$ and the first output row matches the hand-computed vector for the. k.transpose(-2, -1) swaps the last two axes, so the same line works on one sequence of shape (T, d_k) and on a batch of shape (B, T, d_k). dim=-1 makes softmax run along each row, over the keys. The function returns the weights as well as the output so they can be inspected.

For the projections, one option is three nn.Linear layers named q_proj, k_proj and v_proj. Many implementations pack all three into one bigger layer instead and split its output with chunk. This version sets $d_k = d_v = d_{model}$, so q, k and v keep the feature size of x. It uses scaled_dot_product_attention from the block above:

1import torch.nn as nn
2 
3 
4class SelfAttention(nn.Module):
5    def __init__(self, d_model):
6        super().__init__()
7        self.qkv_proj = nn.Linear(
8            in_features=d_model,
9            out_features=3 * d_model,
10        )
11 
12    def forward(self, x):
13        qkv = self.qkv_proj(x)
14        q, k, v = qkv.chunk(3, dim=-1)
15        return scaled_dot_product_attention(q, k, v)
16 
17 
18torch.manual_seed(0)
19attn = SelfAttention(d_model=6)
20x = torch.randn(2, 3, 6)          # 2 sequences, 3 tokens each, 6 features per token
21out, weights = attn(x)
22print(out.shape)
23print(weights.shape)
24print(weights.sum(dim=-1))
1torch.Size([2, 3, 6])
2torch.Size([2, 3, 3])
3tensor([[1., 1., 1.],
4        [1., 1., 1.]], grad_fn=<SumBackward1>)

The layer outputs 18 features per token, and chunk(3, dim=-1) cuts the last axis into three pieces of 6 for q, k and v. Each sequence gets its own $3 \times 3$ weight matrix, and every row sums to 1. If a row of weights does not sum to 1, check first that softmax runs over dim=-1.

Code style 2: one bigger Linear layer. qkv_proj maps x of shape (batch, seq_len, d_model) to 3 × d_model features, and chunk(3, dim=-1) splits them into q, k and v, each of shape (batch, seq_len, d_model).

When self-attention fits, and common mistakes

Self-attention fits whenever each token's new representation should depend on the other tokens in the sequence, which is why transformer layers are built around it. By itself it compares tokens by their content and has no sense of their order, and positional encoding is how transformers add order back.

Mistakes that come up often:

Multi-head attention runs several smaller self-attention computations side by side, each with its own projections, and joins their outputs. Positional encoding adds position information to the token vectors before attention compares them. What is attention in deep learning covers the encoder-decoder version that self-attention grew out of, and how transformers work shows where self-attention sits inside a transformer layer.

QuiddityML teaches self-attention as its own concept in the Intro to NLP track, one step of the formula at a time. Its exercises include filling in the scaled dot-product attention function, spotting the bugs in a SelfAttention class and writing the whole function from scratch.