Skip to content

Why does attention scale the logits by √d_k?

AdvancedAsked sometimesConcept roundConceptTransformers
Asked atGoogleOpenAIAnthropic
#transformers#attention#softmax#scaling#gradients

Company tags are compiled from public interview reports and are signals, not guarantees.

What interviewers are testing

Interviewers use this question to separate candidates who memorized the Transformer diagram from those who understand why the architecture resists saturation. The tell is whether you can connect d_k, the variance of a dot product, and the softmax Jacobian into one causal chain instead of reciting "to keep gradients stable". Follow-ups about QK normalization, temperature, and numerically stable softmax reveal whether the mental model generalizes beyond the original paper.

Mental model

Every attention logit is a dot product of two roughly independent random vectors, so its variance grows linearly with d_k and its standard deviation grows with √d_k. Large logits push softmax into saturation, where the largest weight approaches 1, the rest approach 0, and the Jacobian collapses so almost no gradient reaches the queries and keys. Dividing by √d_k restores unit variance and keeps softmax in its responsive, well-conditioned regime.

Step-by-step solution

  1. Step 1: Variance grows with d_k

    Start with a single attention logit: the dot product of one query row against one key column, written as a sum of d_k products. If query and key entries are roughly independent with zero mean and modest variance, the variance of the sum grows linearly with d_k, so its standard deviation grows with the square root of d_k. At d_k = 64 the logits already have a standard deviation near eight; at d_k = 512 it approaches twenty-three. Softmax is exponential, so it amplifies exactly the gaps the scaling leaves behind. Drag the slider in the animation to change d_k and watch the unscaled logit histogram widen while the largest softmax weight climbs toward one. Dividing the logits by √d_k rescales their variance back to roughly one, which keeps softmax in the range where it can represent differences instead of saturating on them.

  2. Step 2: The scaled dot-product pipeline

    Attention is a pipeline, not a single multiply. First the input tokens are projected into three matrices: queries ask what each token is looking for, keys advertise what each token contains, and values carry the content to be mixed. Every query is dotted with every key to produce an n × n score matrix, and that is where the scaling by √d_k lands, before any exponentiation. Softmax then normalizes each row of scaled scores into weights that sum to one, turning raw similarity into a distribution. Finally, each token's output is the weighted sum of all value vectors, so every position collects context from the positions it attends to. Watch the animation as each phase feeds the next: tokens to Q/K/V, logits, weights, and finally context vectors. The scale factor sits at the softmax boundary on purpose — after the dot product, before the nonlinearity that turns magnitudes into decisions.

  3. Step 3: Saturation versus healthy weights

    Saturation is what makes the scale factor matter. When logits are large, exp amplifies the largest one far more than the rest, so softmax returns a near one-hot vector: one weight close to one and every other weight close to zero. That looks decisive, and it is a dead end for learning. The Jacobian of softmax is diag(p) − p pᵀ, and when p is close to one-hot, every entry of that Jacobian approaches zero, so almost no gradient survives the trip back to the queries and keys. The head effectively stops updating. Scaling by √d_k prevents the logits from arriving that large in the first place. Compare the two panels in the animation: the unscaled row collapses onto a single token, while the scaled row spreads attention across several plausible tokens. A spread distribution has nonzero entropy and a well-conditioned Jacobian, which is exactly what the backward pass needs.

  4. Step 4: Trace the scaling in PyTorch

    The standard PyTorch one-liner hides the entire mechanism behind familiar operators. First, queries, keys, and values are linear projections of the same input tensor. The score matrix is one batched matmul, Q @ K.T, giving all pairwise dot products at once. Then every logit is divided by the square root of d_k — the per-head dimension, not the model dimension — before softmax normalizes each row. Multiplying by V produces each token's contextualized vector. Watch the shape variables in the animation: Q and K are (n, d_k), scores are (n, n), and the softmax rows always sum to one regardless of sequence length. Modern code often calls F.scaled_dot_product_attention(q, k, v), which fuses these steps and adds a numerically stable softmax, but the math being executed is exactly the line shown here. The scale factor is constant per head, so it costs nothing at runtime.

  5. Step 5: Keep logits well-conditioned

    Production softmax implementations subtract the row maximum before exponentiating for numerical stability, but that trick only prevents overflow — it does not fix saturation. Subtracting a constant leaves the relative gaps between logits unchanged, so if the raw logits have a standard deviation of twenty, the distribution is still one-hot after the shift. Keeping logits well-conditioned requires something upstream: dividing by √d_k is the original fix, and modern models add their own tools. Query-key normalization rescales q and k to unit variance so their dot products stay bounded as heads grow; attention logit soft-capping compresses extreme logits; temperature schedules and careful initialization keep propagation stable through the residual stream. Watch the animation: the max subtraction is a safety rail, the scaling is the actual fix, and the gradient signal only stays usable when the two are in place together.

Edge cases & traps

  • Scaling by the model dimension instead of the per-head dimension: the denominator must be d_k = d_model / num_heads, or the logits are shrunk too aggressively and attention flattens toward uniform.
  • Applying the scale after softmax: dividing the weights by √d_k breaks their sum-to-one constraint — the factor belongs on the logits before the softmax.
  • Trusting the numerically stable softmax (row-max subtraction) to fix saturation: it prevents overflow but leaves the relative logit gaps untouched, so one-hot weights and vanishing gradients remain.
  • Hard-coding the scale from sequence length: the factor depends only on d_k and is constant per head — recomputing it from context length is a conceptual bug.
  • Dismissing the issue because small heads still train: the effect is mild for tiny d_k, which is why the failure only shows up as head size or depth grows.

Follow-up questions

Go deeper: Explore the AI visualizer