correct
49_sum_gelu_across_virtual_ranks.py
started
2026-05-11T11:30:36Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 0.00 μs
ref mean / median / std
0.01 / — / 3.37e-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 0169.2s turn · 3.7s LLM · 165.5s tools · tokens in=1,419 · out=227 · total=1,646
reasoning
Let me analyze the task:
1. The model takes an input tensor `x` of shape `(R, B, D)` where R=4, B=14, D=40
2. It computes `F.gelu(x).sum(dim=0)` which applies GELU element-wise and then sums along dimension 0
3. The output shape is `(B, D)`
The GELU function is:
GELU(x) = x * Φ(x) where Φ is the cumulative distribution function of the standard normal distribution
Approximately: GELU(x) ≈ 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3)))
For optimization:
1. I need to apply GELU to each element
2. Then sum across the R dimension
This can be parallelized across the (B, D) dimensions, with each thread handling one output element by summing across R.
Let me first check 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 1196.7s turn · 20.2s LLM · 176.4s tools · tokens in=1,667 · out=1,496 · total=3,163
reasoning
Let me analyze the problem:
1. Input: tensor x of shape (R, B, D) = (4, 14, 40)
2. Operation: F.gelu(x).sum(dim=0)
3. Output: tensor of shape (B, D) = (14, 40)
So we compute GELU element-wise on each element of x, then sum across the first dimension.
GELU formula: GELU(x) = x * Φ(x) where Φ is the CDF of standard normal distribution.
PyTorch uses: GELU(x) ≈ 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x^3)))
The total number of elements is R*B*D = 4*14*40 = 2240, which is very small.
Let me write a simple kernel first:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline
gelu_sum_cuda = load_inline(
name='gelu_sum_cuda',
cpp_sources='''
torch::Tensor gelu_sum_cuda(torch::Tensor x);
''',
cuda_sources='''
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cmath>
// GELU approximation: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))
__device__ __forceinline__ float gelu_approx(float x) {
const float SQRT_2_OVER_PI = 0.7978845608028654f; // sqrt(2/pi)
const float COEFF = 0.044715f;
float x3 = x * x * x;
float inner = SQRT_2_OVER_PI * (x + COEFF * x3);
float tanh_inner = tanhf(inner);
return 0.5f * x * (1.0f + tanh_inner);
}
__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) {
int b = idx / D;
int d = idx % D;
float sum = 0.0f;
for (int r = 0; r < R; r++) {
float val = x[r * B * D + b * D + d];
sum += gelu_approx(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;
}
''',
functions=['gelu_sum_cuda'],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return gelu_sum_cuda.gelu_sum_cuda(x)
```
Let me compile this first.
assistantLooking at this problem:
- Input: tensor x of shape (R, B, D) = (4, 14, 40)
- Operation: `F.gelu(x).sum(dim=0)` - apply GELU element-wise, then sum across first dimension
- Output: tensor of shape (B, D) = (14, 40)
The key insight is that GELU is applied before summing, so I need to compute GELU for each element then accumulate across the R dimension.
Let me start by writing and compiling a basic kernel:
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// GELU approximation: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))\n__device__ __forceinline__ float gelu_approx(float x) {\n const float SQRT_2_OVER_PI = 0.7978845608028654f; // sqrt(2/pi)\n const float COEFF = 0.044715f;\n \n float x3 = x * x * x;\n float inner = SQRT_2_OVER_PI * (x + COEFF * x3);\n float tanh_inner = tanhf(inner);\n return 0.5f * x * (1.0f + tanh_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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_approx(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2254.4s turn · 11.1s LLM · 243.4s tools · tokens in=2,391 · out=608 · total=2,999
reasoning
Good, the kernel compiled. Now let me check correctness against the reference.
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// GELU approximation: 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3)))\n__device__ __forceinline__ float gelu_approx(float x) {\n const float SQRT_2_OVER_PI = 0.7978845608028654f; // sqrt(2/pi)\n const float COEFF = 0.044715f;\n \n float x3 = x * x * x;\n float inner = SQRT_2_OVER_PI * (x + COEFF * x3);\n float tanh_inner = tanhf(inner);\n return 0.5f * x * (1.0f + tanh_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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_approx(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← run_correctness (fail)
failrun_correctness
run_correctness FAILED: (0 / 5) trials did not all match.
correctness_issue: Output mismatch
max_difference: ['0.000863', '0.000863', '0.000863', '0.000863', '0.000863']
avg_difference: ['0.000299', '0.000299', '0.000299', '0.000299', '0.000299']
turn 3170.0s turn · 5.8s LLM · 164.3s tools · tokens in=3,087 · out=608 · total=3,695
reasoning
The GELU approximation isn't close enough to PyTorch's GELU implementation. PyTorch's GELU uses the exact formula: `x * 0.5 * (1.0 + erf(x / sqrt(2)))`. Let me use this instead for better precision.
assistantThe GELU approximation isn't precise enough. PyTorch uses the exact GELU formula with erf. Let me fix that:
call → compile_kernel
callcompile_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// Exact GELU: x * 0.5 * (1.0 + erf(x / sqrt(2)))\n__device__ __forceinline__ float gelu_exact(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f)); // sqrt(0.5) = 0.70710678...\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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_exact(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 4279.2s turn · 5.2s LLM · 274.0s tools · tokens in=3,647 · out=526 · total=4,173
reasoning
Let me test correctness again.
call → run_correctness
callrun_correctness
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// Exact GELU: x * 0.5 * (1.0 + erf(x / sqrt(2)))\n__device__ __forceinline__ float gelu_exact(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f)); // sqrt(0.5) = 0.70710678...\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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_exact(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) 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 55.7s turn · 5.7s LLM · 0.0s tools · tokens in=4,224 · out=554 · total=4,778
reasoning
Correctness passes. Now let me check the static analysis and then submit.
assistantCorrectness passes with the exact GELU formula. Let me run a static check before submitting:
call → static_check
callstatic_check
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// Exact GELU: x * 0.5 * (1.0 + erf(x / sqrt(2)))\n__device__ __forceinline__ float gelu_exact(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f)); // sqrt(0.5) = 0.70710678...\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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_exact(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← static_check (ok)
okstatic_check
static_check PASSED (with warnings):
WARNING: Uses torch.nn compute layer (only containers, Parameter, init allowed)
turn 6337.9s turn · 5.5s LLM · 332.3s tools · tokens in=4,791 · out=572 · total=5,363 · FINAL
reasoning
The warning about torch.nn compute layer is probably from the F import, but it doesn't seem to be a blocking issue. The kernel is correct and passes the static check. Let me submit it.
assistantGood, the static check passes. Let me submit the kernel:
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.cpp_extension import load_inline\n\ngelu_sum_cuda = load_inline(\n name='gelu_sum_cuda',\n cpp_sources='''\ntorch::Tensor gelu_sum_cuda(torch::Tensor x);\n''',\n cuda_sources='''\n#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cmath>\n\n// Exact GELU: x * 0.5 * (1.0 + erf(x / sqrt(2)))\n__device__ __forceinline__ float gelu_exact(float x) {\n return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f)); // sqrt(0.5) = 0.70710678...\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 \n if (idx < total) {\n int b = idx / D;\n int d = idx % D;\n \n float sum = 0.0f;\n for (int r = 0; r < R; r++) {\n float val = x[r * B * D + b * D + d];\n sum += gelu_exact(val);\n }\n out[idx] = sum;\n }\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 \n auto out = torch::empty({B, D}, x.options());\n \n int total = B * D;\n int threads = 256;\n int blocks = (total + threads - 1) / threads;\n \n gelu_sum_kernel<<<blocks, threads>>>(\n x.data_ptr<float>(),\n out.data_ptr<float>(),\n R, B, D\n );\n \n return out;\n}\n''',\n functions=['gelu_sum_cuda'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return gelu_sum_cuda.gelu_sum_cuda(x)"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) 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.0014
final submitted kernel (68 lines, 1,687 chars) — full source, untruncated
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.cpp_extension import load_inline
gelu_sum_cuda = load_inline(
name='gelu_sum_cuda',
cpp_sources='''
torch::Tensor gelu_sum_cuda(torch::Tensor x);
''',
cuda_sources='''
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cmath>
// Exact GELU: x * 0.5 * (1.0 + erf(x / sqrt(2)))
__device__ __forceinline__ float gelu_exact(float x) {
return x * 0.5f * (1.0f + erff(x * 0.7071067811865475f)); // sqrt(0.5) = 0.70710678...
}
__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) {
int b = idx / D;
int d = idx % D;
float sum = 0.0f;
for (int r = 0; r < R; r++) {
float val = x[r * B * D + b * D + d];
sum += gelu_exact(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;
}
''',
functions=['gelu_sum_cuda'],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return gelu_sum_cuda.gelu_sum_cuda(x)