# Why Scale Attention Scores by √d_k?

> Why attention divides its scores by the square root of the key size, what breaks without it, and how to explain it simply for your AI interview.

**In short:** Attention scores are dot products, and they grow as the key vectors get longer. Dividing by the square root of the key size, √d_k, keeps the scores at a size where softmax still gives useful weights and the model keeps learning.

AI and LLM interview question Q045, Transformer architecture. Advanced, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/why-scale-attention-scores-by-square-root-of-d-k

## Say it in 30 seconds

Attention scores come from dot products, which get bigger as the vectors get longer. If the scores are too big, softmax puts almost all its weight on one key, and the learning signal nearly disappears. So each score is divided by the square root of the key length. If the numbers in the vectors are roughly random with spread one, that keeps the spread of the scores near one. It is a simple fix, and the Transformer paper's authors suspected that reason.

## Say it in 2 minutes

Attention compares a query vector with every key vector. The comparison is a dot product: multiply the matching numbers and add them up. The longer the vectors, the more numbers get added, so the total can grow big. A claims adjuster comparing one new claim with eight old ones has the same problem. If one old claim scores far higher than the rest, the adjuster looks only at that one.

Those scores then go through softmax, which turns them into weights that add up to one. When one score is much bigger than the others, softmax gives it nearly all the weight. The gradient, the signal that tells training how to adjust, is tiny in that flat region, so learning fades. The Transformer paper's authors suspect this: the dot products grow large, which pushes softmax into a region with extremely small gradients.

The fix is one division. Divide each score by the square root of the key size. If the numbers are roughly random, with an average of zero and a spread of one, the dot product's spread grows with the square root of the key size. Dividing by that square root brings the spread back to about one. In a made-up test, the top weight reached 0.96 at key size 512 without scaling, while the scaled version stayed near 0.37.

Be honest about the limits. The argument assumes near-random, independent values. That can be a fair picture near the start of training, and a trained model may not keep it. It is the usual choice, not a law. PyTorch's attention function uses this same scale by default.

## What is scaling attention scores, in plain words?

Attention lets a model decide which other words matter for the word it is reading now. For each query, it scores every key, then uses those scores to mix the value vectors. Each score is a dot product, and the paper's keys and queries have a fixed size, written d_k: the count of numbers in one key vector.

Scaling means dividing each score by √d_k, the square root of that count. It is one line of code, and it keeps the scores from getting too large before the softmax step.

- **Dot product:** Multiply matching numbers in two lists, then add them up.
- **Key size (d_k):** How many numbers are in each key vector.
- **Softmax:** Turns a list of scores into weights that add up to one.
- **Gradient:** The signal that tells training how to adjust the weights.

Think of a claims adjuster at an insurer comparing a new claim with eight old ones. If one old claim scores far higher than the rest, the adjuster looks only at that one and ignores the others. Attention has the same risk: one huge score can drown out every other key. The scale keeps all the scores in a range where each one still counts.

## Why do the scores get too big?

Take a made-up contract-search model that scores one query against 8 clause keys. With key size 4, the scores spread out by about 1.7, and the top clause takes about half the weight. With key size 512, the spread is about 21, and the top clause takes 96% of the weight. The question stayed the same, and the vectors just got longer.

The reason is simple. A dot product adds up one product for every number in the vector. Add more numbers and the total spreads further from zero. The paper's authors make the point with random vectors. If each number averages zero and has a spread of one, the dot product's variance grows with the key size. Variance measures how far values spread from their average, and its square root is the usual spread, which grows with √d_k.

The authors put it as a suspicion:

> "the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients" (Attention Is All You Need, the Transformer paper)

The paper also notes, citing earlier work, that at larger key sizes unscaled dot-product attention trails additive attention.

