# 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.

AI and LLM interview question Q043, Transformer architecture. Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/what-is-self-attention

## Say it in 30 seconds

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.

## Say it in 2 minutes

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.

- **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.

*Diagram, How 'it' gets its new meaning: Read left to right. The query from 'it' is scored against every key, softmax makes weights, and the weights mix the values. The numbers are made up.*
1. The query from 'it' is compared with each key.
2. Every word's key is compared with that same query.
3. Softmax turns the scores into weights that add up to 1.
4. Each word's value is multiplied by its weight and added up.
5. The 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.

*Diagram, Several heads, side by side: Each head works on the same word vectors in its own way, then the results are joined. It shows the idea, not a real model.*
1. The word vectors go into the first head.
2. The same word vectors go into the second head.
3. Head 1 passes on the links it found.
4. Head 2 passes on the links it found, which may differ.
5. Everything 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.

```python
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:

```text
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." Better: Self-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." Better: Self-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." Better: Scores 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?

A. Each token builds a query, a key and a value from its own vector.
B. Scores come from comparing a query with every key, then softmax turns them into weights.
C. In a chat model, a token can attend to words that come after it, so it sees the reply's ending while writing its start.
D. The cost of scoring grows with the square of the number of tokens.

**Answer:** C. A chat model uses a causal mask, so a token attends only to itself and the tokens before it. Otherwise it could read the words it is supposed to predict. The other three lines are correct.

**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?

A. Softmax
B. Positional encoding
C. The tokenizer
D. The output layer

**Answer:** A. Softmax turns the raw scores into weights that add up to 1. Positional encoding adds word order, the tokenizer splits text into tokens, and the output layer picks the next token.

## Can you answer these from memory?

**Flash cards**

- **What is self-attention?** Each token scores every token in the input and mixes their values by those scores.
- **What do query, key and value mean?** Query: what I look for. Key: what I offer. Value: what I pass on.
- **Why scale by the square root of the vector size?** Big dot products push softmax into tiny gradients, so training gets harder.
- **What does softmax do here?** It turns the scores into weights that are all positive and add up to 1.
- **What is a causal mask?** It hides later tokens, so a chat model cannot read words it has not written yet.
- **Why is attention costly for long text?** Each token scores every other token, so the work grows with the square of the length.

## Likely follow-up questions

- Q044 What are queries, keys and values? https://designervenkat.online/interview/ai/what-are-queries-keys-and-values
- Q045 Why scale attention scores by √d_k? https://designervenkat.online/interview/ai/why-scale-attention-scores-by-square-root-of-d-k
- Q046 What is multi-head attention? https://designervenkat.online/interview/ai/what-is-multi-head-attention
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q055 What is the KV cache, and why does it speed up generation? https://designervenkat.online/interview/ai/what-is-the-kv-cache
- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length

## Learn it in depth

- [Self-Attention](https://designervenkat.online/learn/machine-learning/self-attention)
- [Attention Mechanisms](https://designervenkat.online/learn/machine-learning/attention-mechanisms)
- [Multi-head Attention](https://designervenkat.online/learn/machine-learning/multi-head-attention)
