correct
8_DeepSeekMoEGroundedTop2Routing.py
started
2026-05-11T11:10:12Z
timingkernelbench.timing
kernel mean / median / std
0.05 / — / 2.58e-04 μs
ref mean / median / std
0.23 / — / 1.83 μ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
warp stalls (top 5)nsight
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn
class Model(nn.Module):
"""
Grounded top-2 MoE router.
Router logits are biased by token-expert similarity against learned
grounding embeddings, then normalized over the selected top-2 experts.
"""
def __init__(self):
super().__init__()
def forward(
self,
token_hidden: torch.Tensor,
router_logits: torch.Tensor,
expert_ground: torch.Tensor,
alpha: float,
) -> torch.Tensor:
grounded = router_logits + alpha * (token_hidden @ expert_ground.t())
top_vals, top_idx = torch.topk(grounded, k=2, dim=-1)
top_weights = torch.softmax(top_vals, dim=-1)
return torch.stack((top_idx.to(torch.float32), top_weights), dim=-1)
num_tokens = 4096
hidden_dim = 128
num_experts = 16
alpha = 0.35
def get_inputs():
p = popcorn_pri
nt = p.jitter_int(num_tokens)
hd = p.jitter_int(hidden_dim, align=16)
ne = p.jitter_int(num_experts, minimum=2)
token_hidden = torch.randn(nt, hd, dtype=torch.float32)
router_logits = torch.randn(nt, ne, dtype=torch.float32)
expert_ground = torch.randn(ne, hd, dtype=torch.float32)
return [token_hidden, router_logits, expert_ground, alpha]
def get_init_inputs():
return []
turn 0333.1s turn · 3.9s LLM · 329.2s tools · tokens in=1,517 · out=6 · total=2,048
reasoning
The task is to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model is a Grounded top-2 MoE router.
I need to replace the forward computation of a PyTorch model with a custom CUDA kernel for a Grounded top-2 MoE router. The model takes token_hidden of shape [num_tokens, hidden_dim], computes grounded = router_logits + alpha * (token_hidden @ expert_ground.
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 1362.5s turn · 9.9s LLM · 352.6s tools · tokens in=2,281 · out=890 · total=3,273
reasoning
GPU is H100, high bandwidth.
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 <cfloat>\n\n__global__ void grounded_top2_kernel(\n const float* __restrict__ token_hidden,\n const float* __restrict__ router_logits,\n const float* __restrict__ expert_ground,\n float* __restrict__ output,\n int num_tokens,\n int hidden_dim,\n int num_experts,\n float alpha\n) {\n int token_idx = blockIdx.x;\n if (token_idx >= num_tokens) return;\n\n extern __shared__ float s_grounded[];\n \n const float* token = token_hidden + token_idx * hidden_dim;\n \n for (int e = threadIdx.x; e < num_experts; e += blockDim.x) {\n float dot = 0.0f;\n const float* expert = expert_ground + e * hidden_dim;\n for (int h = 0; h < hidden_dim; h++) {\n dot += token[h] * expert[h];\n }\n float router = router_logits[token_idx * num_experts + e];\n s_grounded[e] = router + alpha * dot;\n }\n __syncthreads();\n\n if (threadIdx.x == 0) {\n // Find top-2\n float max1 = -FLT_MAX, max2 = -FLT_MAX;\n int idx1 = -1, idx2 = -1;\n for (int e = 0; e < num_experts; e++) {\n float val = s_grounded[e];\n if (val > max1) {\n max2 = max1; idx2 = idx1;\n max1 = val; idx1 = e;\n } else if (val > max2) {\n max2 = val; idx2 = e;\n }\n }\n // Softmax on top2\n float m = fmaxf(max1, max2);\n float sum_exp = expf(max1 - m) + expf(max2 - m);\n float w1 = expf(max1 - m) / sum_exp;\n float w2 = expf(max2 - m) / sum_exp;\n \n // Output: [idx1, w1, idx2, w2] but stacked as [[idx1,w1],[idx2,w2]]\n float* out = output + token_idx * 4;\n out[0] = (float)idx1;\n out[1] = w1;\n out[2] = (float)idx2;\n out[3] = w2;\n }\n}\n\ntorch::Tensor grounded_top2_cuda(\n torch::Tensor token_hidden,\n torch::Tensor router_logits,\n torch::Tensor expert_ground,\n float alpha\n) {\n int num_tokens = token_hidden.size(0);\n int hidden_dim = token_hidden.size(1);\n int num_experts = router_logits.size(1);\n \n auto output = torch::empty({num_tokens, 2, 2}, token_hidden.options());\n \n int threads = 256;\n int smem = num_experts * sizeof(float);\n grounded_top2_kernel<<<num_tokens, threads, smem>>>(\n token_hidden.data_ptr<float>(),\n router_logits.data_ptr<float>(),\n expert_ground.data_ptr<float>(),\n output.data_ptr<float>(),\n num_tokens, hidden_dim, num_experts, alpha\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor grounded_top2_cuda(torch::Tensor token_hidden, torch::Tensor router_logits, torch::Tensor expert_ground, float alpha);\n'''\n\nmodule = load_inline(\n name='grounded_top2',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['grounded_top2_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, token_hidden, router_logits, expert_ground, alpha):\n return self.module.grounded_top2_cuda(token_hidden, router_logits, expert_ground, alpha)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2188.3s turn · 11.8s LLM · 176.5s tools · tokens in=3,290 · out=891 · total=4,188
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 <cfloat>\n\n__global__ void grounded_top2_kernel(\n const float* __restrict__ token_hidden,\n const float* __restrict__ router_logits,\n const float* __restrict__ expert_ground,\n float* __restrict__ output,\n int num_tokens,\n int hidden_dim,\n int num_experts,\n float alpha\n) {\n int token_idx = blockIdx.x;\n if (token_idx >= num_tokens) return;\n\n extern __shared__ float s_grounded[];\n \n const float* token = token_hidden + token_idx * hidden_dim;\n \n for (int e = threadIdx.x; e < num_experts; e += blockDim.x) {\n float dot = 0.0f;\n const float* expert = expert_ground + e * hidden_dim;\n for (int h = 0; h < hidden_dim; h++) {\n dot += token[h] * expert[h];\n }\n float router = router_logits[token_idx * num_experts + e];\n s_grounded[e] = router + alpha * dot;\n }\n __syncthreads();\n\n if (threadIdx.x == 0) {\n // Find top-2\n float max1 = -FLT_MAX, max2 = -FLT_MAX;\n int idx1 = -1, idx2 = -1;\n for (int e = 0; e < num_experts; e++) {\n float val = s_grounded[e];\n if (val > max1) {\n max2 = max1; idx2 = idx1;\n max1 = val; idx1 = e;\n } else if (val > max2) {\n max2 = val; idx2 = e;\n }\n }\n // Softmax on top2\n float m = fmaxf(max1, max2);\n float sum_exp = expf(max1 - m) + expf(max2 - m);\n float w1 = expf(max1 - m) / sum_exp;\n float w2 = expf(max2 - m) / sum_exp;\n \n // Output: [idx1, w1, idx2, w2] but stacked as [[idx1,w1],[idx2,w2]]\n float* out = output + token_idx * 4;\n out[0] = (float)idx1;\n out[1] = w1;\n out[2] = (float)idx2;\n out[3] = w2;\n }\n}\n\ntorch::Tensor grounded_top2_cuda(\n torch::Tensor token_hidden,\n torch::Tensor router_logits,\n torch::Tensor expert_ground,\n float alpha\n) {\n int num_tokens = token_hidden.size(0);\n int hidden_dim = token_hidden.size(1);\n int num_experts = router_logits.size(1);\n \n auto output = torch::empty({num_tokens, 2, 2}, token_hidden.options());\n \n int threads = 256;\n int smem = num_experts * sizeof(float);\n grounded_top2_kernel<<<num_tokens, threads, smem>>>(\n token_hidden.data_ptr<float>(),\n router_logits.data_ptr<float>(),\n expert_ground.data_ptr<float>(),\n output.data_ptr<float>(),\n num_tokens, hidden_dim, num_experts, alpha\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor grounded_top2_cuda(torch::Tensor token_hidden, torch::Tensor router_logits, torch::Tensor expert_ground, float alpha);\n'''\n\nmodule = load_inline(\n name='grounded_top2',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['grounded_top2_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, token_hidden, router_logits, expert_ground, alpha):\n return self.module.grounded_top2_cuda(token_hidden, router_logits, expert_ground, alpha)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=5.07e-07 mean_abs_err=1.46e-08 max_rel_err=2.02e-06
turn 3216.3s turn · 10.0s LLM · 206.2s tools · tokens in=4,248 · out=890 · total=5,309 · FINAL
reasoning
Correct! Now, to check if faster, but since we submit only when confident, and to measure speed we need submit, but submit ends session.
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 <cfloat>\n\n__global__ void grounded_top2_kernel(\n const float* __restrict__ token_hidden,\n const float* __restrict__ router_logits,\n const float* __restrict__ expert_ground,\n float* __restrict__ output,\n int num_tokens,\n int hidden_dim,\n int num_experts,\n float alpha\n) {\n int token_idx = blockIdx.x;\n if (token_idx >= num_tokens) return;\n\n extern __shared__ float s_grounded[];\n \n const float* token = token_hidden + token_idx * hidden_dim;\n \n for (int e = threadIdx.x; e < num_experts; e += blockDim.x) {\n float dot = 0.0f;\n const float* expert = expert_ground + e * hidden_dim;\n for (int h = 0; h < hidden_dim; h++) {\n dot += token[h] * expert[h];\n }\n float router = router_logits[token_idx * num_experts + e];\n s_grounded[e] = router + alpha * dot;\n }\n __syncthreads();\n\n if (threadIdx.x == 0) {\n // Find top-2\n float max1 = -FLT_MAX, max2 = -FLT_MAX;\n int idx1 = -1, idx2 = -1;\n for (int e = 0; e < num_experts; e++) {\n float val = s_grounded[e];\n if (val > max1) {\n max2 = max1; idx2 = idx1;\n max1 = val; idx1 = e;\n } else if (val > max2) {\n max2 = val; idx2 = e;\n }\n }\n // Softmax on top2\n float m = fmaxf(max1, max2);\n float sum_exp = expf(max1 - m) + expf(max2 - m);\n float w1 = expf(max1 - m) / sum_exp;\n float w2 = expf(max2 - m) / sum_exp;\n \n // Output: [idx1, w1, idx2, w2] but stacked as [[idx1,w1],[idx2,w2]]\n float* out = output + token_idx * 4;\n out[0] = (float)idx1;\n out[1] = w1;\n out[2] = (float)idx2;\n out[3] = w2;\n }\n}\n\ntorch::Tensor grounded_top2_cuda(\n torch::Tensor token_hidden,\n torch::Tensor router_logits,\n torch::Tensor expert_ground,\n float alpha\n) {\n int num_tokens = token_hidden.size(0);\n int hidden_dim = token_hidden.size(1);\n int num_experts = router_logits.size(1);\n \n auto output = torch::empty({num_tokens, 2, 2}, token_hidden.options());\n \n int threads = 256;\n int smem = num_experts * sizeof(float);\n grounded_top2_kernel<<<num_tokens, threads, smem>>>(\n token_hidden.data_ptr<float>(),\n router_logits.data_ptr<float>(),\n expert_ground.data_ptr<float>(),\n output.data_ptr<float>(),\n num_tokens, hidden_dim, num_experts, alpha\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor grounded_top2_cuda(torch::Tensor token_hidden, torch::Tensor router_logits, torch::Tensor expert_ground, float alpha);\n'''\n\nmodule = load_inline(\n name='grounded_top2',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['grounded_top2_cuda'],\n verbose=False\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.module = module\n\n def forward(self, token_hidden, router_logits, expert_ground, alpha):\n return self.module.grounded_top2_cuda(token_hidden, router_logits, expert_ground, alpha)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.05 μs
Runtime stats: mean=0.05μs median=?μs std=0.00μs
Numerical precision: max_abs_err=5.07e-07 mean_abs_err=1.46e-08 max_rel_err=2.02e-06
Memory: 35.32 MB peak (ref: 35.76 MB, ratio: 0.9878x)
Kernel launches: 1 (ref: 20, fusion ratio: 20.0)
SOL score: 0.0197
final submitted kernel (112 lines, 3,286 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 <cfloat>
__global__ void grounded_top2_kernel(
const float* __restrict__ token_hidden,
const float* __restrict__ router_logits,
const float* __restrict__ expert_ground,
float* __restrict__ output,
int num_tokens,
int hidden_dim,
int num_experts,
float alpha
) {
int token_idx = blockIdx.x;
if (token_idx >= num_tokens) return;
extern __shared__ float s_grounded[];
const float* token = token_hidden + token_idx * hidden_dim;
for (int e = threadIdx.x; e < num_experts; e += blockDim.x) {
float dot = 0.0f;
const float* expert = expert_ground + e * hidden_dim;
for (int h = 0; h < hidden_dim; h++) {
dot += token[h] * expert[h];
}
float router = router_logits[token_idx * num_experts + e];
s_grounded[e] = router + alpha * dot;
}
__syncthreads();
if (threadIdx.x == 0) {
// Find top-2
float max1 = -FLT_MAX, max2 = -FLT_MAX;
int idx1 = -1, idx2 = -1;
for (int e = 0; e < num_experts; e++) {
float val = s_grounded[e];
if (val > max1) {
max2 = max1; idx2 = idx1;
max1 = val; idx1 = e;
} else if (val > max2) {
max2 = val; idx2 = e;
}
}
// Softmax on top2
float m = fmaxf(max1, max2);
float sum_exp = expf(max1 - m) + expf(max2 - m);
float w1 = expf(max1 - m) / sum_exp;
float w2 = expf(max2 - m) / sum_exp;
// Output: [idx1, w1, idx2, w2] but stacked as [[idx1,w1],[idx2,w2]]
float* out = output + token_idx * 4;
out[0] = (float)idx1;
out[1] = w1;
out[2] = (float)idx2;
out[3] = w2;
}
}
torch::Tensor grounded_top2_cuda(
torch::Tensor token_hidden,
torch::Tensor router_logits,
torch::Tensor expert_ground,
float alpha
) {
int num_tokens = token_hidden.size(0);
int hidden_dim = token_hidden.size(1);
int num_experts = router_logits.size(1);
auto output = torch::empty({num_tokens, 2, 2}, token_hidden.options());
int threads = 256;
int smem = num_experts * sizeof(float);
grounded_top2_kernel<<<num_tokens, threads, smem>>>(
token_hidden.data_ptr<float>(),
router_logits.data_ptr<float>(),
expert_ground.data_ptr<float>(),
output.data_ptr<float>(),
num_tokens, hidden_dim, num_experts, alpha
);
return output;
}
'''
cpp_source = '''
torch::Tensor grounded_top2_cuda(torch::Tensor token_hidden, torch::Tensor router_logits, torch::Tensor expert_ground, float alpha);
'''
module = load_inline(
name='grounded_top2',
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=['grounded_top2_cuda'],
verbose=False
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.module = module
def forward(self, token_hidden, router_logits, expert_ground, alpha):
return self.module.grounded_top2_cuda(token_hidden, router_logits, expert_ground, alpha)