📘
Scaled Dot-Product Attention
Implement scaled dot-product attention.
Given Query (Q), Key (K), and Value (V) matrices, compute: Attention(Q,K,V)=softmax(dkQKT)V
where d_k is the dimension of the keys (number of columns in K).
Input:
- Line 1: n d (sequence length, dimension)
- Next n lines: Q matrix (space-separated floats)
- Next n lines: K matrix
- Next n lines: V matrix
Output: The attention output matrix, values rounded to 4 decimal places.
Example:
Input:
2 2 1 0 0 1 1 0 0 1 1 0 0 1
Output:
[0.7311 0.2689] [0.2689 0.7311]
Reasoning:
- The input provides the sequence length
n = 2and dimensiond = 2, along with theQ,K, andVmatrices. - We compute the dot product of
QandK^T, which is [1001][1001]=[1001], then scale it by d1=21. - We apply the softmax function to the scaled dot product: softmax(21[1001])=e21+e21e21e21+e21e0e21+e21e0e21+e21e21≈[0.73110.26890.26890.7311].
- The final output is obtained by multiplying this softmax result with the
Vmatrix, which yields $\begin{bmatrix} 0.7311 & 0.2689 \ 0.2689 & 0.7311 \end{bmatrix} \begin{bmatrix} 1 & 0 \ 0 & 1 \end{bmatrix} = \begin{bmatrix} 0.
Constraints:
- 1 <= n <= 10, 1 <= d <= 10
- Use numpy for matrix operations
- softmax is applied row-wise
- Round to 4 decimal places
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.