gpt-5.5-priority · original · l12_default_gpt
correct 53_Gemm_Scaling_Hardtanh_GELU.py
model
gpt-5.5-priority
turns / max
10 / 10
tool calls
10
tokens (total)
0
wall clock
—
truncated
no
backend
cuda fp32
variant
original
runtime
5.44 μs
ref runtime
5.53 μs
speedup
1.02x
started
2026-05-02T05:47:11Z
timingkernelbench.timing
kernel runtime
5.44 μs
ref runtime
5.53 μs
speedup
1.02x
kernel mean / median / std
5.44 / — / 0.01 μs
ref mean / median / std
5.53 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
max abs error
0.00
mean abs error
0.00
max rel error
0.00
mean rel error
0.00
gpu memoryextended_metrics.measure_memory
kernel peak
673.06 MB
ref peak
737.06 MB
kernel / ref
0.91x
kernel launches / fusiontorch.profiler
kernel launches
1
ref launches
13
fusion ratio (ref / kernel)
13.00x
total cuda time
22 μs
energyNVML (pynvml)
kernel mJ / run
755.14
ref mJ / run
755.18
ratio (ref / kernel)
1.00x
avg power
138.83 W
ref avg power
136.59 W
SOL (speed-of-light)nsight_hardware_counters
SOL score (0–1)
0.590
dram util %
59.0%
compute util %
5.2%
bottleneck
memory-bound
dominant pipe
tensor-core
arithmetic intensity
—
ridge point
295.22
roofline / occupancynsight_hardware_counters
dram bandwidth
1977.18 GB/s
dram util %
59.0%
fp32 tflops
—
fp32 util %
—
fp16 tflops
—
occupancy %
87.8%
bottleneck
memory-bound
dominant pipe %
5.2%
arithmetic intensity
—
ridge point
295.22
L1 hit %
—
L2 hit %
143.3%
ld sectors / req
8.00
st sectors / req
—
regs / thread
270
smem / block
35840 B
block size
384
peak bw
3350.00 GB/s
peak fp32 tflops
67.00
peak fp16 tflops
1979.00
warp stalls (top 5)nsight
long_scoreboard
1495.0%
short_scoreboard
172.8%
mio_throttle
16.1%
reference PyTorch source (the prompt the agent sees)
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Model that performs a GEMM, scaling, hardtanh, and GELU activation.
    """
    def __init__(self, in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max):
        super(Model, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.scaling_factor = scaling_factor
        self.hardtanh = nn.Hardtanh(min_val=hardtanh_min, max_val=hardtanh_max)
        self.gelu = nn.GELU()

    def forward(self, x):
        x = self.gemm(x)
        x = x * self.scaling_factor
        x = self.hardtanh(x)
        x = self.gelu(x)
        return x

batch_size = 2048
in_features = 8192
out_features = 8192
scaling_factor = 0.5
hardtanh_min = -2
hardtanh_max = 2

def get_inputs():
    return [torch.rand(batch_size, in_features)]

def get_init_inputs():
    return [in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max]
turn 07.4s turn · 7.4s LLM · 0.0s tools
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 123.1s turn · 23.1s LLM · 0.0s tools
reasoning
**Evaluating CUDA and CPP Integration** I’m considering how to include torch extensions in the C++ source by declaring functions and implementations. If those functions are in CUDA, will they be recognized by the auto-generated pybind in the main cpp? Typically, C++ wrappers and CUDA kernels are organized in their respective sources. I want to write a single source for CUDA. I need to define the function `torch::Tensor forward(...)` and ensure all elements are contiguous, especially if the model is to move to the GPU. There’s a lot to unpack!
call → compile_kernel
callcompile_kernel { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n\n__global__ void bias_scale_clamp_gelu_kernel(float* __restrict__ y, const float* __restrict__ bias,\n long total, int N, float scale, float minv, float maxv) {\n long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;\n long stride = (long)blockDim.x * gridDim.x;\n const float inv_sqrt2 = 0.70710678118654752440f;\n for (; idx < total; idx += stride) {\n int col = (int)(idx % N);\n float v = (y[idx] + bias[col]) * scale;\n v = fminf(fmaxf(v, minv), maxv);\n float g = 0.5f * v * (1.0f + erff(v * inv_sqrt2));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv) {\n TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(), \"tensors must be cuda\");\n TORCH_CHECK(x.scalar_type() == torch::kFloat32 && weight.scalar_type() == torch::kFloat32 && bias.scalar_type() == torch::kFloat32, \"fp32 only\");\n TORCH_CHECK(x.dim() == 2 && weight.dim() == 2, \"2d tensors expected\");\n const int64_t M64 = x.size(0);\n const int64_t K64 = x.size(1);\n const int64_t N64 = weight.size(0);\n TORCH_CHECK(weight.size(1) == K64 && bias.numel() == N64, \"shape mismatch\");\n TORCH_CHECK(M64 <= INT_MAX && N64 <= INT_MAX && K64 <= INT_MAX, \"dims too large\");\n int M = (int)M64, N = (int)N64, K = (int)K64;\n auto y = torch::empty({M64, N64}, x.options());\n\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n cublasSetStream(handle, stream);\n cublasSetMathMode(handle, CUBLAS_TF32_TENSOR_OP_MATH);\n float alpha = 1.0f, beta = 0.0f;\n // Row-major y[M,N] is column-major [N,M]. Compute y^T = weight * x^T.\n cublasStatus_t stat = cublasSgemm(handle, CUBLAS_OP_T, CUBLAS_OP_N,\n N, M, K,\n &alpha,\n weight.data_ptr<float>(), K,\n x.data_ptr<float>(), K,\n &beta,\n y.data_ptr<float>(), N);\n TORCH_CHECK(stat == CUBLAS_STATUS_SUCCESS, \"cublasSgemm failed\");\n\n long total = M64 * N64;\n int threads = 256;\n int blocks = (int)((total + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n bias_scale_clamp_gelu_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), total, N, (float)scale, (float)minv, (float)maxv);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(name='fused_linear_act_ext_v1', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['fused_linear_act'], extra_cuda_cflags=['-O3', '--use_fast_math'], extra_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(in_features, out_features)\n self.scaling_factor = scaling_factor\n self.hardtanh_min = hardtanh_min\n self.hardtanh_max = hardtanh_max\n def forward(self, x):\n return _ext.fused_linear_act(x, self.gemm.weight, self.gemm.bias, float(self.scaling_factor), float(self.hardtanh_min), float(self.hardtanh_max))\n" }
result ← compile_kernel (ok)
okcompile_kernel compile_kernel PASSED: kernel compiled without errors.
turn 211.8s turn · 11.8s LLM · 0.0s tools
call → run_correctness
callrun_correctness { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n\n__global__ void bias_scale_clamp_gelu_kernel(float* __restrict__ y, const float* __restrict__ bias,\n long total, int N, float scale, float minv, float maxv) {\n long idx = (long)blockIdx.x * blockDim.x + threadIdx.x;\n long stride = (long)blockDim.x * gridDim.x;\n const float inv_sqrt2 = 0.70710678118654752440f;\n for (; idx < total; idx += stride) {\n int col = (int)(idx % N);\n float v = (y[idx] + bias[col]) * scale;\n v = fminf(fmaxf(v, minv), maxv);\n float g = 0.5f * v * (1.0f + erff(v * inv_sqrt2));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv) {\n TORCH_CHECK(x.is_cuda() && weight.is_cuda() && bias.is_cuda(), \"tensors must be cuda\");\n TORCH_CHECK(x.scalar_type() == torch::kFloat32 && weight.scalar_type() == torch::kFloat32 && bias.scalar_type() == torch::kFloat32, \"fp32 only\");\n TORCH_CHECK(x.dim() == 2 && weight.dim() == 2, \"2d tensors expected\");\n const int64_t M64 = x.size(0);\n const int64_t K64 = x.size(1);\n const int64_t N64 = weight.size(0);\n TORCH_CHECK(weight.size(1) == K64 && bias.numel() == N64, \"shape mismatch\");\n TORCH_CHECK(M64 <= INT_MAX && N64 <= INT_MAX && K64 <= INT_MAX, \"dims too large\");\n int M = (int)M64, N = (int)N64, K = (int)K64;\n auto y = torch::empty({M64, N64}, x.options());\n\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n cublasSetStream(handle, stream);\n cublasSetMathMode(handle, CUBLAS_TF32_TENSOR_OP_MATH);\n float alpha = 1.0f, beta = 0.0f;\n // Row-major y[M,N] is column-major [N,M]. Compute y^T = weight * x^T.\n cublasStatus_t stat = cublasSgemm(handle, CUBLAS_OP_T, CUBLAS_OP_N,\n N, M, K,\n &alpha,\n weight.data_ptr<float>(), K,\n x.data_ptr<float>(), K,\n &beta,\n y.data_ptr<float>(), N);\n TORCH_CHECK(stat == CUBLAS_STATUS_SUCCESS, \"cublasSgemm failed\");\n\n long total = M64 * N64;\n int threads = 256;\n int blocks = (int)((total + threads - 1) / threads);\n if (blocks > 65535) blocks = 65535;\n bias_scale_clamp_gelu_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), total, N, (float)scale, (float)minv, (float)maxv);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(name='fused_linear_act_ext_v1', cpp_sources=[_cpp_src], cuda_sources=[_cuda_src], functions=['fused_linear_act'], extra_cuda_cflags=['-O3', '--use_fast_math'], extra_cflags=['-O3'], verbose=False)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(in_features, out_features)\n self.scaling_factor = scaling_factor\n self.hardtanh_min = hardtanh_min\n self.hardtanh_max = hardtanh_max\n def forward(self, x):\n return _ext.fused_linear_act(x, self.gemm.weight, self.gemm.bias, float(self.scaling_factor), float(self.hardtanh_min), float(self.hardtanh_max))\n" }
result ← run_correctness (fail)
failrun_correctness run_correctness FAILED: (0 / 5) trials did not all match. correctness_issue: Output mismatch max_difference: ['0.000180', '0.000175', '0.000173', '0.000178', '0.000197'] avg_difference: ['0.000019', '0.000019', '0.000019', '0.000019', '0.000019']
turn 37.6s turn · 7.6s LLM · 0.0s tools
call → run_correctness
callrun_correctness { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void k(float* __restrict__ y,const float* __restrict__ bias,long total,int N,float scale,float minv,float maxv){long idx=(long)blockIdx.x*blockDim.x+threadIdx.x; long stride=(long)blockDim.x*gridDim.x; const float inv=0.70710678118654752440f; for(;idx<total;idx+=stride){int col=(int)(idx%N); float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=M64,N=N64,Kd=K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); cublasSetMathMode(h,CUBLAS_DEFAULT_MATH); float alpha=1,beta=0; auto st=cublasSgemm(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,Kd,&alpha,weight.data_ptr<float>(),Kd,x.data_ptr<float>(),Kd,&beta,y.data_ptr<float>(),N); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"sgemm\"); long total=M64*N64; int threads=256, blocks=(int)((total+threads-1)/threads); if(blocks>65535)blocks=65535; k<<<blocks,threads,0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),total,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_v2',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x):\n return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) 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 415.0s turn · 15.0s LLM · 0.0s tools
call → run_correctness
callrun_correctness { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void act2d(float* __restrict__ y,const float* __restrict__ bias,int M,int N,float scale,float minv,float maxv){int col=blockIdx.x*blockDim.x+threadIdx.x; int row=blockIdx.y; if(col<N && row<M){long idx=(long)row*N+col; const float inv=0.70710678118654752440f; float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){TORCH_CHECK(x.is_cuda(),\"cuda\"); int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=(int)M64,N=(int)N64,K=(int)K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); cublasSetMathMode(h,CUBLAS_DEFAULT_MATH); float alpha=1.f,beta=0.f; cublasStatus_t st=cublasSgemm(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,K,&alpha,weight.data_ptr<float>(),K,x.data_ptr<float>(),K,&beta,y.data_ptr<float>(),N); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"sgemm\"); dim3 block(256); dim3 grid((N+255)/256,M); act2d<<<grid,block,0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),M,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_v3',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x):\n return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) 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 512.2s turn · 12.2s LLM · 0.0s tools
call → static_check
callstatic_check { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void act2d(float* __restrict__ y,const float* __restrict__ bias,int M,int N,float scale,float minv,float maxv){int col=blockIdx.x*blockDim.x+threadIdx.x; int row=blockIdx.y; if(col<N && row<M){long idx=(long)row*N+col; const float inv=0.70710678118654752440f; float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){TORCH_CHECK(x.is_cuda(),\"cuda\"); int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=(int)M64,N=(int)N64,K=(int)K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); cublasSetMathMode(h,CUBLAS_DEFAULT_MATH); float alpha=1.f,beta=0.f; cublasStatus_t st=cublasSgemm(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,K,&alpha,weight.data_ptr<float>(),K,x.data_ptr<float>(),K,&beta,y.data_ptr<float>(),N); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"sgemm\"); dim3 block(256); dim3 grid((N+255)/256,M); act2d<<<grid,block,0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),M,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_v3',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x):\n return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← static_check (ok)
okstatic_check static_check PASSED: no violations or warnings detected.
turn 67.5s turn · 7.5s LLM · 0.0s tools
call → run_correctness
callrun_correctness { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void act2d(float* __restrict__ y,const float* __restrict__ bias,int M,int N,float scale,float minv,float maxv){int col=blockIdx.x*blockDim.x+threadIdx.x; int row=blockIdx.y; if(col<N && row<M){long idx=(long)row*N+col; const float inv=0.70710678118654752440f; float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=(int)M64,N=(int)N64,K=(int)K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); cublasSetMathMode(h,CUBLAS_DEFAULT_MATH); float alpha=1.f,beta=0.f; auto st=cublasSgemm(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,K,&alpha,weight.data_ptr<float>(),K,x.data_ptr<float>(),K,&beta,y.data_ptr<float>(),N); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"sgemm\"); act2d<<<dim3((N+255)/256,M),dim3(256),0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),M,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_v4',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3','--use_fast_math'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x):\n return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) 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 712.3s turn · 12.3s LLM · 0.0s tools
call → run_correctness
callrun_correctness { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void act2d(float* __restrict__ y,const float* __restrict__ bias,int M,int N,float scale,float minv,float maxv){int col=blockIdx.x*blockDim.x+threadIdx.x; int row=blockIdx.y; if(col<N){long idx=(long)row*N+col; const float inv=0.70710678118654752440f; float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=(int)M64,N=(int)N64,K=(int)K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); float alpha=1.f,beta=0.f; auto st=cublasGemmEx(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,K,&alpha,weight.data_ptr<float>(),CUDA_R_32F,K,x.data_ptr<float>(),CUDA_R_32F,K,&beta,y.data_ptr<float>(),CUDA_R_32F,N,CUBLAS_COMPUTE_32F,CUBLAS_GEMM_DEFAULT); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"gemmex\"); act2d<<<dim3((N+255)/256,M),dim3(256),0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),M,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_v5',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3','--use_fast_math'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x): return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← run_correctness (ok)
okrun_correctness run_correctness PASSED: (5 / 5) 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 89.5s turn · 9.5s LLM · 0.0s tools
call → static_check
callstatic_check { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n_cpp_src=r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n_cuda_src=r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n__global__ void act2d(float* __restrict__ y,const float* __restrict__ bias,int M,int N,float scale,float minv,float maxv){int col=blockIdx.x*blockDim.x+threadIdx.x; int row=blockIdx.y; if(col<N){long idx=(long)row*N+col; const float inv=0.70710678118654752440f; float v=(y[idx]+bias[col])*scale; v=fminf(fmaxf(v,minv),maxv); y[idx]=0.5f*v*(1.0f+erff(v*inv));}}\ntorch::Tensor fused_linear_act(torch::Tensor x,torch::Tensor weight,torch::Tensor bias,double scale,double minv,double maxv){int64_t M64=x.size(0),K64=x.size(1),N64=weight.size(0); int M=(int)M64,N=(int)N64,K=(int)K64; auto y=torch::empty({M64,N64},x.options()); cublasHandle_t h=at::cuda::getCurrentCUDABlasHandle(); cudaStream_t s=at::cuda::getCurrentCUDAStream(); cublasSetStream(h,s); float alpha=1.f,beta=0.f; auto st=cublasGemmEx(h,CUBLAS_OP_T,CUBLAS_OP_N,N,M,K,&alpha,weight.data_ptr<float>(),CUDA_R_32F,K,x.data_ptr<float>(),CUDA_R_32F,K,&beta,y.data_ptr<float>(),CUDA_R_32F,N,CUBLAS_COMPUTE_32F,CUBLAS_GEMM_DEFAULT); TORCH_CHECK(st==CUBLAS_STATUS_SUCCESS,\"gemmex\"); act2d<<<dim3((N+255)/256,M),dim3(256),0,s>>>(y.data_ptr<float>(),bias.data_ptr<float>(),M,N,(float)scale,(float)minv,(float)maxv); C10_CUDA_KERNEL_LAUNCH_CHECK(); return y;}\n'''\n_ext=load_inline(name='fused_linear_act_ext_final',cpp_sources=[_cpp_src],cuda_sources=[_cuda_src],functions=['fused_linear_act'],extra_cuda_cflags=['-O3','--use_fast_math'],extra_cflags=['-O3'],verbose=False)\nclass ModelNew(nn.Module):\n def __init__(self,in_features,out_features,scaling_factor,hardtanh_min,hardtanh_max):\n super().__init__(); self.gemm=nn.Linear(in_features,out_features); self.scaling_factor=scaling_factor; self.hardtanh_min=hardtanh_min; self.hardtanh_max=hardtanh_max\n def forward(self,x): return _ext.fused_linear_act(x,self.gemm.weight,self.gemm.bias,float(self.scaling_factor),float(self.hardtanh_min),float(self.hardtanh_max))\n" }
result ← static_check (ok)
okstatic_check static_check PASSED: no violations or warnings detected.
turn 96.6s turn · 6.6s LLM · 0.0s tools · FINAL
call → submit_kernel
callsubmit_kernel { "kernel_code": "import torch\nimport torch.nn as nn\nfrom torch.utils.cpp_extension import load_inline\n\n_cpp_src = r'''\n#include <torch/extension.h>\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);\n'''\n\n_cuda_src = r'''\n#include <torch/extension.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cublas_v2.h>\n#include <cmath>\n\n__global__ void act2d(float* __restrict__ y, const float* __restrict__ bias,\n int M, int N, float scale, float minv, float maxv) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < N) {\n long idx = (long)row * N + col;\n const float inv_sqrt2 = 0.70710678118654752440f;\n float v = (y[idx] + bias[col]) * scale;\n v = fminf(fmaxf(v, minv), maxv);\n y[idx] = 0.5f * v * (1.0f + erff(v * inv_sqrt2));\n }\n}\n\ntorch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias,\n double scale, double minv, double maxv) {\n int64_t M64 = x.size(0), K64 = x.size(1), N64 = weight.size(0);\n int M = (int)M64, N = (int)N64, K = (int)K64;\n auto y = torch::empty({M64, N64}, x.options());\n\n cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n cublasSetStream(handle, stream);\n\n float alpha = 1.0f, beta = 0.0f;\n // Treat row-major tensors as column-major transposes: y^T = weight * x^T.\n cublasStatus_t stat = cublasGemmEx(handle,\n CUBLAS_OP_T, CUBLAS_OP_N,\n N, M, K,\n &alpha,\n weight.data_ptr<float>(), CUDA_R_32F, K,\n x.data_ptr<float>(), CUDA_R_32F, K,\n &beta,\n y.data_ptr<float>(), CUDA_R_32F, N,\n CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);\n TORCH_CHECK(stat == CUBLAS_STATUS_SUCCESS, \"cublasGemmEx failed\");\n\n dim3 block(256);\n dim3 grid((N + 255) / 256, M);\n act2d<<<grid, block, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(),\n M, N, (float)scale, (float)minv, (float)maxv);\n C10_CUDA_KERNEL_LAUNCH_CHECK();\n return y;\n}\n'''\n\n_ext = load_inline(\n name='fused_linear_act_ext_submit',\n cpp_sources=[_cpp_src],\n cuda_sources=[_cuda_src],\n functions=['fused_linear_act'],\n extra_cuda_cflags=['-O3', '--use_fast_math'],\n extra_cflags=['-O3'],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max):\n super(ModelNew, self).__init__()\n self.gemm = nn.Linear(in_features, out_features)\n self.scaling_factor = scaling_factor\n self.hardtanh_min = hardtanh_min\n self.hardtanh_max = hardtanh_max\n\n def forward(self, x):\n return _ext.fused_linear_act(\n x, self.gemm.weight, self.gemm.bias,\n float(self.scaling_factor), float(self.hardtanh_min), float(self.hardtanh_max)\n )\n" }
result ← submit_kernel (ok)
oksubmit_kernel submit_kernel PASSED: (5 / 5) correctness trials all passed. Kernel runtime: 5.44 μs Runtime stats: mean=5.44μ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: 673.06 MB peak (ref: 737.06 MB, ratio: 0.9132x) Kernel launches: 1 (ref: 13, fusion ratio: 13.0) Energy: 755.14 mJ/run (ref: 755.18 mJ, ratio: 1.0001x) SOL score: 0.5902
final submitted kernel (86 lines, 3,033 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 fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias, double scale, double minv, double maxv);
'''

_cuda_src = r'''
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cublas_v2.h>
#include <cmath>

__global__ void act2d(float* __restrict__ y, const float* __restrict__ bias,
                      int M, int N, float scale, float minv, float maxv) {
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    int row = blockIdx.y;
    if (col < N) {
        long idx = (long)row * N + col;
        const float inv_sqrt2 = 0.70710678118654752440f;
        float v = (y[idx] + bias[col]) * scale;
        v = fminf(fmaxf(v, minv), maxv);
        y[idx] = 0.5f * v * (1.0f + erff(v * inv_sqrt2));
    }
}

torch::Tensor fused_linear_act(torch::Tensor x, torch::Tensor weight, torch::Tensor bias,
                               double scale, double minv, double maxv) {
    int64_t M64 = x.size(0), K64 = x.size(1), N64 = weight.size(0);
    int M = (int)M64, N = (int)N64, K = (int)K64;
    auto y = torch::empty({M64, N64}, x.options());

    cublasHandle_t handle = at::cuda::getCurrentCUDABlasHandle();
    cudaStream_t stream = at::cuda::getCurrentCUDAStream();
    cublasSetStream(handle, stream);

    float alpha = 1.0f, beta = 0.0f;
    // Treat row-major tensors as column-major transposes: y^T = weight * x^T.
    cublasStatus_t stat = cublasGemmEx(handle,
        CUBLAS_OP_T, CUBLAS_OP_N,
        N, M, K,
        &alpha,
        weight.data_ptr<float>(), CUDA_R_32F, K,
        x.data_ptr<float>(), CUDA_R_32F, K,
        &beta,
        y.data_ptr<float>(), CUDA_R_32F, N,
        CUBLAS_COMPUTE_32F, CUBLAS_GEMM_DEFAULT);
    TORCH_CHECK(stat == CUBLAS_STATUS_SUCCESS, "cublasGemmEx failed");

    dim3 block(256);
    dim3 grid((N + 255) / 256, M);
    act2d<<<grid, block, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(),
                                      M, N, (float)scale, (float)minv, (float)maxv);
    C10_CUDA_KERNEL_LAUNCH_CHECK();
    return y;
}
'''

_ext = load_inline(
    name='fused_linear_act_ext_submit',
    cpp_sources=[_cpp_src],
    cuda_sources=[_cuda_src],
    functions=['fused_linear_act'],
    extra_cuda_cflags=['-O3', '--use_fast_math'],
    extra_cflags=['-O3'],
    verbose=False,
)

class ModelNew(nn.Module):
    def __init__(self, in_features, out_features, scaling_factor, hardtanh_min, hardtanh_max):
        super(ModelNew, self).__init__()
        self.gemm = nn.Linear(in_features, out_features)
        self.scaling_factor = scaling_factor
        self.hardtanh_min = hardtanh_min
        self.hardtanh_max = hardtanh_max

    def forward(self, x):
        return _ext.fused_linear_act(
            x, self.gemm.weight, self.gemm.bias,
            float(self.scaling_factor), float(self.hardtanh_min), float(self.hardtanh_max)
        )