56. Linear Self-Attention hard
Implement Linear Attention for a given set of matrices, following the method described in
"Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
.
Given the query matrix Q of size M×d, key matrix K of size M×d, and value matrix
V of size M×d, your program should compute the output matrix using the formula:
where is a feature map applied element-wise, for example:
All matrices Q, K, V, and output are of type float32, and M and d are of type int32.
Implementation 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):
Output:
output (2×4):
Example 2:
Input:
Q (2×2):
K (2×2):
V (2×2):
Output:
output (2×2):
Constraints
- Matrix
Q,K, andVare all of sizeM×d - 1 ≤
M≤ 10000 - 1 ≤
d≤ 128 - All elements in
Q,K, andVare sampled from[-100.0, 100.0] - Data type for all matrices is
float32 - Performance is measured with
M= 10,000
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) {
}
From LeetGPU, CC BY-NC-ND 4.0.