4.1.4Transformer Architecture

Scaled dot-product attention

2,212 words10 min readdifficulty · medium2 backlinks

What Is Scaled Dot-Product Attention?

Components breakdown:

  1. QKTQK^T: Compatibility scores (how well each query matches each key)
  2. 1dk\frac{1}{\sqrt{d_k}}: Scaling to prevent gradient saturation
  3. softmax: Converts scores to probability distribution (weights sum to 1)
  4. Multiply by VV: Weighted sum of values based on attention weights
Figure — Scaled dot-product attention

Derivation From First Principles

Step 1: Why Dot Product for Similarity?

Start with the fundamental question: How do we measure if query qq matches key kk?

The dot product qk=i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i measures alignment:

  • If qq and kk point in the same direction: large positive value
  • If orthogonal: zero
  • If opposite: large negative value

Why this step? We need a differentiable similarity metric. Dot product is computationally cheap (O(dk)O(d_k)) and naturally captures semantic similarity in embedding spaces.

Step 2: Matrix Form for Batch Processing

For nn queries and mm keys: S=QKTRn×mS = QK^T \in \mathbb{R}^{n \times m}

where Sij=qikjS_{ij} = q_i \cdot k_j is the compatibility score between query ii and key jj.

Why this step? Modern hardware (GPUs/TPUs) is optimized for matrix multiplication. Batching all queries at once is100x faster than loping.

Step 3: The Scaling Problem

Observation: If QQ and KK have entries drawn from N(0,1)\mathcal{N}(0, 1), then:

E[qk]=E[i=1dkqiki]=i=1dkE[qi]E[ki]=0\mathbb{E}[q \cdot k] = \mathbb{E}\left[\sum_{i=1}^{d_k} q_i k_i\right] = \sum_{i=1}^{d_k} \mathbb{E}[q_i]\mathbb{E}[k_i] = 0

Var(qk)=i=1dkVar(qiki)=i=1dkE[qi2]E[ki2]=dk\text{Var}(q \cdot k) = \sum_{i=1}^{d_k} \text{Var}(q_i k_i) = \sum_{i=1}^{d_k} \mathbb{E}[q_i^2]\mathbb{E}[k_i^2] = d_k

So the standard deviation grows as dk\sqrt{d_k}! For typical dk=64d_k = 64, dot products have std 8\approx 8.

Why this matters: Softmax is σ(z)i=ezijezj\sigma(z)_i = \frac{e^{z_i}}{\sum_j e^{z_j}}. When inputs have large magnitude:

  • Large positive values: softmax \approx one-hot (gradient 0\approx 0)
  • Relative differences shrink: hard to learn which key is slightly better

The fix: Divide by dk\sqrt{d_k} to normalize variance back to 1: Var(qkdk)=dkdk=1\text{Var}\left(\frac{q \cdot k}{\sqrt{d_k}}\right) = \frac{d_k}{d_k} = 1

Step 4: Softmax Normalization

Apply softmax row-wise to convert scores to attention weights: A=softmax(QKTdk)Rn×mA = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right) \in \mathbb{R}^{n \times m}

where Aij=exp(Sij/dk)j=1mexp(Sij/dk)A_{ij} = \frac{\exp(S_{ij}/\sqrt{d_k})}{\sum_{j'=1}^m \exp(S_{ij'}/\sqrt{d_k})}.

Why this step?

  • Probabilistic interpretation: Each row of AA is a distribution over keys (jAij=1\sum_j A_{ij} = 1)
  • Differentiability: Smooth function for backprop
  • Competition: Keys compete—attending more to one means less to others

Step 5: Weighted Value Aggregation

Finally, use attention weights to take a weighted average of values: outputi=j=1mAijvj\text{output}_i = \sum_{j=1}^m A_{ij} v_j

In matrix form: Attention(Q,K,V)=AVRn×dv\text{Attention}(Q, K, V) = AV \in \mathbb{R}^{n \times d_v}

Why this step? The query "asks a question," keys "match the question," and values "provide the answer." We retrieve a soft-blended answer based on relevance.

Worked Examples

Common Mistakes

Active Recall Flashcards

#flashcards/ai-ml

What is the formula for scaled dot-product attention? :: Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

Why do we scale by dk\sqrt{d_k} instead of dkd_k?
Because variance of dot product grows as dkd_k, so std grows as dk\sqrt{d_k}. Dividing by dk\sqrt{d_k} normalizes variance back to 1, keeping softmax in its sensitive gradient region.

