← Back to Leaderboard

The AI CUDA Engineer 👷

77_ConvTranspose3d_Scale_BatchNorm_GlobalAvgPooloptimized_global_avg_pool_base

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


def module_fn(
    x: torch.Tensor,
    eps: float,
    momentum: float,
    scale_factor: float,
    conv_transpose: torch.Tensor,
    conv_transpose_bias: torch.Tensor,
    bn_weight: torch.Tensor,
    bn_bias: torch.Tensor,
    bn_running_mean: torch.Tensor,
    bn_running_var: torch.Tensor,
) -> torch.Tensor:
    """
    Applies 3D transposed convolution, scaling, batch normalization and global average pooling.

    Args:
        x (torch.Tensor): Input tensor of shape (batch_size, in_channels, depth, height, width)
        eps (float): Small constant for numerical stability in batch norm
        momentum (float): Momentum for batch norm running stats
        conv_transpose (torch.Tensor): Transposed conv weights
        conv_transpose_bias (torch.Tensor): Transposed conv bias
        bn_weight (torch.Tensor): Batch norm weight parameter
        bn_bias (torch.Tensor): Batch norm bias parameter
        bn_running_mean (torch.Tensor): Batch norm running mean
        bn_running_var (torch.Tensor): Batch norm running variance

    Returns:
        torch.Tensor: Output tensor after applying operations
    """
    x = F.conv_transpose3d(x, conv_transpose, bias=conv_transpose_bias)
    x = x * scale_factor
    x = F.batch_norm(
        x,
        bn_running_mean,
        bn_running_var,
        bn_weight,
        bn_bias,
        training=True,
        momentum=momentum,
        eps=eps,
    )
    x = F.adaptive_avg_pool3d(x, (1, 1, 1))
    return x


class Model(nn.Module):
    """
    Model that performs a 3D transposed convolution, scales the output, applies batch normalization,
    and then performs global average pooling.
    """

    def __init__(
        self, in_channels, out_channels, kernel_size, scale_factor, eps, momentum
    ):
        super(Model, self).__init__()
        conv = nn.ConvTranspose3d(in_channels, out_channels, kernel_size)
        self.conv_transpose_parameter = nn.Parameter(conv.weight)
        self.conv_transpose_bias = nn.Parameter(conv.bias)

        bn = nn.BatchNorm3d(out_channels)
        self.bn_weight = nn.Parameter(bn.weight + torch.randn(bn.weight.shape) * 0.02)
        self.bn_bias = nn.Parameter(bn.bias + torch.randn(bn.bias.shape) * 0.02)
        self.register_buffer(
            "bn_running_mean",
            bn.running_mean + torch.randn(bn.running_mean.shape) * 0.02,
        )
        self.register_buffer(
            "bn_running_var",
            bn.running_var + torch.randn(bn.running_var.shape).abs() * 0.02,
        )

    def forward(self, x, eps, momentum, scale_factor, fn=module_fn):
        return fn(
            x,
            eps,
            momentum,
            scale_factor,
            self.conv_transpose_parameter,
            self.conv_transpose_bias,
            self.bn_weight,
            self.bn_bias,
            self.bn_running_mean,
            self.bn_running_var,
        )


batch_size = 16
in_channels = 64
out_channels = 32
depth, height, width = 16, 32, 32
kernel_size = 3
scale_factor = 2.0
eps = 1e-5
momentum = 0.1


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


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

class Model(nn.Module):
    """
    Model that performs a 3D transposed convolution, scales the output, applies batch normalization, 
    and then performs global average pooling. 
    """
    def __init__(self, in_channels, out_channels, kernel_size, scale_factor, eps=1e-5, momentum=0.1):
        super(Model, self).__init__()
        self.conv_transpose = nn.ConvTranspose3d(in_channels, out_channels, kernel_size)
        self.scale_factor = scale_factor
        self.batch_norm = nn.BatchNorm3d(out_channels, eps=eps, momentum=momentum)
        self.batch_norm.weight = nn.Parameter(self.batch_norm.weight + torch.randn(self.batch_norm.weight.shape)*0.02)
        self.batch_norm.bias = nn.Parameter(self.batch_norm.bias + torch.randn(self.batch_norm.bias.shape)*0.02)
        self.batch_norm.running_mean = self.batch_norm.running_mean + torch.randn(self.batch_norm.running_mean.shape)*0.02
        self.batch_norm.running_var = self.batch_norm.running_var + torch.randn(self.batch_norm.running_var.shape).abs()*0.02
        self.global_avg_pool = nn.AdaptiveAvgPool3d((1, 1, 1))

    def forward(self, x):
        x = self.conv_transpose(x)
        x = x * self.scale_factor
        x = self.batch_norm(x)
        x = self.global_avg_pool(x)
        return x

