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.
11 min readIntermediateCommon · estimateFacts checked 26 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
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.
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.
Key words
- 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
How one query becomes one output
Query
what this token looks for
Keys
one per note, including padding
Dot products
query times each key
Tame the scores
Divide by √d_k
keeps big scores in range
Mask padding
padding gets minus infinity
Softmax
each row adds up to one
Weighted sum
blends the values
- 1The query meets each key in a dot product.
- 2Every key, padding included, takes part.
- 3Each score is divided by the square root of the key size.
- 4Padding positions are set to minus infinity.
- 5Softmax turns each row into weights that add up to one.
- 6The 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.
# 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
[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.
Where the mask goes: before or after softmax
Mask after softmax
Softmax over all scores
padding still takes some weight
Zero padding after
weights stop adding up to one
Mask before softmax
Padding to minus infinity
done on the scores first
Softmax each row
padding ends with exactly zero
Off-scale weights
output is off by the lost weight
Right weights
padding never counts
- 1The padding weight is zeroed only afterwards.
- 2The rest no longer add up to one.
- 3The padding score is set before softmax runs.
- 4Softmax 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."
BetterSoftmax 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."
BetterZero is still a score, so exp(0) gives padding a share. Use minus infinity.
Trap"Divide by the number of tokens."
BetterDivide 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?
Quick check
A row of weights comes out as nan (not a number). What most likely happened?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Learn it in depth
Last updated on 26 November 2026
Building an attention model or an AI feature for your team?
I design and build AI products and agents, the interface and the system behind it. Book a short call and tell me what yours needs to do.