correct
14_GaussianProcessRBFKernel.py
started
2026-05-11T11:27:00Z
timingkernelbench.timing
kernel mean / median / std
4.70 / — / 0.00 μs
ref mean / median / std
0.07 / — / 8.43e-04 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
3.70x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
584.84 GB/s
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 0312.7s turn · 6.7s LLM · 306.1s tools · tokens in=1,695 · out=6 · total=2,306
reasoning
The task is to replace the forward computation of this PyTorch RBF kernel model with a custom CUDA kernel that's faster.
I need to replace the forward computation of a PyTorch model with a custom CUDA kernel for an RBF kernel computation.
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 1412.1s turn · 5.0s LLM · 407.1s tools · tokens in=2,539 · out=660 · total=3,225
reasoning
H100, high bandwidth.
Now, I need to write the kernel code.
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_runtime.h>\n#include <math.h>\n\n__global__ void rbf_kernel(const float* __restrict__ X1, const float* __restrict__ X2, float* __restrict__ K,\n int B, int N, int M, int D, float l2, float var) {\n int b = blockIdx.z;\n int i = blockIdx.y * blockDim.y + threadIdx.y;\n int j = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B || i >= N || j >= M) return;\n\n float dist_sq = 0.0f;\n for (int d = 0; d < D; d++) {\n float x1 = X1[b * N * D + i * D + d];\n float x2 = X2[b * M * D + j * D + d];\n float diff = x1 - x2;\n dist_sq += diff * diff;\n }\n float val = var * expf(-0.5f * dist_sq / l2);\n K[b * N * M + i * M + j] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var) {\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 dim3 threads(16, 16);\n dim3 blocks((M + 15) / 16, (N + 15) / 16, B);\n\n rbf_kernel<<<blocks, threads>>>(X1.data_ptr<float>(), X2.data_ptr<float>(), K.data_ptr<float>(),\n B, N, M, D, l2, var);\n return K;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var);\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=True,\n extra_cuda_cflags=[\"-O3\"]\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 self.module = module\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n l2 = self.log_lengthscale.exp() ** 2\n var = self.log_variance.exp()\n return self.module.rbf_cuda(X1, X2, l2.item(), var.item())\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2321.9s turn · 4.9s LLM · 317.0s tools · tokens in=3,242 · out=661 · total=3,910
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_runtime.h>\n#include <math.h>\n\n__global__ void rbf_kernel(const float* __restrict__ X1, const float* __restrict__ X2, float* __restrict__ K,\n int B, int N, int M, int D, float l2, float var) {\n int b = blockIdx.z;\n int i = blockIdx.y * blockDim.y + threadIdx.y;\n int j = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B || i >= N || j >= M) return;\n\n float dist_sq = 0.0f;\n for (int d = 0; d < D; d++) {\n float x1 = X1[b * N * D + i * D + d];\n float x2 = X2[b * M * D + j * D + d];\n float diff = x1 - x2;\n dist_sq += diff * diff;\n }\n float val = var * expf(-0.5f * dist_sq / l2);\n K[b * N * M + i * M + j] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var) {\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 dim3 threads(16, 16);\n dim3 blocks((M + 15) / 16, (N + 15) / 16, B);\n\n rbf_kernel<<<blocks, threads>>>(X1.data_ptr<float>(), X2.data_ptr<float>(), K.data_ptr<float>(),\n B, N, M, D, l2, var);\n return K;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var);\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 extra_cuda_cflags=[\"-O3\"]\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 self.module = module\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n l2 = self.log_lengthscale.exp() ** 2\n var = self.log_variance.exp()\n return self.module.rbf_cuda(X1, X2, l2.item(), var.item())\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=7.75e-07 mean_abs_err=2.60e-09 max_rel_err=5.88e-06
turn 36.0s turn · 6.0s LLM · 0.0s tools · tokens in=3,970 · out=660 · total=4,721
reasoning
Correct. Now, to submit, I need to check static too, but since it's simple, should be fine.
call → static_check
callstatic_check
{
"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_runtime.h>\n#include <math.h>\n\n__global__ void rbf_kernel(const float* __restrict__ X1, const float* __restrict__ X2, float* __restrict__ K,\n int B, int N, int M, int D, float l2, float var) {\n int b = blockIdx.z;\n int i = blockIdx.y * blockDim.y + threadIdx.y;\n int j = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B || i >= N || j >= M) return;\n\n float dist_sq = 0.0f;\n for (int d = 0; d < D; d++) {\n float x1 = X1[b * N * D + i * D + d];\n float x2 = X2[b * M * D + j * D + d];\n float diff = x1 - x2;\n dist_sq += diff * diff;\n }\n float val = var * expf(-0.5f * dist_sq / l2);\n K[b * N * M + i * M + j] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var) {\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 dim3 threads(16, 16);\n dim3 blocks((M + 15) / 16, (N + 15) / 16, B);\n\n rbf_kernel<<<blocks, threads>>>(X1.data_ptr<float>(), X2.data_ptr<float>(), K.data_ptr<float>(),\n B, N, M, D, l2, var);\n return K;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var);\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 extra_cuda_cflags=[\"-O3\"]\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 self.module = module\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n l2 = self.log_lengthscale.exp() ** 2\n var = self.log_variance.exp()\n return self.module.rbf_cuda(X1, X2, l2.item(), var.item())\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 4953.9s turn · 4.5s LLM · 949.4s tools · tokens in=4,739 · out=660 · total=5,404 · FINAL
reasoning
Good. Now submit.
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_runtime.h>\n#include <math.h>\n\n__global__ void rbf_kernel(const float* __restrict__ X1, const float* __restrict__ X2, float* __restrict__ K,\n int B, int N, int M, int D, float l2, float var) {\n int b = blockIdx.z;\n int i = blockIdx.y * blockDim.y + threadIdx.y;\n int j = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B || i >= N || j >= M) return;\n\n float dist_sq = 0.0f;\n for (int d = 0; d < D; d++) {\n float x1 = X1[b * N * D + i * D + d];\n float x2 = X2[b * M * D + j * D + d];\n float diff = x1 - x2;\n dist_sq += diff * diff;\n }\n float val = var * expf(-0.5f * dist_sq / l2);\n K[b * N * M + i * M + j] = val;\n}\n\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var) {\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 dim3 threads(16, 16);\n dim3 blocks((M + 15) / 16, (N + 15) / 16, B);\n\n rbf_kernel<<<blocks, threads>>>(X1.data_ptr<float>(), X2.data_ptr<float>(), K.data_ptr<float>(),\n B, N, M, D, l2, var);\n return K;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var);\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 extra_cuda_cflags=[\"-O3\"]\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 self.module = module\n\n def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:\n l2 = self.log_lengthscale.exp() ** 2\n var = self.log_variance.exp()\n return self.module.rbf_cuda(X1, X2, l2.item(), var.item())\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 4.70 μs
Runtime stats: mean=4.70μs median=?μs std=0.00μs
Numerical precision: max_abs_err=7.75e-07 mean_abs_err=2.60e-09 max_rel_err=5.88e-06
Memory: 37.32 MB peak (ref: 45.35 MB, ratio: 0.8228x)
Kernel launches: 10 (ref: 37, fusion ratio: 3.7)
Energy: 481.88 mJ/run (ref: 0.0 mJ, ratio: -1x)
SOL score: 0.2259
final submitted kernel (69 lines, 2,148 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_runtime.h>
#include <math.h>
__global__ void rbf_kernel(const float* __restrict__ X1, const float* __restrict__ X2, float* __restrict__ K,
int B, int N, int M, int D, float l2, float var) {
int b = blockIdx.z;
int i = blockIdx.y * blockDim.y + threadIdx.y;
int j = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= B || i >= N || j >= M) return;
float dist_sq = 0.0f;
for (int d = 0; d < D; d++) {
float x1 = X1[b * N * D + i * D + d];
float x2 = X2[b * M * D + j * D + d];
float diff = x1 - x2;
dist_sq += diff * diff;
}
float val = var * expf(-0.5f * dist_sq / l2);
K[b * N * M + i * M + j] = val;
}
torch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var) {
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());
dim3 threads(16, 16);
dim3 blocks((M + 15) / 16, (N + 15) / 16, B);
rbf_kernel<<<blocks, threads>>>(X1.data_ptr<float>(), X2.data_ptr<float>(), K.data_ptr<float>(),
B, N, M, D, l2, var);
return K;
}
"""
cpp_source = """
torch::Tensor rbf_cuda(torch::Tensor X1, torch::Tensor X2, float l2, float var);
"""
module = load_inline(
name="rbf_module",
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=["rbf_cuda"],
verbose=False,
extra_cuda_cflags=["-O3"]
)
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())
self.module = module
def forward(self, X1: torch.Tensor, X2: torch.Tensor) -> torch.Tensor:
l2 = self.log_lengthscale.exp() ** 2
var = self.log_variance.exp()
return self.module.rbf_cuda(X1, X2, l2.item(), var.item())