we have frontier at home dj.kz · transformer & systems notebook
← All essays

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.

Residual stream x ∈ ℝ^(T × d) RMSNorm Multi-Head Causal Attention + RMSNorm SwiGLU MLP Block + token mixing (O(T² · d)) channel mixing (O(T · d²))
Figure 1. A standard Pre-LN transformer decoder block. Attention moves information across token positions while the SwiGLU MLP transforms each position independently.

Inside the attention block, each query vector q∈Rdkq \in \mathbb{R}^{d_k} scores every key vector k∈Rdkk \in \mathbb{R}^{d_k} before normalizing with a softmax:

Attention⁡(Q,K,V)=softmax⁡ ⁣(QK⊤dk+M)V\operatorname{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M\right) V

where MM is the causal mask (Mij=0M_{ij} = 0 for j≤ij \le i and −∞-\infty otherwise).

The variance problem

Suppose the entries of qq and kk are independent random variables with mean 00 and variance 11. Their dot product is a sum of dkd_k products:

z=q⋅k=∑i=1dkqikiz = q \cdot k = \sum_{i=1}^{d_k} q_i k_i

Each term qikiq_i k_i has mean 00 and variance Var⁡(qi)Var⁡(ki)=1\operatorname{Var}(q_i)\operatorname{Var}(k_i) = 1, so the unscaled logit has variance equal to the head dimension:

E[z]=0,Var⁡(z)=dk,std⁡(z)=dk.\mathbb{E}[z] = 0, \qquad \operatorname{Var}(z) = d_k, \qquad \operatorname{std}(z) = \sqrt{d_k}.

When dk=64d_k = 64 or 128128, typical dot products swing by ±8\pm 8 to ±12\pm 12 at initialization. Passing logits of that magnitude through softmax⁡\operatorname{softmax} pushes nearly all probability mass onto whichever single key happens to win by chance.

Interactive explorer

Try toggling the 1/dk1/\sqrt{d_k} scaling off below and sliding dkd_k from 8 up to 256. Watch the entropy drop and the attention distribution collapse onto a single token per row.

Logit std σ 1.00
Mean entropy H 1.01 nats
Max weight 1.00
Query row: context

Click any row to inspect its softmax distribution.

Figure 2. Interactive scaled dot-product attention heatmap. Toggle scaling off and increase d_k to observe softmax saturation; click any query row to inspect its distribution.

Minimal PyTorch implementation

In practice, fused kernels like FlashAttention apply the 1/dk1/\sqrt{d_k} scaling on the fly inside SRAM before computing the online softmax, avoiding ever materializing the full T×TT \times T 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 dk\sqrt{d_k} restores Var⁡(z/dk)=1\operatorname{Var}(z / \sqrt{d_k}) = 1 independent of head width—a small algebraic constant that decouples optimization stability from model scaling.