Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

LABS · 07  /  ATTENTION

The Spotlight.

Inside a Transformer, every word gets to look at every other word and decide how much to listen to each one. Click a word and watch its spotlight fall — the verb leaning on its subject, the determiner pointing at its noun — as glowing links whose weights add up to one.

THE GIST · 20 SECONDS

Self-attention is how a Transformer moves meaning between words. Each token asks a query, compares it to every token's key to get scores, and a softmax turns those into weights that sum to 1. The token's new value is a weighted blend of all the values. So "sat" can pull in "cat" (its subject) and "mat" (its place) — context, computed.

  • Querywhat a word looks for
  • Keywhat a word offers
  • Weighthow much to attend
  • Sum = 1a softmax split

Click any word to make it the query — the links and shading show how its attention is split across the sentence.

UNDER THE HOOD

What you just played, written down

Every token blends in a little of every other token, weighted by relevance. That weighted blend — computed for all tokens at once — is the whole reason Transformers understand context.

How attention works — four moves

  1. Three projections. Each token becomes a query (what I want), a key (what I offer), and a value (what I carry).
  2. Score every pair. A token's query is compared to every key by dot product — high score means "very relevant to me".
  3. Softmax to weights. Scores go through a softmax, becoming non-negative weights that sum to 1 — an attention budget.
  4. Blend the values. The token's output is the weighted sum of all the values, so it absorbs context from the words it attends to.
WHAT YOU'RE SEEING

The links and bars show the softmax weights — the "attends to" part of attention. The full operation then multiplies those weights by the value vectors and sums them: softmax(QKᵀ/√d)·V. These particular numbers are a fixed, hand-picked example built to look like real trained attention, not a live Q·K computation over real query/key vectors — the shape (weight sums to 1, a word leans on the words it depends on) is what a real model actually does.

The whole thing in code

import numpy as np

def attention(Q, K, V):
    d = Q.shape[-1]
    scores = Q @ K.T / np.sqrt(d)      # query · key, scaled
    weights = softmax(scores, axis=-1) # sum to 1 per row
    return weights @ V                 # blend the values

def softmax(x, axis=-1):
    e = np.exp(x - x.max(axis, keepdims=True))
    return e / e.sum(axis, keepdims=True)
WEIGHTSsum to 1softmax over keys
SCALE÷ √dkeeps softmax stable
MANY HEADS, MANY VIEWS

Real models run several attention heads in parallel, each with its own projections. One head may track subjects and verbs, another coreference or position — then their outputs are combined.

⚠ It's quadratic

Every token attends to every token, so cost grows with the square of the sequence length. That's why long context is expensive — and why FlashAttention and linear-attention variants exist.

↔ Self vs cross

Self-attention: queries and keys come from the same sequence (what you see here). Cross-attention: queries come from one sequence, keys/values from another — how a decoder reads an encoder.

★ Where it's used

The core of every Transformer — GPT, BERT, Claude, and Vision Transformers — plus modern speech and multimodal models. Attention is the mechanism the whole era is built on.

STEP BY STEP

Attention, step by step

Scaled dot-product attention as one formula, run by hand on three tokens with two-dimensional vectors, and the costs and tricks that matter once the sequence gets long.

The formula, in five moves

  1. Project. Multiply the token matrix X by learned matrices to get Q, K and V, one row per token.
  2. Score. Compute QKᵀ: entry (i, j) is how strongly token i's query matches token j's key.
  3. Scale. Divide by √dk. A dot product of d-dimensional vectors has variance proportional to d, so without this the softmax saturates in high dimensions and its gradients vanish.
  4. Mask and normalize. For a decoder, set every entry above the diagonal to −∞ so a token cannot see the future, then softmax each row.
  5. Blend. Multiply the weights by V. Each output row is a weighted average of value rows.
Attention(Q, K, V) =
  softmax(Q Kᵀ / sqrt(d_k) + mask) V

Worked example: three tokens, dk = 2

  1. Inputs. Q rows (1, 0), (0, 1), (1, 1); K rows (1, 0), (0, 2), (1, 1); V rows (1, 0), (0, 1), (2, 2).
  2. Scores QKᵀ. Rows read 1, 0, 1 / 0, 2, 1 / 1, 2, 2. Divide by √2 = 1.414 to get 0.707, 0, 0.707 / 0, 1.414, 0.707 / 0.707, 1.414, 1.414.
  3. Softmax, row 3. e0.707 = 2.03 and e1.414 = 4.11, a total of 10.25, so the weights are 0.198, 0.401, 0.401, which sum to 1. Without scaling they would be 0.155, 0.422, 0.422.
  4. Output, row 3. 0.198·(1, 0) + 0.401·(0, 1) + 0.401·(2, 2) = (1.000, 1.203). Rows 1 and 2 give (1.203, 1.000) and (0.708, 1.144).
  5. Causal mask. Row 1 can only see itself: weights (1, 0, 0), output (1, 0). Row 2 sees tokens 1 and 2: weights 0.196 and 0.804, output (0.196, 0.804). Row 3 is unchanged, since it sees everything.

⚠ The n × n matrix

At 8,192 tokens each head holds 67,108,864 scores, 134 MB in FP16, and about 8.6 billion multiply-adds (17 billion FLOPs) for QKᵀ alone at head size 128. Doubling the length quadruples both.

↔ Heads and caching

Multi-head attention splits the model width into several smaller attention operations whose outputs are concatenated, so different heads can follow different relations. When generating, the keys and values of past tokens are cached, so each new token costs one new row of scores.

★ In production

FlashAttention computes exactly the same result in tiles that stay in fast on-chip memory, never writing the full matrix, so it is faster and uses far less memory without approximating anything. Grouped-query attention shares key and value heads to shrink the cache.

