Example 1
Arguments: [
[
1
],
[
[
1
]
],
[
[
2
]
],
1,
[
true
]
]
Expected result: [
2
]The only allowed value is [2], so attention returns [2].
Tokenization and attention · Hard
Problem 20 of 50 · Python and NumPy
Compute one query’s scaled dot-product attention while processing keys in blocks of at most block_size. Return a Dv-wide weighted value vector; mask=false excludes a key, and all-masked input returns zeros.
Maintain a running maximum m, exponential sum l, and weighted-value sum a. When the maximum rises, rescale the previous sums before adding the new block. Do not materialize an S-wide score or probability vector: additional working storage must be O(block_size*(D+Dv) + Dv), apart from input arrays.
def online_attention(query, keys, values, block_size, mask):Arguments: [
[
1
],
[
[
1
]
],
[
[
2
]
],
1,
[
true
]
]
Expected result: [
2
]The only allowed value is [2], so attention returns [2].
Arguments: [
[
0
],
[
[
1
],
[
2
],
[
3
]
],
[
[
1
],
[
2
],
[
6
]
],
2,
[
true,
true,
true
]
]
Expected result: [
3
]A zero query gives equal scores across both blocks; the mean of 1,2,6 is 3.