Attention Pooling to a Single Token
Problem Statement
The simplest bridge is attention pooling: collapse many patch features into one vector using a set of attention weights. Compute the weighted average of the patch features.
Background
Given patch features X (N x D) and attention weights w (length N, already summing to 1), the pooled token is
a convex combination of the rows. This is exactly what a one-query attention layer produces after its softmax.
Your Task
Implement:
def attention_pool(X, w):
Return the pooled D-vector as a list rounded to 4 decimals.
Input Format
- X: N x D nested list.
- w: list of N weights summing to 1.
Output Format
- A list of D floats rounded to 4 decimals.
Sample
print(attention_pool([[1.0, 2.0], [3.0, 4.0]], [0.5, 0.5]))
Output:
[2.0, 3.0]
Example
print(attention_pool([[1.0, 2.0], [3.0, 4.0]], [0.5, 0.5]))
[2.0, 3.0]
- Identify the patch features as a matrix with rows and , and the attention weights as .
- Compute the pooled value for the first dimension by taking the weighted sum of the first column: .
- Compute the pooled value for the second dimension by taking the weighted sum of the second column: .
- Combine these results into the vector and round each element to 4 decimal places, which leaves the values unchanged.
- The final output is [2.0, 3.0]
Constraints
1 <= N <= 5000,1 <= D <= 4096.wis a valid distribution over theNrows.- Round every entry to 4 decimals; avoid
-0.0.