LeetKernels
ProblemsStart solving
Problems

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:

scorei,j​=d​Qi​⋅Kj​​

outputi​=∑j=1M​softmax(scorei,∗​)j​⋅Vj​

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 size window_size around i (positions [i-window_size, ..., i+window_size]).
  • Compute similarity scores between Qi and the keys in this window:

scorei,j​=d​Qi​⋅Kj​​

  • Apply softmax over 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 = 2

Implementation Requirements

  • Use only native features (external libraries are not permitted)
  • The solve function signature must remain unchanged
  • The final result must be stored in the output matrix output

Example 1:

Input:
Q (2×4): [1.00.0​0.01.0​0.00.0​0.00.0​] K (2×4): [1.00.0​0.01.0​0.00.0​0.00.0​] V (2×4): [1.05.0​2.06.0​3.07.0​4.08.0​] window_size: 1

Output:
output (2×4): [2.51016283.4898374​3.51016284.4898376​4.5101635.4898376​5.5101636.489837​]

Example 2:

Input:
Q (2×3): [0.00.0​0.01.0​0.00.0​] K (2×3): [1.00.0​0.01.0​0.00.0​] V (2×3): [1.05.0​2.06.0​3.07.0​] window_size: 1

Output:
output (2×3): [3.03.5618298​4.04.56183​5.05.5618296​]

Constraints

  • Matrix Q, K, and V are all of size M×d
  • 1 ≤ M ≤ 10000
  • 1 ≤ d ≤ 128
  • 1 ≤ window_size ≤ 32
  • All elements in Q, K, and V are in [-100.0, 100.0]
  • Data type for all matrices is float32
  • Performance is measured with M = 5,000 and elements of Q, K and V sampled 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) {}

Solve it on your GPU

Previous: FP16 Dot ProductNext: Top-p Sampling

From LeetGPU, CC BY-NC-ND 4.0.