Guided pathThis is part of Understand Transformers & BERTBack to the path

Scaled Dot-Product Attention

P10.attention.02 · Audience: guest, it-ml, language-pro · Prerequisites: What is Attention?

Customise the corpus these labs use
Real LLM grading for this pageLLM grading (this page):

How the Transformer decides which tokens to attend to — every intermediate tensor computed live from the demo corpus.

Step 1 / 6Input: Position-Aware Embeddings
🗣️ From a linguist's perspective: the sentence as a matrix
Think of the input as a table of contextualised word profiles: each row is one word's complete descriptive record — its meaning features and its place in the sentence — written in numbers instead of prose.
ⓘ Concept: Q, K, V — three roles for every token
Attention gives each token three roles: a query (what am I looking for?), a key (what do I offer?), and a value (what content do I carry?). Unlike the fixed co-occurrence statistics of Block 4, the W matrices are learned by backpropagation — here they are seeded random stand-ins you can reshuffle with the seed control.
Q=XWQ,K=XWK,V=XWVWQ,WK,WVRdmodel×dkQ = X W_Q,\quad K = X W_K,\quad V = X W_V \qquad W_{Q},W_{K},W_{V} \in \mathbb{R}^{d_{\mathrm{model}} \times d_k}

Why it matters — Every contextual embedding a Transformer produces starts from these three projections — asking (Q), advertising (K), and carrying content (V).

Reference: Vaswani et al. 2017 — Attention Is All You Need

Computing…

🎓 Interview deep-dive

Causal vs bidirectional masking. Encoders (BERT) attend in both directions; decoders (GPT) apply a causal mask — token i may only attend to positions ≤ i — implemented by setting the upper triangle of the score matrix to −∞ before softmax. The padding mask you toggled above is the same trick applied to a different pattern.

Complexity. Attention is O(n²·d) in sequence length — the reason long-context models need FlashAttention (tiling that never materialises the full n×n matrix in slow memory) and activation checkpointing during training.

📚 Go further

Check your understanding

The raw score between token i and token j is computed how?

Why divide the scores by √d_k before softmax?

What does each row of the weight matrix sum to, and why does that matter?

Ask the mentor about this module

Ask a question about this content. The mentor explains and grounds its answer in what you are studying; asking is recorded as a learning signal, not a grade.

Ctrl/Cmd + Enter to send

🎓 Practice ladder

1 graded rung · ~12 min

Walk the five steps yourself. The rung is a three-panel workspace: instructions, a code editor, and output + test results. Run checks the visible tests; Submit grades against hidden edge cases — the weights must be row-stochastic, the scores scaled by √dₖ before softmax, and the context a weighted sum of the value rows.

Rung 1 — One attention head, five steps

Loading exercise…

Capstone — Explain attention

Prompt. Explain the attention mechanism to someone who has never studied machine learning. Your explanation should cover: (1) what attention scores measure, (2) why we divide by √dₖ, and (3) how softmax turns scores into weights. Write your own answer first, then reveal the model answer.

💡 Model answer

What attention scores measure. Every word sends out a question (its Query vector) asking the rest of the sentence for relevant context, and simultaneously publishes an advert (its Key vector) describing what it has to offer. An attention score is the dot product of one word's question with another word's advert — a high score means the two are a good match, so the first word should attend to the second.

Why divide by √dₖ. With many dimensions (large dₖ) each dot product sums many products, so its magnitude grows with dₖ. Very large scores push softmax into saturation — one weight becomes ≈ 1 and the rest ≈ 0 — which slows learning. Dividing by √dₖ scales the scores back to a manageable range and keeps the distribution spread across positions.

How softmax turns scores into weights. Softmax exponentiates every score (making them positive) and divides each by the total, so they sum to exactly 1 — a probability distribution. Each token's context vector is then a weighted average of all Value vectors: a token that assigns 0.7 to the subject takes 70 % of its new representation from the subject's value vector.

Try it yourself

A scratch console for this page's ideas — ungraded, nothing you run here is recorded.

Scratch console

A scratch console with the scientific stack (pandas, numpy, scikit-learn). Runs on the server — no network, resource-limited and measured.

Output appears here.

Where next?

Continue

Multi-Head Attention

Attention · P10

Later in Attention