batch_size = 16
in_channels = 64
out_channels = 32
depth, height, width = 16, 32, 32
kernel_size = 3
scale_factor = 2.0

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

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

Kernel Information

Related Kernels (Level 2, Task 77 • 77_ConvTranspose3d_Scale_BatchNorm_GlobalAvgPool)

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

#define WARP_SIZE 32

__device__ float warpReduceSum(float val) {
    for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2)
        val += __shfl_down_sync(0xffffffff, val, offset);
    return val;
}

__global__ void optimized_global_avg_pool_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    int spatial_size
) {
    extern __shared__ float sdata[];

    int tid = threadIdx.x;
    int bid = blockIdx.x;
    int index = bid * spatial_size + tid;

    float sum = 0.0f;

    // Vectorized loads
    int vector_size = spatial_size / 4 * 4;
    for (int i = tid * 4; i < vector_size; i += blockDim.x * 4) {
        float4 in4 = *reinterpret_cast<const float4*>(&input[bid * spatial_size + i]);
        sum += in4.x + in4.y + in4.z + in4.w;
    }

    // Handle remaining elements
    for (int i = vector_size + tid; i < spatial_size; i += blockDim.x) {
        sum += input[bid * spatial_size + i];
    }

    // Intra-warp reduction
    sum = warpReduceSum(sum);

    // Store result in shared memory
    int lane = tid & (WARP_SIZE - 1);
    int warpId = tid >> 5;
    if (lane == 0) {
        sdata[warpId] = sum;
    }
    __syncthreads();

    // Final reduction using the first warp
    if (tid < (blockDim.x + WARP_SIZE - 1) / WARP_SIZE) {
        sum = sdata[tid];
        sum = warpReduceSum(sum);
        if (tid == 0) {
            output[bid] = sum / static_cast<float>(spatial_size);
        }
    }
}

