correct
14_GaussianProcessRBFKernel.py
started
2026-05-11T18:36:16Z
timingkernelbench.timing
kernel mean / median / std
0.05 / — / 0.01 μs
ref mean / median / std
0.10 / — / 0.03 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
7.40x
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 torch
import torch.nn as nn
class Model(nn.Module):
"""
RBF (Squared Exponential) covariance matrix computation for Gaussian
Processes. Given two sets of input points, computes the full
kernel matrix K[i,j] = sigma^2 * exp(-||x_i - x_j||^2 / (2 * l^2)).
The dominant cost in GP inference and a natural target for fusion.
"""
def __init__(self, input_dim, lengthscale=1.0, variance=1.0):
super().__init__()
self.log_lengthscale = nn.Parameter(torch.tensor(lengthscale).log())
self.log_variance = nn.Parameter(torch.tensor(variance).log())
def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:
"""
Args:
X1: (B, N, D) – first set of inputs
X2: (B, M, D) – second set of inputs
Returns:
K: (B, N, M) – covariance matrix
"""
l2 = self.log_lengthscale.exp() ** 2
var = self.log_variance.exp()
# Squared distances via expansion
X1_sq = (X1 ** 2).sum(-1, keepdim=True) # (B, N, 1)
X2_sq = (X2 ** 2).sum(-1, keepdim=True) # (B, M, 1)
dist_sq = X1_sq - 2.0 * X1 @ X2.transpose(-1, -2) + X2_sq.transpose(-1, -2)
dist_sq = dist_sq.clamp(min=0.0)
return var * torch.exp(-0.5 * dist_sq / l2)
input_dim = 8
num_train = 512
num_test = 128
batch_size = 16
def get_inputs():
X1 = torch.randn(popcorn_pri.jitter_int(batch_size), popcorn_pri.jitter_int(num_train), input_dim)
X2 = torch.randn(popcorn_pri.jitter_int(batch_size), popcorn_pri.jitter_int(num_test), input_dim)
return [X1, X2]
def get_init_inputs():
return [input_dim]
turn 063.3s turn · 5.7s LLM · 57.6s tools · tokens in=2,226 · out=6 · total=2,610
reasoning
The task is to replace the forward computation of this RBF kernel model with a custom CUDA kernel that's faster than the PyTorch reference.
The task involves replacing the forward computation of an RBF kernel PyTorch model with a custom CUDA kernel.
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 184.0s turn · 11.2s LLM · 72.8s tools · tokens in=2,843 · out=704 · total=3,631
reasoning
H100 GPU, high bandwidth.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = '''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void rbf_kernel(\n const float* __restrict__ X1,\n const float* __restrict__ X2,\n float* __restrict__ K,\n const float l2_inv,\n const float var,\n int B, int N, int M, int D\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * N * M;\n if (idx >= total) return;\n\n int b = idx / (N * M);\n int rem = idx % (N * M);\n int i = rem / M;\n int j = rem % M;\n\n float dist_sq = 0.0f;\n const float* x1_ptr = X1 + (b * N + i) * D;\n const float* x2_ptr = X2 + (b * M + j) * D;\n for (int d = 0; d < D; d++) {\n float diff = x1_ptr[d] - x2_ptr[d];\n dist_sq += diff * diff;\n }\n\n float val = var * expf(-0.5f * dist_sq * l2_inv);\n K[idx] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance) {\n int B = X1.size(0);\n int N = X1.size(1);\n int D = X1.size(2);\n int M = X2.size(1);\n\n auto K = torch::empty({B, N, M}, X1.options());\n\n float l2 = expf(log_lengthscale);\n l2 = l2 * l2;\n float l2_inv = 1.0f / l2;\n float var = expf(log_variance);\n\n int total = B * N * M;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n\n rbf_kernel<<<blocks, threads>>>(\n X1.data_ptr<float>(),\n X2.data_ptr<float>(),\n K.data_ptr<float>(),\n l2_inv,\n var,\n B, N, M, D\n );\n\n return K;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance);\n'''\n\nmodule = load_inline(\n name='rbf_module',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['rbf_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, input_dim, lengthscale=1.0, variance=1.0):\n super().__init__()\n self.log_lengthscale = nn.Parameter(torch.tensor(lengthscale).log())\n self.log_variance = nn.Parameter(torch.tensor(variance).log())\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n return module.rbf_cuda(X1, X2, self.log_lengthscale.item(), self.log_variance.item())\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 278.7s turn · 5.9s LLM · 72.8s tools · tokens in=3,648 · out=705 · total=4,360
reasoning
Compiled successfully. Now check correctness.
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = '''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void rbf_kernel(\n const float* __restrict__ X1,\n const float* __restrict__ X2,\n float* __restrict__ K,\n const float l2_inv,\n const float var,\n int B, int N, int M, int D\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * N * M;\n if (idx >= total) return;\n\n int b = idx / (N * M);\n int rem = idx % (N * M);\n int i = rem / M;\n int j = rem % M;\n\n float dist_sq = 0.0f;\n const float* x1_ptr = X1 + (b * N + i) * D;\n const float* x2_ptr = X2 + (b * M + j) * D;\n for (int d = 0; d < D; d++) {\n float diff = x1_ptr[d] - x2_ptr[d];\n dist_sq += diff * diff;\n }\n\n float val = var * expf(-0.5f * dist_sq * l2_inv);\n K[idx] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance) {\n int B = X1.size(0);\n int N = X1.size(1);\n int D = X1.size(2);\n int M = X2.size(1);\n\n auto K = torch::empty({B, N, M}, X1.options());\n\n float l2 = expf(log_lengthscale);\n l2 = l2 * l2;\n float l2_inv = 1.0f / l2;\n float var = expf(log_variance);\n\n int total = B * N * M;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n\n rbf_kernel<<<blocks, threads>>>(\n X1.data_ptr<float>(),\n X2.data_ptr<float>(),\n K.data_ptr<float>(),\n l2_inv,\n var,\n B, N, M, D\n );\n\n return K;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance);\n'''\n\nmodule = load_inline(\n name='rbf_module',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['rbf_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, input_dim, lengthscale=1.0, variance=1.0):\n super().__init__()\n self.log_lengthscale = nn.Parameter(torch.tensor(lengthscale).log())\n self.log_variance = nn.Parameter(torch.tensor(variance).log())\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n return module.rbf_cuda(X1, X2, self.log_lengthscale.item(), self.log_variance.item())\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=7.75e-07 mean_abs_err=2.61e-09 max_rel_err=5.86e-06
turn 3272.2s turn · 11.0s LLM · 261.3s tools · tokens in=4,420 · out=704 · total=5,338 · FINAL
reasoning
Correct! Now, to check if faster, I should profile or run timing, but since submit will do it, let's optimize a bit.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = '''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void rbf_kernel(\n const float* __restrict__ X1,\n const float* __restrict__ X2,\n float* __restrict__ K,\n const float l2_inv,\n const float var,\n int B, int N, int M, int D\n) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * N * M;\n if (idx >= total) return;\n\n int b = idx / (N * M);\n int rem = idx % (N * M);\n int i = rem / M;\n int j = rem % M;\n\n float dist_sq = 0.0f;\n const float* x1_ptr = X1 + (b * N + i) * D;\n const float* x2_ptr = X2 + (b * M + j) * D;\n for (int d = 0; d < D; d++) {\n float diff = x1_ptr[d] - x2_ptr[d];\n dist_sq += diff * diff;\n }\n\n float val = var * expf(-0.5f * dist_sq * l2_inv);\n K[idx] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance) {\n int B = X1.size(0);\n int N = X1.size(1);\n int D = X1.size(2);\n int M = X2.size(1);\n\n auto K = torch::empty({B, N, M}, X1.options());\n\n float l2 = expf(log_lengthscale);\n l2 = l2 * l2;\n float l2_inv = 1.0f / l2;\n float var = expf(log_variance);\n\n int total = B * N * M;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n\n rbf_kernel<<<blocks, threads>>>(\n X1.data_ptr<float>(),\n X2.data_ptr<float>(),\n K.data_ptr<float>(),\n l2_inv,\n var,\n B, N, M, D\n );\n\n return K;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance);\n'''\n\nmodule = load_inline(\n name='rbf_module',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['rbf_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, input_dim, lengthscale=1.0, variance=1.0):\n super().__init__()\n self.log_lengthscale = nn.Parameter(torch.tensor(lengthscale).log());\n self.log_variance = nn.Parameter(torch.tensor(variance).log());\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n return module.rbf_cuda(X1, X2, self.log_lengthscale.item(), self.log_variance.item())\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (3 / 3) correctness trials all passed.
Kernel runtime: 0.05 μs
Runtime stats: mean=0.05μs median=?μs std=0.01μs
Numerical precision: max_abs_err=7.75e-07 mean_abs_err=2.61e-09 max_rel_err=5.86e-06
Memory: 37.31 MB peak (ref: 45.35 MB, ratio: 0.8227x)
Kernel launches: 5 (ref: 37, fusion ratio: 7.4)
Energy: 242.12 mJ/run (ref: 0.0 mJ, ratio: -1x)
SOL score: 0.1551
final submitted kernel (89 lines, 2,307 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
cuda_source = '''
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void rbf_kernel(
const float* __restrict__ X1,
const float* __restrict__ X2,
float* __restrict__ K,
const float l2_inv,
const float var,
int B, int N, int M, int D
) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int total = B * N * M;
if (idx >= total) return;
int b = idx / (N * M);
int rem = idx % (N * M);
int i = rem / M;
int j = rem % M;
float dist_sq = 0.0f;
const float* x1_ptr = X1 + (b * N + i) * D;
const float* x2_ptr = X2 + (b * M + j) * D;
for (int d = 0; d < D; d++) {
float diff = x1_ptr[d] - x2_ptr[d];
dist_sq += diff * diff;
}
float val = var * expf(-0.5f * dist_sq * l2_inv);
K[idx] = val;
}
torch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance) {
int B = X1.size(0);
int N = X1.size(1);
int D = X1.size(2);
int M = X2.size(1);
auto K = torch::empty({B, N, M}, X1.options());
float l2 = expf(log_lengthscale);
l2 = l2 * l2;
float l2_inv = 1.0f / l2;
float var = expf(log_variance);
int total = B * N * M;
int threads = 256;
int blocks = (total + threads - 1) / threads;
rbf_kernel<<<blocks, threads>>>(
X1.data_ptr<float>(),
X2.data_ptr<float>(),
K.data_ptr<float>(),
l2_inv,
var,
B, N, M, D
);
return K;
}
'''
cpp_source = '''
torch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float log_lengthscale, float log_variance);
'''
module = load_inline(
name='rbf_module',
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=['rbf_cuda'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, input_dim, lengthscale=1.0, variance=1.0):
super().__init__()
self.log_lengthscale = nn.Parameter(torch.tensor(lengthscale).log());
self.log_variance = nn.Parameter(torch.tensor(variance).log());
def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:
return module.rbf_cuda(X1, X2, self.log_lengthscale.item(), self.log_variance.item())