correct
21_RadialBasisFunctionExpansion.py
started
2026-05-05T00:25:31Z
timingkernelbench.timing
kernel mean / median / std
0.08 / — / 1.39e-04 μs
ref mean / median / std
0.51 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
20.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1386.88 GB/s
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
import math
class Model(nn.Module):
"""
Radial Basis Function (RBF) expansion of interatomic distances.
Standard featurization in molecular graph neural networks (SchNet,
DimeNet, GemNet) that converts scalar distances into a feature vector
of Gaussian-basis evaluations.
"""
def __init__(self, num_rbf=64, cutoff=5.0):
super().__init__()
self.num_rbf = num_rbf
self.cutoff = cutoff
offsets = torch.linspace(0.0, cutoff, num_rbf)
self.register_buffer("offsets", offsets)
coeff = -0.5 / (offsets[1] - offsets[0]).item() ** 2
self.coeff = coeff
def forward(self, distances: torch.Tensor) -> torch.Tensor:
"""
Args:
distances: (B, N, N) – pairwise distance matrix (or (B, E) edge list)
Returns:
rbf_features: (*distances.shape, num_rbf) – expanded features
"""
# Cosine cutoff envelope
d_scaled = distances.unsqueeze(-1) # (..., 1)
envelope = 0.5 * (torch.cos(math.pi * d_scaled / self.cutoff) + 1.0)
envelope = envelope * (d_scaled < self.cutoff).float()
rbf = torch.exp(self.coeff * (d_scaled - self.offsets) ** 2)
return rbf * envelope
num_atoms = 256
num_rbf = 64
cutoff = 5.0
batch_size = 8
def get_inputs():
p = popcorn_pri
coords = torch.randn(p.jitter_int(batch_size), p.jitter_int(num_atoms), 3)
diff = coords.unsqueeze(2) - coords.unsqueeze(1)
distances = torch.sqrt((diff ** 2).sum(-1) + 1e-8)
return [distances]
def get_init_inputs():
return [num_rbf, cutoff]
turn 0 · FINAL · 1 tool call(s) · 46.0s turn · 46.0s LLM · 7,990 chars (click to expand)
turn 046.0s turn · 46.0s LLM · 0.0s tools · FINAL
reasoning
**Optimizing Python module**
I’m focused on creating a Python module that needs to optimize the RBF expansion for specific distances shaped as (8, 256, 256). The output should be (8, 256, 256, 64), comprising around 33.5M floats, or about 134MB. The goal is to compute the exponential and cosine functions efficiently, avoiding recomputation wherever possible. Using a 2D approach appears effective, with a plan to handle blocks and threads smartly for all calculations. I'll have to find a balance to keep overhead minimal and performance high!
**Calculating output elements**
I need to compute around 33 million output elements, focusing on the exponential function, which seems to dominate the calculations. The idea is to use a fast approximation method for the exponential with a precision of about \(1 \times 10^{-4}\). For the cosine functions, I need to ensure a precise cutoff mask, likely supporting a general number of RBFs. The constructor will accept arguments such as distances, num_rbf, and cutoff for flexibility. I'll also explore handling non-contiguous distances and clarify requirements for CPU versus CUDA compatibility, while possibly writing a C++ wrapper to enhance efficiency!
**Including CUDA source**
I need to ensure that the CUDA source code is included in my implementation. It’s important to avoid using Pybind in this case, so I’ll focus solely on the necessary functions that can operate efficiently with CUDA. This streamlining should help me maintain the proper structure and clarity in the code while achieving the desired functionality without additional complexities. I’ll gather all functions and format everything nicely for a smooth integration!
**Organizing C++ bindings**
I'm thinking about the auto-generated C++ binding during the compilation process. The function is implemented in CUDA translation, and I may need to include the function signature in the cpp_sources declaration. The function list wraps around the rbf_forward call. It could compile if I handle just the declaration. I could also merge the host function in cuda_sources, and the pybind process needs a proper declaration. Alright, I’ll finalize the code and submit it through the tool.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nimport math\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor rbf_forward(torch::Tensor distances, int64_t num_rbf, double cutoff);\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#include <vector>\n\n#ifndef CUDART_PI_F\n#define CUDART_PI_F 3.141592654f\n#endif\n\n__global__ void rbf64_kernel(const float* __restrict__ dist,\n float* __restrict__ out,\n const int64_t D,\n const float cutoff) {\n // Four warps per CTA; each warp expands one distance into 64 RBF values.\n const int warp = threadIdx.x >> 5;\n const int lane = threadIdx.x & 31;\n const int64_t idx = (int64_t)blockIdx.x * 4 + warp;\n if (idx >= D) return;\n\n float d = 0.0f;\n float env = 0.0f;\n if (lane == 0) {\n d = dist[idx];\n env = (d < cutoff) ? (0.5f * (cosf(CUDART_PI_F * d / cutoff) + 1.0f)) : 0.0f;\n }\n d = __shfl_sync(0xffffffff, d, 0);\n env = __shfl_sync(0xffffffff, env, 0);\n\n constexpr float inv63 = 1.0f / 63.0f;\n const float spacing = cutoff * inv63;\n const float coeff = -0.5f / (spacing * spacing);\n float* base = out + idx * 64;\n\n int j = lane;\n float x = d - (float)j * spacing;\n base[j] = __expf(coeff * x * x) * env;\n\n j = lane + 32;\n x = d - (float)j * spacing;\n base[j] = __expf(coeff * x * x) * env;\n}\n\n__global__ void rbf_generic_kernel(const float* __restrict__ dist,\n float* __restrict__ out,\n const int64_t total,\n const int64_t num_rbf,\n const float cutoff) {\n const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;\n if (k >= total) return;\n const int64_t d_idx = k / num_rbf;\n const int64_t j = k - d_idx * num_rbf;\n const float d = dist[d_idx];\n const float spacing = cutoff / (float)(num_rbf - 1);\n const float coeff = -0.5f / (spacing * spacing);\n const float env = (d < cutoff) ? (0.5f * (cosf(CUDART_PI_F * d / cutoff) + 1.0f)) : 0.0f;\n const float off = (float)j * spacing;\n const float x = d - off;\n out[k] = __expf(coeff * x * x) * env;\n}\n\ntorch::Tensor rbf_forward(torch::Tensor distances, int64_t num_rbf, double cutoff_d) {\n TORCH_CHECK(distances.is_cuda(), \"distances must be a CUDA tensor\");\n TORCH_CHECK(distances.scalar_type() == at::kFloat, \"only float32 distances are supported\");\n TORCH_CHECK(num_rbf > 1, \"num_rbf must be greater than 1\");\n\n std::vector<int64_t> shape = distances.sizes().vec();\n shape.push_back(num_rbf);\n auto out = torch::empty(shape, distances.options());\n\n const int64_t D = distances.numel();\n if (D == 0) return out;\n\n const float cutoff = static_cast<float>(cutoff_d);\n const float* dist_ptr = distances.data_ptr<float>();\n float* out_ptr = out.data_ptr<float>();\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n\n if (num_rbf == 64) {\n const int threads = 128;\n const dim3 blocks((unsigned int)((D + 3) / 4));\n rbf64_kernel<<<blocks, threads, 0, stream>>>(dist_ptr, out_ptr, D, cutoff);\n } else {\n const int threads = 256;\n const int64_t total = D * num_rbf;\n const dim3 blocks((unsigned int)((total + threads - 1) / threads));\n rbf_generic_kernel<<<blocks, threads, 0, stream>>>(dist_ptr, out_ptr, total, num_rbf, cutoff);\n }\n return out;\n}\n\"\"\"\n\n_rbf_ext = load_inline(\n name=\"rbf_expansion_inline_ext\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"rbf_forward\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n extra_cflags=[\"-O3\"],\n verbose=False,\n)\n\n\nclass ModelNew(nn.Module):\n def __init__(self, num_rbf=64, cutoff=5.0):\n super().__init__()\n self.num_rbf = num_rbf\n self.cutoff = cutoff\n offsets = torch.linspace(0.0, cutoff, num_rbf)\n self.register_buffer(\"offsets\", offsets)\n self.coeff = -0.5 / (offsets[1] - offsets[0]).item() ** 2\n\n def forward(self, distances: torch.Tensor) -> torch.Tensor:\n if not distances.is_contiguous():\n distances = distances.contiguous()\n return _rbf_ext.rbf_forward(distances, int(self.num_rbf), float(self.cutoff))\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.08 μs
Runtime stats: mean=0.08μs median=?μs std=0.00μs
Numerical precision: max_abs_err=1.07e-06 mean_abs_err=1.40e-08 max_rel_err=2.98e+04
Memory: 163.0 MB peak (ref: 293.0 MB, ratio: 0.5563x)
Kernel launches: 1 (ref: 20, fusion ratio: 20.0)
SOL score: 0.414
final submitted kernel (129 lines, 4,416 chars) — full source, untruncated
import torch
import torch.nn as nn
import math
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
torch::Tensor rbf_forward(torch::Tensor distances, int64_t num_rbf, double cutoff);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#ifndef CUDART_PI_F
#define CUDART_PI_F 3.141592654f
#endif
__global__ void rbf64_kernel(const float* __restrict__ dist,
float* __restrict__ out,
const int64_t D,
const float cutoff) {
// Four warps per CTA; each warp expands one distance into 64 RBF values.
const int warp = threadIdx.x >> 5;
const int lane = threadIdx.x & 31;
const int64_t idx = (int64_t)blockIdx.x * 4 + warp;
if (idx >= D) return;
float d = 0.0f;
float env = 0.0f;
if (lane == 0) {
d = dist[idx];
env = (d < cutoff) ? (0.5f * (cosf(CUDART_PI_F * d / cutoff) + 1.0f)) : 0.0f;
}
d = __shfl_sync(0xffffffff, d, 0);
env = __shfl_sync(0xffffffff, env, 0);
constexpr float inv63 = 1.0f / 63.0f;
const float spacing = cutoff * inv63;
const float coeff = -0.5f / (spacing * spacing);
float* base = out + idx * 64;
int j = lane;
float x = d - (float)j * spacing;
base[j] = __expf(coeff * x * x) * env;
j = lane + 32;
x = d - (float)j * spacing;
base[j] = __expf(coeff * x * x) * env;
}
__global__ void rbf_generic_kernel(const float* __restrict__ dist,
float* __restrict__ out,
const int64_t total,
const int64_t num_rbf,
const float cutoff) {
const int64_t k = (int64_t)blockIdx.x * blockDim.x + threadIdx.x;
if (k >= total) return;
const int64_t d_idx = k / num_rbf;
const int64_t j = k - d_idx * num_rbf;
const float d = dist[d_idx];
const float spacing = cutoff / (float)(num_rbf - 1);
const float coeff = -0.5f / (spacing * spacing);
const float env = (d < cutoff) ? (0.5f * (cosf(CUDART_PI_F * d / cutoff) + 1.0f)) : 0.0f;
const float off = (float)j * spacing;
const float x = d - off;
out[k] = __expf(coeff * x * x) * env;
}
torch::Tensor rbf_forward(torch::Tensor distances, int64_t num_rbf, double cutoff_d) {
TORCH_CHECK(distances.is_cuda(), "distances must be a CUDA tensor");
TORCH_CHECK(distances.scalar_type() == at::kFloat, "only float32 distances are supported");
TORCH_CHECK(num_rbf > 1, "num_rbf must be greater than 1");
std::vector<int64_t> shape = distances.sizes().vec();
shape.push_back(num_rbf);
auto out = torch::empty(shape, distances.options());
const int64_t D = distances.numel();
if (D == 0) return out;
const float cutoff = static_cast<float>(cutoff_d);
const float* dist_ptr = distances.data_ptr<float>();
float* out_ptr = out.data_ptr<float>();
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
if (num_rbf == 64) {
const int threads = 128;
const dim3 blocks((unsigned int)((D + 3) / 4));
rbf64_kernel<<<blocks, threads, 0, stream>>>(dist_ptr, out_ptr, D, cutoff);
} else {
const int threads = 256;
const int64_t total = D * num_rbf;
const dim3 blocks((unsigned int)((total + threads - 1) / threads));
rbf_generic_kernel<<<blocks, threads, 0, stream>>>(dist_ptr, out_ptr, total, num_rbf, cutoff);
}
return out;
}
"""
_rbf_ext = load_inline(
name="rbf_expansion_inline_ext",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["rbf_forward"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
extra_cflags=["-O3"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, num_rbf=64, cutoff=5.0):
super().__init__()
self.num_rbf = num_rbf
self.cutoff = cutoff
offsets = torch.linspace(0.0, cutoff, num_rbf)
self.register_buffer("offsets", offsets)
self.coeff = -0.5 / (offsets[1] - offsets[0]).item() ** 2
def forward(self, distances: torch.Tensor) -> torch.Tensor:
if not distances.is_contiguous():
distances = distances.contiguous()
return _rbf_ext.rbf_forward(distances, int(self.num_rbf), float(self.cutoff))