Self-Attention

Comic showing a 'Self-Attention Library' where aliens hold query cards like 'Where is the cat?' and a robot librarian matches them against key drawers labeled 'animal', 'furniture', 'vehicle'. The 'animal' key glows as a strong match, and the librarian hands over a value book labeled 'furry, alive, curious'. Multiple visitors search simultaneously in the background.
What You’ll Learn

You’ll learn how self-attention lets each token look at the other tokens and decide what matters. You’ll use the Query, Key, Value idea to understand scaling, causal masking, and the difference between self-attention and cross-attention.

The Problem: Words Are Islands

After the embedding layer, each word in a sentence becomes a vector. But that vector is the same regardless of context. “Bank” gets the same vector whether the sentence is about a river or about money. “It” gets the same vector whether it refers to a cat or a mat.

This is a real problem. Suppose the model is trying to predict the next word after “The cat sat on the mat because it was ___.” To predict well, it needs to know what “it” refers to. But “it” is just a fixed vector that means “generic pronoun.” The model has no way to figure out which earlier words matter.

Seeing the Problem

Play 3 quick rounds below: watch how changing a single word at the end of the sentence completely changes which noun "it" must attend to:

Round 1 · Who is “it”? The clue is “tired”. Click the word below that “it” should pay attention to!

Same pronoun, same position, completely different referent. The model needs a mechanism that lets each word look at the other words and update its representation based on what it finds relevant. That mechanism is called self-attention.

Why “self”? Because the words are attending to other words in the same sentence. Later we’ll see cross-attention, where tokens from one sequence (like a French translation) attend to a different sequence (the English original). Self-attention is the simpler, more fundamental case.

What Is “Attention”?

Step through the animation below. It shows the three things attention does for a single word:

How Attention Works

Step 1 / 4
The
cat
sat
on
the
mat
because
it
was
tired

The word "it" has no idea what it refers to yet.

That’s all attention is: look at every word, score relevance, blend the winners. Each word’s representation stops being about that word in isolation and starts carrying context from the words it paid attention to.

The Math, in Three Small Steps

Take the sentence “I love cats.” Each word starts as a vector (from the embedding layer). Right now each vector only knows about its own word. “cats” has no idea that someone loves it. We want to produce a new vector for “cats” that blends in information from the relevant words. Three operations get us there:

The Three Operations Behind Attention

How similar are two vectors? Multiply matching dimensions, add them up. Higher total = more similar.

"cats" is most similar to "I" (0.90) and itself (0.85), less similar to "love" (0.29).
1. Similarity

That’s the entire recipe: dot product to score, softmax to normalize, weighted sum to blend. But we used the raw embedding vectors directly. The model needs a way to learn which aspects of each vector to compare. That’s what the Q, K, and V projections do.


The Q, K, V Framework

Each token gets three different learned roles: a question it asks, a description it advertises, and information it carries. The analogy that makes this click: a library search.

Attention as a Library Search

Step 1 / 5

Think of attention like searching a library. You walk in with a question. Each book has a title (so you can judge relevance) and contents (the actual information).

You (a token)
cat
sat
mat
Your question=Query (Q)
Book titles=Keys (K)
Book contents=Values (V)

Why Three Separate Projections?

Why not just use the raw embeddings for everything? Toggle between the two modes to see what goes wrong:

Why Separate Q, K, V?

Problem

Raw embeddings compare surface similarity, not meaning. "mat" scores higher than "cat" because their vectors happen to be close, even though "tired" should connect to "cat." The model has no way to learn what aspects to compare.

Raw embeddings (used for both comparing AND being compared)
"tired" [0.3, 0.9]
"cat" [0.8, 0.3]
"mat" [0.7, 0.4]
Attention from "tired" to each word
"tired" self
n/a
"cat"
49%
"mat"
51%
"tired" attends most to "mat" (wrong!). Raw embeddings can't distinguish "cat" from "mat" for this task because the comparison isn't learnable.

But how do the matrices “know” they’re Q, K, V? They don’t. WQW^Q, WKW^K, and WVW^V all start as random numbers. What makes them different is where they sit in the formula: WQW^Q‘s output is the left side of the dot product (the one asking), WKW^K‘s output is the right side (the one being compared against), and WVW^V‘s output feeds into the weighted sum (the one providing information). Because each matrix occupies a different position, backpropagation sends each one different gradients, and they specialize over training. The “query, key, value” labels describe the architectural role, not something the matrices inherently possess.

