Topic 06 of 62 · Inside the Transformer block
Self-attention and the √d scale
MediumFollow one token: how do queries, keys, masking, and values produce a contextual representation?
Video explanation
Inside Self-Attention
Build it from one example
- 01
0:00 · What problem are we solving?
At “sat”, gather context from “The”, “cat”, and “sat” itself. We are updating a representation, not choosing the next word.
Keep the result above in view. Next, we will use it to work through: 0:35 · Why three vectors: Q, K, V?.
1 · The core intuition
Start with “The”, “cat”, “sat”. These are simplified position labels, not a claim about a particular tokenizer. Focus on “sat”: it needs a representation informed by the context so far. Causal self-attention combines information from earlier positions and the current position itself. The result is an updated vector, not a next-token prediction. Follow the same sequence as the video: project → compare → scale → mask → normalize → mix.
2 · How the mechanism works
Mechanism step 1 of 6 · no question to answer
Project
Stack input vectors into X and use three learned projections: Q = XW_Q, K = XW_K, V = XW_V.
Next, we will look at: Compare. Move on when this operation makes sense.
Visualizing the behavior
The video’s “sat” query: three scores become three weights
Illustrativesoftmax([1, 0, 1] / √2)
3 · The governing equation
Q = XW_Q, K = XW_K, V = XW_V S = QKᵀ / √dₖ Mᵢⱼ = 0 if j ≤ i, otherwise −∞ A = softmax(S + M, across keys) O = AV
Notation: One sequence, one head: Q and K are [T, dₖ]; Kᵀ is [dₖ, T]; S, M, and A are [T, T]; V and O are [T, dᵥ]. Rows identify queries and columns identify keys. The mask here is causal, with no padding; every row has at least one allowed key.
Why √dₖ rather than dₖ? Under independent, zero-mean, unit-variance component assumptions, each product qᵢkᵢ has variance 1. Adding dₖ such products gives Var(q·k) = dₖ and standard deviation √dₖ. Dividing by √dₖ restores unit variance under those assumptions, reducing dimension-driven softmax saturation. This is an explanatory assumption, not a promise that trained scores always have unit variance or uniform weights.
4 · Put concrete numbers on it
Illustrative scenario5 · Common misconception to avoid
Do not replace forbidden scores with zero before softmax: exp(0) = 1. Use −∞ so the forbidden weight is zero. Keep the diagonal allowed, mix V rather than K, and do not confuse attention weights over positions with probabilities over the next word.
In practice · implementation & engineering rule of thumb
First reproduce the video’s one-query calculation, then implement the complete causal operation. The reference below uses one sequence and one head, without padding or dropout. For production, PyTorch scaled_dot_product_attention can select an optimized backend when the inputs and hardware support it; this is an implementation extension beyond the video.
import math
import torch
import torch.nn.functional as F
# Video example: only the final query, with all three keys allowed.
q_sat = torch.tensor([[1., 0.]])
k = torch.tensor([[1., 0.], [0., 1.], [1., 1.]])
v = torch.tensor([[1., 0.], [0., 2.], [1., 1.]])
scores = (q_sat @ k.T) / math.sqrt(q_sat.size(-1))
weights = scores.softmax(dim=-1) # ≈ [[0.401, 0.198, 0.401]]
output_sat = weights @ v # ≈ [[0.802, 0.797]]
# Full sequence reference: q, k: [T, d_k]; v: [T, d_v].
def causal_attention(q, k, v):
scores = (q @ k.T) / math.sqrt(q.size(-1))
allowed = torch.ones(q.size(0), k.size(0),
dtype=torch.bool, device=q.device).tril()
weights = scores.masked_fill(~allowed, float('-inf')).softmax(dim=-1)
return weights @ v, weights
# For full-sequence q, k, v (not the isolated q_sat above):
# out = F.scaled_dot_product_attention(q, k, v,
# is_causal=True, dropout_p=0.0)Go one level deeper
Follow-ups that often come after a correct first answer.
- Cost grows with sequence length squared
- Per head, QKᵀ costs about 2·T²·dₖ FLOPs and the weighted sum over V costs the same again, and the score matrix is T × T. FlashAttention avoids writing that matrix to GPU memory by tiling with an online softmax. It changes memory traffic, not the O(T²) arithmetic.
- Why multiple heads
- With H heads of width dₖ = d_model / H, the Q, K, V and output projections still total about 4·d_model² parameters, whatever H is. Each head can learn a different attention pattern. The head outputs are concatenated and mixed by W_O.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhy can’t forbidden positions be assigned a score of zero before softmax?
Show follow-up reasoning
Because softmax exponentiates scores: exp(0) = 1, so a zero score still contributes positive mass. A forbidden score of −∞ exponentiates to zero. Apply the mask before softmax so normalization is over allowed keys only; for this causal mask, every row includes its diagonal.