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).
softmax(x, axis=-1): weights that are positive and sum to 1 along axis, finite on logits around 10,000.
attention(q, k, v, causal=True): position i attends only to positions j <= i.
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.
Call
Returns
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 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?
Sentence
bank pulls in
So bank means
the river bank
river
the side of a river
the bank gave a loan
loan
a place that keeps money
The token bank means one thing next to river and another next to loan. So every layer of a transformer lets each position pull in information from the other positions.
How much it pulls from each one depends on what the tokens say, not on a fixed window. Attention is the step that does this, and it works like a lookup.
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?
Multiply xi by
To get
WQ
qi, the query: what this token looks for
WK
ki, the key: what it offers to be found by
WV
vi, the value: what it hands over
Token i's vector, xi, is multiplied by three learned matrices, WQ, WK and WV:
qi=xiWQ,ki=xiWK,vi=xiWV
Each of the three has one job:
The queryqi is what position i is looking for.
The keykj is what position j can be found by.
The valuevj is what position j hands over once it's found.
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 npdef 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.
One query, three keys. Each key's score is its dot product with the query, and a bigger score means a better match. A softmax turns the scores into weights that are positive and sum to 1. The output is the values, averaged with those weights.
Query [1, 2]:
Key
Score
Weight
Value
[1, 0]
1
0.09
10
[0, 1]
2
0.24
20
[1, 1]
3
0.67
30
The output blends the values: 0.09·10 + 0.24·20 + 0.67·30 = 25.8.
A Python dict needs an exact key match, and it returns one value. Attention scores every key against the query and returns a blend, weighted toward the best matches.
Nothing is ever picked, only weighted. That's why the whole thing is differentiable: a small change to a score makes a small change to the output.
This softmax is the plain formula. It breaks on huge scores, and Part 4 fixes it.
In symbols, the output for position i is:
outi=j∑softmaxj(dqi⋅kj)vj
Read it from the inside out:
qi⋅kj is query i dotted with key j.
d is the length of each query and key vector. Part 2 explains the division by d.
softmaxj runs over j: one query's scores against every key.
The sum blends the values vj with those weights.
The loop over the keys is fine for three of them. In the editor, do it the NumPy way. keys is (3, 2) and query is (2,), so one @ scores every key at once, as in the NumPy lesson's grades, and one more @ blends the values. query is [0, 3] there, a new query against the same three keys. The keys [0, 1] and [1, 1] tie, so expect them to share most of the weight.
Put the queries in the rows of Q, and the keys and values in the rows of K and V. Then the whole layer is two matrix products and a softmax:
Attention(Q,K,V)=softmax(dQK⊤)V
K⊤ is K with rows and columns swapped, so each key becomes a column. One product scores every query against every key. The second blends the values.
Interviewers care more about the shapes than the formula, because the shapes are where code breaks. With Tq queries, Tk keys, head size d and value size dv:
Tensor
Shape
What it is
q
(..., T_q, d)
one query per position
k
(..., T_k, d)
one key per position
v
(..., T_k, d_v)
one value per key
q @ k.swapaxes(-1, -2)
(..., T_q, T_k)
every query scored against every key
softmax(scores, axis=-1)
(..., T_q, T_k)
each row sums to 1
weights @ v
(..., T_q, d_v)
one blended value per query
The ... is whatever leading axes you have, usually batch and heads.
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.
np.swapaxes(k, -1, -2) trades only the last two axes, so each key becomes a column and the batch and head axes stay in front. @ multiplies over the last two axes and repeats for every axis in front. So q times that flip gives the scores as batch, heads, queries, keys, (2, 4, 3, 5), for one sequence or a whole (batch, heads) stack, with no Python loop.
Expression
Shape
What moved
k
(2, 4, 5, 8)
batch, heads, keys, d
k.swapaxes(-1, -2)
(2, 4, 8, 5)
only the last two trade places
k.T
(8, 5, 4, 2)
every axis reversed
k.T reverses every axis, so it only works on a plain 2-D matrix. The name swapaxes is not the point. Any call that swaps the last two axes works, for example np.moveaxis(k, -1, -2).
In the editor, write scores(q, k) for any number of leading axes. The editor prints the shape for a batch of 2 with 4 heads, which should be (2, 4, 3, 5).
The formula divides the scores by 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?
rng = np.random.default_rng(0)for d in [4, 64, 256]: q = rng.normal(size=(1000, d)) k = rng.normal(size=(1000, d)) # 1,000 dot products s = (q * k).sum(axis=-1) print(d, s.std().round(1), (s / np.sqrt(d)).std().round(2))
4 2.0 1.064 8.0 1.01256 16.1 1.01
Each line is a head size d, then the standard deviation of 1,000 raw scores, then the same after dividing by d. The raw spread grows with d. The divided spread stays near 1.
The standard deviation of the scores
d = 4, raw
2
d = 64, raw
8
d = 256, raw
16
any d, ÷ √d
1
Here is why. Say the entries of q and k are independent, with mean 0 and variance 1. Then q⋅k=∑i=1dqiki adds up d terms that each have variance 1.
So the score has variance d, and standard deviation d. At d=256 that's 16. Dividing by d brings the spread back to about 1 at any head size.
In the editor, s holds 1,000 dot products at d=100. Fill in raw, their standard deviation, and scaled, the same after dividing by d.
The same 8 scores, at spread 1 and at spread 16. At spread 16 one key takes all the weight. That's a one-hot softmax: one weight is 1, and the rest are 0.
The weights on 8 keys
Spread 1
Spread 16
key 1
0.09
0.00
key 2
0.07
0.00
key 3
0.14
0.00
key 4
0.08
0.00
key 5
0.04
0.00
key 6
0.11
0.00
key 7
0.28
1.00
key 8
0.19
0.00
So without the scale, a wide head starts out with a nearly one-hot softmax. The original transformer paper gives this as its reason for the scale: large dot products push the softmax into a region where its gradients are extremely small.
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?
for spread in [1, 16]: p = softmax(spread * s) print(spread, (p * (1 - p)).max().round(4))
1 0.200316 0.0033
Entry (i, j) of the softmax's gradient is how much weight pi moves when score j moves. It is pi(1−pi) when i=j, and −pipj when i=j. The second kind is never positive, so the code prints the largest entry.
When one weight is near 1 and the rest are near 0, every one of those products is near 0. So almost no gradient flows back to the queries and keys. The model stops learning what to attend to.
The largest entry of the softmax's gradient
spread 1
0.2003
spread 16
0.0033
About 60 times smaller.
Push the head size up and watch the unscaled weights collapse onto one key, while the scaled ones stay spread out. Max gradient in the widget is what the code prints: the largest entry of the softmax's gradient.
Why divide by √dInteractive
Head size d
softmax(q·k)
Top weight
1.00
Score spread
19.9
Max gradient
2e-12
softmax(q·k / √d)
Top weight
0.65
Score spread
1.2
Max gradient
0.228
In the editor, finish scaled_scores(q, k). Your scores function is already there. Read d from the last axis of q.
Karpathy's note on why the scores are divided by the square root of the head size, worked in code.
Let's build GPT: from scratch, in code, spelled out. · Andrej Karpathy · Jan 2023YouTube
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?
Position
1
2
3
4
5
6
Token
the
cat
sat
on
the
mat
Position 3 has to predict the token at position 4: on.
Reads
So it
with a mask
positions 1, 2, 3
has to guess
without a mask
positions 1, 2, 3, 4, ...
copies the answer
A language model predicts the token at position t+1 from the tokens at positions 1 to t. In training it sees the whole sequence at once. Without a mask, position 3 could simply read position 4, the answer it's supposed to predict.
The causal mask lets position i attend only to positions j≤i: itself and the positions before it.
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.
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 −∞ 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−∞=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=Tk and the scores are square. That shared length is t in the code, and T 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 futurelate = softmax(scores) * allowedprint(late.round(2))print(late.sum(axis=-1).round(2))
Each row is the softmax of all three scores, with the future cut off afterwards. The weight the future took is simply gone.
Query
Kept weights
Row sum
Lost
q1
0.09
0.09
0.24 + 0.67
q2
0.09, 0.24
0.33
0.67
q3
0.09, 0.24, 0.67
1.00
nothing
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?
A mask that also hides the diagonal
masked (3, 3)
k1k2k3q1-∞-∞-∞q24-∞-∞q378-∞
Every score in q1's row is hidden, so its softmax is NaN.
Position i attends to itself. If the mask also hides j=i, the first row has no visible keys. Every score in it is −∞, and its softmax comes out NaN.
In the editor, write causal(scores): a new array with every score above the diagonal at minus infinity, and the diagonal kept. The editor prints it for the same 3 by 3 scores the mask steps used.
The plain softmax from Part 1 has a flaw, and huge scores expose it.
Predict
What's e to the 1000 in float64?
big = np.array([1000.0, 1001.0, 1002.0])print(np.exp(big))print(softmax(big))
[inf inf inf][nan nan nan]
NumPy also prints a warning for the overflow and one for the division. e1000 is about 10434, and the largest float64 is about 1.8×10308.
Step
Result
e^1000, e^1001, e^1002
inf, inf, inf
inf / (inf + inf + inf)
nan
So each exponent overflows to inf, and inf / inf is nan.
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
scores
1000
1001
1002
minus the max
-2
-1
0
e to the power
0.14
0.37
1.00
the largest is exactly 1
divide by the sum
0.09
0.24
0.67
the sum is 1.50
Subtract the largest score from every score. Now the largest exponent is e0=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=∑keskesj=∑kesk−mesj−m
Here s is one row of scores and m is any number. Subtracting m divides the top and the bottom by the same em. Pick m=maxksk, 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))
The second answer is right: each row minus its own max, so each row's largest entry becomes 0. The first is wrong, and nothing errors.
x
Minus
Result
without keepdims
[[1, 2], [3, 5]]
[2, 5], as a row
[[-1, -3], [1, 0]]: column j loses row j's max
with keepdims
[[1, 2], [3, 5]]
[[2], [5]], as a column
[[-1, 0], [-2, 0]]: each row loses its own max
Without keepdims the maxes come back as a flat (2,) array. Broadcasting lines a flat array up with the columns, so column j loses row j's max. On a square matrix the shapes fit, and the result is quietly wrong.
keepdims=True keeps the reduced axis with size 1, so the maxes stand in a column, one per row. Then the subtraction, and the division by the sum, broadcast back along the right axis. The idea is the point, not the name: np.expand_dims(x.max(axis=axis), axis) puts the axis back by hand and does the same job.
Scores going into a softmax are often called logits. The practice tests feed logits around 10,000. The plain formula fails them, and the shifted one passes.
In the editor, write the stable softmax(x, axis=-1). The checks feed it logits around 10,000, a batch of rows, and axis=0.
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.
Query 1 can now see only key 1. Its weights become [1, 0] and its output [10, 0]. Query 2 doesn't change, because it was already allowed to see both.
Causal
k1
k2
Output
q1
1.00
·
[10, 0]
q2
0.33
0.67
[3.3, 6.7]
In the editor, write attention(q, k, v, causal=False) from the pieces of this lesson. It prints the worked example, with and without the mask, so you can compare it with the outputs on this step.
That's for one head and one sequence, in fp16: 16-bit floats, 2 bytes each. A MiB is 220 bytes. At T=8,192 the score matrix holds 67 million scores, 128 MiB, before you store the weights or anything for the backward pass.
Scores per head, by length
T = 4
16
T = 8
64
Double the length, and the scores quadruple.
Double the context and the matrix gets four times bigger. Memory grows with the square of the context.
In the editor, write score_mib(T, heads, batch, bytes_per): the memory of every score matrix in a batch. The second line is a model with 32 heads and a batch of 8 at 4,096 tokens.
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?
One query, its 8 keys in tiles of 2Interactive
→
→
→
→
[s1 s2]. After each tile, update three running numbers: m, the largest score so far; l, the sum of e^(score - m) so far; and acc, the values blended with those same weights
You don't have to store the matrix. FlashAttention computes exact attention in tiles small enough for the GPU's on-chip SRAM, its small, fast memory. It keeps a running max and a running sum for each row's softmax as it goes. So the full matrix never lands in the GPU's main memory.
Start with a running sum and a running blend for one query, in NumPy, two keys at a time:
rng = np.random.default_rng(0)# one query's scores on 8 keyss = rng.normal(size=8)# one number per key, to keep it shortv = rng.normal(size=8)l, acc = 0.0, 0.0for start in range(0, 8, 2): tile, vt = s[start:start + 2], v[start:start + 2] l = l + np.exp(tile).sum() acc = acc + np.exp(tile) @ vtprint(np.isclose(acc / l, softmax(s) @ v))
True
l adds up e to each score, the softmax's denominator. acc adds up the values, weighted by those same numbers. Divide at the end and you have the softmax blend, and no tile's scores are kept after their turn.
This loop has the overflow from Part 4: a score of 1000 makes np.exp return inf. The fix is the same shift by the max, but the max isn't known until the last tile. So keep a running max m, and work each tile out as e to its score minus new_m, the largest score so far. Whatever is already in l and acc was worked out against the old, smaller max. When a tile brings a bigger max, multiply both by np.exp(m - new_m) first, which shrinks them to the new max.
The output is identical to attention done the plain way. What changes is how much memory it needs and how much data moves.
In the editor, tiled(s, v, tile) is that loop for one query, with a vector for each value and the running max added. Fill in the three updates. The last two lines print its answer next to the plain softmax blend, and they should match. Level 4 of the practice runs the same loop for every query at once.
FlashAttention saves the memory. Is the compute still quadratic in the length?
Full causal against a window of 3
full causal: about T² / 2 (6, 6)
q1q2q3q4q5q6
a window of 3: about 3T (6, 6)
q1q2q3q4q5q6
A marked cell is a score the query computes.
Tiling doesn't cut the arithmetic. Every query is still scored against every key it can see, so the compute still grows with T2. Only the memory and the data that moves drop.
Windowed or sparse attention cut the compute too, by changing what each token can see. A window, as in the figure, lets each token see only itself and the few tokens just before it.
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.The head size goes from 64 to 256 and you forgot the 1/√d scale. What happens to the attention weights?
2.scores has shape (B, H, T, T). Which axis does the softmax run over?
3.You apply the causal mask by multiplying the softmax output by a lower-triangular matrix of ones. What breaks?
4.Why subtract the row max before exponentiating?
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
“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.”