v9.1.1
Menu

Scaled Dot-Product Attention

easyFREEAttention MechanismsLLM 1: Foundations

Implement scaled dot-product attention.

Given Query (Q), Key (K), and Value (V) matrices, compute: Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

where d_k is the dimension of the keys (number of columns in K).

Input:

  • Q, K, V: NumPy float arrays, each of shape (n, d) (sequence length, dimension)

Output: The attention output matrix of shape (n, d). The tests print each row with values rounded to 4 decimal places.

Example

Input
2 2
1 0
0 1
1 0
0 1
1 0
0 1
Output
[0.6698 0.3302]
[0.3302 0.6698]
Reasoning
  • The sample header says n=2n = 2 tokens with d=2d = 2 dimensions, and 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].
  • Entry (i,j)(i, j) of QKTQK^T is the dot product of query ii with key jj: each token matches itself with score 11 and the other with 00. Dividing by dk=2\sqrt{d_k} = \sqrt{2} turns the 11s into 0.70710.7071.
  • Softmax runs along each row. Row 0 is [0.7071,0][0.7071, 0], so the weights are e0.7071e0.7071+e0=2.02813.0281=0.6698\frac{e^{0.7071}}{e^{0.7071} + e^{0}} = \frac{2.0281}{3.0281} = 0.6698 and 13.0281=0.3302\frac{1}{3.0281} = 0.3302. Row 1 is the mirror image, [0.3302,0.6698][0.3302, 0.6698].
  • Each output row is the weighted average of the rows of VV. Since VV is the identity, the weights come through unchanged, giving [0.6698 0.3302] and [0.3302 0.6698], an n×dn \times d result.
  • Notice that each row sums to 11. Without the dk\sqrt{d_k} scaling the weights would be [0.7311,0.2689][0.7311, 0.2689]; scaling keeps them softer. If two keys were identical, the query would split its weight evenly between them.

Constraints

  • 1 <= n <= 10, 1 <= d <= 10
  • Use numpy for matrix operations
  • softmax is applied row-wise
  • 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.