Attention

Attention lets each token retrieve relevant information directly from other tokens instead of relying on a single compressed memory.

The Big Question

LSTMs improved recurrent networks by learning what to remember and what to forget. But they still process a sequence one step at a time.

Suppose Jessie writes: “The burger that Jessie ordered after walking around Manhattan all afternoon was delicious.” To understand delicious, the model needs to connect it to burger.

Why force information to travel through every intermediate word? Why cannot delicious look directly at burger?

That question is the heart of attention. Attention lets each token decide which other tokens are relevant and retrieve information from them directly.

Why Memory Is Not Enough

An LSTM carries information through a hidden state and cell state. This is much better than a vanilla RNN, but it still compresses past context into a moving memory.

Attention changes the strategy. Instead of compressing everything into one memory, keep the token representations available and let each token look up what it needs.

Core Intuition

When you read a confusing sentence, you do not reread every previous word in order. Your eyes jump to the relevant phrase. Your brain selectively focuses on useful information.

Attention gives neural networks that ability. Every token asks: which other tokens matter to me right now?

A Concrete Example

Consider the sentence:

Jessie ate the burger because it looked delicious.

To understand the word it, the model should look strongly at burger. Other words may matter a little, but burger is the key reference.

WordAttention weight from it
Jessie0.02
ate0.05
the0.01
burger0.84
because0.04
looked0.03
delicious0.01

The model has learned where to look. That is the conceptual leap.

Library Analogy

An LSTM is like carrying one notebook and rewriting it after every book you read. Attention is more like keeping every book on the shelf. When you need something, you retrieve the relevant book directly.

Interactive Demo

Attention heat map

Click the query token

queryJessieatetheburgerbecauseitlookeddelicious
Jessie
ate
the
burger
because
it0.020.050.010.840.040.020.010.01
looked
delicious

Attention connections for it

Jessieatetheburgerbecauseitlookeddelicious
tokenattention weightvalue strengthcontribution
Jessie0.020.200.004
ate0.050.350.017
the0.010.050.001
burger0.840.950.798
because0.040.250.010
it0.020.550.011
looked0.010.400.004
delicious0.010.800.008
Selected query
it
Weighted value sum
0.853

This token representation is rebuilt from the values of all tokens, weighted by relevance.

Query

What information is this token looking for?

Key

What information does each token advertise that it contains?

Value

What information does each token contribute if it is selected?

Query-key matching example

Jessie0.15
ate0.18
the0.13
burger0.54

Dot products become scores. Softmax turns those scores into weights.

Click different query tokens. Each row of the attention matrix is that token's personalized view of the sentence.

Mathematics

Queries, Keys, And Values

Every token produces three vectors:

QueryWhat information am I looking for?
KeyWhat information do I contain?
ValueWhat information should I contribute if selected?

From the input embedding matrix XX, the model learns three projections:

Q=XWQ,K=XWK,V=XWVQ=XW_Q,\qquad K=XW_K,\qquad V=XW_V

The matrices WQW_Q, WKW_K, and WVW_V are learned parameters.

Measuring Relevance

A query is compared with every key using a dot product:

QKTQK^T

If a query and key point in similar directions, the dot product is large. If they are unrelated, it is small. This gives a matrix of raw attention scores.

Softmax Turns Scores Into Weights

Raw scores are not probabilities. Softmax converts each row into attention weights that sum to one:

softmax(QKT)\text{softmax}(QK^T)

Each row answers: for this query token, how much attention should go to every token?

Weighted Sum Of Values

The final output is a weighted average of value vectors:

Output=softmax(QKT)V\text{Output}=\text{softmax}(QK^T)V

A token's new representation is no longer based only on itself. It now includes information retrieved from other tokens.

Scaled Dot-Product Attention

The full equation divides by dk\sqrt{d_k}:

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q,K,V)=\text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

When vectors have many dimensions, dot products naturally become large. Large scores can make softmax too extreme, which weakens gradients. Dividing by dk\sqrt{d_k} keeps scores at a more stable scale.

Worked Example

Suppose the word ordered attends to a short sentence:

