# Scaled Dot-Product Attention From Scratch

> How to code scaled dot-product attention in plain Python, with a padding mask, the checks to run and the bugs to avoid, for your AI interview.

**In short:** Compute the dot product of each query with every key, divide by the square root of the key size, set padding to minus infinity, run softmax over each row, then blend the values with those weights. A plain Python version fits in under 30 lines and is easy to test.

AI and LLM interview question Q075, Transformer architecture. Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/code-scaled-dot-product-attention-from-scratch

## Say it in 30 seconds

I would code it in five steps. For each query, I take dot products with every key, divide by the square root of the key size, and set padding to minus infinity. Softmax then turns each row into weights that add up to one, and I blend the values with those weights. I test three things: each row sums to one, padding gets zero weight, and identical keys get the same weight.

## Say it in 2 minutes

Attention has one job: for each query, weigh every key and blend the values with those weights. The query meets each key in a dot product. Then I divide each score by the square root of the key size. The paper suspects big dot products would otherwise push softmax into a corner.

Next is padding, the part most candidates miss. A claims desk assistant reads notes of different lengths, so short notes get padded. Padding is not real text, so its score must be minus infinity before softmax. e raised to the power of minus infinity is zero, so padding gets no weight. Zeroing after softmax would break the sum to one.

Softmax runs along each row, one row per query. Each row should add up to one, padding should get exactly zero, and identical keys should get the same weight. Two of those checks are asserts in the code, and the third is one more line.

Be clear about the limits. This version uses plain lists, no batch dimension and no speed tricks. PyTorch's reference version follows the same steps on tensors, and its optimised kernels may run them differently. Its boolean mask means True is kept. I would present this code as a way to learn and test the idea, not as production code.

## What is scaled dot-product attention, in plain words?

Attention lets a model pick which other tokens matter for the one it is working on. A token is a small piece of text, often a word or part of one. For each query, the model compares it with every key, then blends the values by how well each key matched.

The Transformer paper calls its method "Scaled Dot-Product Attention". Dot-product means each score is a dot product. Scaled means the scores are divided by a fixed number before softmax.

Picture a triage nurse with a patient's handover notes. Her question is the query. Each note has a label, the key, and content, the value. She scores every label against her question, gives the best matches more weight, and writes the summary from them. Attention does the same with numbers.

A claims desk assistant reads four notes from one insurance claim. Short notes are padded to the longest length, and that padding must never count. It is the part most people miss when they code it.

- **Query:** What this token is looking for.
- **Key:** A label each token offers, to match against the query.
- **Value:** The content passed on when a token is picked.
- **Softmax:** Turns scores into weights that add up to one.
- **Padding:** Filler so short inputs line up. Not real text.

## What are the steps, in order?

The paper's recipe is short: dot products with all keys, a division by the square root of the key size, then softmax for the weights on the values. The code follows the same order.

> "apply a softmax function to obtain the weights on the values" (Attention Is All You Need)

*Diagram, How one query becomes one output: Read left to right. Padding is masked before softmax, not after, so its weight is exactly zero.*
1. The query meets each key in a dot product.
2. Every key, padding included, takes part.
3. Each score is divided by the square root of the key size.
4. Padding positions are set to minus infinity.
5. Softmax turns each row into weights that add up to one.
6. The weights blend the values into one output.

1. **Score:** Take the dot product of the query with every key. You get one score per key.
2. **Scale:** Divide each score by the square root of the key size. This keeps big scores in a sensible range.
3. **Mask:** Set the padding positions to minus infinity, so they get no weight at all.
4. **Softmax:** Turn each row of scores into weights that add up to one.
5. **Blend:** Multiply each weight by its value and add them up. That sum is the output for this query.

## What does the code look like from scratch?

Here is the whole thing in plain Python, standard library only, with no tensors and no batch dimension. The made-up claims desk has two queries, four note positions and one padding slot.

```python
# Made-up claims desk: 2 queries read 4 note tokens. The 4th token is padding and must get zero weight.
import math
def softmax(row):
    m = max(row)
    if m == -math.inf:  # every key masked: return zero weights, not nan
        return [0.0] * len(row)
    exps = [math.exp(x - m) for x in row]
    return [e / sum(exps) for e in exps]
def attention(Q, K, V, mask):
    d = len(Q[0])  # key size, used for the scale
    weights, outputs = [], []
    for q in Q:
        scores = [sum(a * b for a, b in zip(q, k)) / math.sqrt(d) for k in K]
        scores = [s if ok else -math.inf for s, ok in zip(scores, mask)]  # mask before softmax
        w = softmax(scores)
        weights.append(w)
        outputs.append([sum(wi * v[j] for wi, v in zip(w, V)) for j in range(len(V[0]))])
    return outputs, weights
Q = [[1.0, 0.5], [0.2, 1.5]]  # 2 queries
K = [[0.9, 0.4], [0.1, 1.2], [1.1, 0.3], [0.0, 0.0]]  # 4 key positions; the last is padding
V = [[1.0, 0.0], [0.0, 1.0], [0.5, 0.5], [9.0, 9.0]]  # value rows
mask = [True, True, True, False]  # False = padding, not allowed
out, weights = attention(Q, K, V, mask)
assert all(abs(sum(w) - 1) < 1e-9 for w in weights)  # each row adds up to 1
assert all(w[3] == 0 for w in weights)  # padding gets no weight
for w, o in zip(weights, out):
    print([round(x, 2) for x in w], [round(x, 2) for x in o])
```

Output:

