correct
30_Softsign.py
started
2026-05-02T03:44:35Z
timingkernelbench.timing
kernel mean / median / std
4.63 / — / 0.15 μs
ref mean / median / std
14.90 / — / 0.09 μs
numerical precisioneval_kernel_against_ref
gpu memoryextended_metrics.measure_memory
kernel launches / fusiontorch.profiler
fusion ratio (ref / kernel)
3.00x
energyNVML (pynvml)
ratio (ref / kernel)
3.57x
SOL (speed-of-light)nsight_hardware_counters
roofline / occupancynsight_hardware_counters
dram bandwidth
2836.80 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 Softsign activation.
"""
def __init__(self):
super(Model, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Applies Softsign activation to the input tensor.
Args:
x (torch.Tensor): Input tensor of any shape.
Returns:
torch.Tensor: Output tensor with Softsign applied, same shape as input.
"""
return x / (1 + torch.abs(x))
batch_size = 4096
dim = 393216
def get_inputs():
x = torch.rand(batch_size, dim)
return [x]
def get_init_inputs():
return [] # No special initialization inputs neededturn 01.7s turn · 1.7s LLM · 0.0s tools
reasoning
We need to replace the forward of a simple PyTorch model x / (1 + abs(x)) with a custom CUDA kernel. The input is shape (4096, 393216). That's huge. It's a simple elementwise kernel, memory-bound. The goal is to write a fused kernel that runs faster than the PyTorch reference.
We need to know GPU specs to optimize. Let's call get_gpu_specs.
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 19.3s turn · 9.3s LLM · 0.0s tools
reasoning
Let me analyze the task:
1. The reference model computes `softsign`: `x / (1 + abs(x))`
2. Input shape: `[4096, 393216]` which is 4096 * 393216 = 1,610,612,736 elements ≈ 1.61B elements
3. In fp32: 1.61B * 4 bytes ≈ 6.44 GB per tensor (input + output ≈ 12.88 GB memory traffic)
This is a simple element-wise operation, memory-bound. The optimization goal is to write an efficient fused CUDA kernel that reads input and writes output directly without intermediate tensors.
For an H100 with 3.35 TB/s bandwidth, the theoretical min time for 12.88 GB is about 3.84 ms.
Let me write a simple fused CUDA kernel:
- Grid-stride loop
- Vectorized loads/stores (float4) for better memory throughput
- Built-in `fabsf` for absolute value
I'll write the kernel using `load_inline`.
call → compile_kernel
callcompile_kernel
{
"kernel_code": "\nimport torch\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\ntemplate <typename scalar_t>\n__global__ void softsign_kernel(const scalar_t* __restrict__ input,\n scalar_t* __restrict__ output,\n int64_t n) {\n int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n int64_t stride = (int64_t)blockDim.x * gridDim.x;\n for (int64_t i = idx; i < n; i += stride) {\n scalar_t x = input[i];\n output[i] = x / (scalar_t(1.0) + fabsf(x));\n }\n}\n\n// Vectorized version using float4\ntemplate <>\n__global__ void softsign_kernel<float>(const float* __restrict__ input,\n float* __restrict__ output,\n int64_t n) {\n int64_t idx = (blockIdx.x * blockDim.x + threadIdx.x) * 4;\n int64_t stride = (int64_t)blockDim.x * gridDim.x * 4;\n for (int64_t i = idx; i < n; i += stride) {\n float4 x4 = reinterpret_cast<const float4*>(input)[i / 4];\n float4 y4;\n y4.x = x4.x / (1.0f + fabsf(x4.x));\n y4.y = x4.y / (1.0f + fabsf(x4.y));\n y4.z = x4.z / (1.0f + fabsf(x4.z));\n y4.w = x4.w / (1.0f + fabsf(x4.w));\n reinterpret_cast<float4*>(output)[i / 4] = y4;\n }\n}\n\ntorch::Tensor softsign_forward(torch::Tensor x) {\n auto y = torch::empty_like(x);\n int64_t n = x.numel();\n const int threads = 256;\n const int blocks = 2048; // Enough parallelism for H100\n \n if (x.dtype() == torch::kFloat) {\n int64_t vec_n = n / 4 * 4;\n if (vec_n > 0) {\n softsign_kernel<float><<<blocks, threads>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), vec_n);\n }\n if (n > vec_n) {\n softsign_kernel<float><<<1, threads>>>(\n x.data_ptr<float>() + vec_n, y.data_ptr<float>() + vec_n, n - vec_n);\n }\n } else if (x.dtype() == torch::kHalf) {\n int64_t vec_n = n / 8 * 8; // float4 = 4 floats = 8 halfs\n // fallback to scalar for half\n softsign_kernel<at::Half><<<blocks, threads>>>(\n x.data_ptr<at::Half>(), y.data_ptr<at::Half>(), n);\n } else {\n AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16,\n x.scalar_type(), \"softsign\", [&]() {\n softsign_kernel<scalar_t><<<blocks, threads>>>(\n x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(), n);\n });\n }\n return y;\n}\n\"\"\"\n\nmodule = load_inline(\n name=\"softsign_cuda\",\n cpp_sources=\"torch::Tensor softsign_forward(torch::Tensor x);\",\n cuda_sources=cuda_source,\n functions=[\"softsign_forward\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(torch.nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return module.softsign_forward(x)\n"
}
result ← compile_kernel (ok)
okcompile_kernel
compile_kernel PASSED: kernel compiled without errors.
turn 2411.0s turn · 411.0s LLM · 0.0s tools
reasoning
Good, the kernel compiled. Let me run the correctness check now.
call → run_correctness
callrun_correctness
{
"kernel_code": "\nimport torch\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\ntemplate <typename scalar_t>\n__global__ void softsign_kernel(const scalar_t* __restrict__ input,\n scalar_t* __restrict__ output,\n int64_t n) {\n int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n int64_t stride = (int64_t)blockDim.x * gridDim.x;\n for (int64_t i = idx; i < n; i += stride) {\n scalar_t x = input[i];\n output[i] = x / (scalar_t(1.0) + fabsf(x));\n }\n}\n\n// Vectorized version using float4\ntemplate <>\n__global__ void softsign_kernel<float>(const float* __restrict__ input,\n float* __restrict__ output,\n int64_t n) {\n int64_t idx = (blockIdx.x * blockDim.x + threadIdx.x) * 4;\n int64_t stride = (int64_t)blockDim.x * gridDim.x * 4;\n for (int64_t i = idx; i < n; i += stride) {\n float4 x4 = reinterpret_cast<const float4*>(input)[i / 4];\n float4 y4;\n y4.x = x4.x / (1.0f + fabsf(x4.x));\n y4.y = x4.y / (1.0f + fabsf(x4.y));\n y4.z = x4.z / (1.0f + fabsf(x4.z));\n y4.w = x4.w / (1.0f + fabsf(x4.w));\n reinterpret_cast<float4*>(output)[i / 4] = y4;\n }\n}\n\ntorch::Tensor softsign_forward(torch::Tensor x) {\n auto y = torch::empty_like(x);\n int64_t n = x.numel();\n const int threads = 256;\n const int blocks = 2048;\n \n if (x.dtype() == torch::kFloat) {\n int64_t vec_n = n / 4 * 4;\n if (vec_n > 0) {\n softsign_kernel<float><<<blocks, threads>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), vec_n);\n }\n if (n > vec_n) {\n softsign_kernel<float><<<1, threads>>>(\n x.data_ptr<float>() + vec_n, y.data_ptr<float>() + vec_n, n - vec_n);\n }\n } else if (x.dtype() == torch::kHalf) {\n int64_t vec_n = n / 8 * 8;\n softsign_kernel<at::Half><<<blocks, threads>>>(\n x.data_ptr<at::Half>(), y.data_ptr<at::Half>(), n);\n } else {\n AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16,\n x.scalar_type(), \"softsign\", [&]() {\n softsign_kernel<scalar_t><<<blocks, threads>>>(\n x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(), n);\n });\n }\n return y;\n}\n\"\"\"\n\nmodule = load_inline(\n name=\"softsign_cuda\",\n cpp_sources=\"torch::Tensor softsign_forward(torch::Tensor x);\",\n cuda_sources=cuda_source,\n functions=[\"softsign_forward\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(torch.nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return module.softsign_forward(x)\n"
}
result ← run_correctness (ok)
okrun_correctness
run_correctness PASSED: (5 / 5) trials all matched the reference.
Numerical precision: max_abs_err=5.96e-08 mean_abs_err=8.32e-09 max_rel_err=1.60e-07
turn 3121.9s turn · 121.9s LLM · 0.0s tools
reasoning
The kernel passed correctness with excellent numerical precision. Let me also run a static_check before submitting, just to be safe. Then I'll submit.
call → static_check
callstatic_check
{
"kernel_code": "\nimport torch\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\ntemplate <typename scalar_t>\n__global__ void softsign_kernel(const scalar_t* __restrict__ input,\n scalar_t* __restrict__ output,\n int64_t n) {\n int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n int64_t stride = (int64_t)blockDim.x * gridDim.x;\n for (int64_t i = idx; i < n; i += stride) {\n scalar_t x = input[i];\n output[i] = x / (scalar_t(1.0) + fabsf(x));\n }\n}\n\n// Vectorized version using float4\ntemplate <>\n__global__ void softsign_kernel<float>(const float* __restrict__ input,\n float* __restrict__ output,\n int64_t n) {\n int64_t idx = (blockIdx.x * blockDim.x + threadIdx.x) * 4;\n int64_t stride = (int64_t)blockDim.x * gridDim.x * 4;\n for (int64_t i = idx; i < n; i += stride) {\n float4 x4 = reinterpret_cast<const float4*>(input)[i / 4];\n float4 y4;\n y4.x = x4.x / (1.0f + fabsf(x4.x));\n y4.y = x4.y / (1.0f + fabsf(x4.y));\n y4.z = x4.z / (1.0f + fabsf(x4.z));\n y4.w = x4.w / (1.0f + fabsf(x4.w));\n reinterpret_cast<float4*>(output)[i / 4] = y4;\n }\n}\n\ntorch::Tensor softsign_forward(torch::Tensor x) {\n auto y = torch::empty_like(x);\n int64_t n = x.numel();\n const int threads = 256;\n const int blocks = 2048;\n \n if (x.dtype() == torch::kFloat) {\n int64_t vec_n = n / 4 * 4;\n if (vec_n > 0) {\n softsign_kernel<float><<<blocks, threads>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), vec_n);\n }\n if (n > vec_n) {\n softsign_kernel<float><<<1, threads>>>(\n x.data_ptr<float>() + vec_n, y.data_ptr<float>() + vec_n, n - vec_n);\n }\n } else if (x.dtype() == torch::kHalf) {\n int64_t vec_n = n / 8 * 8;\n softsign_kernel<at::Half><<<blocks, threads>>>(\n x.data_ptr<at::Half>(), y.data_ptr<at::Half>(), n);\n } else {\n AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16,\n x.scalar_type(), \"softsign\", [&]() {\n softsign_kernel<scalar_t><<<blocks, threads>>>(\n x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(), n);\n });\n }\n return y;\n}\n\"\"\"\n\nmodule = load_inline(\n name=\"softsign_cuda\",\n cpp_sources=\"torch::Tensor softsign_forward(torch::Tensor x);\",\n cuda_sources=cuda_source,\n functions=[\"softsign_forward\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(torch.nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return module.softsign_forward(x)\n"
}
result ← static_check (ok)
okstatic_check
static_check PASSED: no violations or warnings detected.
turn 431.8s turn · 31.8s LLM · 0.0s tools · FINAL
reasoning
The kernel passes correctness and static check. Let me submit it. This should be faster than PyTorch's reference which uses a multi-kernel approach (abs, add, div) and doesn't vectorize.
call → submit_kernel
callsubmit_kernel
{
"kernel_code": "\nimport torch\nfrom torch.utils.cpp_extension import load_inline\n\ncuda_source = \"\"\"\n#include <torch/extension.h>\n#include <cuda_runtime.h>\n\ntemplate <typename scalar_t>\n__global__ void softsign_kernel(const scalar_t* __restrict__ input,\n scalar_t* __restrict__ output,\n int64_t n) {\n int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;\n int64_t stride = (int64_t)blockDim.x * gridDim.x;\n for (int64_t i = idx; i < n; i += stride) {\n scalar_t x = input[i];\n output[i] = x / (scalar_t(1.0) + fabsf(x));\n }\n}\n\n// Vectorized version using float4\ntemplate <>\n__global__ void softsign_kernel<float>(const float* __restrict__ input,\n float* __restrict__ output,\n int64_t n) {\n int64_t idx = (blockIdx.x * blockDim.x + threadIdx.x) * 4;\n int64_t stride = (int64_t)blockDim.x * gridDim.x * 4;\n for (int64_t i = idx; i < n; i += stride) {\n float4 x4 = reinterpret_cast<const float4*>(input)[i / 4];\n float4 y4;\n y4.x = x4.x / (1.0f + fabsf(x4.x));\n y4.y = x4.y / (1.0f + fabsf(x4.y));\n y4.z = x4.z / (1.0f + fabsf(x4.z));\n y4.w = x4.w / (1.0f + fabsf(x4.w));\n reinterpret_cast<float4*>(output)[i / 4] = y4;\n }\n}\n\ntorch::Tensor softsign_forward(torch::Tensor x) {\n auto y = torch::empty_like(x);\n int64_t n = x.numel();\n const int threads = 256;\n const int blocks = 2048;\n \n if (x.dtype() == torch::kFloat) {\n int64_t vec_n = n / 4 * 4;\n if (vec_n > 0) {\n softsign_kernel<float><<<blocks, threads>>>(\n x.data_ptr<float>(), y.data_ptr<float>(), vec_n);\n }\n if (n > vec_n) {\n softsign_kernel<float><<<1, threads>>>(\n x.data_ptr<float>() + vec_n, y.data_ptr<float>() + vec_n, n - vec_n);\n }\n } else if (x.dtype() == torch::kHalf) {\n int64_t vec_n = n / 8 * 8;\n softsign_kernel<at::Half><<<blocks, threads>>>(\n x.data_ptr<at::Half>(), y.data_ptr<at::Half>(), n);\n } else {\n AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16,\n x.scalar_type(), \"softsign\", [&]() {\n softsign_kernel<scalar_t><<<blocks, threads>>>(\n x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(), n);\n });\n }\n return y;\n}\n\"\"\"\n\nmodule = load_inline(\n name=\"softsign_cuda\",\n cpp_sources=\"torch::Tensor softsign_forward(torch::Tensor x);\",\n cuda_sources=cuda_source,\n functions=[\"softsign_forward\"],\n extra_cuda_cflags=[\"-O3\", \"--use_fast_math\"],\n verbose=False,\n)\n\nclass ModelNew(torch.nn.Module):\n def __init__(self):\n super(ModelNew, self).__init__()\n \n def forward(self, x: torch.Tensor) -> torch.Tensor:\n return module.softsign_forward(x)\n"
}
result ← submit_kernel (ok)
oksubmit_kernel
submit_kernel PASSED: (5 / 5) correctness trials all passed.
Kernel runtime: 4.63 μs
Runtime stats: mean=4.63μs median=?μs std=0.15μs
Numerical precision: max_abs_err=5.96e-08 mean_abs_err=8.32e-09 max_rel_err=1.60e-07
Memory: 12288.0 MB peak (ref: 18432.0 MB, ratio: 0.6667x)
Kernel launches: 2 (ref: 6, fusion ratio: 3.0)
Energy: 459.6 mJ/run (ref: 1639.48 mJ, ratio: 3.5672x)
SOL score: 0.8468
final submitted kernel (85 lines, 2,890 chars) — full source, untruncated
import torch
from torch.utils.cpp_extension import load_inline
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
template <typename scalar_t>
__global__ void softsign_kernel(const scalar_t* __restrict__ input,
scalar_t* __restrict__ output,
int64_t n) {
int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;
int64_t stride = (int64_t)blockDim.x * gridDim.x;
for (int64_t i = idx; i < n; i += stride) {
scalar_t x = input[i];
output[i] = x / (scalar_t(1.0) + fabsf(x));
}
}
// Vectorized version using float4
template <>
__global__ void softsign_kernel<float>(const float* __restrict__ input,
float* __restrict__ output,
int64_t n) {
int64_t idx = (blockIdx.x * blockDim.x + threadIdx.x) * 4;
int64_t stride = (int64_t)blockDim.x * gridDim.x * 4;
for (int64_t i = idx; i < n; i += stride) {
float4 x4 = reinterpret_cast<const float4*>(input)[i / 4];
float4 y4;
y4.x = x4.x / (1.0f + fabsf(x4.x));
y4.y = x4.y / (1.0f + fabsf(x4.y));
y4.z = x4.z / (1.0f + fabsf(x4.z));
y4.w = x4.w / (1.0f + fabsf(x4.w));
reinterpret_cast<float4*>(output)[i / 4] = y4;
}
}
torch::Tensor softsign_forward(torch::Tensor x) {
auto y = torch::empty_like(x);
int64_t n = x.numel();
const int threads = 256;
const int blocks = 2048;
if (x.dtype() == torch::kFloat) {
int64_t vec_n = n / 4 * 4;
if (vec_n > 0) {
softsign_kernel<float><<<blocks, threads>>>(
x.data_ptr<float>(), y.data_ptr<float>(), vec_n);
}
if (n > vec_n) {
softsign_kernel<float><<<1, threads>>>(
x.data_ptr<float>() + vec_n, y.data_ptr<float>() + vec_n, n - vec_n);
}
} else if (x.dtype() == torch::kHalf) {
int64_t vec_n = n / 8 * 8;
softsign_kernel<at::Half><<<blocks, threads>>>(
x.data_ptr<at::Half>(), y.data_ptr<at::Half>(), n);
} else {
AT_DISPATCH_FLOATING_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16,
x.scalar_type(), "softsign", [&]() {
softsign_kernel<scalar_t><<<blocks, threads>>>(
x.data_ptr<scalar_t>(), y.data_ptr<scalar_t>(), n);
});
}
return y;
}
"""
module = load_inline(
name="softsign_cuda",
cpp_sources="torch::Tensor softsign_forward(torch::Tensor x);",
cuda_sources=cuda_source,
functions=["softsign_forward"],
extra_cuda_cflags=["-O3", "--use_fast_math"],
verbose=False,
)
class ModelNew(torch.nn.Module):
def __init__(self):
super(ModelNew, self).__init__()
def forward(self, x: torch.Tensor) -> torch.Tensor:
return module.softsign_forward(x)