LeetKernels
ProblemsStart solving
Problems

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:

AttentionALiBi​(Q,K,V)=softmax(d​QKT​+α⋅Δ)V

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 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 (3×4): ​1.00.00.0​0.01.00.0​0.00.01.0​0.00.00.0​​ V (3×4): ​1.05.09.0​2.06.010.0​3.07.011.0​4.08.012.0​​ α=0.5

Output:
output (2×4): [3.053.93​4.054.93​6.055.93​7.056.93​]

Example 2:

Input:
Q (1×2): [1.0​2.0​] K (2×2): [1.00.0​0.01.0​] V (2×2): [3.05.0​4.06.0​] α = 0.8

Output:
output (1×2): [3.95​4.95​]

Constraints

  • Matrix Q is of size M×d and matrices K and V are of size N×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) {}

Solve it on your GPU

Previous: Swish-Gated Linear UnitNext: Linear Self-Attention

From LeetGPU, CC BY-NC-ND 4.0.