PIXELBANKv8.2.1
Menu

Scaled Dot-Product Attention

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:

  • 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 = 2 and dimension d = 2, along with the Q, K, and V matrices.
  • We compute the dot product of Q and K^T, which is [1001][1001]=[1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} = \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, then scale it by 1d=12\frac{1}{\sqrt{d}} = \frac{1}{\sqrt{2}}.
  • We apply the softmax function to the scaled dot product: softmax(12[1001])=[e12e12+e12e0e12+e12e0e12+e12e12e12+e12][0.73110.26890.26890.7311]\text{softmax}\left(\frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}\right) = \begin{bmatrix} \frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}} } + e^{\frac{1}{\sqrt{2}}}} & \frac{e^0}{e^{\frac{1}{\sqrt{2}}} + e^{\frac{1}{\sqrt{2}}}} \\ \frac{e^0}{e^{\frac{1}{\sqrt{2}}} + e^{\frac{1}{\sqrt{2}}}} & \frac{e^{\frac{1}{\sqrt{2}}}}{e^{\frac{1}{\sqrt{2}}} + e^{\frac{1}{\sqrt{2}}}} \end{bmatrix} \approx \begin{bmatrix} 0.7311 & 0.2689 \\ 0.2689 & 0.7311 \end{bmatrix}.
  • The final output is obtained by multiplying this softmax result with the V matrix, 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

Test Results

0/0
Run code to see test results.