59. Sliding Window Self-Attention hard
Implement Sliding Window Self-Attention for a given set of matrices. Before introducing the sliding window version, let's first recall standard Self-Attention.
1. Standard Softmax Attention
Given query matrix Q, key matrix K, and value matrix V, each position i attends to all positions j using a softmax-weighted sum:
In other words, each query computes similarity with all keys, applies a softmax to get attention weights, and then computes a weighted sum of values.
2. Sliding Window Self-Attention
Sliding Window Attention modifies standard attention by restricting each query to attend only to a local window around its position.
- For each position
i, only consider the keys and values within a window of sizewindow_sizearoundi(positions[i-window_size, ..., i+window_size]). - Compute similarity scores between
Qiand the keys in this window:
- Apply
softmaxover these local scores to obtain attention weights. - Use the weights to compute a weighted average of the values in the same window:
\text{output}_i = \sum_{j \in [i-\text{window_size}, \, i+\text{window_size}]} \text{softmax}(\text{score}_{i,*})_j \cdot V_j
In short, each query only attends to its nearby neighbors.
key position → query position 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 window_size = 2Implementation Requirements
- Use only native features (external libraries are not permitted)
- The
solvefunction signature must remain unchanged - The final result must be stored in the output matrix
output
Example 1:
Input:
Q (2×4):
K (2×4):
V (2×4):
window_size: 1
Output:
output (2×4):
Example 2:
Input:
Q (2×3):
K (2×3):
V (2×3):
window_size: 1
Output:
output (2×3):
Constraints
- Matrix
Q,K, andVare all of sizeM×d - 1 ≤
M≤ 10000 - 1 ≤
d≤ 128 - 1 ≤
window_size≤ 32 - All elements in
Q,K, andVare in[-100.0, 100.0] - Data type for all matrices is
float32 - Performance is measured with
M= 5,000 and elements ofQ,KandVsampled from[-1.0, 1.0]
Starter code (CUDA)
#include <cuda_runtime.h>
// Q, K, V, output are device pointers
extern "C" void solve(const float* Q, const float* K, const float* V, float* output, int M, int d,
int window_size) {}
From LeetGPU, CC BY-NC-ND 4.0.