*Diagram, Without the scale, and with it: Two paths side by side. Without the scale, big scores push softmax onto one key and the gradient fades. With the scale, the scores stay moderate and the weights keep moving.*
1. Without the scale, the raw scores go straight into softmax.
2. The top key takes almost all the weight, so the learning signal fades.
3. The same raw scores go down the scaled path instead.
4. Dividing each score by √d_k pulls the spread back down.
5. Moderate scores keep the learning signal useful.

## What does dividing by √d_k actually do?

1. **Multiply:** Take the dot product of the query with each key. You get one raw score per key.
2. **Divide:** Divide every score by √d_k, the square root of the key size. Big scores come down to a sensible range.
3. **Softmax:** Turn the scaled scores into weights that add up to one.
4. **Blend:** Mix the value vectors using those weights. The result carries the most weight from the best-matching keys.

*Diagram, Where the scale sits in attention: The chart shows where the division sits: after the dot products, before softmax. Softmax reads the shrunken scores, and the blend comes last.*
1. The raw scores move on to the division, one per key.
2. The scaled scores go into softmax, one per key.
3. The weights move on to blend the value vectors.

> **Tip:** Put the division before softmax. The scale only helps there, where it reshapes the scores before they become weights.

## What does a small test show?

This made-up test runs in plain Python. It scores one query against eight keys, 500 times for each key size, using random numbers. The table in the output shows the spread of the raw scores, the weight on the top key with and without the scale, and the slope of that top weight.

```python
# Made-up contract search: one query scored against 8 clause keys, 500 trials per key size.
import math, random, statistics
random.seed(7)

def softmax(scores):
    exps = [math.exp(s - max(scores)) for s in scores]
    return [e / sum(exps) for e in exps]

def run(d):
    rows = []
    for _ in range(500):
        q = [random.gauss(0, 1) for _ in range(d)]
        raw = []
        for _ in range(8):
            k = [random.gauss(0, 1) for _ in range(d)]
            raw.append(sum(a * b for a, b in zip(q, k)))
        p = max(softmax(raw))
        r = max(softmax([s / math.sqrt(d) for s in raw]))
        rows.append((statistics.pstdev(raw), p, r, p * (1 - p), r * (1 - r)))
    return [statistics.mean(col) for col in zip(*rows)]

print("key size  spread  top weight raw  top weight scaled  slope raw  slope scaled")
for d in (4, 64, 512):
    spread, raw, scaled, raw_g, scaled_g = run(d)
    print(f"{d:>8}  {spread:>6.2f}  {raw:>14.2f}  {scaled:>17.2f}  {raw_g:>12.4f}  {scaled_g:>15.4f}")
```

Output:

```text
key size  spread  top weight raw  top weight scaled  slope raw  slope scaled
       4    1.68            0.53               0.35        0.2045           0.2068
      64    7.16            0.89               0.36        0.0763           0.2166
     512   20.74            0.96               0.37        0.0291           0.2187
```

Read the output with the story in mind. As the key size grows, the raw top weight climbs to 0.96. Its slope, how much the top weight moves when its score moves, is p times (1 minus p) and falls to about 0.03 at key size 512. That is about seven and a half times weaker than the scaled version's 0.22. The scaled version stays between 0.35 and 0.37 at every size. The numbers come from random vectors, so they show the mechanism only.

## Is the square root always the right number?

It is the usual choice, and the reason is simple. It comes from the variance argument above, which keeps the spread near one when the inputs are roughly random with spread one. Three things to say in an interview:

- **It assumes near-random inputs:** The argument needs values that are roughly independent with spread one. That can be a fair picture near the start of training. A trained model may not keep random-looking values, so the spread can differ.
- **Other scales exist:** PyTorch's default is one over the square root of the length of each query and key vector. Its scale argument is optional, so a model can pass a different value.
- **Check that the scale runs once:** A bug to look for is scaling twice, or scaling after softmax. Read the code path as well as the formula.

> "Scaling factor applied prior to softmax." (PyTorch documentation)

### How would you debug attention that locks onto one token?

