What Is Self-Attention?
How self-attention lets each word weigh every other word in its input, why transformers depend on it, and what it costs, for your AI interview.
In short
Self-attention lets each token, a chunk of text, score every other token, itself included, and mix in their meaning by those scores. It is one of the main building blocks of the transformer, a neural network architecture, and in a chat model a token only uses itself and the tokens before it.
11 min readIntermediateVery common · estimateFacts checked 26 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
Self-attention lets each word in a text score every other word, itself included, and borrow meaning from the ones that matter most. Each word makes a query, a key and a value. The query is matched against every key, then a step called softmax turns those scores into weights that add up to 1, and the new meaning is a weighted mix of the values. In a chat model, each word sees only itself and the words before it. The work grows with the square of the length, so when I scope a contract tool, I plan to split long documents rather than send them whole.
Self-attention is how a transformer works out what each word means in its context. Take this line from a supply contract: "The supplier may suspend the licence if the customer disputes an invoice, unless it has paid the fee in full." To work out what "it" refers to, the model must decide whether it means the supplier or the customer. The model lets self-attention score every other word in the clause.
Each word makes three vectors. The query is what it is looking for, the key is what it offers, and the value is what it passes on. The model compares the query for "it" with every key, divides each score by the square root of the key size, and runs softmax to turn the scores into weights that add up to one. The new meaning of "it" is the weighted mix of all the values. Several heads run this in parallel, each finding different links.
Two limits matter in the work I do. A chat model writes one token at a time, so it can only use the words it has already written. And the work grows with the square of the length. Doubling a text roughly quadruples the scoring, so a 2,000-token prompt needs about four million scores per head in each layer. That is why I would split long documents or retrieve only the parts that matter.
What is self-attention, in plain words?
A transformer works on the whole text in a small, fixed number of steps. In each step, self-attention lets each word look at every other word and take in the ones that matter for its meaning. The word 'self' means the text attends to itself.
“The self part of self-attention refers to the sequence attending to itself rather than to some other context.”
Google Machine Learning Glossary
“For each word in an input sequence, the network scores the relevance of the word to every element in the whole sequence of words.”
Google Machine Learning Glossary
Think of a claims handler at an insurance firm reading a long file. Her eye keeps going back to the two or three lines that matter for the claim in front of her, and she skims the rest. Self-attention does this with numbers: a weight for every word, and more weight where it counts.
Key words
- Token
- A chunk of text the model reads, often a word or part of a word.
- Query
- What a token is looking for in the other tokens.
- Key
- What a token offers, so other tokens can match it.
- Value
- The information a token passes on when other tokens pick it.
Self-attention on its own has no sense of word order, so the paper adds position information to the input. It says the model must inject some information about the relative or absolute position of the tokens in the sequence.
How does self-attention work, step by step?
Each token starts as a vector of numbers, and the model makes three more from it: a query, a key and a value. For one token, the steps are these.
- 1
Score
Compare its query with every key using a dot product, a multiply-and-add that gives a bigger number for a better match.
- 2
Scale
Divide each score by the square root of the key size, so the numbers stay in a workable range.
- 3
Weigh
Run softmax, which turns the scores into weights that are all positive and add up to 1.
- 4
Mix
Multiply each value by its weight and add them up. That total is the token's new meaning.
The paper's reason for the scale is that big dot products push softmax into regions where its gradients are extremely small, which makes learning harder. Google's 2017 blog describes the same step for any given word, such as 'bank': the Transformer compares it to every other word in the sentence.
How 'it' gets its new meaning
Query from 'it'
the question it asks of each word
Keys and values
from every word in the clause
Scores
query matched against each key
Softmax weights
weights add up to 1
Weighted mix
values, each times its weight
New 'it'
mostly 'customer' in this example
- 1The query from 'it' is compared with each key.
- 2Every word's key is compared with that same query.
- 3Softmax turns the scores into weights that add up to 1.
- 4Each word's value is multiplied by its weight and added up.
- 5The total is the new meaning of 'it'.
Models do not run attention just once. They run several heads in parallel, each with its own learned weights, and join the results. The paper says multi-head attention lets the model attend to different representation subspaces at different positions. A figure shows two heads, both in layer 5 of 6, apparently involved in anaphora resolution, which links a pronoun to its noun.
Several heads, side by side
Token vectors
one vector per word
Heads in parallel
Head 1
one pattern of links
Head 2
its own pattern of links
Join the results
combines what every head found
Richer meaning
one vector per word, again
- 1The word vectors go into the first head.
- 2The same word vectors go into the second head.
- 3Head 1 passes on the links it found.
- 4Head 2 passes on the links it found, which may differ.
- 5Everything is joined and mapped back to one vector per word.
What does it look like in a contract clause?
A supply contract says: "The supplier may suspend the licence if the customer disputes an invoice, unless it has paid the fee in full." A review tool has to decide who 'it' refers to. If it links 'it' to the supplier, the tool flags the wrong party as the one who paid, and a legal team could act on that. The attention should lean to the customer.
The script below is a small stand-in. It uses five made-up words and one made-up vector per word, so the scores come from those numbers alone. The three marked lines do the work: the scaling, the softmax and the weighted mix.
import math
# shortcut: no learned query, key and value weights; one made-up vector per word does all three
WORDS = ["supplier", "customer", "disputes", "unless", "it"]
VECTORS = [[1.2, 0.3], [2.8, 0.6], [0.2, 2.2], [0.4, 1.1], [2.0, 0.5]]
def softmax(scores):
top = max(scores)
exps = [math.exp(s - top) for s in scores]
total = sum(exps)
return [e / total for e in exps]
def self_attention(i):
query = VECTORS[i]
scores = [sum(q * k for q, k in zip(query, key)) / math.sqrt(2) for key in VECTORS]
weights = softmax(scores)
mixed = [sum(w * v[d] for w, v in zip(weights, VECTORS)) for d in range(2)]
return weights, mixed
weights, mixed = self_attention(4)
for word, w in zip(WORDS, weights):
print(f"{word:<9} {w:.2f}")
print("new 'it':", [round(x, 2) for x in mixed])Output
supplier 0.06 customer 0.67 disputes 0.03 unless 0.03 it 0.21 new 'it': [2.39, 0.62]
With these vectors, 'it' puts 0.67 of its attention on 'customer' and 0.21 on itself. Supplier gets 0.06. A real model learns the weights that build the query, key and value from each word's vector, so its numbers would not be hand-picked, but the mechanism is the same.
The weights are only a guess at what matters, so a lawyer checks every flagged clause before anything is sent. That check takes time.
Does every token see the whole text, and what does it cost?
There are two common setups, and the difference matters in interviews.
- Encoder
Reads the whole input
Each token scores all the tokens, including the ones after it. Good for reading a clause or finding a party's name.
- Decoder (chat)
Sees only what came before
A causal mask hides later tokens, so the model cannot read the words it is about to write.
The paper states the decoder rule, because a chat model writes one token at a time and must not read ahead.
“We need to prevent leftward information flow in the decoder to preserve the auto-regressive property.”
Vaswani et al., 2017 (the transformer paper)
The cost is the other half. Each token scores every other token, so with n tokens there are n times n scores per head in each layer. A 2,000-token prompt means about 4 million scores per head per layer, and an 8,000-token one about 64 million. Doubling the text roughly quadruples the scoring work.
Tip
Asked how you would handle a 300-page policy? Say the scoring work grows fast, so you split the document or retrieve the relevant pages, and you weigh the cost of each choice.
What does the interviewer want to hear?
A strong answer covers
- A plain definition: each token scores every token and mixes their meaning by those scores.
- The three roles: query, key and value, and what each one is for.
- The steps: dot product, scale, softmax, then the weighted sum.
- Why a chat model masks later tokens, and what an encoder does instead.
- The cost: work grows with the square of the length.
- Word order is added separately, because attention alone ignores it.
Common traps
Trap"Self-attention and cross-attention are the same thing."
BetterSelf-attention reads one sequence against itself. Cross-attention, which the 2017 paper calls encoder-decoder attention, reads the decoder's queries against the encoder's output.
Trap"The model reads the sentence left to right, one word at a time."
BetterSelf-attention scores all the words at once. Only a decoder's mask stops a token from reading the words after it.
Trap"A longer input costs about the same."
BetterScores grow with the square of the length. Doubling the text roughly quadruples the scoring work.
Can you spot the mistake?
Spot the mistake
A junior engineer wrote this note for the team wiki about a chat model. Which line is wrong?
Quick check
In the worked example, 'it' gives 0.67 to 'customer' and 0.21 to itself. Which step makes those weights add up to 1?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 26 November 2026
Building a tool that reads long contracts or policies?
I design and build AI products and agents, the interface and the system behind them. Book a short call and tell me what your tool needs to do.