Multi-Head Cross-Attention Output
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:
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
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))
[[1.4621, 1.5]]
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.