LeetKernels
ProblemsStart solving
Problems

80. Grouped Query Attention medium

Implement Grouped Query Attention (GQA), the attention mechanism used in modern large language models such as LLaMA-3, Mistral, and Gemma. GQA reduces the KV-cache memory footprint during inference by sharing key and value heads across groups of query heads. Given query tensor Q with num_q_heads heads and key/value tensors K, V each with num_kv_heads heads, compute scaled dot-product attention where every group of num_q_heads / num_kv_heads consecutive query heads attends to the same key and value head. All tensors use float32.

Grouped Query Attention (num_q_heads=4, num_kv_heads=2, groups=2) Q heads Q[0] Q[1] Q[2] Q[3] KV heads K[0], V[0] K[1], V[1] group 0 group 1 Q[0], Q[1] attend to K[0], V[0] Q[2], Q[3] attend to K[1], V[1] scale = 1 / sqrt(head_dim) scores = Q @ K^T * scale weights = softmax(scores) output = weights @ V

Implementation Requirements

  • Implement the function solve(Q, K, V, output, num_q_heads, num_kv_heads, seq_len, head_dim).
  • Do not change the function signature or use external libraries beyond the standard GPU frameworks.
  • Write the result into the provided output buffer.
  • num_q_heads is always divisible by num_kv_heads.
  • Use scaled dot-product attention with scale factor 1 / sqrt(head_dim) and a softmax over the key dimension.

Example

With num_q_heads = 4, num_kv_heads = 2 (groups of 2), seq_len = 3, head_dim = 4:

Input:
Q0​ (3×4): ​101​011​010​100​​ Q1​ (3×4): ​010​100​011​101​​ Q2​ (3×4): ​−100.5​0−10​0.50−1​00.50​​ Q3​ (3×4): ​00.50​0.500​000.5​−1−10.5​​ K0​ (3×4): ​101​011​101​011​​ K1​ (3×4): ​0−10​10−1​010​−101​​ V0​ (3×4): ​159​2610​3711​4812​​ V1​ (3×4): ​−126​−237​−348​−459​​ Groups: Q0​,Q1​→K0​,V0​; \quad Q2​,Q3​→K1​,V1​

Output (values rounded to 2 decimal places):
output0​ (3×4): ​5.715.715.71​6.716.716.71​7.717.717.71​8.718.718.71​​ output1​ (3×4): ​6.075.005.71​7.076.006.71​8.077.007.71​9.078.008.71​​ output2​ (3×4): ​2.243.962.40​2.764.702.60​3.275.442.79​3.796.172.98​​ output3​ (3×4): ​0.761.172.84​0.581.083.37​0.401.003.91​0.220.914.44​​

Constraints

  • 1 ≤ num_kv_heads ≤ num_q_heads ≤ 64
  • num_q_heads is divisible by num_kv_heads
  • 1 ≤ seq_len ≤ 4,096
  • 8 ≤ head_dim ≤ 256; head_dim is a multiple of 8
  • All tensor values are float32
  • Performance is measured with num_q_heads = 32, num_kv_heads = 8, seq_len = 1,024, head_dim = 128

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 num_q_heads, int num_kv_heads, int seq_len, int head_dim) {}

Solve it on your GPU

Previous: 2D FFTNext: INT4 Weight-Only Quantized MatMul

From LeetGPU, CC BY-NC-ND 4.0.