correct
49_sum_gelu_across_virtual_ranks.py
started
2026-05-11T19:36:24Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 1.72e-04 μs
ref mean / median / std
0.01 / — / 5.46e-04 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
3.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
"""
Order-sensitive virtual collective: out = sum_r GELU(x_r), same shape as one rank slice (B, D).
Note: this is not equal to GELU(sum_r x_r).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from kernelbench.distributed_collectives import default_device
R = 4
B = 14
D = 40
class Model(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return F.gelu(x).sum(dim=0)
def get_inputs():
dev = default_device()
p = popcorn_pri
return [torch.randn(p.jitter_int(R), p.jitter_int(B), p.jitter_int(D, align=8), device=dev)]
def get_init_inputs():
return []
turn 07.2s turn · 7.2s LLM · 0.0s tools · tokens in=1,946 · out=6 · total=2,292
reasoning
The task is to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model sums GELU activations over the first dimension.
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 1121.0s turn · 8.1s LLM · 112.9s tools · tokens in=2,525 · out=498 · total=3,079
reasoning
GPU is H100, high bandwidth, but data is tiny: 4*14*40*4bytes ~ 9KB, so memory bound but tiny.
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__device__ __forceinline__ float gelu(float x) {\n const float sqrt_2_over_pi = 0.7978845608028654f;\n const float coeff = 0.044715f;\n float x3 = x * x * x;\n float inner = sqrt_2_over_pi * (x + coeff * x3);\n return 0.5f * x * (1.0f + tanhf(inner));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=True,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 281.5s turn · 4.8s LLM · 76.7s tools · tokens in=3,096 · out=499 · total=3,602
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__device__ __forceinline__ float gelu(float x) {\n const float sqrt_2_over_pi = 0.7978845608028654f;\n const float coeff = 0.044715f;\n float x3 = x * x * x;\n float inner = sqrt_2_over_pi * (x + coeff * x3);\n return 0.5f * x * (1.0f + tanhf(inner));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=False,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← run_correctness (fail)
failrun_correctness
run_correctness FAILED: (0 / 3) trials did not all match.
correctness_issue: Output mismatch
max_difference: ['0.000863', '0.000863', '0.000863']
avg_difference: ['0.000299', '0.000299', '0.000299']
turn 384.2s turn · 8.7s LLM · 75.4s tools · tokens in=3,675 · out=463 · total=4,303
reasoning
GELU mismatch. PyTorch's GELU uses a slightly different constant or erf?
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__device__ __forceinline__ float gelu(float x) {\n return 0.5f * x * (1.0f + tanhf(0.7978845608028654f * (x + 0.044715f * x * x * x)));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=False,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← run_correctness (fail)
failrun_correctness
run_correctness FAILED: (0 / 3) trials did not all match.
correctness_issue: Output mismatch
max_difference: ['0.000863', '0.000863', '0.000863']
avg_difference: ['0.000299', '0.000299', '0.000299']
turn 43.9s turn · 3.9s LLM · 0.0s tools · tokens in=4,376 · out=44 · total=4,539
reasoning
Still same. Let's find PyTorch's exact GELU.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nprint(torch.__version__)\nx = torch.tensor([1.0], device='cuda')\nprint(torch.nn.functional.gelu(x, approximate='tanh'))"
}
result ← compile_kernel (fail)
failcompile_kernel
compile_kernel FAILED: ModelNew class not found or syntax error prevented execution.
2.11.0+cu128
tensor([0.8412], device='cuda:0')
turn 582.7s turn · 6.4s LLM · 76.3s tools · tokens in=4,583 · out=481 · total=5,098
reasoning
Not helpful. I know the issue is the constant: it's 0.797884560802865355879892119868763075
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#include <cmath>\n\n__device__ __forceinline__ float gelu(float x) {\n const float kAlpha = 0.79788456080286535587989211986876f;\n return 0.5f * x * (1.0f + tanhf(kAlpha * (x + 0.044715f * x * x * x)));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=False,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← run_correctness (fail)
failrun_correctness
run_correctness FAILED: (0 / 3) trials did not all match.
correctness_issue: Output mismatch
max_difference: ['0.000863', '0.000863', '0.000863']
avg_difference: ['0.000299', '0.000299', '0.000299']
turn 683.6s turn · 8.3s LLM · 75.3s tools · tokens in=5,171 · out=449 · total=5,769
reasoning
Still. Perhaps use erf for exact, but PyTorch default is tanh.
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__device__ __forceinline__ float gelu(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=False,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=2.90e-08 max_rel_err=2.91e-05
turn 793.6s turn · 4.8s LLM · 88.7s tools · tokens in=5,829 · out=448 · total=6,317 · FINAL
reasoning
Great, now correct. I can submit, as it's faster surely, being a fused kernel vs two ops.
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__device__ __forceinline__ float gelu(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f));\n}\n\n__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {\n int idx = blockIdx.x * blockDim.x + threadIdx.x;\n int total = B * D;\n if (idx >= total) return;\n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * total + idx];\n sum += gelu(val);\n }\n out[idx] = sum;\n}\n\ntorch::Tensor gelu_sum_cuda(torch::Tensor x) {\n int R = x.size(0);\n int B = x.size(1);\n int D = x.size(2);\n auto out = torch::empty({B, D}, x.options());\n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);\n return out;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n\"\"\"\n\nmodule = load_inline(\n name=\"gelu_sum\",\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=[\"gelu_sum_cuda\"],\n verbose=False,\n extra_cuda_cflags=[\"-O3\"]\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return self.module.gelu_sum_cuda(x)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (3 / 3) correctness trials all passed.
Kernel runtime: 0.01 μs
Runtime stats: mean=0.01μs median=?μs std=0.00μs
Numerical precision: max_abs_err=4.77e-07 mean_abs_err=2.90e-08 max_rel_err=2.91e-05
Memory: 33.01 MB peak (ref: 33.02 MB, ratio: 0.9997x)
Kernel launches: 1 (ref: 3, fusion ratio: 3.0)
SOL score: 0.0013
final submitted kernel (59 lines, 1,504 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>
__device__ __forceinline__ float gelu(float x) {
return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f));
}
__global__ void gelu_sum_kernel(const float* __restrict__ x, float* __restrict__ out, int R, int B, int D) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
int total = B * D;
if (idx >= total) return;
float sum = 0.0f;
for (int r = 0; r < R; r++) {
float val = x[r * total + idx];
sum += gelu(val);
}
out[idx] = sum;
}
torch::Tensor gelu_sum_cuda(torch::Tensor x) {
int R = x.size(0);
int B = x.size(1);
int D = x.size(2);
auto out = torch::empty({B, D}, x.options());
int total = B * D;
int threads = 256;
int blocks = (total + threads - 1) / threads;
gelu_sum_kernel<<<blocks, threads>>>(x.data_ptr<float>(), out.data_ptr<float>(), R, B, D);
return out;
}
"""
cpp_source = """
torch::Tensor gelu_sum_cuda(torch::Tensor x);
"""
module = load_inline(
name="gelu_sum",
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=["gelu_sum_cuda"],
verbose=False,
extra_cuda_cflags=["-O3"]
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.module = module
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.module.gelu_sum_cuda(x)