THE PICTURE

The picture: one query, from scores to output

query key score q·k/√2 weight × value output q3 (1,1) k1 (1,0) k2 (0,2) k3 (1,1) 1/√2 = 0.707 2/√2 = 1.414 2/√2 = 1.414 0.198 × (1,0) 0.401 × (0,1) 0.401 × (2,2) (1.000,1.203) softmax: e^s ÷ (2.03 + 4.11 + 4.11), so the weights sum to 1
Row 3 of the worked example above. The query (1, 1) is scored against each key, divided by √2, and the softmax turns the three scores into 0.198, 0.401 and 0.401. The output is those weights times the value rows, summed: (1.000, 1.203). The widget draws only the weights; this is the whole path from a query to its new vector, and every row of the matrix runs it at once.
TRADE-OFFS

Complexity and trade-offs

For one head over n tokens with head size d. Several heads of size d/h do the same arithmetic as one head of full width, but hold h score matrices.

CaseTimeSpaceWhy
Full attention, training or prefillO(n²·d): 8,192² × 128 ≈ 8.6 billion multiply-adds for QKᵀ in one headO(n²) scores: 67,108,864 per head, 134 MB in FP16Every query meets every key. Doubling n quadruples both.
FlashAttentionThe same O(n²·d), exactO(n) extra: the n × n matrix is never written outTiles stay in on-chip memory, so it runs faster with identical arithmetic.
Decoding with a KV cacheO(n·d) per new token: one row of scoresO(n·d) per head per layer for cached keys and valuesLlama 3 8B caches 128 KiB per token; 8,192 tokens is 1 GiB per sequence.
Decoding without a cacheO(t²·d) for token t, so about n³/3 score entries to generate n tokensO(n²) per stepRecomputes every past key and value on every step. Nobody serves this way.
Grouped-query attentionAbout the same as fullCache divided by query heads ÷ KV headsLlama 3 8B shares 8 KV heads among 32 query heads: a 4× smaller cache.

At 8,192 tokens and head size 128, QKᵀ is 8,192 × 8,192 × 128 ≈ 8.6 billion multiply-adds, or about 17 billion floating-point operations, since each multiply-add is two. Either way the n² term is why long context is expensive: going from 8,192 to 32,768 tokens multiplies the score work by 16.

WATCH FOR

Common mistakes when implementing attention

  • Normalizing the wrong axis

    The softmax runs across keys, along each query’s row (axis=-1 on QKᵀ). Run it down the columns and each key’s weights sum to 1 instead, so a query’s output is no longer a weighted average. The shapes still line up, so nothing errors.

  • Forgetting the causal mask in training

    A decoder trained without the mask can read the very token it is meant to predict. Training loss drops suspiciously fast, then generation, where the future really is unknown, falls apart. In the worked example the mask is what turns row 1’s output from (1.203, 1.000) into (1, 0).

  • Ignoring padding, or masking a whole row

    Batched sequences are padded to one length. Without a padding mask, real tokens attend to pad tokens and the output changes with the batch. The opposite edge: a row with every key masked is a softmax of all −∞, which is 0/0 = NaN, and the NaN spreads through every later layer.

  • Scaling by the model width, not the head size

    The divisor is the square root of one head’s size, d_k. With 32 heads of 128 in a 4,096-wide model that is √128 ≈ 11.3, not √4,096 = 64. Divide by 64 and every score is 5.7 times too small, so the softmax comes out far flatter than the model was designed for.

  • Reading the weights as an explanation

    A weight says where one head looked in one layer, not why the model answered. The output projection and later layers remix every head, and a large weight on a near-zero value vector contributes almost nothing. The widget’s hand-picked weights are exactly the kind of picture that is easy to over-read.

QUICK CHECK

Did it stick?

See every answer, with the reasoning
  1. In self-attention, what do a token’s attention weights represent?

    Answer: How much of each other token it blends into its own representation — Each token computes a weight over every token (via softmax of query·key). Those weights say how much of each token’s value to mix in — so a token gathers context from the words it attends to.

  2. Why do a query’s attention weights sum to 1?

    Answer: Because a softmax turns the raw scores into a probability distribution — The query·key scores are passed through a softmax, which exponentiates and normalizes them into non-negative weights that sum to 1 — a proper attention budget split across the tokens.

  3. What are the query, key, and value in attention?

    Answer: What a token looks for, what it offers, and what it contributes — Each token is projected into a query (what it seeks), a key (what it advertises), and a value (the information it passes on). Scores come from query·key; the output is the softmax-weighted sum of values.

FAQ

Attention, answered

What is self-attention?

A mechanism where every token looks at every other token and weights how much to draw from each. A token's new representation is a weighted blend of all tokens' values, with the weights from softmax over query·key scores.

What are query, key, and value?

Three projections of each token: the query (what it's looking for), the key (what it offers), and the value (what it contributes). Scores are query·key; the output is the softmax-weighted sum of values.

Why do the weights sum to one?

A softmax turns the raw scores into a probability distribution — non-negative and summing to 1 — so each token's output is a proper weighted average.

Why divide by √d?

Dot products grow with dimension and can make the softmax too peaked (tiny gradients). Scaling by √d keeps scores in a stable range — the "scaled" in scaled dot-product attention.

What is multi-head attention?

Several attention computations in parallel, each with its own projections. Different heads capture different relationships, and their outputs are concatenated and combined.

RESULT

—

Next → stack these attention layers dozens deep, add feed-forward blocks, and train on the internet — that's a Transformer, the engine behind every modern LLM.

Finished this one? 0 / 61 Labs done
NextInside a Transformer: Self-Attention Next on the “The transformer, opened up” ladder · rung 2 of 5

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Labs