Why We Divide by √d_k: Geometry of Scaled Dot-Product Attention
A quick look at variance growth in attention logits, softmax saturation, and why a single square-root factor keeps transformer gradients alive.
Every modern decoder-only transformer alternates between two operations reading from and writing to a shared residual stream: token mixing via causal self-attention, and channel mixing via a gated feed-forward network.
Inside the attention block, each query vector scores every key vector before normalizing with a softmax:
where is the causal mask ( for and otherwise).
The variance problem
Suppose the entries of and are independent random variables with mean and variance . Their dot product is a sum of products:
Each term has mean and variance , so the unscaled logit has variance equal to the head dimension:
When or , typical dot products swing by to at initialization. Passing logits of that magnitude through pushes nearly all probability mass onto whichever single key happens to win by chance.
Interactive explorer
Try toggling the scaling off below and sliding from 8 up to 256. Watch the entropy drop and the attention distribution collapse onto a single token per row.
Minimal PyTorch implementation
In practice, fused kernels like FlashAttention apply the scaling on the fly inside SRAM before computing the online softmax, avoiding ever materializing the full score matrix in HBM:
import math
import torch
import torch.nn.functional as F
def scaled_dot_product_attention(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
"""q, k, v: (batch, heads, seq_len, d_k)"""
d_k = q.size(-1)
scores = (q @ k.transpose(-2, -1)) / math.sqrt(d_k)
seq_len = q.size(-2)
mask = torch.triu(torch.ones(seq_len, seq_len, device=q.device, dtype=torch.bool), diagonal=1)
scores = scores.masked_fill(mask, float("-inf"))
weights = F.softmax(scores, dim=-1)
return weights @ v
Dividing by restores independent of head width—a small algebraic constant that decouples optimization stability from model scaling.