torch::Tensor module_fn_cuda(
    torch::Tensor x,
    double eps,
    double momentum,
    double scale_factor,
    torch::Tensor conv_transpose,
    torch::Tensor conv_transpose_bias,
    torch::Tensor bn_weight,
    torch::Tensor bn_bias,
    torch::Tensor bn_running_mean,
    torch::Tensor bn_running_var
) {
    // Perform ConvTranspose3d
    x = torch::conv_transpose3d(
        x,
        conv_transpose,
        conv_transpose_bias,
        /*stride=*/{1, 1, 1},
        /*padding=*/{0, 0, 0},
        /*output_padding=*/{0, 0, 0},
        /*groups=*/1,
        /*dilation=*/{1, 1, 1}
    );

    // Multiply by scale_factor
    x = x * scale_factor;

    // Batch Normalization
    x = torch::batch_norm(
        x,
        bn_weight,
        bn_bias,
        bn_running_mean,
        bn_running_var,
        /*training=*/true,
        momentum,
        eps,
        /*cudnn_enabled=*/true
    );

    // Custom global average pooling implementation
    auto sizes = x.sizes();
    int batch_size = sizes[0];
    int channels = sizes[1];
    int spatial_size = sizes[2] * sizes[3] * sizes[4];
    
    auto x_reshaped = x.view({batch_size * channels, spatial_size});
    auto output = torch::empty({batch_size * channels}, x.options());
    
    dim3 threads(256);
    dim3 blocks(batch_size * channels);
    int shared_mem_size = ((threads.x + WARP_SIZE - 1) / WARP_SIZE) * sizeof(float);
    
    optimized_global_avg_pool_kernel<<<blocks, threads, shared_mem_size>>>(
        x_reshaped.data_ptr<float>(),
        output.data_ptr<float>(),
        spatial_size
    );
    
    return output.view({batch_size, channels, 1, 1, 1});
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &module_fn_cuda, "Module function forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.308 inst/cycle 0.000 5
Executed Ipc Elapsed 0.238 inst/cycle 0.000 5
Issue Slots Busy 7.870 % 0.011 5
Issued Ipc Active 0.316 inst/cycle 0.000 5
SM Busy 7.870 % 0.011 5
Memory Throughput 2185785578031.706 byte/second 380768165865048965120.000 5
Mem Busy 36.176 % 0.114 5
Max Bandwidth 65.290 % 0.316 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 4.142 % 0.000 5
Mem Pipes Busy 2.674 % 0.001 5
Warp Cycles Per Issued Instruction 93.800 cycle 0.137 5
Warp Cycles Per Executed Instruction 95.776 cycle 0.143 5
Avg. Active Threads Per Warp 31.600 0.000 5
Avg. Not Predicated Off Threads Per Warp 30.600 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 10.000 block 0.000 5
Block Limit Shared Mem 28.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 46.516 % 0.002 5
Achieved Active Warps Per SM 29.770 warp 0.001 5
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 (46.5%) 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::conv_transpose3d
CPU Time 3513329.13 μs
Device Time 3426538.30 μs
Self CPU Time 15631.03 μ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 3497698.10 μs
Device Time 3426538.30 μs
Self CPU Time 15574.61 μ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 3482123.49 μs
Device Time 3426538.30 μs
Self CPU Time 31682.63 μ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_transpose
CPU Time 883750.85 μs
Device Time 3182255.88 μs
Self CPU Time 177069.48 μs
Self Device Time 3182255.88 μ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 3324844.42 μs
Device Time 37005.97 μs
Self CPU Time 3324844.42 μs
Self Device Time 37005.97 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
sm90_xmma_dgrad_implicit_gemm_f32f32_tf32f32_f32_nhwckrsc_nhwc_tilesize256x32x32_warpgroupsize1x1x1_g1_execute_segment_k_off_kernel__5x_cudnn
CPU Time 0.00 μs
Device Time 2653766.49 μs
Self CPU Time 0.00 μs
Self Device Time 2653766.49 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::add_
CPU Time 2558423.91 μs
Device Time 244282.43 μs
Self CPU Time 29635.67 μs
Self Device Time 244282.43 μ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
45297 warnings generated when compiling for host.
Suppressed 45330 warnings (45283 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/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:20:15 bugprone-narrowing-conversions
20 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:21:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
21 | int bid = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:22:9: warning: Value stored to 'index' during its initialization is never read [clang-analyzer-deadcode.DeadStores]
22 | int index = bid * spatial_size + tid;
| ^~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:22:9: note: Value stored to 'index' during its initialization is never read
22 | int index = bid * spatial_size + tid;
| ^~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:28:49: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | for (int i = tid * 4; i < vector_size; i += blockDim.x * 4) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:34:60: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
34 | for (int i = vector_size + tid; i < spatial_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:62:5: warning: 2 adjacent parameters of 'module_fn_cuda' of similar type ('double') are easily swapped by mistake [bugprone-easily-swappable-parameters]
62 | double momentum,
| ^~~~~~~~~~~~~~~~
63 | double scale_factor,
| ~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:62:12: note: the first parameter in the range is 'momentum'
62 | double momentum,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:63:12: note: the last parameter in the range is 'scale_factor'
63 | double scale_factor,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:64:19: warning: the parameter 'conv_transpose' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
64 | torch::Tensor conv_transpose,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:65:5: warning: 2 adjacent parameters of 'module_fn_cuda' of similar type ('torch::Tensor') are easily swapped by mistake [bugprone-easily-swappable-parameters]
65 | torch::Tensor conv_transpose_bias,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
66 | torch::Tensor bn_weight,
| ~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:65:19: note: the first parameter in the range is 'conv_transpose_bias'
65 | torch::Tensor conv_transpose_bias,
| ^~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:66:19: note: the last parameter in the range is 'bn_weight'
66 | torch::Tensor bn_weight,
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:101:22: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
101 | int batch_size = sizes[0];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:102:20: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
102 | int channels = sizes[1];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:103:24: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
103 | int spatial_size = sizes[2] * sizes[3] * sizes[4];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:105:31: warning: performing an implicit widening conversion to type 'const long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
105 | auto x_reshaped = x.view({batch_size * channels, spatial_size});
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:105:31: note: make conversion explicit to silence this warning
4 | auto x_reshaped = x.view({batch_size * channels, spatial_size});
| ^~~~~~~~~~~~~~~~~~~~~
| static_cast<const long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:105:31: note: perform multiplication in a wider type
105 | auto x_reshaped = x.view({batch_size * channels, spatial_size});
| ^~~~~~~~~~
| static_cast<const long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:106:33: warning: performing an implicit widening conversion to type 'const long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
106 | auto output = torch::empty({batch_size * channels}, x.options());
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:106:33: note: make conversion explicit to silence this warning
106 | auto output = torch::empty({batch_size * channels}, x.options());
| ^~~~~~~~~~~~~~~~~~~~~
| static_cast<const long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:106:33: note: perform multiplication in a wider type
106 | auto output = torch::empty({batch_size * channels}, x.options());
| ^~~~~~~~~~
| static_cast<const long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b4_s1_optimized_global_avg_pool/base/base.cu:110:27: warning: narrowing conversion from 'unsigned long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
110 | int shared_mem_size = ((threads.x + WARP_SIZE - 1) / WARP_SIZE) * sizeof(float);
| ^