PIXELBANKv9.1.0
Menu

Problem Statement

Extend single-head cross-attention to h heads: split the model dimension across heads, run scaled dot-product attention independently per head, then concatenate. This is the resampler/Q-Former core.

Background

With model dimension d_model and h heads, each head works in dimension d_k = d_model / h. Given already-projected Q (n_q x d_model), K, V (n_kv x d_model), split each along the feature axis into h contiguous blocks. For head j:

Oj=softmax ⁣(QjKj⊀dk)VjO_j = \text{softmax}\!\left(\frac{Q_j K_j^\top}{\sqrt{d_k}}\right) V_j

Concatenate O_0, ..., O_{h-1} back to n_q x d_model. (No output projection here β€” just the attention.) Softmax is row-wise and numerically stable.

Your Task

Implement:

def multihead_cross_attention(Q, K, V, h):

Return the n_q x d_model output as a nested list rounded to 4 decimals.

Input Format

  • Q: n_q x d_model; K, V: n_kv x d_model.
  • h (int): number of heads; d_model divisible by h.

Output Format

  • An n_q x d_model nested list rounded to 4 decimals.

Sample

Q = [[1.0, 0.0]]
K = [[1.0, 0.0], [0.0, 1.0]]
V = [[2.0, 0.0], [0.0, 3.0]]
print(multihead_cross_attention(Q, K, V, 2))

Output:

[[1.4621, 1.5]]

Example:

Input:
Q = [[1.0, 0.0]]
K = [[1.0, 0.0], [0.0, 1.0]]
V = [[2.0, 0.0], [0.0, 3.0]]
print(multihead_cross_attention(Q, K, V, 2))
Output:
[[1.4621, 1.5]]
Reasoning:

Two heads of size 1 (d_k=1, scale=1). Head 0: Q=[1], K=[[1],[0]] gives scores [1,0], softmax [0.7311,0.2689], attending V0=[2],V1=[0] -> 1.4621. Head 1: Q=[0], K=[[0],[1]] gives scores [0,1], softmax [0.2689,0.7311], attending V0=[0],V1=[3] -> 1.5. Concatenated: [1.4621, 1.5].

Constraints:

  • d_model % h == 0; d_k = d_model / h.
  • Each head scales by 1/sqrt(d_k) and softmaxes over the key axis, stably.
  • Concatenate heads in order; round to 4 decimals; avoid -0.0.
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Multi-Head Cross-Attention Output - Medium | PixelBank