LeetKernels
ProblemsStart solving
Problems

12. Multi-Head Attention hard

Implement a program for multi-head self-attention. Given three input matrices Q (queries), K (keys), and V (values) of size N×dmodel​, compute: MultiHead(Q,K,V)=Concat(head1​,…,headh​) where each head computes: headi​=softmax(dk​​Qi​KiT​​)Vi​ with dk​=dmodel​/h and Qi​,Ki​,Vi​ being the i-th head's partition of the input matrices.

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 array

Example 1:

Input: NQKV​=2,dmodel​=4,h=2=[1.04.0​0.05.0​2.06.0​3.07.0​]=[1.05.0​2.06.0​3.07.0​4.08.0​]=[0.52.5​1.03.0​1.53.5​2.04.0​]​ Output: [2.392.50​2.893.00​3.503.50​4.004.00​]

Example 2:

Input: NQKV​=1,dmodel​=2,h=1=[1.0​1.0​]=[1.0​1.0​]=[2.0​3.0​]​ Output: [2.0​3.0​]

Constraints

  • 1 ≤ N ≤ 10000
  • 2 ≤ d_model ≤ 1024
  • 1 ≤ h ≤ d_model
  • d_model % h == 0
  • -10.0 ≤ values ≤ 10.0
  • Performance is measured with N = 1,024, d_model = 1,024, and values sampled from [-1.0, 1.0]

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 N,
                      int d_model, int h) {}

Solve it on your GPU

Previous: 3D ConvolutionNext: Histogramming

From LeetGPU, CC BY-NC-ND 4.0.