LeetKernels
ProblemsStart solving
Problems

6. Softmax Attention medium

Implement a GPU program that computes the softmax attention operation 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: Attention(Q,K,V)=softmax(d​QKT​)V, where the softmax function is applied row-wise.

Implementation Requirements

  • Use only GPU 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​​

Output:
output (2×4): [4.295.00​5.296.00​6.297.00​7.298.00​]

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​]

Output:
output (1×2): [4.34​5.34​]

Constraints

  • Matrix Q is of size M×d and matrices K and V are of size N×d
  • 1 ≤ M, N ≤ 100,000
  • 1 ≤ d ≤ 128
  • Performance is measured with M = 512, N = 256

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) {}

Solve it on your GPU

Previous: SoftmaxNext: Color Inversion

From LeetGPU, CC BY-NC-ND 4.0.