v9.1.1
Menu

Causal Attention Mask

mediumFREEAttention MechanismsLLM 1: Foundations

Implement causal (autoregressive) masked attention.

In causal attention, each position can only attend to itself and previous positions. This is achieved by masking future positions with -infinity before softmax.

Given Q, K, V matrices, compute attention with a causal mask:

  1. Compute scores = QK^T / sqrt(d_k)
  2. Apply causal mask: set scores[i][j] = -inf where j > i
  3. Apply softmax row-wise
  4. Multiply by V

Input: causal_attention(Q, K, V) receives three NumPy arrays of shape (n,d)(n, d) (queries, keys, values), where dk=dd_k = d.

Output: Return the masked attention output as an (n,d)(n, d) array. The tests print each value to 4 decimal places.

Example

Input
2 2
1 0
0 1
1 0
0 1
1 0
0 1
Output
[1.0000 0.0000]
[0.3302 0.6698]
Reasoning
  • Inputs: n=2n = 2 tokens with dk=2d_k = 2 features each. QQ, KK and VV are all the 2×22 \times 2 identity: token 0 is [1,0][1, 0], token 1 is [0,1][0, 1].
  • Scores: each query–key dot product divided by 2≈1.4142\sqrt{2} \approx 1.4142. Matching tokens score 1/2≈0.70711/\sqrt{2} \approx 0.7071, different tokens score 00: [0.7071000.7071]\begin{bmatrix}0.7071 & 0\\0 & 0.7071\end{bmatrix}.
  • Mask: a query at position ii may not look at a key at position j>ij > i. Only row 0, column 1 qualifies, so it becomes −109-10^9.
  • Softmax per row: row 0 is [0.7071,−109][0.7071, -10^9]; e−109e^{-10^9} is effectively 00, so the weights are [1,0][1, 0]. Row 1 is [0,0.7071][0, 0.7071]: with e0.7071≈2.0281e^{0.7071} \approx 2.0281, the weights are 13.0281≈0.3302\frac{1}{3.0281} \approx 0.3302 and 2.02813.0281≈0.6698\frac{2.0281}{3.0281} \approx 0.6698.
  • Output: a 2×22 \times 2 matrix whose rows are those weights mixing the rows of VV. Since VV is the identity, the output equals the weights: [1.0000 0.0000], [0.3302 0.6698].
  • Notice that the first token can only attend to itself, so its row is always exactly its own value vector.

Constraints

  • 1 <= n <= 10, 1 <= d <= 10
  • Use -1e9 as the mask value (approximating -inf)
  • Round to 4 decimal places

Learn this in

More from LLM 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.