correct
1_Square_matrix_multiplication_.py
started
2026-05-10T23:28:09Z
timingkernelbench.timing
kernel mean / median / std
15.40 / — / 0.01 μs
ref mean / median / std
2.66 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
0.50x
energyNVML (pynvml)
ratio (ref / kernel)
0.19x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
2667.94 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):
"""
Simple model that performs a single square matrix multiplication (C = A * B)
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, A: torch.Tensor, B: torch.Tensor) -> torch.Tensor:
"""
Performs the matrix multiplication.
Args:
A (torch.Tensor): Input matrix A of shape (N, N).
B (torch.Tensor): Input matrix B of shape (N, N).
Returns:
torch.Tensor: Output matrix C of shape (N, N).
"""
return torch.matmul(A, B)
N = 2048 * 2
def get_inputs():
A = torch.rand(N, N)
B = torch.rand(N, N)
return [A, B]
def get_init_inputs():
return [] # No special initialization inputs neededturn 06.2s turn · 6.2s LLM · 0.0s tools · tokens in=1,960 · out=6 · total=2,209
reasoning
The task is to replace the forward computation of a PyTorch model that does matrix multiplication with a custom CUDA kernel. The model is simple: just torch.matmul(A, B) for two N x N matrices where N...
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 191.2s turn · 18.7s LLM · 72.5s tools · tokens in=2,442 · out=624 · total=3,230
reasoning
It's an H100, with high bandwidth and TFLOPS.
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#define TILE_SIZE 16\n\n__global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {\n __shared__ float As[TILE_SIZE][TILE_SIZE];\n __shared__ float Bs[TILE_SIZE][TILE_SIZE];\n\n int row = blockIdx.y * TILE_SIZE + threadIdx.y;\n int col = blockIdx.x * TILE_SIZE + threadIdx.x;\n\n float sum = 0.0f;\n\n for (int t = 0; t < (N + TILE_SIZE - 1) / TILE_SIZE; ++t) {\n if (row < N && t * TILE_SIZE + threadIdx.x < N) {\n As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE_SIZE + threadIdx.x];\n } else {\n As[threadIdx.y][threadIdx.x] = 0.0f;\n }\n if (col < N && t * TILE_SIZE + threadIdx.y < N) {\n Bs[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * N + col];\n } else {\n Bs[threadIdx.y][threadIdx.x] = 0.0f;\n }\n __syncthreads();\n\n for (int k = 0; k < TILE_SIZE; ++k) {\n sum += As[threadIdx.y][k] * Bs[k][threadIdx.x];\n }\n __syncthreads();\n }\n\n if (row < N && col < N) {\n C[row * N + col] = sum;\n }\n}\n\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {\n int N = A.size(0);\n auto C = torch::zeros({N, N}, A.options());\n dim3 block(TILE_SIZE, TILE_SIZE);\n dim3 grid((N + TILE_SIZE - 1) / TILE_SIZE, (N + TILE_SIZE - 1) / TILE_SIZE);\n matmul_kernel<<<grid, block>>>(A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);\n return C;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);\n'''\n\nmodule = load_inline(\n name='custom_matmul',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['matmul_cuda'],\n verbose=True,\n extra_cuda_cflags=['-O3']\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n self.module = module\n \n def forward(self, A, B):\n return self.module.matmul_cuda(A, B)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 279.8s turn · 6.7s LLM · 73.1s tools · tokens in=3,247 · out=625 · total=3,879
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#define TILE_SIZE 16\n\n__global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {\n __shared__ float As[TILE_SIZE][TILE_SIZE];\n __shared__ float Bs[TILE_SIZE][TILE_SIZE];\n\n int row = blockIdx.y * TILE_SIZE + threadIdx.y;\n int col = blockIdx.x * TILE_SIZE + threadIdx.x;\n\n float sum = 0.0f;\n\n for (int t = 0; t < (N + TILE_SIZE - 1) / TILE_SIZE; ++t) {\n if (row < N && t * TILE_SIZE + threadIdx.x < N) {\n As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE_SIZE + threadIdx.x];\n } else {\n As[threadIdx.y][threadIdx.x] = 0.0f;\n }\n if (col < N && t * TILE_SIZE + threadIdx.y < N) {\n Bs[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * N + col];\n } else {\n Bs[threadIdx.y][threadIdx.x] = 0.0f;\n }\n __syncthreads();\n\n for (int k = 0; k < TILE_SIZE; ++k) {\n sum += As[threadIdx.y][k] * Bs[k][threadIdx.x];\n }\n __syncthreads();\n }\n\n if (row < N && col < N) {\n C[row * N + col] = sum;\n }\n}\n\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {\n int N = A.size(0);\n auto C = torch::zeros({N, N}, A.options());\n dim3 block(TILE_SIZE, TILE_SIZE);\n dim3 grid((N + TILE_SIZE - 1) / TILE_SIZE, (N + TILE_SIZE - 1) / TILE_SIZE);\n matmul_kernel<<<grid, block>>>(A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);\n return C;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);\n'''\n\nmodule = load_inline(\n name='custom_matmul',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['matmul_cuda'],\n verbose=False,\n extra_cuda_cflags=['-O3']\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n self.module = module\n \n def forward(self, A, B):\n return self.module.matmul_cuda(A, B)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (3 / 3) trials all matched the reference.
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
turn 399.3s turn · 9.6s LLM · 89.7s tools · tokens in=3,939 · out=624 · total=4,707
reasoning
Correct, but is it faster? With TILE=16, for N=4096, it's probably much slower than cuBLAS.
call → profile_kernel
callprofile_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#define TILE_SIZE 32\n\n__global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {\n __shared__ float As[TILE_SIZE][TILE_SIZE];\n __shared__ float Bs[TILE_SIZE][TILE_SIZE];\n\n int row = blockIdx.y * TILE_SIZE + threadIdx.y;\n int col = blockIdx.x * TILE_SIZE + threadIdx.x;\n\n float sum = 0.0f;\n\n for (int t = 0; t < (N + TILE_SIZE - 1) / TILE_SIZE; ++t) {\n if (row < N && t * TILE_SIZE + threadIdx.x < N) {\n As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE_SIZE + threadIdx.x];\n } else {\n As[threadIdx.y][threadIdx.x] = 0.0f;\n }\n if (col < N && t * TILE_SIZE + threadIdx.y < N) {\n Bs[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * N + col];\n } else {\n Bs[threadIdx.y][threadIdx.x] = 0.0f;\n }\n __syncthreads();\n\n for (int k = 0; k < TILE_SIZE; ++k) {\n sum += As[threadIdx.y][k] * Bs[k][threadIdx.x];\n }\n __syncthreads();\n }\n\n if (row < N && col < N) {\n C[row * N + col] = sum;\n }\n}\n\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {\n int N = A.size(0);\n auto C = torch::zeros({N, N}, A.options());\n dim3 block(TILE_SIZE, TILE_SIZE);\n dim3 grid((N + TILE_SIZE - 1) / TILE_SIZE, (N + TILE_SIZE - 1) / TILE_SIZE);\n matmul_kernel<<<grid, block>>>(A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);\n return C;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);\n'''\n\nmodule = load_inline(\n name='custom_matmul',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['matmul_cuda'],\n verbose=False,\n extra_cuda_cflags=['-O3']\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n self.module = module\n \n def forward(self, A, B):\n return self.module.matmul_cuda(A, B)\n"
}
result ← profile_kernel (ok)
okprofile_kernel
profile_kernel PASSED: profiling complete.
=== Kernel Profile Summary ===
--- Kernel Breakdown (by GPU time) ---
#1: aten::zeros 8483.0μs (34%) calls=1
#2: aten::zero_ 7919.0μs (32%) calls=1
#3: aten::fill_ 7893.0μs (32%) calls=1
#4: aten::empty 501.0μs (2%) calls=1
--- Timing ---
GPU time: 15393.31 μs
--- Memory Bandwidth ---
DRAM BW: 2655.2/3350 GB/s (79.3%)
read=548.3 write=2106.9 GB/s
Hit rates: L2=137.8%
--- Compute Throughput ---
Dominant pipe: FP32 util=18.3%
Pipe util: FMA=18.3%, Tensor=0.8%
--- Roofline Analysis ---
Ridge point (FP32): 20.00 FLOPs/byte
Classification: MEMORY-BOUND
--- Occupancy ---
Achieved: 183.9%
Eligible warps/cycle: 3.17
Launch: regs/thread=48, smem/blk=10240B, block=1152, grid=32768
--- Memory Access Quality ---
Global ld coalescing: 4.00 sectors/req (4.0x wasted BW)
--- Warp Stall Reasons (% of issue cycles) ---
mio_throttle 6588.2% ####################
short_scoreboard 3475.0% ####################
long_scoreboard 697.8% ####################
--- Optimization Hints ---
-> 6588% stalls: memory-instruction throttle. Too many outstanding memory ops; batch loads, reduce address divergence.
-> Global load coalescing=4.0x (ideal=1.0) -> 4x wasted DRAM BW. Make per-warp accesses contiguous.
turn 4174.3s turn · 13.8s LLM · 160.5s tools · tokens in=5,151 · out=624 · total=6,220 · FINAL
reasoning
This shows the kernel itself isn't even profiled properly because of zeros overhead? The matmul kernel is not listed in breakdown, probably because it's slow or something. Wait, GPU time 15ms but most...I need to replace the forward computation of a PyTorch model with a custom CUDA kernel. The model takes the same inputs as the original, implements forward with the same signature, and outputs a matrix multiplication result of shape (N, N), where N is 2048*2.
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#define TILE_SIZE 32\n\n__global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {\n __shared__ float As[TILE_SIZE][TILE_SIZE];\n __shared__ float Bs[TILE_SIZE][TILE_SIZE];\n\n int row = blockIdx.y * TILE_SIZE + threadIdx.y;\n int col = blockIdx.x * TILE_SIZE + threadIdx.x;\n\n float sum = 0.0f;\n\n for (int t = 0; t < (N + TILE_SIZE - 1) / TILE_SIZE; ++t) {\n if (row < N && t * TILE_SIZE + threadIdx.x < N) {\n As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE_SIZE + threadIdx.x];\n } else {\n As[threadIdx.y][threadIdx.x] = 0.0f;\n }\n if (col < N && t * TILE_SIZE + threadIdx.y < N) {\n Bs[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * N + col];\n } else {\n Bs[threadIdx.y][threadIdx.x] = 0.0f;\n }\n __syncthreads();\n\n for (int k = 0; k < TILE_SIZE; ++k) {\n sum += As[threadIdx.y][k] * Bs[k][threadIdx.x];\n }\n __syncthreads();\n }\n\n if (row < N && col < N) {\n C[row * N + col] = sum;\n }\n}\n\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {\n int N = A.size(0);\n auto C = torch::zeros({N, N}, A.options());\n dim3 block(TILE_SIZE, TILE_SIZE);\n dim3 grid((N + TILE_SIZE - 1) / TILE_SIZE, (N + TILE_SIZE - 1) / TILE_SIZE);\n matmul_kernel<<<grid, block>>>(A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);\n return C;\n}\n'''\n\ncpp_source = '''\ntorch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);\n'''\n\nmodule = load_inline(\n name='custom_matmul',\n cpp_sources=[cpp_source],\n cuda_sources=[cuda_source],\n functions=['matmul_cuda'],\n verbose=False,\n extra_cuda_cflags=['-O3']\n)\n\nclass ModelNew(nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n self.module = module\n \n def forward(self, A, B):\n return self.module.matmul_cuda(A, B)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (3 / 3) correctness trials all passed.
Kernel runtime: 15.40 μs
Runtime stats: mean=15.40μs median=?μs std=0.01μs
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
Memory: 224.0 MB peak (ref: 224.0 MB, ratio: 1.0x)
Kernel launches: 4 (ref: 2, fusion ratio: 0.5)
Energy: 6366.22 mJ/run (ref: 1188.72 mJ, ratio: 0.1867x)
SOL score: 0.7964
final submitted kernel (74 lines, 2,086 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>
#define TILE_SIZE 32
__global__ void matmul_kernel(const float* A, const float* B, float* C, int N) {
__shared__ float As[TILE_SIZE][TILE_SIZE];
__shared__ float Bs[TILE_SIZE][TILE_SIZE];
int row = blockIdx.y * TILE_SIZE + threadIdx.y;
int col = blockIdx.x * TILE_SIZE + threadIdx.x;
float sum = 0.0f;
for (int t = 0; t < (N + TILE_SIZE - 1) / TILE_SIZE; ++t) {
if (row < N && t * TILE_SIZE + threadIdx.x < N) {
As[threadIdx.y][threadIdx.x] = A[row * N + t * TILE_SIZE + threadIdx.x];
} else {
As[threadIdx.y][threadIdx.x] = 0.0f;
}
if (col < N && t * TILE_SIZE + threadIdx.y < N) {
Bs[threadIdx.y][threadIdx.x] = B[(t * TILE_SIZE + threadIdx.y) * N + col];
} else {
Bs[threadIdx.y][threadIdx.x] = 0.0f;
}
__syncthreads();
for (int k = 0; k < TILE_SIZE; ++k) {
sum += As[threadIdx.y][k] * Bs[k][threadIdx.x];
}
__syncthreads();
}
if (row < N && col < N) {
C[row * N + col] = sum;
}
}
torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B) {
int N = A.size(0);
auto C = torch::zeros({N, N}, A.options());
dim3 block(TILE_SIZE, TILE_SIZE);
dim3 grid((N + TILE_SIZE - 1) / TILE_SIZE, (N + TILE_SIZE - 1) / TILE_SIZE);
matmul_kernel<<<grid, block>>>(A.data_ptr<float>(), B.data_ptr<float>(), C.data_ptr<float>(), N);
return C;
}
'''
cpp_source = '''
torch::Tensor matmul_cuda(torch::Tensor A, torch::Tensor B);
'''
module = load_inline(
name='custom_matmul',
cpp_sources=[cpp_source],
cuda_sources=[cuda_source],
functions=['matmul_cuda'],
verbose=False,
extra_cuda_cflags=['-O3']
)
class ModelNew(nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
self.module = module
def forward(self, A, B):
return self.module.matmul_cuda(A, B)