GeekCoding101 make your way to geek

Self-Attention in Transformers, Explained

How self-attention works in Transformers: queries, keys and values, softmax weights, a worked pronoun example, multi-head attention and the O(n²) cost.

9 min read
Daily Ai Insight Issue 2 20241203
On this pageOn this page

Daily AI Insight · Topics: ai, self-attention, transformer

Self-attention is the mechanism that lets every token in a sequence look at every other token in the same sequence and decide how much each one matters to it. In a Transformer, each token is turned into a query, a key and a value. The model scores each query against every key, turns those scores into weights with softmax, and uses the weights to blend the values into a new, context-aware representation of that token.

That is the whole trick, and it is why Transformers handle long-range relationships far better than RNNs and LSTMs did. The rest of this post walks through where attention came from, how the math works step by step, a worked example, and where self-attention runs into limits.

On this page

  1. Attention, self-attention and cross-attention
  2. Where the attention mechanism came from
  3. How self-attention works, step by step
  4. A worked example: what does “it” refer to?
  5. Multi-head attention
  6. Word order and masking
  7. Where self-attention is used
  8. Why it beats RNNs and LSTMs
  9. Limits: the O(n²) problem
  10. One-line summary
  11. FAQ

1. Attention, self-attention and cross-attention

These three terms get mixed up a lot. The difference is simply which sequence looks at which.

TermQueries come fromKeys and values come fromTypical use
Attention (original, 2014)Decoder stateEncoder outputs (source sentence)Neural machine translation with RNNs
Self-attentionA sequenceThe same sequenceEvery Transformer layer: BERT, GPT, ViT
Cross-attentionOne sequence (e.g. the output being generated)Another sequence (e.g. the input)Encoder–decoder Transformers, text-to-image models

The original attention connected two separate sequences, input and output. Self-attention lets each element of one sequence interact with every other element in that same sequence. That is what gives a model a global view of its context.

2. Where the attention mechanism came from

The attention mechanism was introduced in the 2014 paper Neural Machine Translation by Jointly Learning to Align and Translate. It tackled a specific problem. Encoder–decoder RNNs squeezed a whole source sentence into a single fixed-size vector, and long sentences lost information.

Attention let the decoder look back at all the encoder’s outputs at every step and focus on the most relevant ones. It works much like a reader who skims past filler words and zeroes in on the parts that matter.

In 2017, the paper Attention Is All You Need went a step further. It dropped recurrence entirely and built a model, the Transformer, out of self-attention layers. Nearly every large language model since then is built on that design.

3. How self-attention works, step by step

The core idea is that each token gets a weighted view of the whole sequence. Higher weights mean “more relevant to me”.

The three vectors: query, key, value

For every token, the model multiplies its embedding by three learned weight matrices:

  • Query (Q): what this token is looking for.
  • Key (K): what this token offers to others.
  • Value (V): the information this token passes along if it gets attention.

A useful mental model is a search engine. Your query is compared against every document’s key, and the best matches contribute the most of their content (value) to the result.

The four steps

  1. Relevance scoring. Take the dot product of a token’s query with every token’s key, including its own. A higher score means a stronger match.
  2. Scaling. Divide each score by √dₖ, the square root of the key vector’s dimension.
  3. Weight normalization. Apply softmax so the scores become weights between 0 and 1 that sum to 1.
  4. Weighted summation. Multiply each value vector by its weight and add them up. The result is the token’s new, context-aware vector.

Written as one formula (scaled dot-product attention):

Attention(Q, K, V) = softmax( Q · Kᵀ / √dₖ ) · V

Because all tokens are processed as matrices, the computation for the whole sequence happens at once rather than one word at a time.

Why divide by √dₖ?

With large vector dimensions, dot products can grow big. Softmax then becomes very “peaky”: one weight near 1, the rest near 0, and training gradients get tiny. Scaling keeps the scores in a range where softmax behaves well.

4. A worked example: what does “it” refer to?

Take the sentence: “I bought a book yesterday. It is fascinating.”

When the model builds a representation for “it”, it scores the query for “it” against the key of every other word. A trained model will give “book” the highest weight, because “book” is the thing that can be fascinating. “Yesterday” and “I” get much less.

The numbers below are made up for illustration. They show the shape of the result, not output from a real model:

WordIllustrative attention weight from “it”
book0.62
bought0.10
fascinating0.09
yesterday0.07
I0.05
a0.04
is0.03

The weights sum to 1. The new vector for “it” is mostly built from the value vector of “book”, so later layers “know” what “it” means.