```text
[0.35, 0.26, 0.39, 0.0] [0.54, 0.46]
[0.25, 0.52, 0.23, 0.0] [0.36, 0.64]
```

Each row adds up to one and the padding gets exactly 0.0. Its large value, (9, 9), never enters the blend.

## Why does the padding need a mask?

Without the mask, padding is treated like a real note. If you set every mask entry to True, padding takes 14% of the first query's weight, and the first output's first number moves from 0.54 to 1.71. The large value in the padding slot pulls the answer far away.

Setting the padding score to 0 is a common slip. Zero is still a score, and exp(0) is 1, so padding takes a share. Here the padding key is [0.0, 0.0], so a 0 score would give padding the same 14% as no mask. That is a quirk of this data, not a rule.

The paper blocks illegal connections in the softmax input, which stops decoder positions from seeing later tokens. Padding is hidden the same way, before softmax. PyTorch's reference does it with minus infinity too. The order is the whole point: mask first, then softmax.

*Diagram, Where the mask goes: before or after softmax: Two orders, one above the other. Zeroing after softmax breaks the sum to one. Masking before softmax gives padding exactly zero.*
1. The padding weight is zeroed only afterwards.
2. The rest no longer add up to one.
3. The padding score is set before softmax runs.
4. Softmax then gives padding exactly zero.

> **Tip:** In the interview, say the mask goes into the scores before softmax, because softmax is what turns scores into shares.

## How would you test the code?

Three checks catch most bugs. The code above asserts the first two. The third is one more assert: give two identical key rows and check their weights match.

- **Each row adds up to one:** Softmax output must be a set of shares. If a row misses one, the softmax or the mask is wrong.
- **Padding gets exactly zero:** Run a row with padding and check that its weight is 0.0, not a small number.
- **Identical keys get the same weight:** Two identical key rows should get identical weights. The code above does not check this yet.

## How does this compare with PyTorch?

Real models run this on tensors, which are multi-dimensional arrays, so one call can handle many sentences at once. PyTorch's function computes scaled dot product attention on query, key and value tensors, with an optional mask. The PyTorch docs say it accepts any number of batch dimensions.

Its reference version scales by one over the square root of the query's last size, and runs softmax over the last dimension, which holds the keys. Its boolean mask is the reverse of MultiheadAttention's: True keeps a value in attention, where MultiheadAttention uses True for padding to mask out. The function may also call optimised kernels on CUDA, so a real system runs the steps differently.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] The steps in order: dot products, scale, mask, softmax, weighted sum.
- [ ] Why the scale: the paper suspects big dot products push softmax where gradients are tiny.
- [ ] How padding is hidden: minus infinity before softmax, never zero after.
- [ ] Softmax runs over each row of keys, one row per query.
- [ ] Tests: rows add up to one, padding weighs zero, identical keys get the same weight.
- [ ] Honesty about scope: a teaching version, not a production kernel.

**Common traps**

- Trap: "Softmax over the whole matrix is fine." Better: Softmax runs per row, one row per query, so each query's weights add up to one.
- Trap: "Set padding to zero and you are done." Better: Zero is still a score, so exp(0) gives padding a share. Use minus infinity.
- Trap: "Divide by the number of tokens." Better: Divide by the square root of the key size, which the paper uses to counteract large dot products.

## Can you spot the padding bug?

**Spot the padding bug:** A teammate sent this padding fix for the scores. Which line is right?

A. scores = [0.0 if not ok else s for s, ok in zip(scores, mask)]
B. scores = [s if ok else -math.inf for s, ok in zip(scores, mask)]
C. w = [x if ok else 0.0 for x, ok in zip(softmax(scores), mask)]
D. scores = [s for s, ok in zip(scores, mask) if ok]

**Answer:** B. Minus infinity makes exp() zero, so padding gets exactly zero and the rest still add up to one. A 0.0 score still gives padding a share, and zeroing after softmax breaks the sum.

**Quick check:** A row of weights comes out as nan (not a number). What most likely happened?

A. The scores were scaled by the key size, not its square root
B. Every key in that row is masked, so the largest score is minus infinity
C. The values are all zero
D. The query and the key are the same vector

**Answer:** B. Softmax subtracts the largest score from each one. If every score is minus infinity, that subtraction gives minus infinity minus itself, which is nan. The guard turns the nan into zero weights for that row. That row then sums to zero, so the add-to-one check must skip rows with no valid key.

## Can you answer these from memory?

**Flash cards**

- **What is scaled dot-product attention?** Query-key dot products, scaled, then softmax, then a weighted sum of the values.
- **Why divide by the square root of the key size?** The paper suspects big dot products push softmax where gradients are tiny. Dividing keeps scores in range.
- **How do you hide padding?** Set its score to minus infinity before softmax, so its weight comes out exactly zero.
- **Why not set padding to 0?** exp(0) is 1, so a zero score still gets a share of the weight.
- **Name three checks for your code.** Each row sums to one, padding gets zero weight, identical keys get the same weight.

## Likely follow-up questions

- Q045 Why scale attention scores by √d_k? https://designervenkat.online/interview/ai/why-scale-attention-scores-by-square-root-of-d-k
- Q050 What is causal (masked) attention? https://designervenkat.online/interview/ai/what-is-causal-masked-attention
- Q066 Attention masks and padding? (full answer coming)
- 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
- Q073 Walk through one decoder block's forward pass. https://designervenkat.online/interview/ai/walk-through-one-decoder-block-forward-pass

## Learn it in depth

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