← Back to Leaderboard

The AI CUDA Engineer 👷

27_Conv3d_HardSwish_ReLU_Softmax_Meanldg_aligned_access_edit_1

Level 2 • Task 27
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,
) -> torch.Tensor:
    """
    Applies 3D convolution, HardSwish, ReLU, Softmax and mean reduction.

    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)

    Returns:
        torch.Tensor: Output tensor after applying convolution, activations and reduction,
            with shape (batch_size, out_channels)
    """
    x = F.conv3d(x, conv_weight, bias=conv_bias)
    x = F.hardswish(x)
    x = F.relu(x)
    x = F.softmax(x, dim=1)
    x = torch.mean(x, dim=[2, 3, 4])
    return x


class Model(nn.Module):
    """
    Simple model that performs a 3D convolution, applies HardSwish, ReLU, Softmax, and then calculates the mean.
    """

    def __init__(self, in_channels, out_channels, kernel_size):
        super(Model, self).__init__()

        conv = nn.Conv3d(in_channels, out_channels, kernel_size)
        self.conv_weight = nn.Parameter(conv.weight)
        self.conv_bias = nn.Parameter(conv.bias + torch.ones_like(conv.bias) * 0.02)

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


batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3


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


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

class Model(nn.Module):
    """
    Simple model that performs a 3D convolution, applies HardSwish, ReLU, Softmax, and then calculates the mean.
    """
    def __init__(self, in_channels, out_channels, kernel_size, bias=True):
        super(Model, self).__init__()
        self.conv = nn.Conv3d(in_channels, out_channels, kernel_size, bias=bias)
        self.conv.bias = nn.Parameter(self.conv.bias + torch.ones_like(self.conv.bias) * 0.02)

    def forward(self, x):
        x = self.conv(x)
        x = torch.nn.functional.hardswish(x)
        x = torch.relu(x)
        x = torch.softmax(x, dim=1)
        x = torch.mean(x, dim=[2, 3, 4])
        return x

batch_size = 128
in_channels = 3
out_channels = 16
depth, height, width = 16, 32, 32
kernel_size = 3

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

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

Kernel Information

Related Kernels (Level 2, Task 27 • 27_Conv3d_HardSwish_ReLU_Softmax_Mean)

#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <cfloat>

// Combined HardSwish and ReLU with aligned memory access
__global__ void fused_hswish_relu_kernel(const float* __restrict__ input,
                                        float* __restrict__ output,
                                        int64_t size) {
    int index = blockIdx.x * blockDim.x + threadIdx.x;
    if (index < size) {
        // Use __ldg for read-only access with 128-bit alignment assumption
        float x = __ldg(input + index);
        float relu6 = fminf(fmaxf(x + 3.0f, 0.0f), 6.0f);
        output[index] = fmaxf(x * relu6 * 0.16666667f, 0.0f);
    }
}

// Softmax kernel with read-only cache optimization
__global__ void optimized_softmax_kernel(const float* __restrict__ input,
                                      float* __restrict__ output,
                                      int batch_size,
                                      int channels,
                                      int spatial_size) {
    extern __shared__ float shared_max[];
    int index = blockIdx.x * blockDim.x + threadIdx.x;
    int tid = threadIdx.x;
    int total_elements = batch_size * spatial_size;

    if (index < total_elements) {
        int batch_idx = index / spatial_size;
        int spatial_idx = index % spatial_size;

        // Load through read-only cache with alignment
        float max_val = -FLT_MAX;
        for (int c = 0; c < channels; ++c) {
            int idx = batch_idx * channels * spatial_size + c * spatial_size + spatial_idx;
            max_val = fmaxf(max_val, __ldg(input + idx));
        }
        shared_max[tid] = max_val;

        // Block-wide max reduction
        __syncthreads();
        for (int s = blockDim.x/2; s > 0; s >>= 1) {
            if (tid < s) {
                shared_max[tid] = fmaxf(shared_max[tid], shared_max[tid + s]);
            }
            __syncthreads();
        }
        float block_max = shared_max[0];

        // Compute exp with stable values
        float sum_exp = 0.0f;
        for (int c = 0; c < channels; ++c) {
            int idx = batch_idx * channels * spatial_size + c * spatial_size + spatial_idx;
            float val = expf(__ldg(input + idx) - block_max);
            sum_exp += val;
            output[idx] = val;
        }

        // Normalize using fast reciprocal
        float inv_sum = 1.0f / sum_exp;
        for (int c = 0; c < channels; ++c) {
            int idx = batch_idx * channels * spatial_size + c * spatial_size + spatial_idx;
            output[idx] *= inv_sum;
        }
    }
}