The same mechanism works across a whole sentence. When translating “I love cats”, the link between “love” and “cats” carries more meaning than the link between “I” and “cats”. Attention lets the model weight it that way.

5. Multi-head attention

One set of attention weights can only capture one kind of relationship at a time. Transformers therefore run several attention “heads” in parallel. Each head has its own Q, K and V matrices.

One head might pick up pronoun references, another subject–verb links, another nearby-word patterns. The heads’ outputs are concatenated and projected back into a single vector. Stacking many layers of multi-head self-attention is what lets models like GPT and BERT build up rich language understanding.

6. Word order and masking

Two details trip up a lot of first-time readers.

Self-attention has no built-in sense of order. Shuffle the words and the dot products stay the same. Transformers therefore add positional information (positional encodings or embeddings) to each token so the model can tell “dog bites man” from “man bites dog”.

Generative models use a causal mask. In decoder models like GPT, a token may only attend to tokens before it. Future positions are masked out before the softmax, so the model can’t peek at the word it is supposed to predict. Encoder models like BERT have no such mask, so each token can see both sides of its context.

7. Where self-attention is used

Machine translation

This is where attention started. The model focuses on the relevant parts of the source sentence while producing each word of the translation, which makes translations more accurate and fluent.

Large language models

  • Transformer architecture: attention powers both the encoder and the decoder.
  • BERT is encoder-only. It uses bidirectional self-attention and is strong at understanding tasks such as classification and search.
  • GPT is decoder-only. It uses masked (causal) self-attention and is strong at generating text.

Computer vision

Vision Transformers (ViT) split an image into patches, treat each patch like a token, and use self-attention to relate different parts of the image. With enough training data, they are competitive with, and on many benchmarks better than, traditional convolutional neural networks (CNNs).

Multimodal models

Models that work with both text and images, such as CLIP and the DALL-E family, rely on Transformer-style attention. That attention lets them caption images, match images to text, and generate pictures from text descriptions.

8. Why it beats RNNs and LSTMs

  • Short paths between any two tokens. In an RNN, information from word 1 has to pass through every step to reach word 50. In self-attention, any token can attend to any other token directly in a single layer, so long-range dependencies are much easier to learn.
  • Parallel computation. RNNs process tokens one after another. Self-attention processes the whole sequence at once, which maps well onto modern hardware and makes training on huge datasets practical.
  • Global context. Every token’s representation can draw on the entire sequence, which helps with complex context.
  • Broad applicability. The same mechanism works on text, image patches, audio and mixed inputs.

This is why attention gets called “AI magic”. It isn’t magic, though. It is weighted averaging with learned weights, done at scale.

9. Limits: the O(n²) problem

  • Compute and memory grow quadratically. Every token scores against every other token, so a sequence of n tokens needs an n × n score matrix. Doubling the input length roughly quadruples that work and memory. This is the main reason long context windows are expensive.
  • Scaling to very long inputs such as whole books, long videos or high-resolution images is hard with full attention.

Ongoing research attacks this from several angles:

  • Sparse attention only scores selected pairs of tokens.
  • Linear-attention approximations avoid building the full n × n matrix.
  • Memory-efficient exact implementations such as FlashAttention reorganize the computation to cut memory traffic, while still computing standard attention.

10. One-line summary

Self-attention lets every token weigh every other token and rebuild itself from the most relevant ones. That simple, parallel “prioritize what matters” step is the engine inside every Transformer.

11. FAQ

What is the difference between attention and self-attention? Classic attention lets one sequence (for example, a translation being generated) focus on a different sequence (the source sentence). Self-attention lets each element of a sequence focus on the other elements of the same sequence. Transformers use self-attention in every layer, and encoder–decoder models also use cross-attention between the two sides.

What are Q, K and V in self-attention? They are three vectors computed from each token using learned weight matrices. The query says what the token is looking for, the key says what it offers, and the value is the content it passes on. Scores come from query·key, and the output is a weighted sum of values.

Why is self-attention O(n²)? Each of the n tokens computes a score against all n tokens, which produces an n × n matrix. Compute and memory therefore grow with the square of the sequence length.

Does self-attention understand word order? Not by itself. Self-attention treats its input as a set, so Transformers add positional encodings or embeddings to each token to give the model information about order.

Why do GPT-style models mask attention? So each token can only attend to earlier tokens. That keeps text generation honest: the model predicts the next word without seeing it.


Thanks for being with me on this Daily AI Insight journey into self-attention! If you want to keep going, other posts in the series cover prompt engineering, why model parameters affect inference speed, and serving models with Ray Serve.

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts