402. Apply a causal mask when queries are fewer than keys
Why it matters KV-cached decoding and chunked prefill in every serving engine depend on this offset being right.
During cached generation or chunked prefill, the newest q queries attend to k cached keys, with q <= k. The plain lower-triangular mask is then wrong: the queries are the LAST q positions.
Write causal_softmax(scores). scores has shape (q, k). Query i sits at absolute position k - q + i and may attend to key j only if j <= k - q + i. Set disallowed scores to -inf, apply a numerically stable softmax over each row and return the (q, k) weights. Raise ValueError if q > k.
def causal_softmax(scores)Example 1
Input: causal_softmax(np.zeros((2, 3)))
Output: [[0.5, 0.5, 0.0], [1/3, 1/3, 1/3]]
Example 2
Input: scores = [[1.0, 2.0], [3.0, 1.0]]
Output: [[1.0, 0.0], [0.880797, 0.119203]]
Example 3
Input: scores = [[0.0, 1.0, 2.0, 0.0]]
Output: [[0.082595, 0.224515, 0.610296, 0.082595]]
Constraints
scoreshas shape(q, k)- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
Hint 1
Compare np.arange(k)[None, :] with np.arange(q)[:, None] + (k - q).
Hint 2
Work out the absolute position of query i.
Hint 3
Broadcast a row of key indices against a column of query positions.
Hint 4
Subtract the row max before exp.
Common mistakes
- Using
np.trilwith no offset. - Masking with a large negative number but forgetting the stable softmax.
Understand the idea
A causal mask stops a token from looking at the future. When queries and keys are the same sequence, the mask is the familiar lower triangle. In generation, though, only the new tokens are queries while all past tokens are keys, so the triangle must be shifted to the right end.
3 keys at positions 0, 1, 2 and 2 new queries. The queries are the last two tokens, at positions 1 and 2. Query 0 (position 1) may see keys 0 and 1; query 1 (position 2) sees all three. With equal scores, the weights are [0.5, 0.5, 0] and [1/3, 1/3, 1/3].
offset = k - q; allowed[i, j] = (j <= i + offset)
Masked scores become -inf before softmax.
With one query (a decode step) the offset is k - 1 and the query sees every key. Serving engines use this same rule for chunked prefill, where a long prompt is processed a few hundred tokens at a time.
Shapes and data flow
scores (q, k); allowed (q, k) bool; weights (q, k), rows sum to 1
Companies2
- DeepMind a candidate reported this question Google DeepMind interview guide (landedjobs/ai-interview-guides)
- OpenAI a candidate reported this question OpenAI Research Engineer Interview Guide (Dataford)
From public interview reports and guides. Not affiliated with or endorsed by these companies.