correct
68_Matmul_Min_Subtract.py
started
2026-05-05T02:03:52Z
timingkernelbench.timing
kernel mean / median / std
1.43 / — / 0.00 μs
ref mean / median / std
1.44 / — / 0.00 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
2.00x
energyNVML (pynvml)
ratio (ref / kernel)
1.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1905.36 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 matrix multiplication, applies minimum, and subtracts a constant.
"""
def __init__(self, in_features, out_features, constant):
super(Model, self).__init__()
self.linear = nn.Linear(in_features, out_features)
self.constant = nn.Parameter(torch.tensor(constant))
def forward(self, x):
x = self.linear(x)
x = torch.min(x, self.constant)
x = x - self.constant
return x
batch_size = 128
in_features = 16384
out_features = 16384
constant = 2.0
def get_inputs():
return [torch.rand(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, constant]turn 032.0s turn · 32.0s LLM · 0.0s tools · FINAL
reasoning
**Considering wrapper implementation**
I'm trying to understand if using `at::linear` inside C++ with PyTorch is still okay. I think I need to use `load_inline` while avoiding my own PYBIND. Implementing a wrapper in `cpp_sources` seems like the next step. It sounds like `load_inline` with `cuda_sources` can include the C++ host. I need to make sure to utilize the functions list and confirm that no PYBIND is necessary for this implementation.
**Exploring PyTorch Performance**
I’m considering the PyTorch reference, particularly with constant parameter scalar broadcasts. It seems like using torch.min(x, constant) could potentially involve just one kernel call, which might execute in under a second. It’s intriguing how this fused operation could save around 16 MB in read and write, making it more efficient. I want to make sure I understand how this helps with performance optimization!
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\n\ntorch::Tensor linear_min_sub(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor constant);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <c10/cuda/CUDAGuard.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n\n__global__ void min_sub_kernel(float* __restrict__ y, const float* __restrict__ cptr, long long n) {\n const float c = __ldg(cptr);\n long long i4 = (long long)(blockIdx.x) * blockDim.x + threadIdx.x;\n long long n4 = n >> 2;\n float4* __restrict__ y4 = reinterpret_cast<float4*>(y);\n for (long long i = i4; i < n4; i += (long long)blockDim.x * gridDim.x) {\n float4 v = y4[i];\n v.x = fminf(v.x, c) - c;\n v.y = fminf(v.y, c) - c;\n v.z = fminf(v.z, c) - c;\n v.w = fminf(v.w, c) - c;\n y4[i] = v;\n }\n long long base = n4 << 2;\n for (long long j = base + i4; j < n; j += (long long)blockDim.x * gridDim.x) {\n float v = y[j];\n y[j] = fminf(v, c) - c;\n }\n}\n\ntorch::Tensor linear_min_sub(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor constant) {\n c10::cuda::CUDAGuard device_guard(x.device());\n // Equivalent to torch.nn.functional.linear(x, weight, bias). weight.t() is a view;\n // addmm dispatches to cuBLAS/cuBLASLt for the large GEMM.\n torch::Tensor out = at::addmm(bias, x, weight.t());\n\n const long long n = out.numel();\n if (n > 0) {\n const int threads = 256;\n long long work = (n + 3) >> 2;\n int blocks = (int)((work + threads - 1) / threads);\n if (blocks > 4096) blocks = 4096;\n min_sub_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(\n out.data_ptr<float>(), constant.data_ptr<float>(), n);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n }\n return out;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"linear_min_sub_ext_v1\",\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=[\"linear_min_sub\"],\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, in_features, out_features, constant):\n super(ModelNew, self).__init__()\n self.linear = nn.Linear(in_features, out_features)\n self.constant = nn.Parameter(torch.tensor(constant))\n\n def forward(self, x):\n return _ext.linear_min_sub(x, self.linear.weight, self.linear.bias, self.constant)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 1.43 μs
Runtime stats: mean=1.43μs median=?μs std=0.00μs
Numerical precision: max_abs_err=0.00e+00 mean_abs_err=0.00e+00 max_rel_err=0.00e+00
Memory: 2097.13 MB peak (ref: 2105.13 MB, ratio: 0.9962x)
Kernel launches: 4 (ref: 8, fusion ratio: 2.0)
Energy: 241.78 mJ/run (ref: 241.8 mJ, ratio: 1.0001x)
SOL score: 0.8701
final submitted kernel (79 lines, 2,594 chars) — full source, untruncated
import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
_cpp_src = r"""
#include <torch/extension.h>
torch::Tensor linear_min_sub(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor constant);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDAGuard.h>
#include <cuda.h>
#include <cuda_runtime.h>
__global__ void min_sub_kernel(float* __restrict__ y, const float* __restrict__ cptr, long long n) {
const float c = __ldg(cptr);
long long i4 = (long long)(blockIdx.x) * blockDim.x + threadIdx.x;
long long n4 = n >> 2;
float4* __restrict__ y4 = reinterpret_cast<float4*>(y);
for (long long i = i4; i < n4; i += (long long)blockDim.x * gridDim.x) {
float4 v = y4[i];
v.x = fminf(v.x, c) - c;
v.y = fminf(v.y, c) - c;
v.z = fminf(v.z, c) - c;
v.w = fminf(v.w, c) - c;
y4[i] = v;
}
long long base = n4 << 2;
for (long long j = base + i4; j < n; j += (long long)blockDim.x * gridDim.x) {
float v = y[j];
y[j] = fminf(v, c) - c;
}
}
torch::Tensor linear_min_sub(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, torch::Tensor constant) {
c10::cuda::CUDAGuard device_guard(x.device());
// Equivalent to torch.nn.functional.linear(x, weight, bias). weight.t() is a view;
// addmm dispatches to cuBLAS/cuBLASLt for the large GEMM.
torch::Tensor out = at::addmm(bias, x, weight.t());
const long long n = out.numel();
if (n > 0) {
const int threads = 256;
long long work = (n + 3) >> 2;
int blocks = (int)((work + threads - 1) / threads);
if (blocks > 4096) blocks = 4096;
min_sub_kernel<<<blocks, threads, 0, at::cuda::getCurrentCUDAStream()>>>(
out.data_ptr<float>(), constant.data_ptr<float>(), n);
C10_CUDA_KERNEL_LAUNCH_CHECK();
}
return out;
}
"""
_ext = load_inline(
name="linear_min_sub_ext_v1",
cpp_sources=[_cpp_src],
cuda_sources=[_cuda_src],
functions=["linear_min_sub"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
extra_cflags=["-O3"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, in_features, out_features, constant):
super(ModelNew, self).__init__()
self.linear = nn.Linear(in_features, out_features)
self.constant = nn.Parameter(torch.tensor(constant))
def forward(self, x):
return _ext.linear_min_sub(x, self.linear.weight, self.linear.bias, self.constant)