correct
98_KLDivLoss.py
started
2026-05-05T02:19:21Z
timingkernelbench.timing
kernel mean / median / std
0.72 / — / 0.00 μs
ref mean / median / std
3.91 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
9.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
3009.80 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):
"""
A model that computes Kullback-Leibler Divergence for comparing two distributions.
Parameters:
None
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, predictions, targets):
return torch.nn.functional.kl_div(torch.log(predictions), targets, reduction='batchmean')
batch_size = 8192 * 2
input_shape = (8192 * 2,)
dim = 1
def get_inputs():
scale = torch.rand(())
return [(torch.rand(batch_size, *input_shape)*scale).softmax(dim=-1), torch.rand(batch_size, *input_shape).softmax(dim=-1)]
def get_init_inputs():
return []
turn 0 · FINAL · 1 tool call(s) · 110.3s turn · 110.3s LLM · 6,755 chars (click to expand)
turn 0110.3s turn · 110.3s LLM · 0.0s tools · FINAL
reasoning
**Evaluating kernel operations**
I'm considering whether to return an output batch. It might involve a kernel performing an atomic operation on unnormalized data, and then a second kernel could divide it. I’m wondering if the atomic add could normalize terms by using the inverse of the batch size, which might help reduce the magnitude. There’s definitely a lot to think through in terms of how these processes interact!
**Considering compilation options**
I'm thinking about using `load_inline`, but I realize it might take extra time and memory to compile everything. I need to make sure that I'm managing resources efficiently, particularly with ninja. The C++ source doesn't have any pybind, and it looks like my functions might include `kl_forward`. I’m also considering whether to set `with_cuda` to true. Alright, it’s time to submit this!
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 kl_forward(torch::Tensor predictions, torch::Tensor targets);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\nstatic __inline__ __device__ float warp_sum(float v) {\n v += __shfl_down_sync(0xffffffff, v, 16);\n v += __shfl_down_sync(0xffffffff, v, 8);\n v += __shfl_down_sync(0xffffffff, v, 4);\n v += __shfl_down_sync(0xffffffff, v, 2);\n v += __shfl_down_sync(0xffffffff, v, 1);\n return v;\n}\n\nstatic __inline__ __device__ float block_sum(float v) {\n __shared__ float smem[32];\n const int lane = threadIdx.x & 31;\n const int wid = threadIdx.x >> 5;\n v = warp_sum(v);\n if (lane == 0) smem[wid] = v;\n __syncthreads();\n v = (threadIdx.x < (blockDim.x >> 5)) ? smem[lane] : 0.0f;\n if (wid == 0) v = warp_sum(v);\n return v;\n}\n\n__global__ void kl_div_kernel_vec4(const float* __restrict__ p,\n const float* __restrict__ t,\n float* __restrict__ out,\n long long n4,\n long long n,\n float inv_batch) {\n const float4* __restrict__ p4 = reinterpret_cast<const float4*>(p);\n const float4* __restrict__ t4 = reinterpret_cast<const float4*>(t);\n const long long stride = (long long)blockDim.x * gridDim.x;\n long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;\n\n float s = 0.0f;\n for (long long i = idx; i < n4; i += stride) {\n float4 pv = p4[i];\n float4 tv = t4[i];\n // KL component: target * (log(target) - log(prediction)) == target * log(target/prediction).\n // Inputs are softmax outputs, hence strictly positive for the benchmark.\n s = fmaf(tv.x, __logf(tv.x / pv.x), s);\n s = fmaf(tv.y, __logf(tv.y / pv.y), s);\n s = fmaf(tv.z, __logf(tv.z / pv.z), s);\n s = fmaf(tv.w, __logf(tv.w / pv.w), s);\n }\n\n // Generic tail handling (benchmark size is divisible by 4).\n const long long base = n4 << 2;\n for (long long j = base + idx; j < n; j += stride) {\n float tv = t[j];\n float pv = p[j];\n s = fmaf(tv, __logf(tv / pv), s);\n }\n\n s = block_sum(s);\n if (threadIdx.x == 0) {\n atomicAdd(out, s * inv_batch);\n }\n}\n\ntorch::Tensor kl_forward(torch::Tensor predictions, torch::Tensor targets) {\n TORCH_CHECK(predictions.is_cuda(), \"predictions must be a CUDA tensor\");\n TORCH_CHECK(targets.is_cuda(), \"targets must be a CUDA tensor\");\n TORCH_CHECK(predictions.scalar_type() == at::kFloat, \"only float32 is supported\");\n TORCH_CHECK(targets.scalar_type() == at::kFloat, \"only float32 is supported\");\n TORCH_CHECK(predictions.numel() == targets.numel(), \"input sizes must match\");\n TORCH_CHECK(predictions.dim() >= 1, \"predictions must have at least one dimension\");\n\n c10::cuda::CUDAGuard device_guard(predictions.device());\n auto p = predictions.contiguous();\n auto t = targets.contiguous();\n auto out = torch::empty({}, p.options());\n\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n cudaMemsetAsync(out.data_ptr<float>(), 0, sizeof(float), stream);\n\n const long long n = (long long)p.numel();\n const long long n4 = n >> 2;\n const int threads = 256;\n const int sm_count = at::cuda::getCurrentDeviceProperties()->multiProcessorCount;\n int blocks = sm_count * 8;\n long long needed = (n4 + threads - 1) / threads;\n if (needed < 1) needed = 1;\n if ((long long)blocks > needed) blocks = (int)needed;\n if (blocks < 1) blocks = 1;\n\n const float inv_batch = 1.0f / (float)predictions.size(0);\n kl_div_kernel_vec4<<<blocks, threads, 0, stream>>>(\n p.data_ptr<float>(), t.data_ptr<float>(), out.data_ptr<float>(), n4, n, inv_batch);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"kl_div_batchmean_fused_ext\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"kl_forward\"],\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, predictions, targets):\n return _ext.kl_forward(predictions, targets)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.72 μs
Runtime stats: mean=0.72μs median=?μs std=0.00μs
Numerical precision: max_abs_err=8.20e-08 mean_abs_err=4.32e-08 max_rel_err=1.22e-06
Memory: 2048.0 MB peak (ref: 6144.0 MB, ratio: 0.3333x)
Kernel launches: 1 (ref: 9, fusion ratio: 9.0)
SOL score: 0.8984
final submitted kernel (126 lines, 4,488 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 kl_forward(torch::Tensor predictions, torch::Tensor targets);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda.h>
#include <cuda_runtime.h>
static __inline__ __device__ float warp_sum(float v) {
v += __shfl_down_sync(0xffffffff, v, 16);
v += __shfl_down_sync(0xffffffff, v, 8);
v += __shfl_down_sync(0xffffffff, v, 4);
v += __shfl_down_sync(0xffffffff, v, 2);
v += __shfl_down_sync(0xffffffff, v, 1);
return v;
}
static __inline__ __device__ float block_sum(float v) {
__shared__ float smem[32];
const int lane = threadIdx.x & 31;
const int wid = threadIdx.x >> 5;
v = warp_sum(v);
if (lane == 0) smem[wid] = v;
__syncthreads();
v = (threadIdx.x < (blockDim.x >> 5)) ? smem[lane] : 0.0f;
if (wid == 0) v = warp_sum(v);
return v;
}
__global__ void kl_div_kernel_vec4(const float* __restrict__ p,
const float* __restrict__ t,
float* __restrict__ out,
long long n4,
long long n,
float inv_batch) {
const float4* __restrict__ p4 = reinterpret_cast<const float4*>(p);
const float4* __restrict__ t4 = reinterpret_cast<const float4*>(t);
const long long stride = (long long)blockDim.x * gridDim.x;
long long idx = (long long)blockIdx.x * blockDim.x + threadIdx.x;
float s = 0.0f;
for (long long i = idx; i < n4; i += stride) {
float4 pv = p4[i];
float4 tv = t4[i];
// KL component: target * (log(target) - log(prediction)) == target * log(target/prediction).
// Inputs are softmax outputs, hence strictly positive for the benchmark.
s = fmaf(tv.x, __logf(tv.x / pv.x), s);
s = fmaf(tv.y, __logf(tv.y / pv.y), s);
s = fmaf(tv.z, __logf(tv.z / pv.z), s);
s = fmaf(tv.w, __logf(tv.w / pv.w), s);
}
// Generic tail handling (benchmark size is divisible by 4).
const long long base = n4 << 2;
for (long long j = base + idx; j < n; j += stride) {
float tv = t[j];
float pv = p[j];
s = fmaf(tv, __logf(tv / pv), s);
}
s = block_sum(s);
if (threadIdx.x == 0) {
atomicAdd(out, s * inv_batch);
}
}
torch::Tensor kl_forward(torch::Tensor predictions, torch::Tensor targets) {
TORCH_CHECK(predictions.is_cuda(), "predictions must be a CUDA tensor");
TORCH_CHECK(targets.is_cuda(), "targets must be a CUDA tensor");
TORCH_CHECK(predictions.scalar_type() == at::kFloat, "only float32 is supported");
TORCH_CHECK(targets.scalar_type() == at::kFloat, "only float32 is supported");
TORCH_CHECK(predictions.numel() == targets.numel(), "input sizes must match");
TORCH_CHECK(predictions.dim() >= 1, "predictions must have at least one dimension");
c10::cuda::CUDAGuard device_guard(predictions.device());
auto p = predictions.contiguous();
auto t = targets.contiguous();
auto out = torch::empty({}, p.options());
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
cudaMemsetAsync(out.data_ptr<float>(), 0, sizeof(float), stream);
const long long n = (long long)p.numel();
const long long n4 = n >> 2;
const int threads = 256;
const int sm_count = at::cuda::getCurrentDeviceProperties()->multiProcessorCount;
int blocks = sm_count * 8;
long long needed = (n4 + threads - 1) / threads;
if (needed < 1) needed = 1;
if ((long long)blocks > needed) blocks = (int)needed;
if (blocks < 1) blocks = 1;
const float inv_batch = 1.0f / (float)predictions.size(0);
kl_div_kernel_vec4<<<blocks, threads, 0, stream>>>(
p.data_ptr<float>(), t.data_ptr<float>(), out.data_ptr<float>(), n4, n, inv_batch);
C10_CUDA_KERNEL_LAUNCH_CHECK();
return out;
}
"""
_ext = load_inline(
name="kl_div_batchmean_fused_ext",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["kl_forward"],
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, predictions, targets):
return _ext.kl_forward(predictions, targets)