correct
15_GQAKVHeadExpansionAttention.py
started
2026-05-11T14:47:02Z
timingkernelbench.timing
kernel mean / median / std
0.32 / — / 0.00 μs
ref mean / median / std
95.20 / — / 140.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
9720.60x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import math
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Causal grouped-query attention with KV-head expansion.
Query heads outnumber KV heads. Keys and values are expanded by repeating
each KV head across its assigned query-head group before causal attention.
"""
def __init__(self):
super().__init__()
def forward(
self,
q: torch.Tensor,
k: torch.Tensor,
v: torch.Tensor,
) -> torch.Tensor:
batch_size, seq_len, num_q_heads, head_dim = q.shape
num_kv_heads = k.shape[2]
group_size = num_q_heads // num_kv_heads
expanded_k = k.repeat_interleave(group_size, dim=2)
expanded_v = v.repeat_interleave(group_size, dim=2)
out = torch.zeros_like(q)
scale = 1.0 / math.sqrt(head_dim)
for b in range(batch_size):
for h in range(num_q_heads):
for t in range(seq_len):
q_t = q[b, t, h]
k_hist = expanded_k[b, : t + 1, h]
v_hist = expanded_v[b, : t + 1, h]
scores = (k_hist * q_t.unsqueeze(0)).sum(dim=-1) * scale
attn = torch.softmax(scores, dim=0)
out[b, t, h] = (attn.unsqueeze(-1) * v_hist).sum(dim=0)
return out
batch_size = 2
seq_len = 80
num_q_heads = 8
num_kv_heads = 2
head_dim = 32
def get_inputs():
p = popcorn_pri
q = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_q_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
k = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_kv_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
v = torch.randn(p.jitter_int(batch_size), p.jitter_int(seq_len), p.jitter_int(num_kv_heads), p.jitter_int(head_dim, align=8), dtype=torch.float32)
return [q, k, v]
def get_init_inputs():
return []
turn 0201.8s turn · 2.7s LLM · 199.0s tools · tokens in=1,682 · out=171 · total=1,853
reasoning
Let me analyze this task. I need to implement a causal grouped-query attention with KV-head expansion as a custom CUDA kernel.
The reference implementation:
1. Takes q (batch_size, seq_len, num_q_heads, head_dim), k and v (batch_size, seq_len, num_kv_heads, head_dim)
2. Expands k and v by repeating each KV head across its assigned query-head group
3. For each batch, head, and position t:
- Computes attention scores between q[b,t,h] and k[b,:t+1,h]
- Applies softmax
- Computes weighted sum of v[b,:t+1,h]
This is a causal attention pattern - each position can only attend to itself and earlier positions.
Let me first get the GPU specs to understand the hardware.
call → get_gpu_specs
callget_gpu_specs
{}
result ← get_gpu_specs (ok)
okget_gpu_specs
GPU specs for NVIDIA H100 80GB HBM3:
total memory (runtime): 79.1 GB
spec entry: H100
GPU Architecture: Hopper
GPU Memory: 80GB
Memory Bandwidth: 3.35 TB/s
FP64 TFLOPS: 34
FP64 Tensor Core TFLOPS: 67
FP32 TFLOPS: 67
TF32 Tensor Core TFLOPS: 989 with sparsity
BFLOAT16 Tensore Core TFLOPS: 1979 with sparsity
FP16 Tensor Core TFLOPS: 1979 with sparsity
FP8 Tensor Core TFLOPS: 3958 with sparsity
INT8 Tensor Core TOPS: 3958 with sparsity
Register File Size: 64K 32-bit registers per SM
Maximum number of registers per thread: 255
Maximum number of thread blocks per SM: 32
Shared memory capacity per SM: 228 KB
Maximum shared memory per thread block: 227 KB
turn 1 · 1 tool call(s) · 163.5s turn · 17.7s LLM · tokens in=1,930 · out=1,828 · total=3,758 · 11,356 chars (click to expand)
turn 1163.5s turn · 17.7s LLM · 145.8s tools · tokens in=1,930 · out=1,828 · total=3,758
reasoning
Now let me write an optimized CUDA kernel for this grouped-query attention. The key observations:
1. Each query head position computes attention against all previous positions (causal)
2. KV heads are expanded by repeating - each KV head serves group_size query heads
3. The computation is [seq_len] softmax over [t+1] positions for each (batch, head, time)
My approach:
- Each thread block handles one (batch, head) pair
- Within a block, threads iterate over t=0 to seq_len-1
- For each t, compute attention scores against all positions 0..t
- Use shared memory to cache K and V values
Let me write the kernel:
assistantLet me write an optimized CUDA kernel for this grouped-query attention. The key is to parallelize efficiently while handling the causal mask.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import math\nimport torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n# Define the CUDA kernel source\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n#define BLOCK_SIZE 256\n\n__device__ float warp_reduce_max(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val = fmaxf(val, __shfl_down_sync(0xffffffff, val, offset));\n }\n return val;\n}\n\n__device__ float warp_reduce_sum(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val += __shfl_down_sync(0xffffffff, val, offset);\n }\n return val;\n}\n\n__global__ void grouped_query_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n float* __restrict__ out,\n int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size\n) {\n // Each thread block handles one (batch, head) pair\n int batch_idx = blockIdx.x / num_q_heads;\n int q_head_idx = blockIdx.x % num_q_heads;\n \n // Determine which KV head this query head uses\n int kv_head_idx = q_head_idx / group_size;\n \n // Thread index within the block\n int tid = threadIdx.x;\n \n // Pointers to the relevant slices\n const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n \n // Scale factor\n float scale = 1.0f / sqrtf((float)head_dim);\n \n // Shared memory for scores and attention weights (one per position in sequence)\n extern __shared__ float shared_mem[];\n float* scores = shared_mem; // seq_len elements\n float* attn_weights = shared_mem + seq_len; // seq_len elements\n \n // Iterate over each query position\n for (int t = 0; t < seq_len; t++) {\n // Get query vector at position t\n const float* q_t = q_ptr + t * num_q_heads * head_dim;\n \n // Compute scores for all positions 0..t using all threads in block\n float max_score = -INFINITY;\n \n // Each thread computes scores for some positions\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;\n \n float score = 0.0f;\n for (int d = 0; d < head_dim; d++) {\n score += q_t[d] * k_pos[d];\n }\n score *= scale;\n scores[pos] = score;\n }\n \n // Also set scores beyond t to -inf for safety\n for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {\n scores[pos] = -INFINITY;\n }\n \n __syncthreads();\n \n // Find max score (for numerical stability)\n if (tid == 0) {\n max_score = scores[0];\n for (int i = 1; i <= t; i++) {\n if (scores[i] > max_score) max_score = scores[i];\n }\n }\n \n // Broadcast max_score to all threads\n __shared__ float shared_max;\n if (tid == 0) shared_max = max_score;\n __syncthreads();\n max_score = shared_max;\n \n // Compute exp(scores - max) and sum\n float sum_exp = 0.0f;\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n float exp_val = expf(scores[pos] - max_score);\n attn_weights[pos] = exp_val;\n sum_exp += exp_val;\n }\n \n // Reduce sum_exp across threads\n sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));\n \n __shared__ float total_sum[BLOCK_SIZE / 32];\n int warp_id = tid / 32;\n int lane_id = tid % 32;\n if (lane_id == 0) {\n total_sum[warp_id] = sum_exp;\n }\n __syncthreads();\n \n if (tid == 0) {\n float final_sum = 0.0f;\n for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {\n final_sum += total_sum[i];\n }\n shared_max = final_sum; // Reuse shared_max for final_sum\n }\n __syncthreads();\n float inv_sum = 1.0f / shared_max;\n \n // Normalize attention weights\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n attn_weights[pos] *= inv_sum;\n }\n __syncthreads();\n \n // Compute output: weighted sum of V\n // Each thread computes part of the output dimension\n for (int d = tid; d < head_dim; d += BLOCK_SIZE) {\n float out_val = 0.0f;\n for (int pos = 0; pos <= t; pos++) {\n const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;\n out_val += attn_weights[pos] * v_pos[d];\n }\n out_ptr[t * num_q_heads * head_dim + d] = out_val;\n }\n __syncthreads();\n }\n}\n\ntorch::Tensor grouped_query_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v\n) {\n int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_q_heads = q.size(2);\n int head_dim = q.size(3);\n int num_kv_heads = k.size(2);\n \n auto out = torch::zeros_like(q);\n \n int group_size = num_q_heads / num_kv_heads;\n \n int num_blocks = batch_size * num_q_heads;\n size_t shared_mem_size = seq_len * 2 * sizeof(float);\n \n grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n out.data_ptr<float>(),\n batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size\n );\n \n return out;\n}\n\"\"\"\n\n# Load the CUDA extension\ngrouped_query_attention = load_inline(\n name='grouped_query_attention',\n cpp_sources='',\n cuda_sources=cuda_source,\n functions=['grouped_query_attention_cuda'],\n extra_cuda_cflags=['-O3'],\n verbose=False\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n return grouped_query_attention.grouped_query_attention_cuda(q, k, v)"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: RuntimeError.
RuntimeError: Error building extension 'grouped_query_attention': [1/3] /opt/conda/bin/x86_64-conda-linux-gnu-c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=grouped_query_attention -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /opt/conda/include/python3.10 -fPIC -std=c++17 -c /scratch/abaner/KernelBench/runs/pop_l123_default_gpt/popcorn/FW-GLM-5-1/level_2_problem_15_cache/k_e48e3bef4c1b/grouped_query_attention/main.cpp -o main.o
FAILED: [code=1] main.o
/opt/conda/bin/x86_64-conda-linux-gnu-c++ -MMD -MF main.o.d -DTORCH_EXTENSION_NAME=grouped_query_attention -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /opt/conda/include/python3.10 -fPIC -std=c++17 -c /scratch/abaner/KernelBench/runs/pop_l123_default_gpt/popcorn/FW-GLM-5-1/level_2_problem_15_cache/k_e48e3bef4c1b/grouped_query_attention/main.cpp -o main.o
/scratch/abaner/KernelBench/runs/pop_l123_default_gpt/popcorn/FW-GLM-5-1/level_2_problem_15_cache/k_e48e3bef4c1b/grouped_query_attention/main.cpp: In function 'void pybind11_init_grouped_query_attention(pybind11::module_&)':
/scratch/abaner/KernelBench/runs/pop_l123_default_gpt/popcorn/FW-GLM-5-1/level_2_problem_15_cache/k_e48e3bef4c1b/grouped_query_attention/main.cpp:4:67: error: 'grouped_query_attention_cuda' was not declared in this scope
4 | m.def("grouped_query_attention_cuda", torch::wrap_pybind_function(grouped_query_attention_cuda), "grouped_query_attention_cuda");
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
[2/3] /usr/local/cuda/bin/nvcc -MD -MF cuda.cuda.o.d -ccbin /opt/conda/bin/x86_64-conda-linux-gnu-cc -DTORCH_EXTENSION_NAME=grouped_query_attention -DTORCH_API_INCLUDE_EXTENSION_H -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include -isystem /scratch/abaner/KernelBench/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -isystem /usr/local/cuda/include -isystem /opt/conda/include/python3.10 -D__CUDA_NO_HALF_OPERATORS__ -D__CUDA_NO_HALF_CONVERSIONS__ -D__CUDA_NO_BFLOAT16_CONVERSIONS__ -D__CUDA_NO_HALF2_OPERATORS__ --expt-relaxed-constexpr -gencode=arch=compute_90,code=compute_90 -gencode=arch=compute_90,code=sm_90 --compiler-options '-fPIC' -O3 -std=c++17 -c /scratch/abaner/KernelBench/runs/pop_l123_default_gpt/popcorn/FW-GLM-5-1/level_2_problem_15_cache/k_e48e3bef4c1b/grouped_query_attention/cuda.cu -o cuda.cuda.o
nvcc warning : incompatible redefinition for option 'compiler-bindir', the last value of this option was used
ninja: build stopped: subcommand failed.
turn 2 · 1 tool call(s) · 630.4s turn · 24.0s LLM · tokens in=4,531 · out=1,661 · total=6,192 · 7,582 chars (click to expand)
turn 2630.4s turn · 24.0s LLM · 606.5s tools · tokens in=4,531 · out=1,661 · total=6,192
reasoning
The error is that the C++ wrapper can't find the CUDA function. I need to add a C++ declaration for the CUDA function. Let me add cpp_sources to provide the function declaration.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import math\nimport torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n# Define the CUDA kernel source\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n#define BLOCK_SIZE 256\n\n__device__ float warp_reduce_sum(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val += __shfl_down_sync(0xffffffff, val, offset);\n }\n return val;\n}\n\n__global__ void grouped_query_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n float* __restrict__ out,\n int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size\n) {\n // Each thread block handles one (batch, head) pair\n int batch_idx = blockIdx.x / num_q_heads;\n int q_head_idx = blockIdx.x % num_q_heads;\n \n // Determine which KV head this query head uses\n int kv_head_idx = q_head_idx / group_size;\n \n // Thread index within the block\n int tid = threadIdx.x;\n \n // Pointers to the relevant slices\n const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n \n // Scale factor\n float scale = 1.0f / sqrtf((float)head_dim);\n \n // Shared memory for scores and attention weights (one per position in sequence)\n extern __shared__ float shared_mem[];\n float* scores = shared_mem; // seq_len elements\n float* attn_weights = shared_mem + seq_len; // seq_len elements\n \n // Iterate over each query position\n for (int t = 0; t < seq_len; t++) {\n // Get query vector at position t\n const float* q_t = q_ptr + t * num_q_heads * head_dim;\n \n // Compute scores for all positions 0..t using all threads in block\n float max_score = -INFINITY;\n \n // Each thread computes scores for some positions\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;\n \n float score = 0.0f;\n for (int d = 0; d < head_dim; d++) {\n score += q_t[d] * k_pos[d];\n }\n score *= scale;\n scores[pos] = score;\n }\n \n // Also set scores beyond t to -inf for safety\n for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {\n scores[pos] = -INFINITY;\n }\n \n __syncthreads();\n \n // Find max score (for numerical stability)\n if (tid == 0) {\n max_score = scores[0];\n for (int i = 1; i <= t; i++) {\n if (scores[i] > max_score) max_score = scores[i];\n }\n }\n \n // Broadcast max_score to all threads\n __shared__ float shared_max;\n if (tid == 0) shared_max = max_score;\n __syncthreads();\n max_score = shared_max;\n \n // Compute exp(scores - max) and sum\n float sum_exp = 0.0f;\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n float exp_val = expf(scores[pos] - max_score);\n attn_weights[pos] = exp_val;\n sum_exp += exp_val;\n }\n \n // Reduce sum_exp across threads\n sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));\n \n __shared__ float total_sum[BLOCK_SIZE / 32];\n int warp_id = tid / 32;\n int lane_id = tid % 32;\n if (lane_id == 0) {\n total_sum[warp_id] = sum_exp;\n }\n __syncthreads();\n \n if (tid == 0) {\n float final_sum = 0.0f;\n for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {\n final_sum += total_sum[i];\n }\n shared_max = final_sum; // Reuse shared_max for final_sum\n }\n __syncthreads();\n float inv_sum = 1.0f / shared_max;\n \n // Normalize attention weights\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n attn_weights[pos] *= inv_sum;\n }\n __syncthreads();\n \n // Compute output: weighted sum of V\n // Each thread computes part of the output dimension\n for (int d = tid; d < head_dim; d += BLOCK_SIZE) {\n float out_val = 0.0f;\n for (int pos = 0; pos <= t; pos++) {\n const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;\n out_val += attn_weights[pos] * v_pos[d];\n }\n out_ptr[t * num_q_heads * head_dim + d] = out_val;\n }\n __syncthreads();\n }\n}\n\ntorch::Tensor grouped_query_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v\n) {\n int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_q_heads = q.size(2);\n int head_dim = q.size(3);\n int num_kv_heads = k.size(2);\n \n auto out = torch::zeros_like(q);\n \n int group_size = num_q_heads / num_kv_heads;\n \n int num_blocks = batch_size * num_q_heads;\n size_t shared_mem_size = seq_len * 2 * sizeof(float);\n \n grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n out.data_ptr<float>(),\n batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor grouped_query_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v);\n\"\"\"\n\n# Load the CUDA extension\ngrouped_query_attention = load_inline(\n name='grouped_query_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['grouped_query_attention_cuda'],\n extra_cuda_cflags=['-O3'],\n verbose=False\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n return grouped_query_attention.grouped_query_attention_cuda(q, k, v)"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 3 · 1 tool call(s) · 334.6s turn · 13.0s LLM · tokens in=6,166 · out=1,642 · total=7,808 · 7,607 chars (click to expand)
turn 3334.6s turn · 13.0s LLM · 321.6s tools · tokens in=6,166 · out=1,642 · total=7,808
reasoning
The kernel compiled successfully. Let me run correctness check to see if the output matches the reference.
call → run_correctness
callrun_correctness
{
"kernel_code": "import math\nimport torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n# Define the CUDA kernel source\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n#define BLOCK_SIZE 256\n\n__device__ float warp_reduce_sum(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val += __shfl_down_sync(0xffffffff, val, offset);\n }\n return val;\n}\n\n__global__ void grouped_query_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n float* __restrict__ out,\n int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size\n) {\n // Each thread block handles one (batch, head) pair\n int batch_idx = blockIdx.x / num_q_heads;\n int q_head_idx = blockIdx.x % num_q_heads;\n \n // Determine which KV head this query head uses\n int kv_head_idx = q_head_idx / group_size;\n \n // Thread index within the block\n int tid = threadIdx.x;\n \n // Pointers to the relevant slices\n const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n \n // Scale factor\n float scale = 1.0f / sqrtf((float)head_dim);\n \n // Shared memory for scores and attention weights (one per position in sequence)\n extern __shared__ float shared_mem[];\n float* scores = shared_mem; // seq_len elements\n float* attn_weights = shared_mem + seq_len; // seq_len elements\n \n // Iterate over each query position\n for (int t = 0; t < seq_len; t++) {\n // Get query vector at position t\n const float* q_t = q_ptr + t * num_q_heads * head_dim;\n \n // Compute scores for all positions 0..t using all threads in block\n float max_score = -INFINITY;\n \n // Each thread computes scores for some positions\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;\n \n float score = 0.0f;\n for (int d = 0; d < head_dim; d++) {\n score += q_t[d] * k_pos[d];\n }\n score *= scale;\n scores[pos] = score;\n }\n \n // Also set scores beyond t to -inf for safety\n for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {\n scores[pos] = -INFINITY;\n }\n \n __syncthreads();\n \n // Find max score (for numerical stability)\n if (tid == 0) {\n max_score = scores[0];\n for (int i = 1; i <= t; i++) {\n if (scores[i] > max_score) max_score = scores[i];\n }\n }\n \n // Broadcast max_score to all threads\n __shared__ float shared_max;\n if (tid == 0) shared_max = max_score;\n __syncthreads();\n max_score = shared_max;\n \n // Compute exp(scores - max) and sum\n float sum_exp = 0.0f;\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n float exp_val = expf(scores[pos] - max_score);\n attn_weights[pos] = exp_val;\n sum_exp += exp_val;\n }\n \n // Reduce sum_exp across threads\n sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));\n \n __shared__ float total_sum[BLOCK_SIZE / 32];\n int warp_id = tid / 32;\n int lane_id = tid % 32;\n if (lane_id == 0) {\n total_sum[warp_id] = sum_exp;\n }\n __syncthreads();\n \n if (tid == 0) {\n float final_sum = 0.0f;\n for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {\n final_sum += total_sum[i];\n }\n shared_max = final_sum; // Reuse shared_max for final_sum\n }\n __syncthreads();\n float inv_sum = 1.0f / shared_max;\n \n // Normalize attention weights\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n attn_weights[pos] *= inv_sum;\n }\n __syncthreads();\n \n // Compute output: weighted sum of V\n // Each thread computes part of the output dimension\n for (int d = tid; d < head_dim; d += BLOCK_SIZE) {\n float out_val = 0.0f;\n for (int pos = 0; pos <= t; pos++) {\n const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;\n out_val += attn_weights[pos] * v_pos[d];\n }\n out_ptr[t * num_q_heads * head_dim + d] = out_val;\n }\n __syncthreads();\n }\n}\n\ntorch::Tensor grouped_query_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v\n) {\n int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_q_heads = q.size(2);\n int head_dim = q.size(3);\n int num_kv_heads = k.size(2);\n \n auto out = torch::zeros_like(q);\n \n int group_size = num_q_heads / num_kv_heads;\n \n int num_blocks = batch_size * num_q_heads;\n size_t shared_mem_size = seq_len * 2 * sizeof(float);\n \n grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n out.data_ptr<float>(),\n batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor grouped_query_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v);\n\"\"\"\n\n# Load the CUDA extension\ngrouped_query_attention = load_inline(\n name='grouped_query_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['grouped_query_attention_cuda'],\n extra_cuda_cflags=['-O3'],\n verbose=False\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n return grouped_query_attention.grouped_query_attention_cuda(q, k, v)"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=8.34e-07 mean_abs_err=4.19e-08 max_rel_err=1.01e-01
turn 4 · 1 tool call(s) · 13.2s turn · 13.2s LLM · tokens in=7,846 · out=1,642 · total=9,488 · 7,497 chars (click to expand)
turn 413.2s turn · 13.2s LLM · 0.0s tools · tokens in=7,846 · out=1,642 · total=9,488
reasoning
The kernel passed correctness. Now let me check if there are any reward-hacking patterns before submitting.
call → static_check
callstatic_check
{
"kernel_code": "import math\nimport torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n# Define the CUDA kernel source\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n#define BLOCK_SIZE 256\n\n__device__ float warp_reduce_sum(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val += __shfl_down_sync(0xffffffff, val, offset);\n }\n return val;\n}\n\n__global__ void grouped_query_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n float* __restrict__ out,\n int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size\n) {\n // Each thread block handles one (batch, head) pair\n int batch_idx = blockIdx.x / num_q_heads;\n int q_head_idx = blockIdx.x % num_q_heads;\n \n // Determine which KV head this query head uses\n int kv_head_idx = q_head_idx / group_size;\n \n // Thread index within the block\n int tid = threadIdx.x;\n \n // Pointers to the relevant slices\n const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n \n // Scale factor\n float scale = 1.0f / sqrtf((float)head_dim);\n \n // Shared memory for scores and attention weights (one per position in sequence)\n extern __shared__ float shared_mem[];\n float* scores = shared_mem; // seq_len elements\n float* attn_weights = shared_mem + seq_len; // seq_len elements\n \n // Iterate over each query position\n for (int t = 0; t < seq_len; t++) {\n // Get query vector at position t\n const float* q_t = q_ptr + t * num_q_heads * head_dim;\n \n // Compute scores for all positions 0..t using all threads in block\n float max_score = -INFINITY;\n \n // Each thread computes scores for some positions\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;\n \n float score = 0.0f;\n for (int d = 0; d < head_dim; d++) {\n score += q_t[d] * k_pos[d];\n }\n score *= scale;\n scores[pos] = score;\n }\n \n // Also set scores beyond t to -inf for safety\n for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {\n scores[pos] = -INFINITY;\n }\n \n __syncthreads();\n \n // Find max score (for numerical stability)\n if (tid == 0) {\n max_score = scores[0];\n for (int i = 1; i <= t; i++) {\n if (scores[i] > max_score) max_score = scores[i];\n }\n }\n \n // Broadcast max_score to all threads\n __shared__ float shared_max;\n if (tid == 0) shared_max = max_score;\n __syncthreads();\n max_score = shared_max;\n \n // Compute exp(scores - max) and sum\n float sum_exp = 0.0f;\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n float exp_val = expf(scores[pos] - max_score);\n attn_weights[pos] = exp_val;\n sum_exp += exp_val;\n }\n \n // Reduce sum_exp across threads\n sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));\n \n __shared__ float total_sum[BLOCK_SIZE / 32];\n int warp_id = tid / 32;\n int lane_id = tid % 32;\n if (lane_id == 0) {\n total_sum[warp_id] = sum_exp;\n }\n __syncthreads();\n \n if (tid == 0) {\n float final_sum = 0.0f;\n for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {\n final_sum += total_sum[i];\n }\n shared_max = final_sum; // Reuse shared_max for final_sum\n }\n __syncthreads();\n float inv_sum = 1.0f / shared_max;\n \n // Normalize attention weights\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n attn_weights[pos] *= inv_sum;\n }\n __syncthreads();\n \n // Compute output: weighted sum of V\n // Each thread computes part of the output dimension\n for (int d = tid; d < head_dim; d += BLOCK_SIZE) {\n float out_val = 0.0f;\n for (int pos = 0; pos <= t; pos++) {\n const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;\n out_val += attn_weights[pos] * v_pos[d];\n }\n out_ptr[t * num_q_heads * head_dim + d] = out_val;\n }\n __syncthreads();\n }\n}\n\ntorch::Tensor grouped_query_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v\n) {\n int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_q_heads = q.size(2);\n int head_dim = q.size(3);\n int num_kv_heads = k.size(2);\n \n auto out = torch::zeros_like(q);\n \n int group_size = num_q_heads / num_kv_heads;\n \n int num_blocks = batch_size * num_q_heads;\n size_t shared_mem_size = seq_len * 2 * sizeof(float);\n \n grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n out.data_ptr<float>(),\n batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor grouped_query_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v);\n\"\"\"\n\n# Load the CUDA extension\ngrouped_query_attention = load_inline(\n name='grouped_query_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['grouped_query_attention_cuda'],\n extra_cuda_cflags=['-O3'],\n verbose=False\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n return grouped_query_attention.grouped_query_attention_cuda(q, k, v)"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 5 · FINAL · 1 tool call(s) · 319.2s turn · 13.1s LLM · tokens in=9,482 · out=1,648 · total=11,130 · 7,922 chars (click to expand)
turn 5319.2s turn · 13.1s LLM · 306.1s tools · tokens in=9,482 · out=1,648 · total=11,130 · FINAL
reasoning
The kernel passes correctness and static checks. Let me submit it and see how it performs. If needed, I can optimize further.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import math\nimport torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n# Define the CUDA kernel source\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n#define BLOCK_SIZE 256\n\n__device__ float warp_reduce_sum(float val, int warp_size) {\n for (int offset = warp_size / 2; offset > 0; offset /= 2) {\n val += __shfl_down_sync(0xffffffff, val, offset);\n }\n return val;\n}\n\n__global__ void grouped_query_attention_kernel(\n const float* __restrict__ q,\n const float* __restrict__ k,\n const float* __restrict__ v,\n float* __restrict__ out,\n int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size\n) {\n // Each thread block handles one (batch, head) pair\n int batch_idx = blockIdx.x / num_q_heads;\n int q_head_idx = blockIdx.x % num_q_heads;\n \n // Determine which KV head this query head uses\n int kv_head_idx = q_head_idx / group_size;\n \n // Thread index within the block\n int tid = threadIdx.x;\n \n // Pointers to the relevant slices\n const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;\n float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;\n \n // Scale factor\n float scale = 1.0f / sqrtf((float)head_dim);\n \n // Shared memory for scores and attention weights (one per position in sequence)\n extern __shared__ float shared_mem[];\n float* scores = shared_mem; // seq_len elements\n float* attn_weights = shared_mem + seq_len; // seq_len elements\n \n // Iterate over each query position\n for (int t = 0; t < seq_len; t++) {\n // Get query vector at position t\n const float* q_t = q_ptr + t * num_q_heads * head_dim;\n \n // Compute scores for all positions 0..t using all threads in block\n float max_score = -INFINITY;\n \n // Each thread computes scores for some positions\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;\n \n float score = 0.0f;\n for (int d = 0; d < head_dim; d++) {\n score += q_t[d] * k_pos[d];\n }\n score *= scale;\n scores[pos] = score;\n }\n \n // Also set scores beyond t to -inf for safety\n for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {\n scores[pos] = -INFINITY;\n }\n \n __syncthreads();\n \n // Find max score (for numerical stability)\n if (tid == 0) {\n max_score = scores[0];\n for (int i = 1; i <= t; i++) {\n if (scores[i] > max_score) max_score = scores[i];\n }\n }\n \n // Broadcast max_score to all threads\n __shared__ float shared_max;\n if (tid == 0) shared_max = max_score;\n __syncthreads();\n max_score = shared_max;\n \n // Compute exp(scores - max) and sum\n float sum_exp = 0.0f;\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n float exp_val = expf(scores[pos] - max_score);\n attn_weights[pos] = exp_val;\n sum_exp += exp_val;\n }\n \n // Reduce sum_exp across threads\n sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));\n \n __shared__ float total_sum[BLOCK_SIZE / 32];\n int warp_id = tid / 32;\n int lane_id = tid % 32;\n if (lane_id == 0) {\n total_sum[warp_id] = sum_exp;\n }\n __syncthreads();\n \n if (tid == 0) {\n float final_sum = 0.0f;\n for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {\n final_sum += total_sum[i];\n }\n shared_max = final_sum; // Reuse shared_max for final_sum\n }\n __syncthreads();\n float inv_sum = 1.0f / shared_max;\n \n // Normalize attention weights\n for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {\n attn_weights[pos] *= inv_sum;\n }\n __syncthreads();\n \n // Compute output: weighted sum of V\n // Each thread computes part of the output dimension\n for (int d = tid; d < head_dim; d += BLOCK_SIZE) {\n float out_val = 0.0f;\n for (int pos = 0; pos <= t; pos++) {\n const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;\n out_val += attn_weights[pos] * v_pos[d];\n }\n out_ptr[t * num_q_heads * head_dim + d] = out_val;\n }\n __syncthreads();\n }\n}\n\ntorch::Tensor grouped_query_attention_cuda(\n torch::Tensor q,\n torch::Tensor k,\n torch::Tensor v\n) {\n int batch_size = q.size(0);\n int seq_len = q.size(1);\n int num_q_heads = q.size(2);\n int head_dim = q.size(3);\n int num_kv_heads = k.size(2);\n \n auto out = torch::zeros_like(q);\n \n int group_size = num_q_heads / num_kv_heads;\n \n int num_blocks = batch_size * num_q_heads;\n size_t shared_mem_size = seq_len * 2 * sizeof(float);\n \n grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(\n q.data_ptr<float>(),\n k.data_ptr<float>(),\n v.data_ptr<float>(),\n out.data_ptr<float>(),\n batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size\n );\n \n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor grouped_query_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v);\n\"\"\"\n\n# Load the CUDA extension\ngrouped_query_attention = load_inline(\n name='grouped_query_attention',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['grouped_query_attention_cuda'],\n extra_cuda_cflags=['-O3'],\n verbose=False\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:\n return grouped_query_attention.grouped_query_attention_cuda(q, k, v)"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.32 μs
Runtime stats: mean=0.32μs median=?μs std=0.00μs
Numerical precision: max_abs_err=8.34e-07 mean_abs_err=4.19e-08 max_rel_err=1.01e-01
Memory: 33.39 MB peak (ref: 33.71 MB, ratio: 0.9904x)
Kernel launches: 5 (ref: 48603, fusion ratio: 9720.6)
SOL score: 0.0089
Flagged for excessive speedup — this submission may have been rejected by automated review.
final submitted kernel (193 lines, 6,295 chars) — full source, untruncated
import math
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
# Define the CUDA kernel source
cuda_source = """
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cmath>
#define BLOCK_SIZE 256
__device__ float warp_reduce_sum(float val, int warp_size) {
for (int offset = warp_size / 2; offset > 0; offset /= 2) {
val += __shfl_down_sync(0xffffffff, val, offset);
}
return val;
}
__global__ void grouped_query_attention_kernel(
const float* __restrict__ q,
const float* __restrict__ k,
const float* __restrict__ v,
float* __restrict__ out,
int batch_size, int seq_len, int num_q_heads, int num_kv_heads, int head_dim, int group_size
) {
// Each thread block handles one (batch, head) pair
int batch_idx = blockIdx.x / num_q_heads;
int q_head_idx = blockIdx.x % num_q_heads;
// Determine which KV head this query head uses
int kv_head_idx = q_head_idx / group_size;
// Thread index within the block
int tid = threadIdx.x;
// Pointers to the relevant slices
const float* q_ptr = q + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;
const float* k_ptr = k + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;
const float* v_ptr = v + (batch_idx * seq_len * num_kv_heads + kv_head_idx) * head_dim;
float* out_ptr = out + (batch_idx * seq_len * num_q_heads + q_head_idx) * head_dim;
// Scale factor
float scale = 1.0f / sqrtf((float)head_dim);
// Shared memory for scores and attention weights (one per position in sequence)
extern __shared__ float shared_mem[];
float* scores = shared_mem; // seq_len elements
float* attn_weights = shared_mem + seq_len; // seq_len elements
// Iterate over each query position
for (int t = 0; t < seq_len; t++) {
// Get query vector at position t
const float* q_t = q_ptr + t * num_q_heads * head_dim;
// Compute scores for all positions 0..t using all threads in block
float max_score = -INFINITY;
// Each thread computes scores for some positions
for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {
const float* k_pos = k_ptr + pos * num_kv_heads * head_dim;
float score = 0.0f;
for (int d = 0; d < head_dim; d++) {
score += q_t[d] * k_pos[d];
}
score *= scale;
scores[pos] = score;
}
// Also set scores beyond t to -inf for safety
for (int pos = tid + t + 1; pos < seq_len; pos += BLOCK_SIZE) {
scores[pos] = -INFINITY;
}
__syncthreads();
// Find max score (for numerical stability)
if (tid == 0) {
max_score = scores[0];
for (int i = 1; i <= t; i++) {
if (scores[i] > max_score) max_score = scores[i];
}
}
// Broadcast max_score to all threads
__shared__ float shared_max;
if (tid == 0) shared_max = max_score;
__syncthreads();
max_score = shared_max;
// Compute exp(scores - max) and sum
float sum_exp = 0.0f;
for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {
float exp_val = expf(scores[pos] - max_score);
attn_weights[pos] = exp_val;
sum_exp += exp_val;
}
// Reduce sum_exp across threads
sum_exp = warp_reduce_sum(sum_exp, min(BLOCK_SIZE, 32));
__shared__ float total_sum[BLOCK_SIZE / 32];
int warp_id = tid / 32;
int lane_id = tid % 32;
if (lane_id == 0) {
total_sum[warp_id] = sum_exp;
}
__syncthreads();
if (tid == 0) {
float final_sum = 0.0f;
for (int i = 0; i < (BLOCK_SIZE + 31) / 32; i++) {
final_sum += total_sum[i];
}
shared_max = final_sum; // Reuse shared_max for final_sum
}
__syncthreads();
float inv_sum = 1.0f / shared_max;
// Normalize attention weights
for (int pos = tid; pos <= t; pos += BLOCK_SIZE) {
attn_weights[pos] *= inv_sum;
}
__syncthreads();
// Compute output: weighted sum of V
// Each thread computes part of the output dimension
for (int d = tid; d < head_dim; d += BLOCK_SIZE) {
float out_val = 0.0f;
for (int pos = 0; pos <= t; pos++) {
const float* v_pos = v_ptr + pos * num_kv_heads * head_dim;
out_val += attn_weights[pos] * v_pos[d];
}
out_ptr[t * num_q_heads * head_dim + d] = out_val;
}
__syncthreads();
}
}
torch::Tensor grouped_query_attention_cuda(
torch::Tensor q,
torch::Tensor k,
torch::Tensor v
) {
int batch_size = q.size(0);
int seq_len = q.size(1);
int num_q_heads = q.size(2);
int head_dim = q.size(3);
int num_kv_heads = k.size(2);
auto out = torch::zeros_like(q);
int group_size = num_q_heads / num_kv_heads;
int num_blocks = batch_size * num_q_heads;
size_t shared_mem_size = seq_len * 2 * sizeof(float);
grouped_query_attention_kernel<<<num_blocks, BLOCK_SIZE, shared_mem_size>>>(
q.data_ptr<float>(),
k.data_ptr<float>(),
v.data_ptr<float>(),
out.data_ptr<float>(),
batch_size, seq_len, num_q_heads, num_kv_heads, head_dim, group_size
);
return out;
}
"""
cpp_source = """
torch::Tensor grouped_query_attention_cuda(torch::Tensor q, torch::Tensor k, torch::Tensor v);
"""
# Load the CUDA extension
grouped_query_attention = load_inline(
name='grouped_query_attention',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['grouped_query_attention_cuda'],
extra_cuda_cflags=['-O3'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
return grouped_query_attention.grouped_query_attention_cuda(q, k, v)