Softmax-Weighted Value Mixing for Query Rows
Arrays & HashingAuto-graded · 17 test casesLast updated
Implement scaled dot-product attention on nested lists using a numerically stable softmax and a weighted average of value rows.
Softmax-Weighted Value Mixing for Query Rows
You are given three matrices stored as lists of lists of numbers:
queries:nrows, each of widthd.keys:mrows, each of widthd.values:mrows, each of widthw. The widthwneed not equald.
Write a function that returns, for every query row, a blend of the value rows. The blend weights come from how well the query matches each key.
Procedure
For a query row q:
- For every key row
k_j, compute the scores_j = (q · k_j) / sqrt(d). Hereq · k_jis the dot product anddis the length of the query row. - Convert the scores into weights with a softmax:
p_j = exp(s_j) / sum_t exp(s_t).- To avoid overflow, subtract the largest score in the row from every score before exponentiating. This does not change the result mathematically.
- The output row for
qis the weighted sum of the value rows:out[c] = sum_j p_j * values[j][c]for each columncin0..w-1.
Return the output rows in the same order as the queries, as a list of lists of floats (n rows, w columns each).
Edge-case rules
- If
queriesis empty, return[]. - If all scores in a row are equal, the weights are uniform, so the output is the mean of the value rows.
- Use the width of the first value row as
w. Ifvaluesis empty, each output row is an empty list.
Constraints
0 <= n <= 200,1 <= m <= 200,1 <= d <= 64,1 <= w <= 64.keysandvalueshave the same number of rows.- Every query and key row has the same length
d. - Entries are finite real numbers, and scores may be large in magnitude, so the softmax must be numerically stable.
- Results are compared to the expected output within floating-point tolerance.
Examples
Example 1
Input: attend([[1, 0, 1], [0, 1, 0]], [[1, 0, 1], [0, 1, 0]], [[1, 2, 3], [4, 5, 6]])
Output: [[1.718894674425938, 2.718894674425938, 3.718894674425938], [2.9213724270418826, 3.9213724270418826, 4.921372427041883]]
Example 2
Input: attend([[1, 2, 3], [4, 5, 6]], [[1, 0, 0], [0, 1, 0]], [[10, 20, 30], [40, 50, 60]])
Output: [[29.213724270418822, 39.21372427041882, 49.21372427041883], [29.213724270418822, 39.21372427041882, 49.21372427041883]]
Example 3
Input: attend([[0, 0, 0]], [[0, 0, 0]], [[7, 8, 9]])
Output: [[7, 8, 9]]
Hints
Hint 1
Handle each query row independently: first build its list of scores against all keys, then turn that list into weights.
Hint 2
Before calling exp, subtract the maximum score in the row. The weights stay the same, but nothing can overflow and the denominator is at least 1.
Hint 3
Once you have the weights for a row, each output column is the dot product of the weights with that column of the value matrix. Take the output width from the first value row, not from the query width.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Each query row is handled independently, in three steps.
- Scores. Take the dot product of the query with every key and divide by
sqrt(d), wheredis the query length. This gives one score per key. - Stable softmax. Find the maximum score and subtract it from every score. Exponentiate the shifted scores and divide by their sum. The shift cancels in the ratio, so the weights are mathematically identical to a plain softmax. Every exponent is now at most 0, so nothing overflows. The largest term is exactly 1, so the denominator is at least 1 and never zero.
- Mixing. For each output column, compute the weighted sum of that column over the value rows. The output row is therefore a convex combination of the value rows, because the weights are non-negative and sum to 1.
Why it is correct
- Softmax is invariant under adding a constant to every input, so subtracting the row maximum does not change the weights.
- Equal scores give equal weights, so the output is the mean of the value rows. A single key gives weight 1, so the output is that value row. Both cases match the edge-case rules.
- The output width comes from the first value row, so
wmay differ fromd. - An empty query list returns
[]immediately.
Complexity
With n queries, m keys, key width d and value width w:
- Time:
O(n * m * (d + w)). - Space:
O(m)working memory per query, plusO(n * w)for the output.
Reference solution
import math
from typing import List
def attend(queries: List[List[float]], keys: List[List[float]], values: List[List[float]]) -> List[List[float]]:
if not queries:
return []
d = len(queries[0])
scale = math.sqrt(d)
num_keys = len(keys)
width = len(values[0]) if values else 0
result = []
for q in queries:
scores = []
for key in keys:
scores.append(sum(a * b for a, b in zip(q, key)) / scale)
top = max(scores)
exps = [math.exp(s - top) for s in scores]
denom = sum(exps)
weights = [e / denom for e in exps]
row = []
for c in range(width):
row.append(sum(weights[j] * values[j][c] for j in range(num_keys)))
result.append(row)
return result