← Back to Leaderboard

The AI CUDA Engineer 👷

65_Conv2d_AvgPool_Sigmoid_Sumefficient_3d_indexing_base

Level 2 • Task 65
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:
    """
    Performs convolution, average pooling, applies sigmoid, and sums the result.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, height, width)
        conv_weight (torch.Tensor): Convolution weights of shape (out_channels, in_channels, kernel_size, kernel_size)
        conv_bias (torch.Tensor): Convolution bias of shape (out_channels)

    Returns:
        torch.Tensor: Output tensor of shape (batch_size,) containing summed values
    """
    x = F.conv2d(x, conv_weight, bias=conv_bias)
    x = F.avg_pool2d(x, pool_kernel_size)
    x = torch.sigmoid(x)
    x = torch.sum(x, dim=[1, 2, 3])
    return x


class Model(nn.Module):
    """
    This model performs a convolution, average pooling, applies sigmoid, and sums the result.
    """

    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(Model, self).__init__()
        conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.conv_weight = nn.Parameter(conv.weight)
        self.conv_bias = nn.Parameter(conv.bias)

    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
height, width = 32, 32
kernel_size = 3
pool_kernel_size = 2


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


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

class Model(nn.Module):
    """
    This model performs a convolution, average pooling, applies sigmoid, and sums the result.
    """
    def __init__(self, in_channels, out_channels, kernel_size, pool_kernel_size):
        super(Model, self).__init__()
        self.conv = nn.Conv2d(in_channels, out_channels, kernel_size)
        self.avg_pool = nn.AvgPool2d(pool_kernel_size)

    def forward(self, x):
        x = self.conv(x)
        x = self.avg_pool(x)
        x = torch.sigmoid(x)
        x = torch.sum(x, dim=[1,2,3]) # Sum over all spatial dimensions
        return x

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

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

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

Kernel Information

Related Kernels (Level 2, Task 65 • 65_Conv2d_AvgPool_Sigmoid_Sum)

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

#define POOL_SIZE 2
#define BLOCK_SIZE 256

// Kernel using a 3D grid mapping:
//   gridDim.x -> batch index
//   gridDim.y -> output channel index
//   gridDim.z -> blocks of pooling spatial indices

__global__ void conv_pool_sigmoid_sum_kernel(
    const float* __restrict__ input,
    const float* __restrict__ weight,
    const float* __restrict__ bias,
    float* output,
    const int batch_size,
    const int in_channels,
    const int out_channels,
    const int height,
    const int width,
    const int kernel_size,
    const int pool_out_height,
    const int pool_out_width
) {
    // Mapping: batch index and output channel from grid.x and grid.y
    int batch = blockIdx.x;
    int oc = blockIdx.y;
    
    // Total number of pooling output positions
    int pool_total = pool_out_height * pool_out_width;
    
    // Each block in grid.z covers a segment of pooling indices
    int idx = blockIdx.z * blockDim.x + threadIdx.x;
    
    float value = 0.0f;
    if (idx < pool_total) {
        // Calculate pooling spatial coordinates
        int pool_h = idx / pool_out_width;
        int pool_w = idx % pool_out_width;

        float conv_result = bias[oc];

        // Perform convolution over input channels and kernel window
        #pragma unroll
        for (int ic = 0; ic < in_channels; ic++) {
            // Compute base offsets for input and weight
            int input_channel_offset = ((batch * in_channels) + ic) * height * width;
            int weight_channel_offset = ((oc * in_channels) + ic) * kernel_size * kernel_size;
            
            int base_h = pool_h * POOL_SIZE;
            int base_w = pool_w * POOL_SIZE;

            #pragma unroll
            for (int kh = 0; kh < kernel_size; kh++) {
                int h_in = base_h + kh;
                #pragma unroll
                for (int kw = 0; kw < kernel_size; kw++) {
                    int w_in = base_w + kw;
                    if (h_in < height && w_in < width) {
                        int input_index = input_channel_offset + h_in * width + w_in;
                        int weight_index = weight_channel_offset + kh * kernel_size + kw;
                        conv_result += input[input_index] * weight[weight_index];
                    }
                }
            }
        }
        
        // Average pooling and apply sigmoid activation
        conv_result *= (1.0f / (POOL_SIZE * POOL_SIZE));
        value = 1.0f / (1.0f + expf(-conv_result));
    } else {
        value = 0.0f;
    }

    // Block-level reduction using shared memory
    extern __shared__ float sdata[];
    sdata[threadIdx.x] = value;
    __syncthreads();

    // Standard reduction in shared memory
    for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (threadIdx.x < s) {
            sdata[threadIdx.x] += sdata[threadIdx.x + s];
        }
        __syncthreads();
    }

    // Thread 0 of each block atomically adds the partial sum to global output for the batch
    if (threadIdx.x == 0) {
        atomicAdd(&output[batch], sdata[0]);
    }
}

