PIXELBANKv9.1.0
Menu

Implement multi-head attention by splitting Q, K, V into multiple heads.

Given Q, K, V of shape (n, d) and number of heads h:

  1. Split each into h heads: reshape (n, d) → (n, h, d/h) → (h, n, d/h)
  2. Apply scaled dot-product attention per head
  3. Concatenate heads: (h, n, d/h) → (n, d)

Assume d is divisible by h. No linear projections needed — just split and concat.

Input:

  • Line 1: n d h
  • Next n lines: Q matrix
  • Next n lines: K matrix
  • Next n lines: V matrix

Output: Multi-head attention output (n, d), values rounded to 4 decimal places.

Example:

Input:
2 4 2
1 0 0 1
0 1 1 0
1 0 0 1
0 1 1 0
1 2 3 4
5 6 7 8
Output:
[1.7311 2.7311 3.2689 4.2689]
[4.2689 5.2689 6.7311 7.7311]
Reasoning:
  • First, we split the input matrices Q, K, V into 2 heads: Q = [1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, [0110]\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, K = [1001]\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}, [0110]\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}, V = [1256]\begin{bmatrix} 1 & 2 \\ 5 & 6 \end{bmatrix}, [3478]\begin{bmatrix} 3 & 4 \\ 7 & 8 \end{bmatrix}
  • Then, we apply scaled dot-product attention per head: for the first head, Attention(Q,K,V)=Qâ‹…KT2â‹…V=[1001]â‹…[1001]2â‹…[1256]Attention(Q, K, V) = \frac{Q \cdot K^T}{\sqrt{2}} \cdot V = \frac{\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix} \cdot \begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}}{\sqrt{2}} \cdot \begin{bmatrix} 1 & 2 \\ 5 & 6 \end{bmatrix} and similarly for the second head
  • Next, we calculate the attention output for each head and concatenate them: Output=Concat(Attention1,Attention2)=[1.73112.73114.26895.2689]Output = Concat(Attention_1, Attention_2) = \begin{bmatrix} 1.7311 & 2.7311 \\ 4.2689 & 5.2689 \end{bmatrix}, [3.26894.26896.73117.7311]\begin{bmatrix} 3.2689 & 4.2689 \\ 6.7311 & 7.7311 \end{bmatrix}
  • The final output is the concatenated output matrix, rounded to 4 decimal places: [1.73112.73113.26894.26894.26895.26896.73117.7311]\begin{bmatrix} 1.7311 & 2.7311 & 3.2689 & 4.2689 \\ 4.2689 & 5.2689 & 6.7311 & 7.7311 \end{bmatrix}

Constraints:

  • d is divisible by h
  • 1 <= h <= d, 1 <= n <= 10
  • No projection matrices — just split/concat
  • Round to 4 decimal places
solution.py

Test Results

0/0
Run code to see test results.