Quick Check
Why does self-attention use separate Q, K, V projections instead of using the raw token embeddings directly?
Your turn
Choose an answer to check your understanding.

Step-by-Step: The Math with Real Numbers

Let’s trace through self-attention with actual numbers. Click “Next” to advance through each computation step:

Self-Attention Step by Step

Step 1/7: Input Embeddings
Input X (3 × 4)
"I"
-1.00
0.74
0.37
-0.98
"love"
-0.34
-0.63
-0.87
0.06
"cats"
0.83
0.02
0.14
0.47

How It Works, Step by Step

Here’s what self-attention does in plain language (matching the steps above):

StepWhat HappensPlain English
1Start with embeddingsEach token is a vector that knows only about its own word
2Three weight matricesThe model has learned weights W_Q, W_K, W_V that extract different roles from each embedding
3Multiply to get Q, K, VEach embedding × W_Q = its query (what am I looking for?), × W_K = its key (what do I offer?), × W_V = its value (what will I share?)
4Score all pairsCompare every query against every key (dot product + scale) to get relevance scores
5SoftmaxTurn scores into weights that sum to 1 (like percentages)
6Weighted blendEach token collects a blend of all values, weighted by relevance
7OutputEach token’s vector is now context-aware, carrying information from the words that mattered to it

Why does comparing queries and keys measure relevance? Each token’s query encodes what it’s looking for (“something alive that can feel tired”), and each token’s key encodes what it offers (“I’m alive, I can feel things”). When a query and key point in the same direction, the match score is high. When they’re unrelated, the score is low or negative.


What Did We Just Build?

Step through the animation below to see how self-attention fits into the bigger picture: from static embeddings to context-aware representations, stacked layers, and finally next-word prediction.

What Did We Just Build?

1 / 4

After the embedding layer, each word is a fixed vector. The same word always gets the same vector, no matter what sentence it appears in.

Iwalkedalongtheriver bank
river bank (edge of water)
Idepositedmoneyatthe bank
bank (financial institution)
"bank" vector [0.31, -0.72, 0.55, 0.18]
=
"bank" vector [0.31, -0.72, 0.55, 0.18]
Identical vectors. The model can't tell these two meanings apart.

Self-attention is one building block. Multi-Head Attention runs multiple self-attention operations in parallel for different perspectives. The full transformer architecture shows how all the pieces fit together.


Why Scale the Scores?

You may have noticed the ”÷ √d_k” in step 4 of the visualization above. Each attention score is a dot product, a sum of many small numbers (one per dimension). The more dimensions, the bigger the total. With 64 dimensions, scores can easily reach values like 20 or 30.

Why is that a problem?

Large scores push softmax into saturation, where outputs become nearly one-hot:

Without Scaling (64 dimensions)With Scaling
Raw scores[30, 25, -10, 5][3.75, 3.125, -1.25, 0.625]
After softmax[0.993, 0.007, 0.000, 0.000][0.63, 0.34, 0.004, 0.03]
AttentionAlmost all on one tokenSpread across tokens
GradientsNear-zero (vanishing)Healthy range

When softmax saturates, the model puts nearly all its attention on a single token and ignores everything else. Worse, the gradients become near-zero, so the network can’t learn to fix this. Dividing by the square root of the dimension keeps scores in a reasonable range where softmax can spread attention across multiple tokens.

Quick Check
What happens to the attention distribution if we DON'T scale by √d_k and d_k is large?
Your turn
Choose an answer to check your understanding.

Interactive: Explore Attention Patterns

Play with the attention visualizer below. Try different sentences and see how tokens attend to each other:

Self-Attention Visualizer

Click a token to see its attention distribution
Key (attends to) →
← Query
Attention:
0% 100%
Attention(Q, K, V) = softmax(QKT / √dk)V

Things to try:

  • Increase temperature to see how it softens the attention distribution
  • Click a token to see its complete attention pattern
  • Try sentences with ambiguous words like “bank” to see context effects

Causal (Masked) Self-Attention

For language generation (GPT, LLaMA), we need a critical constraint: each token can only attend to itself and the tokens before it. It can’t see the future.

Think of it like writing an exam. You can only use information you’ve already seen, not answers that haven’t been revealed yet.