What is the shape of QKTQK^T if QQ isn \times d_kandandKisism \times d_k?:::? ::: n \times m(eachelement(each element(i,j)isthesimilaritybetweenqueryis the similarity between queryiandkeyand keyj$)

What happens if you don't scale the dot product with large dkd_k?
Softmax saturates (becomes nearly one-hot), gradients vanish, and the model can't learn subtle differences between keys.
In attention mechanism, what do Q, K, V represent?
Q (query): what you're looking for; K (key): what's available to match; V (value): actual content to retrieve.
What does the softmax output represent in attention?
A probability distribution over keys—attention weights that sum to 1, indicating how much to "look at" each position.
Why use dot product instead of other similarity metrics?
Computationally efficient (O(dk)O(d_k)), differentiable, naturally captures alignment in embedding spaces, and hardware-optimized (matrix multiplication).
What is the output dimension of attention with nn queries and mm keys?
n×dvn \times d_v (one output vector per query, each with dimension dvd_v)

Mnemonic

Feynman Explanation

Recall Explain to a 12-year-old

Imagine you're doing homework and you can ask your textbook questions. But your textbook is HUGE—hundreds of pages.

Attention is like a smart search system:

  1. Query (Q): You write down your question: "What is photosynthesis?"
  2. Keys (K): Each page in the textbook has a title/summary (like "Plants," "Cells," "Energy "History")
  3. Comparison: You check how well your question matches each page title. The "Plants" page is a great match (score = 10), "Energy" is okay (score = 5), "History" barely matches (score = 1).
  4. The Scaling Trick: If your textbook was MASSIVE (thousands of pages), the scores would get huge (score = 1000 for best match). That makes your brain say "ONLY look at this ONE page" and ignore everything else. Scaling is like saying "let's keep scores between 1-10 so I consider multiple pages."
  5. Softmax: Convert scores to percentages: 70% Plants, 25% Energy, 5% History.
  6. Values (V): Each page has actual content (paragraphs about plants, energy, etc.)
  7. Output: You read70% of the Plants page, 25% of Energy page, 5% of History page, and blend them into one answer.

Why scaling matters: Without it, you'd become a robot that reads ONLY the top match and ignores everything else—even if the second-best page has useful info too! Scaling keeps your mind open to multiple sources.

Connections

  • Multi-Head Attention — uses multiple scaled dot-product attention operations in parallel
  • Self-Attention — when Q, K, V all come from the same sequence
  • Cross-Attention — when Q comes from one sequence, K/V from another (encoder-decoder)
  • Softmax Function — the normalization function that converts scores to probabilities
  • Gradient Descent — why scaling matters for stable learning
  • Positional Encoding — provides sequence order information (attention is permutation-invariant)
  • Query-Key-Value Model — the conceptual framework borrowed from information retrieval
  • Attention Mask — used to prevent attending to certain positions (future tokens, padding)

Last updated: 2026-07-01 | Master this before moving to multi-head attention

Concept Map

matches against

matched by

has variance d_k

std grows sqrt d_k

saturates

causes

prevents

divided by

feeds

weights

weighted sum

Query Q

Compatibility Scores QK^T

Key K

Variance grows with d_k

Large dot products

Softmax saturation

Vanishing gradients

Scale by 1 over sqrt d_k

Softmax weights sum to 1

Value V

Attention Output

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Scaled dot-product attention basically ek smart tarika hai information retrieve karne. Socho tumhare pas ek query hai (jo tum dhondh rahe ho) aur bahut sare keys hain (jo available options hain). Ab simple dot product se tum check karte ho ki tumhari query kis key se match karti hai. Lekin problem ye hai ki jab dimensions bade ho jate hain (jaise d_k = 64 ya 512), tab dot product ki values bhi bahut badi ho jaati hain. Agar tum directly softmax lagao, toh wo almost one-hot ban jata hai—matlab sirf ek hi key pe focus ho jata hai aur baki sab ignore ho jaate hain. Learning ke liye ye bahut bura hai kyunki model subtle differences nahi seekh pata.

Isliye hum scale karte hain √d_k se divide karke. Ye scaling ensure karti hai ki softmax sensitive region mein rahe, jahan gradients healthy rahein aur model properly learn kar sake. Iske baad softmax se hum attention weights nikaalte hain (probability distribution), aur phir un weights se values ka weighted average lete hain. Final output mein humein mil jata hai ek context-aware representation jo query ke liye sabse relevant information contain karta hai.

Ye mechanism Transformers ka heart hai—bilkul jaise tum library mein relevant books dhoondh rahe ho. Query tumhara sawaal hai, keys books ke titles hain, aur values actual content hai. Scaling ensure karti hai ki tum multiple relevant books consider kar sako, na ki sirf ek pe fixate ho jao. Isi wajah se Transformers itne powerful hain—wo flexible attention patterns seekh sakte hain without losing gradient signal during training.

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections