← Back to Leaderboard

The AI CUDA Engineer 👷

7_Conv3d_ReLU_LeakyReLU_GELU_Sigmoid_BiasAddcombined_activation_bias_base

Level 2 • Task 7
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(
    x: torch.Tensor,
    conv_weight: torch.Tensor,
    conv_bias: torch.Tensor,
    bias: torch.Tensor,
) -> torch.Tensor:
    """
    Applies 3D convolution followed by ReLU, LeakyReLU, GELU, Sigmoid activations and bias addition.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        conv_weight (torch.Tensor): 3D convolution weight tensor of shape
            (out_channels, in_channels, kernel_size, kernel_size, kernel_size)
        conv_bias (torch.Tensor): Bias tensor for 3D convolution of shape (out_channels)
        bias (torch.Tensor): Bias tensor for addition of shape (out_channels, 1, 1, 1)

    Returns:
        torch.Tensor: Output tensor after applying convolution and activations
    """
    x = F.conv3d(x, conv_weight, bias=conv_bias)
    x = F.relu(x)
    x = F.leaky_relu(x, negative_slope=0.01)
    x = F.gelu(x)
    x = torch.sigmoid(x)
    x = x + bias
    return x


class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies ReLU, LeakyReLU, GELU, Sigmoid activations, and bias in sequence.
    """

    def __init__(self, in_channels, out_channels, kernel_size, bias_shape):
        super(Model, self).__init__()
        conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.bias = nn.Parameter(torch.randn(bias_shape) * 0.02)

        self.conv_weight = nn.Parameter(conv.weight)
        self.conv_bias = nn.Parameter(conv.bias)
        self.bias = self.bias

    def forward(self, x, fn=module_fn):
        return fn(x, self.conv_weight, self.conv_bias, self.bias)


batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
bias_shape = (out_channels, 1, 1, 1)


def get_inputs():
    return [torch.randn(batch_size, in_channels, depth, height, width)]


def get_init_inputs():
    return [in_channels, out_channels, kernel_size, bias_shape]
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Model that performs a 3D convolution, applies ReLU, LeakyReLU, GELU, Sigmoid activations, and bias in sequence.
    """
    def __init__(self, in_channels, out_channels, kernel_size, bias_shape):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.bias = nn.Parameter(torch.randn(bias_shape) * 0.02) 

    def forward(self, x):
        x = self.conv(x)
        x = torch.relu(x)
        x = torch.nn.functional.leaky_relu(x, negative_slope=0.01)
        x = torch.nn.functional.gelu(x)
        x = torch.sigmoid(x)
        x = x + self.bias
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3
bias_shape = (out_channels, 1, 1, 1)

def get_inputs():
    return [torch.randn(batch_size, in_channels, depth, height, width)]

def get_init_inputs():
    return [in_channels, out_channels, kernel_size, bias_shape]

Kernel Information

Related Kernels (Level 2, Task 7 • 7_Conv3d_ReLU_LeakyReLU_GELU_Sigmoid_BiasAdd)

#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>

#ifndef BLOCK_SIZE
#define BLOCK_SIZE 256  // Tunable block size for experimentation
#endif

#define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)

// This kernel fuses the conv3d output activation and bias addition in one pass.
// It combines vectorized memory accesses (using float4) with a grid-stride loop for coalesced memory access
// and tunable block size for better efficiency.
__global__ void combined_activation_bias_kernel(
    float* __restrict__ output,
    const float* __restrict__ bias,
    int total_elements,
    int out_channels,
    int dwh  // depth * height * width
) {
    int tid = blockIdx.x * blockDim.x + threadIdx.x;
    const int numVec = total_elements / 4;  // Number of vectorized elements
    const int remainder = total_elements % 4;  // Leftover scalar elements
    const float sqrt_2_over_pi = sqrtf(2.0f / M_PI);

    // Process vectorized elements using float4
    float4* outputVec = reinterpret_cast<float4*>(output);
    for (int i = tid; i < numVec; i += gridDim.x * blockDim.x) {
        float4 vec = outputVec[i];
        float* vals = reinterpret_cast<float*>(&vec);
        int base = i * 4;  // Starting index for these four elements
        int channel = (base / dwh) % out_channels;
        float b = __ldg(&bias[channel]);

        #pragma unroll
        for (int j = 0; j < 4; j++) {
            float val = vals[j];
            // ReLU
            val = fmaxf(0.0f, val);
            // LeakyReLU
            val = fmaxf(0.01f * val, val);
            // GELU approximation
            float cube = val * val * val;
            float inner = sqrt_2_over_pi * (val + 0.044715f * cube);
            val = 0.5f * val * (1.0f + tanhf(inner));
            // Sigmoid
            val = 1.0f / (1.0f + expf(-val));
            // Add bias
            vals[j] = val + b;
        }
        outputVec[i] = vec;
    }

    // Process any remaining scalar elements
    int scalarStart = total_elements - remainder;
    for (int i = scalarStart + tid; i < total_elements; i += gridDim.x * blockDim.x) {
        int channel = (i / dwh) % out_channels;
        float val = output[i];
        val = fmaxf(0.0f, val);
        val = fmaxf(0.01f * val, val);
        float cube = val * val * val;
        float inner = sqrt_2_over_pi * (val + 0.044715f * cube);
        val = 0.5f * val * (1.0f + tanhf(inner));
        val = 1.0f / (1.0f + expf(-val));
        output[i] = val + __ldg(&bias[channel]);
    }
}