The Mask

We block future positions by setting their scores to an extremely negative number before softmax, so they get zero attention weight:

“The""cat""sat""on"
"The”can seeblockedblockedblocked
”cat”can seecan seeblockedblocked
”sat”can seecan seecan seeblocked
”on”can seecan seecan seecan see

Each row shows what a token can attend to. The lower-left triangle is visible; the upper-right is blocked.

Notice how the upper-right triangle of the attention matrix is zeroed out:

Self-Attention Visualizer

Click a token to see its attention distribution
Key (attends to) →
← Query
Attention:
0% 100%
Attention(Q, K, V) = softmax(QKT / √dk)V

When to Mask

ArchitectureMaskingWhy
BERT (encoder)No maskUnderstanding needs full context
GPT (decoder)Causal maskCan’t see future during generation
T5 encoderNo maskInput is fully visible
T5 decoderCausal maskOutput is generated left-to-right
Fill in the Blanks
In causal self-attention, position i can attend to positions 0 through , preventing the model from seeing tokens.
Fill in every blank, then check your answer.

Self-Attention vs. Cross-Attention

In self-attention, Q, K, and V all come from the same sequence. But there’s a variant called cross-attention where Q comes from one sequence and K, V come from another. This is how translation models let the decoder “read” the encoder’s output.

AspectSelf-AttentionCross-Attention
Q, K, V sourceAll from same sequenceQ from one, K/V from another
Used inEvery transformer blockEncoder-decoder models only
PurposeTokens communicate within a sequenceDecoder reads from encoder
Example”cat” attends to “sat” in same sentenceFrench “chat” attends to English “cat”

Self-attention is the fundamental building block. We’ll explore cross-attention in detail later in Seq2Seq Attention →, where we trace the historical origin of the attention idea.


The Cost of Full Context

Self-attention’s power comes from comparing every token to every other token. But that power has a cost. Drag the slider and watch the attention matrix grow:

Attention Matrix Size

What to look for: Start at 4 tokens and slowly drag to 64. The grid area grows much faster than the slider moves. At 4 tokens, there are 16 comparisons. At 8 tokens, there are 64 (not 32). At 64 tokens, there are 4,096. Every time you double the sequence length, the number of comparisons quadruples.

Think of it like seating at a round table. If 4 people need to introduce themselves to everyone else, that’s manageable. But double the guests to 8, and the introductions don’t just double, they quadruple. With 64 guests, you’d need 4,096 introductions. That’s the n2n^2 pattern: the work grows as the square of the input size.

For real models, this gets serious. A 128,000-token context window means over 16 billion entries in the attention matrix, per head, per layer. This is why researchers developed techniques like Flash Attention (exact attention with better memory access patterns), sliding window attention (attend only to nearby tokens), and sparse attention (skip most of the matrix). The quadratic nature is fundamental to the mechanism, but clever engineering works around the worst of the cost.

Fill in the Blanks
If a sequence has 10 tokens, the attention matrix has entries. If we double the sequence to 20 tokens, it has entries, which is times more.
Fill in every blank, then check your answer.


Quick Summary

ConceptWhat HappensIntuition
Self-attentionEvery token computes relevance scores with every other tokenEach word gets to “look around” and gather context from the whole sentence
Q, K, V projectionsEach token is projected into three separate rolesLike a library: your question (Q), book titles (K), and book contents (V) are different things
Score scalingDivide scores by the square root of the key dimensionKeeps softmax from becoming overconfident and killing gradients
Causal maskingBlock future positions so tokens can only see the pastLike writing an exam: you can only use information already revealed
Quadratic costnn tokens require n2n^2 comparisons: double the length, quadruple the workThis is both the power (full context) and the limitation (expensive for long sequences)

Learning Checklist
  • I can explain why self-attention is needed, and how it solves the “which word does ‘it’ refer to?” problem
  • I understand the Query, Key, Value framework using the library analogy
  • I know why separate Q, K, V projections are needed instead of using raw embeddings
  • I can explain in plain language why scaling scores matters and what breaks without it
  • I understand how causal masking works and when it’s used (decoders) vs. not used (encoders)
  • I can describe the difference between self-attention and cross-attention

Next: Multi-Head Attention

A single attention head gives one perspective. But language is multi-faceted, and we need multiple perspectives simultaneously. That’s Multi-Head Attention →