correct
47_virtual_all_gather_concat_linear.py
started
2026-05-11T11:00:59Z
timingkernelbench.timing
kernel mean / median / std
0.01 / — / 2.22e-04 μs
ref mean / median / std
0.01 / — / 3.76e-04 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
14.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)
"""
Virtual all-gather on the last dim: stack R tensors of shape (B, H) into (B, R*H), then Linear.
"""
import torch
import torch.nn as nn
from kernelbench.distributed_collectives import default_device
R = 4
B = 12
H = 32
K = 56
class Model(nn.Module):
def __init__(self):
super().__init__()
self.proj = nn.Linear(R * H, K, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
r, b, h = x.shape
assert r == R and h == H
parts = [x[i] for i in range(R)]
gathered = torch.cat(parts, dim=-1)
return self.proj(gathered)
def get_inputs():
dev = default_device()
p = popcorn_pri
return [torch.randn(p.jitter_int(R), p.jitter_int(B), p.jitter_int(D, align=8), device=dev)]
def get_init_inputs():
return []
turn 0727.8s turn · 5.4s LLM · 722.4s tools · tokens in=1,458 · out=6 · total=1,738
reasoning
The task is to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model does a virtual all-gather on the last dim: stack R tensors of shape (B, H) into (B, R*H), then Li...
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 1246.3s turn · 12.3s LLM · 234.0s tools · tokens in=1,971 · out=545 · total=2,716
reasoning
It's an 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_runtime.h>\n\n__global__ void fused_gather_linear_kernel(const float* x, const float* weight, const float* bias, float* output, int R, int B, int H, int K) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n int k = blockIdx.y * blockDim.y + threadIdx.y;\n if (b >= B || k >= K) return;\n \n float sum = bias[k];\n for (int r = 0; r < R; r++) {\n for (int h = 0; h < H; h++) {\n int x_idx = r * B * H + b * H + h;\n int w_idx = k * (R * H) + r * H + h;\n sum += x[x_idx] * weight[w_idx];\n }\n }\n output[b * K + k] = sum;\n}\n\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {\n int R = x.size(0);\n int B = x.size(1);\n int H = x.size(2);\n int K = weight.size(0);\n \n auto output = torch::empty({B, K}, x.options());\n \n dim3 block(16, 16);\n dim3 grid((B + 15) / 16, (K + 15) / 16);\n \n fused_gather_linear_kernel<<<grid, block>>>(\n x.data_ptr<float>(), weight.data_ptr<float>(), bias.data_ptr<float>(),\n output.data_ptr<float>(), R, B, H, K\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\n'''\n\nmodule = load_inline(\n name='fused_gather_linear',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['fused_gather_linear'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.proj = nn.Linear(4 * 32, 56, bias=True)\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n weight = self.proj.weight\n bias = self.proj.bias\n return module.fused_gather_linear(x, weight, bias)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2363.8s turn · 4.6s LLM · 359.2s tools · tokens in=2,733 · out=546 · total=3,286
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_runtime.h>\n\n__global__ void fused_gather_linear_kernel(const float* x, const float* weight, const float* bias, float* output, int R, int B, int H, int K) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n int k = blockIdx.y * blockDim.y + threadIdx.y;\n if (b >= B || k >= K) return;\n \n float sum = bias[k];\n for (int r = 0; r < R; r++) {\n for (int h = 0; h < H; h++) {\n int x_idx = r * B * H + b * H + h;\n int w_idx = k * (R * H) + r * H + h;\n sum += x[x_idx] * weight[w_idx];\n }\n }\n output[b * K + k] = sum;\n}\n\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {\n int R = x.size(0);\n int B = x.size(1);\n int H = x.size(2);\n int K = weight.size(0);\n \n auto output = torch::empty({B, K}, x.options());\n \n dim3 block(16, 16);\n dim3 grid((B + 15) / 16, (K + 15) / 16);\n \n fused_gather_linear_kernel<<<grid, block>>>(\n x.data_ptr<float>(), weight.data_ptr<float>(), bias.data_ptr<float>(),\n output.data_ptr<float>(), R, B, H, K\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\n'''\n\nmodule = load_inline(\n name='fused_gather_linear',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['fused_gather_linear'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.proj = nn.Linear(4 * 32, 56, bias=True)\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n weight = self.proj.weight\n bias = self.proj.bias\n return module.fused_gather_linear(x, weight, bias)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=8.34e-07 mean_abs_err=9.15e-08 max_rel_err=2.98e-05
turn 37.5s turn · 7.5s LLM · 0.0s tools · tokens in=3,346 · out=545 · total=3,926
reasoning
Correct! Now, to submit, I need to check static and then submit.
call → static_check
callstatic_check
{
"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_runtime.h>\n\n__global__ void fused_gather_linear_kernel(const float* x, const float* weight, const float* bias, float* output, int R, int B, int H, int K) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n int k = blockIdx.y * blockDim.y + threadIdx.y;\n if (b >= B || k >= K) return;\n \n float sum = bias[k];\n for (int r = 0; r < R; r++) {\n for (int h = 0; h < H; h++) {\n int x_idx = r * B * H + b * H + h;\n int w_idx = k * (R * H) + r * H + h;\n sum += x[x_idx] * weight[w_idx];\n }\n }\n output[b * K + k] = sum;\n}\n\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {\n int R = x.size(0);\n int B = x.size(1);\n int H = x.size(2);\n int K = weight.size(0);\n \n auto output = torch::empty({B, K}, x.options());\n \n dim3 block(16, 16);\n dim3 grid((B + 15) / 16, (K + 15) / 16);\n \n fused_gather_linear_kernel<<<grid, block>>>(\n x.data_ptr<float>(), weight.data_ptr<float>(), bias.data_ptr<float>(),\n output.data_ptr<float>(), R, B, H, K\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\n'''\n\nmodule = load_inline(\n name='fused_gather_linear',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['fused_gather_linear'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.proj = nn.Linear(4 * 32, 56, bias=True)\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n weight = self.proj.weight\n bias = self.proj.bias\n return module.fused_gather_linear(x, weight, bias)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 4248.8s turn · 17.9s LLM · 230.9s tools · tokens in=3,944 · out=545 · total=4,494 · FINAL
reasoning
Good, now submit.
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_runtime.h>\n\n__global__ void fused_gather_linear_kernel(const float* x, const float* weight, const float* bias, float* output, int R, int B, int H, int K) {\n int b = blockIdx.x * blockDim.x + threadIdx.x;\n int k = blockIdx.y * blockDim.y + threadIdx.y;\n if (b >= B || k >= K) return;\n \n float sum = bias[k];\n for (int r = 0; r < R; r++) {\n for (int h = 0; h < H; h++) {\n int x_idx = r * B * H + b * H + h;\n int w_idx = k * (R * H) + r * H + h;\n sum += x[x_idx] * weight[w_idx];\n }\n }\n output[b * K + k] = sum;\n}\n\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {\n int R = x.size(0);\n int B = x.size(1);\n int H = x.size(2);\n int K = weight.size(0);\n \n auto output = torch::empty({B, K}, x.options());\n \n dim3 block(16, 16);\n dim3 grid((B + 15) / 16, (K + 15) / 16);\n \n fused_gather_linear_kernel<<<grid, block>>>(\n x.data_ptr<float>(), weight.data_ptr<float>(), bias.data_ptr<float>(),\n output.data_ptr<float>(), R, B, H, K\n );\n \n return output;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);\n'''\n\nmodule = load_inline(\n name='fused_gather_linear',\n cpp_sources=cpp_source,\n cuda_sources=cuda_source,\n functions=['fused_gather_linear'],\n verbose=True\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super().__init__()\n self.proj = nn.Linear(4 * 32, 56, bias=True)\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n weight = self.proj.weight\n bias = self.proj.bias\n return module.fused_gather_linear(x, weight, bias)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 0.01 μs
Runtime stats: mean=0.01μs median=?μs std=0.00μs
Numerical precision: max_abs_err=8.34e-07 mean_abs_err=9.15e-08 max_rel_err=2.98e-05
Memory: 33.06 MB peak (ref: 33.07 MB, ratio: 0.9998x)
Kernel launches: 1 (ref: 14, fusion ratio: 14.0)
SOL score: 0.0017
final submitted kernel (66 lines, 1,873 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_runtime.h>
__global__ void fused_gather_linear_kernel(const float* x, const float* weight, const float* bias, float* output, int R, int B, int H, int K) {
int b = blockIdx.x * blockDim.x + threadIdx.x;
int k = blockIdx.y * blockDim.y + threadIdx.y;
if (b >= B || k >= K) return;
float sum = bias[k];
for (int r = 0; r < R; r++) {
for (int h = 0; h < H; h++) {
int x_idx = r * B * H + b * H + h;
int w_idx = k * (R * H) + r * H + h;
sum += x[x_idx] * weight[w_idx];
}
}
output[b * K + k] = sum;
}
torch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias) {
int R = x.size(0);
int B = x.size(1);
int H = x.size(2);
int K = weight.size(0);
auto output = torch::empty({B, K}, x.options());
dim3 block(16, 16);
dim3 grid((B + 15) / 16, (K + 15) / 16);
fused_gather_linear_kernel<<<grid, block>>>(
x.data_ptr<float>(), weight.data_ptr<float>(), bias.data_ptr<float>(),
output.data_ptr<float>(), R, B, H, K
);
return output;
}
'''
cpp_source = '''
torch::Tensor fused_gather_linear(torch::Tensor x, torch::Tensor weight, torch::Tensor bias);
'''
module = load_inline(
name='fused_gather_linear',
cpp_sources=cpp_source,
cuda_sources=cuda_source,
functions=['fused_gather_linear'],
verbose=True
)
class ModelNew(nn.Module):
def __init__(self):
super().__init__()
self.proj = nn.Linear(4 * 32, 56, bias=True)
def forward(self, x: torch.Tensor) -> torch.Tensor:
weight = self.proj.weight
bias = self.proj.bias
return module.fused_gather_linear(x, weight, bias)