// Host function that performs a conv3d and then applies the fused activation and bias kernel
torch::Tensor module_fn_cuda(
    torch::Tensor x,
    torch::Tensor conv_weight,
    torch::Tensor conv_bias,
    torch::Tensor bias
) {
    CHECK_INPUT(x);
    CHECK_INPUT(conv_weight);
    CHECK_INPUT(conv_bias);
    CHECK_INPUT(bias);

    // Perform 3D convolution
    auto output = torch::conv3d(x, conv_weight, conv_bias);

    const int batch_size = output.size(0);
    const int out_channels = output.size(1);
    const int depth = output.size(2);
    const int height = output.size(3);
    const int width = output.size(4);
    int total_elements = output.numel();
    int dwh = depth * height * width;

    // Launch kernel with tunable block size and grid-stride loop for efficient processing
    int threads = BLOCK_SIZE;
    int numVec = total_elements / 4;  // Number of vectorized iterations
    int blocks = (numVec + threads - 1) / threads;

    combined_activation_bias_kernel<<<blocks, threads>>>(
        output.data_ptr<float>(),
        bias.data_ptr<float>(),
        total_elements,
        out_channels,
        dwh
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &module_fn_cuda, "Combined CUDA kernel for conv3d activation fusion with bias addition");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 3.134 inst/cycle 0.000 5
Executed Ipc Elapsed 3.018 inst/cycle 0.000 5
Issue Slots Busy 78.444 % 0.139 5
Issued Ipc Active 3.136 inst/cycle 0.000 5
SM Busy 78.444 % 0.139 5
Memory Throughput 2568602254344.524 byte/second 149278874942622040064.000 5
Mem Busy 43.520 % 0.053 5
Max Bandwidth 76.656 % 0.131 5
L1/TEX Hit Rate 47.756 % 0.008 5
L2 Hit Rate 50.412 % 0.014 5
Mem Pipes Busy 21.634 % 0.010 5
Warp Cycles Per Issued Instruction 16.802 cycle 0.010 5
Warp Cycles Per Executed Instruction 16.826 cycle 0.010 5
Avg. Active Threads Per Warp 27.570 0.000 5
Avg. Not Predicated Off Threads Per Warp 24.710 0.000 5
Max Active Clusters 0.000 cluster 0.000 5
Max Cluster Size 8.000 block 0.000 5
Overall GPU Occupancy 0.000 % 0.000 5
Cluster Occupancy 0.000 % 0.000 5
Block Limit SM 32.000 block 0.000 5
Block Limit Registers 8.000 block 0.000 5
Block Limit Shared Mem 32.000 block 0.000 5
Block Limit Warps 8.000 block 0.000 5
Theoretical Active Warps per SM 64.000 warp 0.000 5
Theoretical Occupancy 100.000 % 0.000 5
Achieved Occupancy 82.476 % 0.006 5
Achieved Active Warps Per SM 52.786 warp 0.002 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (46.9%) based on active cycles, taking into account the rates of its different instructions. It executes integer and logic operations. It is well-utilized, but should not be a bottleneck.
INF CPIStall Check the Warp Stall Sampling (All Cycles) table for the top stall locations in your source based on sampling data. The Kernel Profiling Guide (https://docs.nvidia.com/nsight-compute/ProfilingGuide/index.html#metrics-reference) provides more details on each stall reason.
WRN Occupancy This kernel's theoretical occupancy is not impacted by any block limit. The difference between calculated theoretical (100.0%) and measured achieved occupancy (82.6%) can be the result of warp scheduling overheads or workload imbalances during the kernel execution. Load imbalances can occur between warps within a block as well as across blocks of the same kernel. See the CUDA Best Practices Guide (https://docs.nvidia.com/cuda/cuda-c-best-practices-guide/index.html#occupancy) for more details on optimizing occupancy.
Operation / Metric Value Unit
aten::conv3d
CPU Time 760450.71 μs
Device Time 5474718.11 μs
Self CPU Time 13268.31 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::convolution
CPU Time 747182.41 μs
Device Time 5474718.11 μs
Self CPU Time 17658.02 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::_convolution
CPU Time 729524.39 μs
Device Time 5474718.11 μs
Self CPU Time 35900.97 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::cudnn_convolution
CPU Time 610016.53 μs
Device Time 4745201.83 μs
Self CPU Time 185659.26 μs
Self Device Time 4745201.83 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaEventRecord
CPU Time 631672.71 μs
Device Time 0.00 μs
Self CPU Time 631672.71 μs
Self Device Time 0.00 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
sm80_xmma_fprop_implicit_gemm_indexed_f32f32_f32f32_f32_nchwkcrs_nchw_tilesize32x32x8_stage3_warpsize1x2x1_g1_ffma_aligna4_alignc4_execute_kernel__5x_cudnn
CPU Time 0.00 μs
Device Time 4745199.15 μs
Self CPU Time 0.00 μs
Self Device Time 4745199.15 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
cudaLaunchKernel
CPU Time 5101311.32 μs
Device Time 331400.62 μs
Self CPU Time 5101311.32 μs
Self Device Time 331400.62 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
Status: Completed
45293 warnings generated when compiling for host.
Suppressed 45324 warnings (45277 in non-user code, 47 NOLINT).
Use -header-filter=.* to display errors from all non-system headers. Use -system-headers to display errors from system headers as well.
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:10:35 bugprone-macro-parentheses
10 | #define CHECK_CUDA(x) TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor")
| ^
| ()
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:11:41: warning: macro argument should be enclosed in parentheses [bugprone-macro-parentheses]
11 | #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
| ^
| ()
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:20:5: warning: 2 adjacent parameters of 'combined_activation_bias_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
20 | int total_elements,
| ^~~~~~~~~~~~~~~~~~~
21 | int out_channels,
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:20:9: note: the first parameter in the range is 'total_elements'
20 | int total_elements,
| ^~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:21:9: note: the last parameter in the range is 'out_channels'
21 | int out_channels,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:24:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | int tid = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:31:40: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
31 | for (int i = tid; i < numVec; i += gridDim.x * blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:59:62: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
59 | for (int i = scalarStart + tid; i < total_elements; i += gridDim.x * blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:74:19: warning: the parameter 'x' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
74 | torch::Tensor x,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:75:19: warning: the parameter 'conv_weight' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
75 | torch::Tensor conv_weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:77:19: warning: the parameter 'bias' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
77 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:87:15: warning: Value stored to 'batch_size' during its initialization is never read [clang-analyzer-deadcode.DeadStores]
87 | const int batch_size = output.size(0);
| ^~~~~~~~~~ ~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:87:15: note: Value stored to 'batch_size' during its initialization is never read
87 | const int batch_size = output.size(0);
| ^~~~~~~~~~ ~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:87:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
87 | const int batch_size = output.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:88:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
88 | const int out_channels = output.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:89:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
89 | const int depth = output.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:90:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
90 | const int height = output.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:91:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
91 | const int width = output.size(4);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_sweep_rag_optim/level_2/task_7/b8_s2_combined_activation_bias/base/base.cu:92:26: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
92 | int total_elements = output.numel();
| ^