55. Attention with Linear Biases medium
Implement Attention with Linear Biases (ALiBi), following the method described in
"Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation"
, for a given set of matrices.
Given the query matrix Q of size M×d, key matrix K of size N×d, and value matrix
V of size N×d, your program should compute the output matrix using the formula:
where α is a slope controlling the linear bias and Δ = i - j represents the relative position between query i and key j.
The softmax function is applied row-wise. Q, K, V, output, and α are all of data type float32;
M, N, d are of data 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 (3×4):
V (3×4):
Output:
output (2×4):
Example 2:
Input:
Q (1×2):
K (2×2):
V (2×2):
α = 0.8
Output:
output (1×2):
Constraints
- Matrix
Qis of sizeM×dand matricesKandVare of sizeN×d - 1 ≤
M,N≤ 2048 - 1 ≤
d≤ 1024 - -1.0 ≤
α≤ 1.0 - Performance is measured with
M= 2,048,N= 2,048
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 N,
int d, float alpha) {}
From LeetGPU, CC BY-NC-ND 4.0.