WordWeight
Jessie0.45
ordered0.05
a0.05
burger0.45
0.45VJessie+0.05Vordered+0.05Va+0.45Vburger0.45V_{\text{Jessie}}+0.05V_{\text{ordered}}+0.05V_{\text{a}}+0.45V_{\text{burger}}

The representation of ordered now includes information about who ordered and what was ordered. This is contextual representation.

Self-Attention

In self-attention, every token attends to other tokens in the same sequence. The word ordered might attend to Jessie and burger. The word burger might attend to ordered. Each token builds its own contextual view.

Why Attention Beat Recurrence

RNNs process tokens sequentially. Token 300 can only receive information from token 1 after it passes through every intermediate step. Attention allows token 300 to directly attend to token 1.

Attention also processes all tokens in parallel, which makes it much friendlier to GPUs than recurrence.

Multi-Head Attention

One attention mechanism can learn one kind of relationship. Multiple heads allow the model to attend in several ways at once: grammar, reference, sentiment, object relationships, or other patterns discovered during training.

Computational Cost

Attention compares every token with every other token. For sequence length nn, the attention matrix has n×nn\times n entries:

cost=O(n2)\text{cost}=O(n^2)

This quadratic cost becomes expensive for very long documents and motivates research into efficient attention mechanisms.

Implementation

Scaled dot-product attention is short to implement. The important part is the order of operations: project to Q, K, V; compute scores; scale; softmax; combine values.

import math
import torch
from torch import nn

def scaled_dot_product_attention(Q, K, V, mask=None):
    d_k = Q.size(-1)
    scores = Q @ K.transpose(-2, -1)
    scores = scores / math.sqrt(d_k)

    if mask is not None:
        scores = scores.masked_fill(mask == 0, float("-inf"))

    weights = torch.softmax(scores, dim=-1)
    output = weights @ V
    return output, weights

batch_size = 2
sequence_length = 5
embed_dim = 16

X = torch.randn(batch_size, sequence_length, embed_dim)

W_q = nn.Linear(embed_dim, embed_dim)
W_k = nn.Linear(embed_dim, embed_dim)
W_v = nn.Linear(embed_dim, embed_dim)

Q = W_q(X)
K = W_k(X)
V = W_v(X)

output, attention_weights = scaled_dot_product_attention(Q, K, V)

print(output.shape)             # (2, 5, 16)
print(attention_weights.shape)  # (2, 5, 5)

The attention weights form a heat map. Row ii shows which tokens token ii attends to.

Interview Discussion

Why was attention introduced?

It lets tokens retrieve relevant information directly from other tokens, avoiding the bottleneck of passing all information through sequential memory.

What are queries, keys, and values?

A query says what a token is looking for, a key says what a token contains, and a value is the information contributed if that token is attended to.

Why use a dot product?

The dot product measures compatibility between a query and a key. Similar vectors produce larger scores.

Why apply softmax?

Softmax converts raw scores into attention weights that sum to one.

Why divide by sqrt(d_k)?

It prevents dot products from becoming too large in high dimensions, keeping softmax and gradients stable.

What is self-attention?

Self-attention is attention where tokens attend to other tokens in the same sequence.

Why is multi-head attention useful?

Different heads can learn different relationships, allowing the model to gather several kinds of context simultaneously.

Active Recall

1. Why is attention better described as retrieval than memory?

2. Write the scaled dot-product attention equation from memory.

3. What does the query vector represent?

4. What is the difference between keys and values?

5. Why does self-attention process long-range dependencies better than an RNN?

6. Why is attention easier to parallelize than recurrence?

7. What is the computational complexity of full self-attention?

Common Mistakes

  • Thinking attention is itself a memory rather than a retrieval mechanism.
  • Confusing keys and values.
  • Believing attention replaces every other neural network component.
  • Assuming attention always sees every token; masks and sparse patterns can restrict it.
  • Forgetting that attention has quadratic cost in sequence length.

Connection To Transformers

Attention lets tokens communicate directly. The next chapter asks what happens if we build an entire architecture around attention, removing recurrence altogether. That is the transformer.