← Back to Leaderboard

The AI CUDA Engineer 👷

77_ConvTranspose3d_Scale_BatchNorm_GlobalAvgPoolmemory_coalescing_optimization_edit_1

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>

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

__global__ void 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;
    
    // Ensure coalesced access by iterating over spatial_size in strides of blockDim.x
    for (int i = tid; i < spatial_size; i += blockDim.x) {
        sum += input[index];
        index += blockDim.x;
    }
    
    // Store in shared memory
    sdata[tid] = sum;
    __syncthreads();
    
    // Reduce within block using shared memory
    for (int s = blockDim.x/2; s > 32; s >>= 1) {
        if (tid < s) {
            sdata[tid] += sdata[tid + s];
        }
        __syncthreads();
    }
    
    // Final reduction within warp
    if (tid < 32) {
        sum = sdata[tid];
        if (blockDim.x >= 64) sum += sdata[tid + 32];
        sum = warpReduceSum(sum);
    }
    
    // Write result
    if (tid == 0) {
        output[bid] = sum / 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(512); // Align to warp size
    dim3 blocks(batch_size * channels);
    int shared_mem_size = threads.x * sizeof(float);
    
    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.646 inst/cycle 0.000 5
Executed Ipc Elapsed 0.514 inst/cycle 0.000 5
Issue Slots Busy 16.290 % 0.032 5
Issued Ipc Active 0.650 inst/cycle 0.000 5
SM Busy 16.290 % 0.032 5
Memory Throughput 1704232967232.410 byte/second 184190999218094505984.000 5
Mem Busy 28.084 % 0.042 5
Max Bandwidth 50.872 % 0.169 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 9.320 % 0.001 5
Mem Pipes Busy 7.676 % 0.003 5
Warp Cycles Per Issued Instruction 90.864 cycle 0.099 5
Warp Cycles Per Executed Instruction 91.822 cycle 0.100 5
Avg. Active Threads Per Warp 31.920 0.000 5
Avg. Not Predicated Off Threads Per Warp 30.490 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 10.000 block 0.000 5
Block Limit Warps 4.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 93.720 % 0.009 5
Achieved Active Warps Per SM 59.980 warp 0.003 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.
INF Occupancy This kernel's theoretical occupancy is not impacted by any block limit.
Operation / Metric Value Unit
aten::conv_transpose3d
CPU Time 3520366.42 μs
Device Time 3419594.59 μs
Self CPU Time 15282.19 μ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 3505084.23 μs
Device Time 3419594.59 μs
Self CPU Time 14889.82 μ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 3490194.41 μs
Device Time 3419594.59 μs
Self CPU Time 30548.27 μ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 899968.72 μs
Device Time 3173693.94 μs
Self CPU Time 180520.88 μs
Self Device Time 3173693.94 μ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 3366029.65 μs
Device Time 37242.38 μs
Self CPU Time 3366029.65 μs
Self Device Time 37242.38 μ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 2639977.58 μs
Self CPU Time 0.00 μs
Self Device Time 2639977.58 μ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 2551881.54 μs
Device Time 245900.65 μs
Self CPU Time 30540.69 μs
Self Device Time 245900.65 μ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
45298 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:18:15 bugprone-narrowing-conversions
18 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:19:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
19 | int bid = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:24:46: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | for (int i = tid; i < spatial_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:26:18: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
26 | index += blockDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:34:18: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
34 | for (int s = blockDim.x/2; s > 32; s >>= 1) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:50:29: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
50 | output[bid] = sum / spatial_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:57:5: warning: 2 adjacent parameters of 'module_fn_cuda' of similar type ('double') are easily swapped by mistake [bugprone-easily-swappable-parameters]
57 | double momentum,
| ^~~~~~~~~~~~~~~~
58 | double scale_factor,
| ~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:57:12: note: the first parameter in the range is 'momentum'
57 | double momentum,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:58:12: note: the last parameter in the range is 'scale_factor'
58 | double scale_factor,
| ^~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:59: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]
59 | torch::Tensor conv_transpose,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:60:5: warning: 2 adjacent parameters of 'module_fn_cuda' of similar type ('torch::Tensor') are easily swapped by mistake [bugprone-easily-swappable-parameters]
60 | torch::Tensor conv_transpose_bias,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
61 | torch::Tensor bn_weight,
| ~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:60:19: note: the first parameter in the range is 'conv_transpose_bias'
60 | torch::Tensor conv_transpose_bias,
| ^~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:61:19: note: the last parameter in the range is 'bn_weight'
61 | torch::Tensor bn_weight,
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:96:22: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
96 | int batch_size = sizes[0];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:97:20: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
97 | int channels = sizes[1];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_2/task_77/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:98:24: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
98 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:100:31: warning: performing an implicit widening conversion to type 'const long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
100 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:100: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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:100:31: note: perform multiplication in a wider type
100 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:101:33: warning: performing an implicit widening conversion to type 'const long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
101 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:101:33: note: make conversion explicit to silence this warning
101 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:101:33: note: perform multiplication in a wider type
101 | 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/b2_s0_memory_coalescing_optimization/edit_1/edit_1.cu:105:27: warning: narrowing conversion from 'unsigned long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
105 | int shared_mem_size = threads.x * sizeof(float);
| ^