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
causal_softmax(np.zeros((2, 3))) is [[0.5, 0.5, 0.0], [1/3, 1/3, 1/3]].
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.
Example: 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].
Rule: 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