correct
28_DirichletMultinomialLogLikelihood.py
started
2026-05-11T17:36:20Z
timingkernelbench.timing
kernel mean / median / std
0.30 / — / 0.00 μs
ref mean / median / std
0.13 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
2.57x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Log-likelihood under the Dirichlet-Multinomial (Polya) distribution.
Given count vectors n and concentration parameters alpha, computes
log p(n | alpha) using the log-gamma formulation. Core computation
in Bayesian topic models and mixed-membership models.
"""
def __init__(self, vocab_size):
super().__init__()
self.vocab_size = vocab_size
self.log_alpha = nn.Parameter(torch.zeros(vocab_size))
def forward(self, counts: torch.Tensor) -> torch.Tensor:
"""
Args:
counts: (B, V) – integer count vectors (as float for differentiability)
Returns:
log_lik: (B,) – log p(counts | alpha) for each sample
"""
alpha = torch.exp(self.log_alpha).unsqueeze(0) # (1, V)
N = counts.sum(-1) # (B,)
alpha_sum = alpha.sum(-1) # (1,)
# log p(n | alpha) = log Gamma(alpha_sum) - log Gamma(N + alpha_sum)
# + sum_v [ log Gamma(n_v + alpha_v) - log Gamma(alpha_v) ]
log_lik = (
torch.lgamma(alpha_sum)
- torch.lgamma(N + alpha_sum)
+ (torch.lgamma(counts + alpha) - torch.lgamma(alpha)).sum(-1)
)
return log_lik
vocab_size = 256
batch_size = 512
def get_inputs():
bs = popcorn_pri.jitter_int(batch_size)
counts = torch.randint(0, 10, (bs, vocab_size)).float()
return [counts]
def get_init_inputs():
return [vocab_size]
turn 0241.3s turn · 21.0s LLM · 220.3s tools · tokens in=2,133 · out=601 · total=3,178
reasoning
The task is to replace the forward computation of this PyTorch model with a custom CUDA kernel. The model computes the log-likelihood under the Dirichlet-Multinomial distribution.
I need to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model computes the log-likelihood under the Dirichlet-Multinomial distribution. It takes counts of shape (B, V) and a parameter log_alpha of shape (V,), and outputs log_likelihood of shape (B,).
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#include <cmath>\n\n__global__ void dirichlet_multinomial_log_lik(\n const float* __restrict__ counts,\n const float* __restrict__ alpha,\n float* __restrict__ log_lik,\n int B,\n int V,\n float alpha_sum,\n const float* __restrict__ log_alpha // unused, alpha precomputed\n) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B) return;\n\n float sum = 0.0f;\n for (int v = 0; v < V; ++v) {\n float count = counts[b * V + v];\n float a = alpha[v];\n sum += lgammaf(count + a) - lgammaf(a);\n }\n float N = 0.0f; // will recompute? wait better pass or compute\n // Actually compute N here too? or pre-sum\n for (int v = 0; v < V; ++v) {\n N += counts[b * V + v];\n }\n log_lik[b] = lgammaf(alpha_sum) - lgammaf(N + alpha_sum) + sum;\n}\n\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha) {\n int B = counts.size(0);\n int V = counts.size(1);\n auto alpha = torch::exp(log_alpha);\n float alpha_sum = alpha.sum().item<float>();\n auto log_lik = torch::empty({B}, counts.options());\n \n dim3 block(256);\n dim3 grid((B + 255) / 256);\n \n dirichlet_multinomial_log_lik<<<grid, block>>>(\n counts.data_ptr<float>(),\n alpha.data_ptr<float>(),\n log_lik.data_ptr<float>(),\n B, V, alpha_sum,\n log_alpha.data_ptr<float>()\n );\n return log_lik;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha);\n\"\"\"\n\nmodule = load_inline(\n name='dirichlet_multinomial',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['dirichlet_multinomial_forward'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, vocab_size):\n super().__init__()\n self.vocab_size = vocab_size\n self.log_alpha = nn.Parameter(torch.zeros(vocab_size))\n self.module = module\n\n def forward(self, counts: torch.Tensor) -> torch.Tensor:\n return self.module.dirichlet_multinomial_forward(counts, self.log_alpha)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 196.1s turn · 5.4s LLM · 90.7s tools · tokens in=3,195 · out=530 · total=3,732
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#include <cmath>\n\n__global__ void dirichlet_multinomial_log_lik(\n const float* __restrict__ counts,\n const float* __restrict__ alpha,\n float* __restrict__ log_lik,\n int B,\n int V,\n float alpha_sum\n) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B) return;\n\n float sum = 0.0f;\n float N = 0.0f;\n for (int v = 0; v < V; ++v) {\n float count = counts[b * V + v];\n float a = alpha[v];\n sum += lgammaf(count + a) - lgammaf(a);\n N += count;\n }\n log_lik[b] = lgammaf(alpha_sum) - lgammaf(N + alpha_sum) + sum;\n}\n\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha) {\n int B = counts.size(0);\n int V = counts.size(1);\n auto alpha = torch::exp(log_alpha);\n float alpha_sum = alpha.sum().item<float>();\n auto log_lik = torch::empty({B}, counts.options());\n \n dim3 block(256);\n dim3 grid((B + 255) / 256);\n \n dirichlet_multinomial_log_lik<<<grid, block>>>(\n counts.data_ptr<float>(),\n alpha.data_ptr<float>(),\n log_lik.data_ptr<float>(),\n B, V, alpha_sum\n );\n return log_lik;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha);\n\"\"\"\n\nmodule = load_inline(\n name='dirichlet_multinomial',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['dirichlet_multinomial_forward'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, vocab_size):\n super().__init__()\n self.vocab_size = vocab_size\n self.log_alpha = nn.Parameter(torch.zeros(vocab_size))\n self.module = module\n\n def forward(self, counts: torch.Tensor) -> torch.Tensor:\n return self.module.dirichlet_multinomial_forward(counts, self.log_alpha)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=1.46e-03 mean_abs_err=5.56e-04 max_rel_err=2.42e-07
turn 2119.7s turn · 8.0s LLM · 111.7s tools · tokens in=3,792 · out=539 · total=4,546
reasoning
Correctness passed, though error is a bit high for fp32 atol=1e-4, but 1.46e-3 is larger, wait it passed? The tolerance in tool is probably loose, but spec says atol=rtol=1e-4.
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__global__ void dirichlet_multinomial_log_lik(\n const float* __restrict__ counts,\n const float* __restrict__ alpha,\n float* __restrict__ log_lik,\n int B,\n int V,\n float alpha_sum\n) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B) return;\n\n float sum = 0.0f;\n float N = 0.0f;\n for (int v = 0; v < V; ++v) {\n float count = counts[b * V + v];\n float a = alpha[v];\n sum += lgammaf(count + a) - lgammaf(a);\n N += count;\n }\n log_lik[b] = lgammaf(alpha_sum) - lgammaf(N + alpha_sum) + sum;\n}\n\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha) {\n int B = counts.size(0);\n int V = counts.size(1);\n auto alpha = torch::exp(log_alpha);\n auto alpha_sum_t = alpha.sum();\n float alpha_sum = alpha_sum_t.item<float>();\n auto log_lik = torch::empty({B}, counts.options());\n \n dim3 block(256);\n dim3 grid((B + 255) / 256);\n \n dirichlet_multinomial_log_lik<<<grid, block>>>(\n counts.data_ptr<float>(),\n alpha.data_ptr<float>(),\n log_lik.data_ptr<float>(),\n B, V, alpha_sum\n );\n return log_lik;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha);\n\"\"\"\n\nmodule = load_inline(\n name='dirichlet_multinomial',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['dirichlet_multinomial_forward'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, vocab_size):\n super().__init__()\n self.vocab_size = vocab_size\n self.log_alpha = nn.Parameter(torch.zeros(vocab_size))\n self.module = module\n\n def forward(self, counts: torch.Tensor) -> torch.Tensor:\n return self.module.dirichlet_multinomial_forward(counts, self.log_alpha)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=1.46e-03 mean_abs_err=5.56e-04 max_rel_err=2.42e-07
turn 3274.2s turn · 5.8s LLM · 268.5s tools · tokens in=4,606 · out=552 · total=5,264 · FINAL
reasoning
Still same error. The issue is likely the accumulation of lgamma in float, or difference in lgamma implementation between torch and CUDA.
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#include <cmath>\n\n__global__ void dirichlet_multinomial_log_lik(\n const float* __restrict__ counts,\n const float* __restrict__ alpha,\n float* __restrict__ log_lik,\n int B,\n int V,\n float alpha_sum\n) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n if (b >= B) return;\n\n double sum = 0.0;\n double N = 0.0;\n for (int v = 0; v < V; ++v) {\n float count = counts[b * V + v];\n float a = alpha[v];\n sum += lgamma(static_cast<double>(count + a)) - lgamma(static_cast<double>(a));\n N += count;\n }\n log_lik[b] = static_cast<float>(lgamma(static_cast<double>(alpha_sum)) - lgamma(static_cast<double>(N + alpha_sum)) + sum);\n}\n\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha) {\n int B = counts.size(0);\n int V = counts.size(1);\n auto alpha = torch::exp(log_alpha);\n auto alpha_sum_t = alpha.sum();\n float alpha_sum = alpha_sum_t.item<float>();\n auto log_lik = torch::empty({B}, counts.options());\n \n dim3 block(256);\n dim3 grid((B + 255) / 256);\n \n dirichlet_multinomial_log_lik<<<grid, block>>>(\n counts.data_ptr<float>(),\n alpha.data_ptr<float>(),\n log_lik.data_ptr<float>(),\n B, V, alpha_sum\n );\n return log_lik;\n}\n\"\"\"\n\ncpp_source = \"\"\"\ntorch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha);\n\"\"\"\n\nmodule = load_inline(\n name='dirichlet_multinomial',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['dirichlet_multinomial_forward'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, vocab_size):\n super().__init__()\n self.vocab_size = vocab_size\n self.log_alpha = nn.Parameter(torch.zeros(vocab_size))\n self.module = module\n\n def forward(self, counts: torch.Tensor) -> torch.Tensor:\n return self.module.dirichlet_multinomial_forward(counts, self.log_alpha)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (3 / 3) correctness trials all passed.
Kernel runtime: 0.30 μs
Runtime stats: mean=0.30μs median=?μs std=0.00μs
Numerical precision: max_abs_err=9.77e-04 mean_abs_err=3.46e-04 max_rel_err=1.68e-07
Memory: 0.51 MB peak (ref: 1.51 MB, ratio: 0.3351x)
Kernel launches: 7 (ref: 18, fusion ratio: 2.5714)
SOL score: 0.0545
final submitted kernel (75 lines, 2,131 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>
#include <cmath>
__global__ void dirichlet_multinomial_log_lik(
const float* __restrict__ counts,
const float* __restrict__ alpha,
float* __restrict__ log_lik,
int B,
int V,
float alpha_sum
) {
int b = blockIdx.x * blockDim.x + threadIdx.x;
if (b >= B) return;
double sum = 0.0;
double N = 0.0;
for (int v = 0; v < V; ++v) {
float count = counts[b * V + v];
float a = alpha[v];
sum += lgamma(static_cast<double>(count + a)) - lgamma(static_cast<double>(a));
N += count;
}
log_lik[b] = static_cast<float>(lgamma(static_cast<double>(alpha_sum)) - lgamma(static_cast<double>(N + alpha_sum)) + sum);
}
torch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha) {
int B = counts.size(0);
int V = counts.size(1);
auto alpha = torch::exp(log_alpha);
auto alpha_sum_t = alpha.sum();
float alpha_sum = alpha_sum_t.item<float>();
auto log_lik = torch::empty({B}, counts.options());
dim3 block(256);
dim3 grid((B + 255) / 256);
dirichlet_multinomial_log_lik<<<grid, block>>>(
counts.data_ptr<float>(),
alpha.data_ptr<float>(),
log_lik.data_ptr<float>(),
B, V, alpha_sum
);
return log_lik;
}
"""
cpp_source = """
torch::Tensor dirichlet_multinomial_forward(torch::Tensor counts, torch::Tensor log_alpha);
"""
module = load_inline(
name='dirichlet_multinomial',
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=['dirichlet_multinomial_forward'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self, vocab_size):
super().__init__()
self.vocab_size = vocab_size
self.log_alpha = nn.Parameter(torch.zeros(vocab_size))
self.module = module
def forward(self, counts: torch.Tensor) -> torch.Tensor:
return self.module.dirichlet_multinomial_forward(counts, self.log_alpha)