correct
88_MinGPTNewGelu.py
started
2026-05-05T00:30:57Z
timingkernelbench.timing
kernel mean / median / std
0.18 / — / 7.13e-04 μs
ref mean / median / std
1.62 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
5.00x
energyNVML (pynvml)
ratio (ref / kernel)
1.32x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
2970.41 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
# From https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
class Model(nn.Module):
"""
Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT).
Reference: Gaussian Error Linear Units (GELU) paper: https://arxiv.org/abs/1606.08415
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, x):
return 0.5 * x * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (x + 0.044715 * torch.pow(x, 3.0))))
batch_size = 8192
dim = 8192
def get_inputs():
return [torch.rand(batch_size, dim)]
def get_init_inputs():
return []turn 023.1s turn · 23.1s LLM · 0.0s tools · FINAL
reasoning
**Considering CUDA wrapper alignment**
I’m thinking about how to implement a C++ wrapper in CUDA sources with ATen includes. I need to handle whether N is divisible. For example, 67,108,864 is divisible by 4, which seems like a good check. I’ll want to ensure that the implementation is aligned using float4. This way, tensor allocations in Torch will stay aligned as well. It’s all about keeping everything in order and efficient!
**Exploring tanh optimizations**
I'm considering improvements to the PyTorch tanh kernel, as it might be fast but involves multiple operations. A custom tanh per element could enhance speed. I wonder about using an approximate sigmoid or polynomial approximations for tanh within the range [0,0.833]. The accuracy of evaluating it with random inputs from 0 to 1 is essential. I'd also contemplate trying 7th-degree Taylor approximation. Additionally, I'm thinking about whether a rational approximation could be faster than the traditional tanh implementation. It's crucial to ensure that the module compiles without issues.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor gelu_forward_cuda(torch::Tensor x);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\nstatic __device__ __forceinline__ float gelu_tanh_f32(float x) {\n const float kAlpha = 0.79788456080286535588f; // sqrt(2/pi)\n const float kBeta = 0.044715f;\n float x2 = x * x;\n float u = kAlpha * (x + kBeta * x * x2);\n return 0.5f * x * (1.0f + tanhf(u));\n}\n\n__global__ void gelu_float4_kernel(const float* __restrict__ x,\n float* __restrict__ y,\n long long n4) {\n long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n long long stride = (long long)blockDim.x * gridDim.x;\n const float4* __restrict__ x4 = reinterpret_cast<const float4*>(x);\n float4* __restrict__ y4 = reinterpret_cast<float4*>(y);\n for (; i < n4; i += stride) {\n float4 v = x4[i];\n v.x = gelu_tanh_f32(v.x);\n v.y = gelu_tanh_f32(v.y);\n v.z = gelu_tanh_f32(v.z);\n v.w = gelu_tanh_f32(v.w);\n y4[i] = v;\n }\n}\n\n__global__ void gelu_tail_kernel(const float* __restrict__ x,\n float* __restrict__ y,\n long long start,\n long long n) {\n long long idx = start + (long long)blockIdx.x * blockDim.x + threadIdx.x;\n if (idx < n) y[idx] = gelu_tanh_f32(x[idx]);\n}\n\ntorch::Tensor gelu_forward_cuda(torch::Tensor x) {\n auto y = torch::empty_like(x);\n const long long n = x.numel();\n if (n == 0) return y;\n\n const int threads = 256;\n const long long n4 = n >> 2;\n if (n4 > 0) {\n int blocks = (int)((n4 + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n gelu_float4_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), n4);\n }\n const long long start = n4 << 2;\n if (start < n) {\n gelu_tail_kernel<<<1, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), start, n);\n }\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"gelu_tanh_inline_ext\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"gelu_forward_cuda\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n\n def forward(self, x):\n return _ext.gelu_forward_cuda(x)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.18 μs
Runtime stats: mean=0.18μs median=?μs std=0.00μs
Numerical precision: max_abs_err=2.21e-06 mean_abs_err=3.28e-07 max_rel_err=3.97e-06
Memory: 545.0 MB peak (ref: 1057.0 MB, ratio: 0.5156x)
Kernel launches: 2 (ref: 10, fusion ratio: 5.0)
Energy: 568.66 mJ/run (ref: 750.34 mJ, ratio: 1.3195x)
SOL score: 0.8867
final submitted kernel (88 lines, 2,707 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
torch::Tensor gelu_forward_cuda(torch::Tensor x);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
static __device__ __forceinline__ float gelu_tanh_f32(float x) {
const float kAlpha = 0.79788456080286535588f; // sqrt(2/pi)
const float kBeta = 0.044715f;
float x2 = x * x;
float u = kAlpha * (x + kBeta * x * x2);
return 0.5f * x * (1.0f + tanhf(u));
}
__global__ void gelu_float4_kernel(const float* __restrict__ x,
float* __restrict__ y,
long long n4) {
long long i = (long long)blockIdx.x * blockDim.x + threadIdx.x;
long long stride = (long long)blockDim.x * gridDim.x;
const float4* __restrict__ x4 = reinterpret_cast<const float4*>(x);
float4* __restrict__ y4 = reinterpret_cast<float4*>(y);
for (; i < n4; i += stride) {
float4 v = x4[i];
v.x = gelu_tanh_f32(v.x);
v.y = gelu_tanh_f32(v.y);
v.z = gelu_tanh_f32(v.z);
v.w = gelu_tanh_f32(v.w);
y4[i] = v;
}
}
__global__ void gelu_tail_kernel(const float* __restrict__ x,
float* __restrict__ y,
long long start,
long long n) {
long long idx = start + (long long)blockIdx.x * blockDim.x + threadIdx.x;
if (idx < n) y[idx] = gelu_tanh_f32(x[idx]);
}
torch::Tensor gelu_forward_cuda(torch::Tensor x) {
auto y = torch::empty_like(x);
const long long n = x.numel();
if (n == 0) return y;
const int threads = 256;
const long long n4 = n >> 2;
if (n4 > 0) {
int blocks = (int)((n4 + threads - 1) / threads);
if (blocks > 65535) blocks = 65535;
gelu_float4_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
x.data_ptr<float>(), y.data_ptr<float>(), n4);
}
const long long start = n4 << 2;
if (start < n) {
gelu_tail_kernel<<<1, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
x.data_ptr<float>(), y.data_ptr<float>(), start, n);
}
return y;
}
"""
_ext = load_inline(
name="gelu_tanh_inline_ext",
cpp_sources=[_cpp_src],
cuda_sources=[_cuda_src],
functions=["gelu_forward_cuda"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
def forward(self, x):
return _ext.gelu_forward_cuda(x)