Scaled dot-product attention

60 min6 partsCoreFundamentalsChecked Dec 2026
Start the lessonShort steps, each with something to do
What you'll learn
  • What a query, a key and a value are, and why attention is a lookup that returns a blend
  • The formula, and the shape of every tensor in it, with any batch and head axes in front
  • Why the scores are divided by √d, shown with numbers
  • Where the causal mask goes, and what breaks when it goes in the wrong place
  • A softmax that stays finite on huge logits, and the axis it runs over
  • What the score matrix costs on long inputs, and how FlashAttention avoids storing it

Attention, the way the coding round asks for it

Model coding rounds ask for attention from scratch. One OpenAI ML engineer's phone screen mainly tested how well they knew the Transformer (1 report), and the same candidate's onsite needed NumPy cold (1 report). A Netflix screen asked what attention is and exactly how Q, K and V are computed (1 report). This lesson's practice problem is that round, in four levels:

Write scaled dot-product attention in NumPy, with no Python loops over batches or heads. q is (..., T_q, d), k is (..., T_k, d) and v is (..., T_k, d_v).

  1. softmax(x, axis=-1): weights that are positive and sum to 1 along axis, finite on logits around 10,000.
  2. attention(q, k, v): softmax(q kᵀ / √d) v, shape (..., T_q, d_v).
  3. attention(q, k, v, causal=True): position i attends only to positions j <= i.
  4. attention_blocks(q, k, v, block): the level 2 output, reading the keys block at a time, without ever building the (T_q, T_k) score matrix.
CallReturns
softmax([1000, 1001, 1002])[0.09, 0.24, 0.67]
attention(Q, K, V), with Q = [[1, 0], [0, 1]], K = [[1, 0], [1, 1]] and V = [[10, 0], [0, 10]][[5, 5], [3.3, 6.7]]
attention(Q, K, V, causal=True)[[10, 0], [3.3, 6.7]]
attention_blocks(Q, K, V, 1)[[5, 5], [3.3, 6.7]], the level 2 answer

The lesson builds attention one piece at a time: the lookup, the scores, the d\sqrt{d} scale, the mask and a stable softmax, then the long-input follow-up that level 4 asks for. Nine steps end with a small task in the editor. It builds on the NumPy lesson: axes, keepdims, broadcasting and @ on stacks.

Part 1 of 6about 14 min
The lookup

A token's meaning depends on its neighbors

Start with what attention is for: the same word can mean different things.

Predict

In "the bank gave a loan", which word tells you what bank means?

Pick an answer above to see the rest

Each token makes a query, a key and a value

Attention works like a lookup, and each token plays three parts in it.

Predict

How many vectors does each token make for attention?

Pick an answer above to see the rest

One query scores every key, then blends the values

Here's one lookup in NumPy: one query, three keys.

import numpy as np


def softmax(s, axis=-1):
    e = np.exp(s)
    return e / e.sum(axis=axis, keepdims=True)


keys = np.array([[1.0, 0.0],
                 [0.0, 1.0],
                 [1.0, 1.0]])
values = np.array([10.0, 20.0, 30.0])
query = np.array([1.0, 2.0])

scores = np.array([key @ query for key in keys])
weights = softmax(scores)
print(scores)
print(weights.round(2))
print((weights * values).sum().round(1))
Predict

Query [1, 2] against keys [1, 0], [0, 1] and [1, 1]. Which key gets the biggest weight?

Pick one to see what it prints.
Pick an answer above to see the rest

The formula is two matrix products and a softmax

One query at a time would be a loop. Stack the queries as rows, and one product scores them all.

Predict

q has shape (3, d) and k has shape (4, d). What shape is q @ k swapped?

Pick an answer above to see the rest

The same line works with batch and heads in front

Real inputs have a batch and several heads in front of the queries.

Predict

k has shape (2, 4, 5, 8). What shape is k.T?

Pick an answer above to see the rest
Part 1 done
Part 2 of 6about 12 min
Scaling

Longer vectors give bigger scores

The formula divides the scores by d\sqrt{d}. Here's why, with numbers.

Predict

Query and key entries have variance 1, and d = 64. About what's the standard deviation of a raw dot product?

Pick an answer above to see the rest

Far-apart scores make the softmax one-hot

Bigger gaps between the scores change what the softmax does.

Predict

Spread the 8 scores 16 times wider. What does the softmax do with them?

Pick an answer above to see the rest

A one-hot softmax passes back almost no gradient

A one-hot softmax is bad news for training.