// Host function to setup grid and launch kernel
torch::Tensor forward(
    torch::Tensor input,
    torch::Tensor weight,
    torch::Tensor bias
) {
    const int batch_size = input.size(0);
    const int in_channels = input.size(1);
    const int height = input.size(2);
    const int width = input.size(3);
    const int out_channels = weight.size(0);
    const int kernel_size = weight.size(2);

    // Compute convolution output dimensions
    int out_height = height - kernel_size + 1;
    int out_width = width - kernel_size + 1;
    
    // Compute pooling output dimensions
    int pool_out_height = out_height / POOL_SIZE;
    int pool_out_width = out_width / POOL_SIZE;
    int pool_total = pool_out_height * pool_out_width;

    // Determine grid dimensions using 3D indexing
    // grid.x: batch dimension
    // grid.y: out_channels dimension
    // grid.z: covers pooled spatial positions, chunked by BLOCK_SIZE
    int blocks_z = (pool_total + BLOCK_SIZE - 1) / BLOCK_SIZE;
    dim3 blocks(batch_size, out_channels, blocks_z);
    int threads = BLOCK_SIZE;

    auto output = torch::zeros({batch_size}, input.options());

    // Launch kernel with shared memory per block
    conv_pool_sigmoid_sum_kernel<<<blocks, threads, BLOCK_SIZE * sizeof(float)>>>(
        input.data_ptr<float>(),
        weight.data_ptr<float>(),
        bias.data_ptr<float>(),
        output.data_ptr<float>(),
        batch_size,
        in_channels,
        out_channels,
        height,
        width,
        kernel_size,
        pool_out_height,
        pool_out_width
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "3D indexing optimized convolution + pool + sigmoid + sum forward");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 2.896 inst/cycle 0.000 5
Executed Ipc Elapsed 2.440 inst/cycle 0.000 5
Issue Slots Busy 72.766 % 0.082 5
Issued Ipc Active 2.910 inst/cycle 0.000 5
SM Busy 72.766 % 0.082 5
Memory Throughput 83811807780.318 byte/second 73851470715469872.000 5
Mem Busy 57.580 % 0.039 5
Max Bandwidth 35.710 % 0.016 5
L1/TEX Hit Rate 82.986 % 0.002 5
L2 Hit Rate 84.770 % 0.201 5
Mem Pipes Busy 52.714 % 0.034 5
Warp Cycles Per Issued Instruction 18.828 cycle 0.006 5
Warp Cycles Per Executed Instruction 18.932 cycle 0.006 5
Avg. Active Threads Per Warp 28.810 0.000 5
Avg. Not Predicated Off Threads Per Warp 25.210 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 16.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 85.814 % 0.008 5
Achieved Active Warps Per SM 54.922 warp 0.003 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (43.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.
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 (85.8%) 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.
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.
Operation / Metric Value Unit
aten::to
CPU Time 697858.56 μs
Device Time 82.94 μs
Self CPU Time 81.23 μ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::zeros
CPU Time 5946598.09 μs
Device Time 215226.67 μs
Self CPU Time 133792.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::zero_
CPU Time 6439289.28 μs
Device Time 7121760.86 μs
Self CPU Time 276509.53 μ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::fill_
CPU Time 6162782.07 μs
Device Time 7121760.86 μs
Self CPU Time 367878.09 μs
Self Device Time 7121758.33 μ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 6141737.39 μs
Device Time 2686.96 μs
Self CPU Time 6141737.39 μs
Self Device Time 2686.96 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
conv_pool_sigmoid_sum_kernel(float const*, float const*, float const*, float*, int, int, int, int, int, int, int, int)
CPU Time 0.00 μs
Device Time 1393261.47 μs
Self CPU Time 0.00 μs
Self Device Time 1393261.47 μ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 282040.59 μs
Device Time 1145304.03 μs
Self CPU Time 282040.59 μs
Self Device Time 1145304.03 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void at::native::vectorized_elementwise_kernel<4, at::native::FillFunctor<int>, at::detail::Array<char*, 1> >(int, at::native::FillFunctor<int>, at::detail::Array<char*, 1>)
CPU Time 0.00 μs
Device Time 6906534.19 μs
Self CPU Time 0.00 μs
Self Device Time 6906534.19 μ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
45291 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/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:16:5 bugprone-easily-swappable-parameters
16 | const float* __restrict__ weight,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 | const float* __restrict__ bias,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:16:31: note: the first parameter in the range is 'weight'
16 | const float* __restrict__ weight,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:17:31: note: the last parameter in the range is 'bias'
17 | const float* __restrict__ bias,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:19:5: warning: 3 adjacent parameters of 'conv_pool_sigmoid_sum_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
19 | const int batch_size,
| ^~~~~~~~~~~~~~~~~~~~~
20 | const int in_channels,
| ~~~~~~~~~~~~~~~~~~~~~~
21 | const int out_channels,
| ~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:19:15: note: the first parameter in the range is 'batch_size'
19 | const int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:21:15: note: the last parameter in the range is 'out_channels'
21 | const int out_channels,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:23:5: warning: 3 adjacent parameters of 'conv_pool_sigmoid_sum_kernel' of similar type ('const int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
23 | const int width,
| ^~~~~~~~~~~~~~~~
24 | const int kernel_size,
| ~~~~~~~~~~~~~~~~~~~~~~
25 | const int pool_out_height,
| ~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:23:15: note: the first parameter in the range is 'width'
23 | const int width,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:25:15: note: the last parameter in the range is 'pool_out_height'
25 | const int pool_out_height,
| ^~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:29:17: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | int batch = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:30:14: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
30 | int oc = blockIdx.y;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:36:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
36 | int idx = blockIdx.z * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:99:19: warning: the parameter 'input' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
99 | torch::Tensor input,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:100:19: warning: the parameter 'weight' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
100 | torch::Tensor weight,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:101: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]
101 | torch::Tensor bias
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:103:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
103 | const int batch_size = input.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:104:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
104 | const int in_channels = input.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:105:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
105 | const int height = input.size(2);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:106:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
106 | const int width = input.size(3);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:107:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
107 | const int out_channels = weight.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250203_optimize_b10_s4_e0_sweep/level_2/task_65/b10_s1_efficient_3d_indexing/base/base.cu:108:29: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
108 | const int kernel_size = weight.size(2);
| ^