This is the Transformer from Attention Is All You Need (Vaswani et al., 2017):

For a very intuitive visual walkthrough, try the Transformer Explainer.
The diagram looks like a lot, but the orange boxes are all the same operation: attention. Zoom into one and you get this:

Two matrix multiplications, a scale, an optional mask and a softmax. That’s the core of every modern LLM.
I understood the formula fairly quickly. What took me longer was a much simpler question: what makes the query the query? Q, K and V come out of three linear layers that look exactly alike. Why does one of them end up “asking” and another one “answering”? This post is how I worked that out. The short answer is that it’s basic linear algebra, and specifically how matrix multiplication pairs rows with columns.
What is attention trying to do?
Take the sentence:
the animal crossed the street because it was tired
To understand “it”, the model has to work out that “it” means the animal and not the street. So each word needs a way to look at the other words and pull in information from the ones that matter.
The paper describes attention as mapping a query and a set of key-value pairs to an output, where the weight on each value comes from how well the query matches the corresponding key. In plain terms:
- Query: what this word is looking for.
- Key: what each word offers, used for matching.
- Value: what each word actually hands over once it’s picked.
And the formula:
\[ \text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V \]
Where do Q, K and V come from?
This is where my question started. Every word begins as an embedding vector. Stack them up and you get a matrix \(X\), one row per word. Then:
\[ Q = XW_Q \qquad K = XW_K \qquad V = XW_V \]
Three weight matrices with the same shape, all filled with random numbers at the start, all applied to the same \(X\). In PyTorch it’s three identical lines:
self.w_q = nn.Linear(d_model, d_k, bias=False)
self.w_k = nn.Linear(d_model, d_k, bias=False)
self.w_v = nn.Linear(d_model, d_k, bias=False)Nothing in these lines says “query” or “key”. So what makes w_q a query maker?
I knew the weights are learned with backprop and cross-entropy loss. But learned into what? If they start out the same, something has to push them in different directions. The only thing that treats them differently is the formula. So the answer has to be in where each one sits in the formula.
Rows ask, columns answer
Look at \(QK^\top\). In matrix multiplication, each entry of the result is a row of the first matrix dotted with a column of the second.
- \(Q\) has one row per word. Row 6 is the query vector for “it”.
- \(K^\top\) is \(K\) flipped, so it has one column per word. Column 1 is the key vector for “animal”.
- Entry (6, 1) of the result is “it”’s query dotted with “animal”’s key: one number for how much “it” cares about “animal”.
To fill row 6, the multiplication keeps the query of “it” fixed and runs it across every column, one key at a time. That’s exactly what a search does: one question checked against every label in an index. The query is the row because it’s the thing that stays fixed while the keys go past.
To make this concrete I built a toy version with weights set by hand, so the numbers are easy to read. Each word has 5 features (noun, living, place, pronoun, other) and \(d_k = 2\). I gave “it” a query that says I’m looking for a living thing, and gave “animal” and “street” keys that say I’m living and I’m a place. In a real model nobody sets these. They’re learned.

Every entry of the score matrix answers one question: how well does row word’s question match column word’s label?
The small detail I was missing
Here’s what bothered me next. A dot product is symmetric: \(q \cdot k = k \cdot q\). So if I swap the code to compute \(KQ^\top\) instead, is anything different?
There is a difference, and it isn’t in the dot product. It’s in what happens to the rows afterwards:
- Softmax runs along each row. Each row gets turned into weights that sum to 1. So each row word spreads its attention over the column words.
- The output has one row per row word. Multiplying by \(V\) gives row 6 of the output to “it”. The row word is the one that gets updated.
So the query is whatever lands on the rows, because the rows are the ones that receive the result. If you swapped the names and computed K @ Q.T, the network would still train fine. The layer called w_k would just learn to make queries, and w_q would learn to make keys. The names are labels for us. Algebraic position is what gives each layer its role, and backprop then trains each layer for the role its position gives it.
Why divide by √d_k?
The paper explains this one. If the parts of \(q\) and \(k\) are random with mean 0 and variance 1, their dot product has variance \(d_k\). With \(d_k = 64\) (the size the paper uses per head) the scores get large, and softmax becomes almost one-hot. When that happens the gradients become tiny and learning slows down. Dividing by \(\sqrt{d_k}\) brings the variance back to 1.
The mask: no peeking at the next word
For predicting the next word, a word can’t be allowed to look at words that come after it. Otherwise the model would just copy the answer. That’s the “Mask (opt.)” box. Before the softmax, every score above the diagonal is set to \(-\infty\), and \(e^{-\infty} = 0\).

