Scaled dot-product self-attention and masking
What it is
Self-attention derives queries, keys, and values from the same sequence, then computes softmax(QKᵀ / √d) V. The dot-product matrix contains every query–key compatibility score; dividing by √d keeps their scale manageable before softmax. Padding masks prevent attention to fake tokens added only to make batches rectangular, while causal masks prevent a next-token model from seeing future tokens. Multi-head attention repeats this with several smaller learned projections, then combines the resulting contexts.
Why it matters
The mask is part of the model definition. Without the causal mask, a language model can cheat during training by reading the answer it is asked to predict, producing impressive training loss and a useless generator. Standard attention also creates an n×n matrix, so context length affects memory and compute quadratically; efficient-attention methods are responses to that concrete bottleneck, not merely architectural fashion.
In the real world: How a language model relates every word in a contract to every other word.
Visual example
Interactive causal maskSelect a token: cells to its right are absent, so its prediction cannot use future information.
Why this matters
A causal mask changes what the model is permitted to know. It enforces the same left-to-right information boundary it will have while generating text.
Common misconception
Wrong idea: the model simply learns not to look right.
Correct idea: the mask removes future positions from the softmax entirely, so looking right is mathematically impossible during training.
import torch
import torch.nn.functional as F
x = torch.randn(2, 6, 64) # (batch, tokens, d_model)
q, k, v = W_q(x), W_k(x), W_v(x) # all three from the SAME x
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
out.shape # (2, 6, 64)Ignoring the quadratic attention matrix. Standard attention over length n stores and computes n² pairwise interactions, which dominates long-context memory and runtime.
Practise it: ReLU, Forward and Backward, Scaled Dot-Product Attention