torch::Tensor module_forward(
    torch::Tensor x,
    torch::Tensor conv_weight,
    torch::Tensor conv_bias)
{
    // Ensure 128-bit aligned memory access
    x = x.contiguous().cuda();
    conv_weight = conv_weight.contiguous().cuda();
    conv_bias = conv_bias.contiguous().cuda();

    x = torch::conv3d(x, conv_weight, conv_bias);

    int64_t batch_size = x.size(0);
    int64_t channels = x.size(1);
    int64_t depth = x.size(2);
    int64_t height = x.size(3);
    int64_t width = x.size(4);
    int64_t total_size = batch_size * channels * depth * height * width;

    torch::Tensor x_processed = torch::empty_like(x);

    // Launch fused HS-RReLU with optimal block size
    const int block_size = 256;
    int blocks = (total_size + block_size - 1) / block_size;
    fused_hswish_relu_kernel<<<blocks, block_size>>>(
        x.data_ptr<float>(),
        x_processed.data_ptr<float>(),
        total_size
    );

    // Process softmax
    x_processed = x_processed.view({batch_size, channels, depth * height * width});
    torch::Tensor x_softmax = torch::empty_like(x_processed);
    
    int spatial_size = depth * height * width;
    blocks = (batch_size * spatial_size + block_size - 1) / block_size;
    optimized_softmax_kernel<<<blocks, block_size, block_size * sizeof(float)>>>(
        x_processed.data_ptr<float>(),
        x_softmax.data_ptr<float>(),
        batch_size,
        channels,
        spatial_size
    );

    return x_softmax.view({batch_size, channels, depth, height, width})
                    .mean({2, 3, 4});
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &module_forward, "CUDA optimized memory forward");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.383 inst/cycle 0.000 3
Executed Ipc Elapsed 1.323 inst/cycle 0.000 3
Issue Slots Busy 34.670 % 0.027 3
Issued Ipc Active 1.387 inst/cycle 0.000 3
SM Busy 34.670 % 0.027 3
Memory Throughput 2144599632738.143 byte/second 199253842380319064064.000 3
Mem Busy 63.807 % 0.153 3
Max Bandwidth 68.570 % 0.186 3
L1/TEX Hit Rate 54.283 % 0.000 3
L2 Hit Rate 71.820 % 0.015 3
Mem Pipes Busy 29.757 % 0.039 3
Warp Cycles Per Issued Instruction 38.967 cycle 0.037 3
Warp Cycles Per Executed Instruction 39.027 cycle 0.037 3
Avg. Active Threads Per Warp 32.000 0.000 3
Avg. Not Predicated Off Threads Per Warp 28.500 0.000 3
Max Active Clusters 0.000 cluster 0.000 3
Max Cluster Size 8.000 block 0.000 3
Overall GPU Occupancy 0.000 % 0.000 3
Cluster Occupancy 0.000 % 0.000 3
Block Limit SM 32.000 block 0.000 3
Block Limit Registers 8.000 block 0.000 3
Block Limit Shared Mem 16.000 block 0.000 3
Block Limit Warps 8.000 block 0.000 3
Theoretical Active Warps per SM 64.000 warp 0.000 3
Theoretical Occupancy 100.000 % 0.000 3
Achieved Occupancy 84.640 % 0.001 3
Achieved Active Warps Per SM 54.167 warp 0.000 3
Analysis Rules
Rule Description
WRN HighPipeUtilization All compute pipelines are under-utilized. Either this kernel is very small or it doesn't issue enough warps per scheduler. Check the Launch Statistics and Scheduler Statistics sections for further details.
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 (84.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::fill_
CPU Time 2960688.48 μs
Device Time 407455.94 μs
Self CPU Time 18916.07 μs
Self Device Time 407455.94 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::conv3d
CPU Time 1082741.36 μs
Device Time 3621308.04 μs
Self CPU Time 12144.33 μ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 1070597.03 μs
Device Time 3621308.04 μs
Self CPU Time 13994.00 μ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 1056603.04 μs
Device Time 3621308.04 μs
Self CPU Time 29213.33 μ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 570894.97 μs
Device Time 3143800.65 μs
Self CPU Time 185763.18 μs
Self Device Time 3143800.65 μ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 3143798.99 μs
Self CPU Time 0.00 μs
Self Device Time 3143798.99 μ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 3920648.84 μs
Device Time 94145.25 μs
Self CPU Time 3920648.84 μs
Self Device Time 94145.25 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::zero_
CPU Time 2973836.45 μs
Device Time 407455.94 μs
Self CPU Time 13158.49 μ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
Status: Completed
45286 warnings generated when compiling for host.
Suppressed 45323 warnings (45276 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/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:11:17 bugprone-narrowing-conversions
11 | int index = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:23:39: warning: 2 adjacent parameters of 'optimized_softmax_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
23 | int batch_size,
| ^~~~~~~~~~~~~~~
24 | int channels,
| ~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:23:43: note: the first parameter in the range is 'batch_size'
23 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:24:43: note: the last parameter in the range is 'channels'
24 | int channels,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:27:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
27 | int index = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:28:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:45:22: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
45 | for (int s = blockDim.x/2; s > 0; s >>= 1) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:94:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
94 | int blocks = (total_size + block_size - 1) / block_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:105:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
105 | int spatial_size = depth * height * width;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:106:14: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
106 | blocks = (batch_size * spatial_size + block_size - 1) / block_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:110:9: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
110 | batch_size,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_2/task_27/b4_s0_ldg_aligned_access/edit_1/edit_1.cu:111:9: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
111 | channels,
| ^