Row 6 is the one I set up, and you can check it by hand: “animal” scores 2.83 and the other six visible words score 0, so the weight on “animal” is \(e^{2.83} / (e^{2.83} + 6) = 0.74\).
The other rows are flat because I only gave “it” a real query. They spread their attention evenly over everything they’re allowed to see. In a trained model every row would have its own pattern.
This matrix is the attention matrix. I think of it as a priority table: row by row, it says how much each word should pull from every other word.
So what’s the value?
My first guess was that the key is what the word means and the value is some category the word belongs to. It’s actually the other way round:
- The key is a label, tuned for matching. It only needs whatever helps queries find the right word.
- The value is the content, what actually gets handed over once the word is picked.
They’re kept separate because the two jobs are different. What makes a word easy to find is not the same as what’s useful to pass on. (These descriptions are intuitions. In a real model keys and values are learned vectors without readable meanings.)
The last matrix multiplication, attention weights × \(V\), is a weighted average. Row 6 of the output is 0.74 × value of “animal” plus 0.04 × each of the other six visible values. In my toy each value is just the word’s own features, so you can read the result directly:

Before attention, “it” was only a pronoun. After attention, its vector mostly says living noun. It has taken on the meaning of “animal”, and that’s what goes on to the next layer.
The whole thing in code
Put together, it’s about ten lines:
import torch
import torch.nn as nn
import torch.nn.functional as F
class SelfAttention(nn.Module):
def __init__(self, d_model, d_k):
super().__init__()
self.w_q = nn.Linear(d_model, d_k, bias=False)
self.w_k = nn.Linear(d_model, d_k, bias=False)
self.w_v = nn.Linear(d_model, d_k, bias=False)
self.d_k = d_k
def forward(self, x, causal=True):
Q, K, V = self.w_q(x), self.w_k(x), self.w_v(x) # same x, three projections
scores = Q @ K.transpose(-2, -1) / self.d_k ** 0.5 # rows ask, columns answer
if causal:
n = x.size(-2)
future = torch.triu(torch.ones(n, n, dtype=torch.bool, device=x.device), 1)
scores = scores.masked_fill(future, float("-inf")) # no peeking ahead
weights = F.softmax(scores, dim=-1) # each row sums to 1
return weights @ V # weighted mix of valuesEach line matches a box in the attention diagram above, from bottom to top.
What I take from this
- It’s mostly linear algebra. Three matrix multiplications make Q, K and V. One more makes the scores, and a last one mixes the values. The only non-linear step inside the box is the softmax.
- Roles come from position, not from the layers.
w_q,w_kandw_vstart out the same. The formula decides which one ends up on the rows, which one gets transposed into columns and which one sits outside the softmax, and training does the rest. - Rows are the askers. Softmax normalises each row and each row of the output belongs to one word, so whatever lands on the rows plays the query.
Two extensions from the paper fit the same picture. Multi-head attention runs 8 of these side by side with smaller \(d_k\), so each head can learn a different kind of question. In cross-attention (the middle orange box on the decoder side), the queries come from the decoder and the keys and values come from the encoder output. There the roles also differ in where their inputs come from, not just in where they sit in the formula.
Source
- Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser, Polosukhin. Attention Is All You Need. NeurIPS 2017, arXiv:1706.03762. Both diagrams in this post are from the paper.