correct
95_Matmul_Add_Swish_Tanh_GELU_Hardtanh.py
started
2026-05-02T18:15:26Z
timingkernelbench.timing
kernel mean / median / std
2.76 / — / 0.01 μs
ref mean / median / std
2.85 / — / 0.01 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
4.00x
energyNVML (pynvml)
ratio (ref / kernel)
1.00x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
1582.22 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, adds a value, applies Swish, Tanh, GELU, and Hardtanh activation functions.
"""
def __init__(self, in_features, out_features, add_value_shape):
super(Model, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.add_value = nn.Parameter(torch.randn(add_value_shape))
def forward(self, x):
x = self.matmul(x)
x = x + self.add_value
x = torch.sigmoid(x) * x # Swish
x = torch.tanh(x)
x = torch.nn.functional.gelu(x) # GELU
x = torch.nn.functional.hardtanh(x, min_val=-1, max_val=1) # Hardtanh
return x
batch_size = 1024
in_features = 8192
out_features = 8192
add_value_shape = (out_features,)
def get_inputs():
return [torch.rand(batch_size, in_features)]
def get_init_inputs():
return [in_features, out_features, add_value_shape]turn 010.2s turn · 10.2s LLM · 0.0s tools
reasoning
**Implementing activation functions**
I'm trying to implement a series of operations in C++. It starts with `auto out = at::matmul(input, weight.t());` and then I need to add biases and activate with functions like swish, tanh, and GELU. I recall that for torch's GELU, the default is approximate, but I want the exact version using the formula. I'm now wondering if using hardtanh will have any effect on the outcome. Let's reason this out clearly!
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 117.5s turn · 17.5s LLM · 0.0s tools
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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n long total, int ncols) {\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 j = (int)(idx % ncols);\n float v = y[idx] + bias[j] + addv[j];\n float s = 1.0f / (1.0f + expf(-v));\n float sw = v * s;\n float t = tanhf(sw);\n float g = 0.5f * t * (1.0f + erff(t * inv_sqrt2));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto wt = weight.t();\n auto y = at::mm(input, wt);\n const long total = y.numel();\n const int ncols = (int)y.size(1);\n const int threads = 256;\n int blocks = (int)((total + threads - 1) / threads);\n if (blocks > 32768) blocks = 32768;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), total, ncols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 25.1s turn · 5.1s 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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n long total, int ncols) {\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 j = (int)(idx % ncols);\n float v = y[idx] + bias[j] + addv[j];\n float s = 1.0f / (1.0f + expf(-v));\n float sw = v * s;\n float t = tanhf(sw);\n float g = 0.5f * t * (1.0f + erff(t * inv_sqrt2));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto wt = weight.t();\n auto y = at::mm(input, wt);\n const long total = y.numel();\n const int ncols = (int)y.size(1);\n const int threads = 256;\n int blocks = (int)((total + threads - 1) / threads);\n if (blocks > 32768) blocks = 32768;\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), total, ncols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v1\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=8.23e-06 mean_abs_err=7.99e-07 max_rel_err=1.41e-05
turn 314.7s turn · 14.7s LLM · 0.0s tools
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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n int rows, int cols) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < cols) {\n int idx = row * cols + col;\n float v = y[idx] + bias[col] + addv[col];\n float s = 1.0f / (1.0f + expf(-v));\n float t = tanhf(v * s);\n float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto y = at::mm(input, weight.t());\n const int rows = (int)y.size(0);\n const int cols = (int)y.size(1);\n const int threads = 256;\n dim3 blocks((cols + threads - 1) / threads, rows);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v2\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 45.2s turn · 5.2s 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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n int rows, int cols) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < cols) {\n int idx = row * cols + col;\n float v = y[idx] + bias[col] + addv[col];\n float s = 1.0f / (1.0f + expf(-v));\n float t = tanhf(v * s);\n float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto y = at::mm(input, weight.t());\n const int rows = (int)y.size(0);\n const int cols = (int)y.size(1);\n const int threads = 256;\n dim3 blocks((cols + threads - 1) / threads, rows);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v2\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=8.23e-06 mean_abs_err=7.99e-07 max_rel_err=1.41e-05
turn 56.2s turn · 6.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\n_cpp_src = r\"\"\"\n#include <torch/extension.h>\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n int rows, int cols) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < cols) {\n int idx = row * cols + col;\n float v = y[idx] + bias[col] + addv[col];\n float s = 1.0f / (1.0f + expf(-v));\n float t = tanhf(v * s);\n float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto y = at::mm(input, weight.t());\n const int rows = (int)y.size(0);\n const int cols = (int)y.size(1);\n const int threads = 256;\n dim3 blocks((cols + threads - 1) / threads, rows);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v2\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 67.9s turn · 7.9s LLM · 0.0s tools
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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n int rows, int cols) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < cols) {\n int idx = row * cols + col;\n float v = y[idx] + bias[col] + addv[col];\n float s = 1.0f / (1.0f + expf(-v));\n float t = tanhf(v * s);\n float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto y = at::mm(input, weight.t());\n const int rows = (int)y.size(0);\n const int cols = (int)y.size(1);\n const int threads = 256;\n dim3 blocks((cols + threads - 1) / threads, rows);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v2\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← submit_kernel (fail)
failsubmit_kernel
submit_kernel FAILED: unexpected error during tool execution.
_WorkItemTimeout: work item exceeded soft timeout budget
Traceback (most recent call last):
File "/scratch/tejas/PopcornBench/src/kernelbench/agent/agent.py", line 627, in _execute_tool
return tool.execute(self.ctx, **args)
File "/scratch/tejas/PopcornBench/src/kernelbench/agent/tools.py", line 770, in execute
return ctx.eval_client.submit_kernel(ctx, kernel_code)
File "/scratch/tejas/PopcornBench/src/kernelbench/agent/eval_client.py", line 50, in submit_kernel
return self._call("submit", args)
File "/scratch/tejas/PopcornBench/src/kernelbench/agent/eval_client.py", line 117, in _call
payload = self._response_q.get(timeout=remaining)
File "<string>", line 2, in get
File "/home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/lib/python3.10/multiprocessing/managers.py", line 818, in _callmethod
kind, result = conn.recv()
File "/home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/lib/python3.10/multiprocessing/connection.py", line 250, in recv
buf = self._recv_bytes()
File "/home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/lib/python3.10/multiprocessing/connection.py", line 414, in _recv_bytes
buf = self._recv(4)
File "/home/prabhune/.local/share/uv/python/cpython-3.10-linux-x86_64-gnu/lib/python3.10/multiprocessing/connection.py", line 379, in _recv
chunk = read(handle, remaining)
File "/scratch/tejas/PopcornBench/scripts/run_sweep.py", line 161, in _alarm_handler
raise _WorkItemTimeout("work item exceeded soft timeout budget")
__mp_main__._WorkItemTimeout: work item exceeded soft timeout budget
turn 7481.9s turn · 481.9s LLM · 0.0s tools · FINAL
reasoning
**Evaluating timeout issues**
I'm considering why my submission failed due to a timeout. It seems like the evaluation process might be slow because of heavy compile demands. The session should only end if the submission fails, but perhaps the compile and submit processes are separated in a way that causes a timeout. Also, replicating operations like GEMM could contribute to this. I wonder if there's a way to optimize compile time or adapt to reduce runtime without sacrificing results.
**Analyzing compile timeout reasons**
I'm thinking about why the load_inline compile might be causing a timeout on submission. It seems that the inclusion of heavy torch headers could be a factor, especially if I'm not utilizing cached components. The problem may lie in the time it takes to ensure correctness with multiple trials and expensive reference evaluations. I wonder if simplifying my includes could help. Unfortunately, avoiding GEMM doesn’t seem feasible. Still, I need to consider if human error in error checking is part of the issue as well.
**Exploring compile and submission issues**
I'm analyzing the timing for the work item, which seems to take around 30 seconds, while the compilation could be adding another 20 seconds. Speeding up the compile time doesn't look promising if I'm avoiding the --use_fast_math option. I wonder if I could implement the forward method through torch.ops, or perhaps consider using cublasLt instead of at::mm, but it might not change much. I think I should try submitting again, even though it previously failed, just to see if there’s a chance for a successful outcome this time.
**Reassessing the submission process**
I need to ensure a successful submission. Maybe I should try a simpler code or use the built-in Torch with a custom activation function in the forward pass. There's also the option to compile using Torch, but that might not apply here. The task might need a method called load_inline. I’m considering if the initial submission had a timeout due to compilation. If I retry with the same name, the cache might be ready for evaluation. Let's see if static is an option. I can retry the same approach.
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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);\n\"\"\"\n\n_cuda_src = r\"\"\"\n#include <torch/extension.h>\n#include <ATen/ATen.h>\n#include <ATen/cuda/CUDAContext.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <math.h>\n\n__global__ void add_act_kernel(float* __restrict__ y,\n const float* __restrict__ bias,\n const float* __restrict__ addv,\n int rows, int cols) {\n int col = blockIdx.x * blockDim.x + threadIdx.x;\n int row = blockIdx.y;\n if (col < cols) {\n int idx = row * cols + col;\n float v = y[idx] + bias[col] + addv[col];\n float s = 1.0f / (1.0f + expf(-v));\n float t = tanhf(v * s);\n float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));\n y[idx] = g;\n }\n}\n\ntorch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {\n auto y = at::mm(input, weight.t());\n const int rows = (int)y.size(0);\n const int cols = (int)y.size(1);\n const int threads = 256;\n dim3 blocks((cols + threads - 1) / threads, rows);\n cudaStream_t stream = at::cuda::getCurrentCUDAStream();\n add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);\n return y;\n}\n\"\"\"\n\n_ext = load_inline(\n name=\"fused_linear_acts_ext_v2\",\n cpp_sources=_cpp_src,\n cuda_sources=_cuda_src,\n functions=[\"fused_forward\"],\n extra_cflags=[\"-O3\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(nn.Module):\n def __init__(self, in_features, out_features, add_value_shape):\n super(ModelNew, self).__init__()\n self.matmul = nn.Linear(in_features, out_features)\n self.add_value = nn.Parameter(torch.randn(add_value_shape))\n\n def forward(self, x):\n return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 2.76 μs
Runtime stats: mean=2.76μs median=?μs std=0.01μs
Numerical precision: max_abs_err=8.23e-06 mean_abs_err=7.99e-07 max_rel_err=1.41e-05
Memory: 609.12 MB peak (ref: 673.12 MB, ratio: 0.9049x)
Kernel launches: 4 (ref: 16, fusion ratio: 4.0)
Energy: 323.18 mJ/run (ref: 322.92 mJ, ratio: 0.9992x)
SOL score: 0.4723
final submitted kernel (64 lines, 2,176 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_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value);
"""
_cuda_src = r"""
#include <torch/extension.h>
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>
__global__ void add_act_kernel(float* __restrict__ y,
const float* __restrict__ bias,
const float* __restrict__ addv,
int rows, int cols) {
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y;
if (col < cols) {
int idx = row * cols + col;
float v = y[idx] + bias[col] + addv[col];
float s = 1.0f / (1.0f + expf(-v));
float t = tanhf(v * s);
float g = 0.5f * t * (1.0f + erff(t * 0.70710678118654752440f));
y[idx] = g;
}
}
torch::Tensor fused_forward(torch::Tensor input, torch::Tensor weight, torch::Tensor bias, torch::Tensor add_value) {
auto y = at::mm(input, weight.t());
const int rows = (int)y.size(0);
const int cols = (int)y.size(1);
const int threads = 256;
dim3 blocks((cols + threads - 1) / threads, rows);
cudaStream_t stream = at::cuda::getCurrentCUDAStream();
add_act_kernel<<<blocks, threads, 0, stream>>>(y.data_ptr<float>(), bias.data_ptr<float>(), add_value.data_ptr<float>(), rows, cols);
return y;
}
"""
_ext = load_inline(
name="fused_linear_acts_ext_v2",
cpp_sources=_cpp_src,
cuda_sources=_cuda_src,
functions=["fused_forward"],
extra_cflags=["-O3"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False,
)
class ModelNew(nn.Module):
def __init__(self, in_features, out_features, add_value_shape):
super(ModelNew, self).__init__()
self.matmul = nn.Linear(in_features, out_features)
self.add_value = nn.Parameter(torch.randn(add_value_shape))
def forward(self, x):
return _ext.fused_forward(x, self.matmul.weight, self.matmul.bias, self.add_value)