LeetKernels
ProblemsStart solving
Problems

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: LinearAttention(Q,K,V)=ϕ(Q)(∑j​ϕ(Kj​))ϕ(Q)(ϕ(K)TV)​

where ϕ(x) is a feature map applied element-wise, for example: ϕ(x)=ELU(x)+1={x+1,ex,​x>0x≤0​ 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 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​]

Output:
output (2×4): [2.84615373.1538463​3.84615374.1538463​4.84615375.1538463​5.84615376.1538463​]

Example 2:

Input:
Q (2×2): [0.01.0​0.01.0​] K (2×2): [1.00.0​0.01.0​] V (2×2): [3.05.0​4.06.0​]

Output:
output (2×2): [4.04.0​5.05.0​]

Constraints

  • Matrix Q, K, and V are all of size M×d
  • 1 ≤ M ≤ 10000
  • 1 ≤ d ≤ 128
  • All elements in Q, K, and V are 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) {

}

Solve it on your GPU

Previous: Attention with Linear BiasesNext: FP16 Batched Matrix Multiplication

From LeetGPU, CC BY-NC-ND 4.0.