A made-up contract-search team ported an attention layer from a notebook. After the team raised the key size to 512, every query puts 95% of its weight on one clause, and the search misses the right clause in the top results. Here is how I would check it.

1. **Find the division:** Search the code for the line that divides the scores by √d_k. Make sure it runs once, before softmax.
2. **Check the size:** Print the spread of the raw scores at the key size you use. If the spread is large and the scale is missing, you have found the cause.
3. **Fix and re-test:** Put the division in the right place, then rerun the search on contracts with known answers and count how often the right clause comes back in the top results.

Fixing one line is cheap. The real cost is a search that quietly misses clauses for weeks, so the test with known answers matters most.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain reason: dot products grow with the key size, so the scores get too big.
- [ ] What softmax does with huge scores: one key takes almost all the weight and gradients shrink.
- [ ] The fix: divide by √d_k, before softmax.
- [ ] Why the square root: the spread grows with √d_k, so dividing brings it back near one.
- [ ] Honesty: the argument assumes random, independent values, so it is a standard choice with reasons.
- [ ] A check you would run: the spread of the scores and the top weight at two key sizes.

**Common traps**

- Trap: "Divide by d_k to make the numbers smaller." Better: Dividing by d_k shrinks the scores too much. The variance argument gives the square root, since the spread grows with √d_k.
- Trap: "The model learns the scale, so we never need it." Better: The standard scale is fixed in code: divide by √d_k, then train.
- Trap: "Softmax handles big numbers, so scaling is optional." Better: Softmax copes with big numbers, but a big gap still gives one winner and tiny gradients.

## Can you spot the bug?

**Spot the right line:** A teammate ported attention from a notebook. Which line scores the keys correctly?

A. scores = q @ k.T / d_k
B. scores = q @ k.T / math.sqrt(d_k)
C. scores = q @ k.T / math.sqrt(seq_len)
D. scores = q @ k.T * math.sqrt(d_k)

**Answer:** B. Dividing by d_k shrinks the scores too much. Dividing by the sequence length uses the wrong size, and multiplying makes the spread worse. Only the square root of the key size matches the fix.

**Quick check:** A layer with 512-number keys puts 99% of its softmax weight on one key. What is the first thing to check?

A. Replace softmax with a plain average
B. Check that the scores are divided by √d_k before softmax
C. Add more layers to the network
D. Raise the learning rate

**Answer:** B. A missing scale leaves the scores too big, so softmax locks onto one key. Adding layers or changing the learning rate does not shrink the scores in a single pass.

## Can you answer these from memory?

**Flash cards**

- **Why divide by √d_k?** Dot products grow with key size. Dividing by √d_k keeps the spread near one.
- **Why do big scores hurt?** Softmax puts almost all the weight on one key, and its gradient becomes tiny.
- **Where does the scale go?** On the raw scores, before softmax turns them into weights.
- **Why the square root, not d_k?** The spread grows with √d_k. Dividing by d_k shrinks the scores too much.
- **What does PyTorch use by default?** One over the square root of E, the length of each query and key vector, per its docs.
- **Is √d_k a law?** No. It is the standard fix, built on a simple random-input argument.

## Likely follow-up questions

- Q044 What are queries, keys and values? https://designervenkat.online/interview/ai/what-are-queries-keys-and-values
- Q043 What is self-attention? https://designervenkat.online/interview/ai/what-is-self-attention
- Q075 Code scaled dot-product attention from scratch. https://designervenkat.online/interview/ai/code-scaled-dot-product-attention-from-scratch
- Q022 What are logits, and what does softmax do? https://designervenkat.online/interview/ai/what-are-logits-and-what-does-softmax-do
- Q046 What is multi-head attention? https://designervenkat.online/interview/ai/what-is-multi-head-attention
- Q056 Why is attention quadratic in sequence length? https://designervenkat.online/interview/ai/why-is-attention-quadratic-in-sequence-length

## Learn it in depth

- [Self-Attention](https://designervenkat.online/learn/machine-learning/self-attention)