Predict

A softmax that's nearly one-hot: how much gradient does it pass back to the scores?

Pick an answer above to see the rest
Part 2 done
Part 3 of 6about 9 min
The mask

Without a mask, a position can read its own answer

A language model needs one more piece: a mask.

Predict

Without a mask, what can position 3 do while it predicts the token at position 4?

Pick an answer above to see the rest

Put minus infinity on the scores, before the softmax

The fix is a mask on the scores, built from a lower triangle.

scores = np.array([[1.0, 2.0, 3.0],
                   [4.0, 5.0, 6.0],
                   [7.0, 8.0, 9.0]])
t = scores.shape[-1]
# True where j <= i
allowed = np.tril(np.ones((t, t), dtype=bool))
masked = np.where(allowed, scores, -np.inf)
print(masked)
print(softmax(masked).round(2))
[[  1. -inf -inf]
 [  4.   5. -inf]
 [  7.   8.   9.]]
[[1.   0.   0.  ]
 [0.27 0.73 0.  ]
 [0.09 0.24 0.67]]

np.tril keeps the lower triangle, so allowed is True on and below the diagonal. np.where(allowed, scores, -np.inf) keeps each score where allowed is True, and puts −∞-\infty everywhere else.

Mask the future, then the softmax, row by row
scores (3, 3)
123456789
masked (3, 3)
1-∞-∞45-∞789
softmax (3, 3)
1.00000.270.7300.090.240.67

A row is a query and a column is a key.

Since e−∞=0e^{-\infty} = 0, the future keys get exactly zero weight. The visible weights still sum to 1.

In self-attention the queries and keys are the same positions, so Tq=TkT_q = T_k and the scores are square. That shared length is t in the code, and TT from here on.

The names are not the point. Any lower triangle of True works, for example np.arange(t)[:, None] >= np.arange(t).

The tempting shortcut is to softmax first and zero out the future afterwards. Switch the widget's mask to after softmax and watch the row sums.

An attention patternInteractive
Mask applied
The
cat
sat
on
the
mat
row sum
The
1.00
1.00
cat
0.99
0.01
1.00
sat
0.84
0.15
0.01
1.00
on
0.10
0.22
0.47
0.22
1.00
the
0.00
0.12
0.83
0.00
0.04
1.00
mat
0.08
0.03
0.04
0.58
0.13
0.15
1.00
Rows are queries, columns are keys. Hover a cell.
01

Masking after the softmax leaves rows that sum to less than 1

Here are the numbers for that shortcut, on the same scores.

# softmax first, then zero the future
late = softmax(scores) * allowed
print(late.round(2))
print(late.sum(axis=-1).round(2))
[[0.09 0.   0.  ]
 [0.09 0.24 0.  ]
 [0.09 0.24 0.67]]
[0.09 0.33 1.  ]

Each row is the softmax of all three scores, with the future cut off afterwards. The weight the future took is simply gone.

QueryKept weightsRow sumLost
q10.090.090.24 + 0.67
q20.09, 0.240.330.67
q30.09, 0.24, 0.671.00nothing

Keep the diagonal: each position sees itself

One more detail decides whether the first row works at all.

Predict

A mask that also hides the diagonal leaves q1 with every score at minus infinity. What does its softmax give?

Pick an answer above to see the rest
Part 3 done
Part 4 of 6about 7 min
A stable softmax

e to a big number overflows

The plain softmax from Part 1 has a flaw, and huge scores expose it.

Predict

What's e to the 1000 in float64?

Pick an answer above to see the rest

Subtract the largest score first, and the answer doesn't change

The fix is to shift the scores before the exponential.

Step
scores100010011002
minus the max-2-10
e to the power0.140.371.00the largest is exactly 1
divide by the sum0.090.240.67the sum is 1.50

Subtract the largest score from every score. Now the largest exponent is e0=1e^0 = 1, so nothing overflows. The sum is at least 1, so nothing divides by zero.

And the answer doesn't change, because softmax doesn't change when you subtract the same number from every input:

softmax(s)j=esj∑kesk=esj−m∑kesk−m\text{softmax}(s)_j = \frac{e^{s_j}}{\sum_k e^{s_k}} = \frac{e^{s_j - m}}{\sum_k e^{s_k - m}}

Here ss is one row of scores and mm is any number. Subtracting mm divides the top and the bottom by the same eme^m. Pick m=max⁡kskm = \max_k s_k, the largest score.

Here it is for one row of scores:

def shifted(s):
    e = np.exp(s - s.max())
    return e / e.sum()


print(shifted(big))
print(shifted(big - 1000))
[0.09003057 0.24472847 0.66524096]
[0.09003057 0.24472847 0.66524096]

The same weights for 1000, 1001, 1002 as for 0, 1, 2. Only the differences between the scores matter.

keepdims keeps each row's max next to its own row

On a batch of rows, each row needs its own max.

Predict

x is (2, 2) and x.max(axis=-1) has shape (2,). Subtract it from x without keepdims. What happens?

Pick an answer above to see the rest

The softmax runs over the keys, the last axis

One choice is left: which axis the softmax runs over.

# 2 queries, 3 keys
s = np.array([[1.0, 2.0, 3.0],
              [1.0, 1.0, 1.0]])
print(softmax(s, axis=-1).sum(axis=-1))
print(softmax(s, axis=-2).sum(axis=-1).round(2))
[1. 1.]
[2.11 0.89]

Both lines run. Only the first gives each query weights that sum to 1.

Scores: a row for each query, a column for each key
scores (2, 3)
k1k2k3q11.02.03.0q21.01.01.0

Axis -1 runs along a row: one query's weights over the keys. Right. Axis -2 runs down a column: one key's weights over the queries. Wrong, and no error.

The scores are (T_q, T_k), one row per query. Each query needs its weights over the keys to sum to 1, so the softmax runs over the last axis, the keys.

Run it over axis -2 and each key's weights over the queries sum to 1 instead. The shapes still line up, nothing errors, and every output is wrong. Only a test that checks the actual numbers catches it. That's why interviewers like it.

Part 4 done
Part 5 of 6about 5 min
The worked example

A worked example: two tokens by hand

Here's all of it on two tokens, small enough to check by hand.

Q = np.array([[1.0, 0.0], [0.0, 1.0]])
K = np.array([[1.0, 0.0], [1.0, 1.0]])
V = np.array([[10.0, 0.0], [0.0, 10.0]])

s = Q @ K.T / np.sqrt(2)
w = softmax(s)
print(s.round(2))
print(w.round(2))
print((w @ V).round(1))
Predict

q1 = [1, 0] dots to 1 with both keys. The values are [10, 0] and [0, 10]. What's q1's output?

Pick one to see what it prints.
Pick an answer above to see the rest
Part 5 done
Part 6 of 6about 13 min
Follow-ups

The score matrix grows with the square of the length

Once your attention works, the usual follow-up is long inputs. What does attention cost as the context grows, and what would you do about it?

Predict

Double the length from 4 tokens to 8. How many scores does one head compute?

Pick an answer above to see the rest

FlashAttention computes it in tiles and never stores the matrix

The fix keeps the answer exact and drops the matrix.

Predict

FlashAttention computes attention in tiles. Does it ever store the full score matrix?

Pick an answer above to see the rest

The compute is still quadratic

Tiling saves memory. It doesn't save arithmetic.

Predict

FlashAttention saves the memory. Is the compute still quadratic in the length?

Pick an answer above to see the rest

The practice problem, start to finish

That's every piece the practice problem needs. It asks for the four levels from the start of the lesson, from a blank file, and the interviewer follows up after each one.

Check yourself
5 questions
  1. 1.The head size goes from 64 to 256 and you forgot the 1/√d scale. What happens to the attention weights?

  2. 2.scores has shape (B, H, T, T). Which axis does the softmax run over?

  3. 3.You apply the causal mask by multiplying the softmax output by a lower-triangular matrix of ones. What breaks?

  4. 4.Why subtract the row max before exponentiating?

  5. 5.At 8,192 tokens of context, how big is one head's fp16 score matrix for one sequence?

Where this shows up

The reports behind this lesson, each with its source.

MLE candidate (interviewed Oct 2025, rejected): phone screen ML coding mainly tested Transformer architecture knowledge.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source

Same MLE report, onsite ML coding: NumPy fluency was essential.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-08-25Source

Same screen: what attention is and exactly how Q, K and V are computed.

Candidate report·PracHub (first-person report, curated and edited by the site)·2026-10-10Source

Practice

Sources (2)
  1. Attention Is All You Need · arXiv 1706.03762 · Jun 12, 2017
    “the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients”
  2. FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness · arXiv 2205.14135 · May 27, 2022
    “We propose FlashAttention, an IO-aware exact attention algorithm that uses tiling to reduce the number of memory reads/writes between GPU high bandwidth memory (HBM) and GPU on-chip SRAM.”