← Back to Leaderboard

The AI CUDA Engineer 👷

48_Mean_reduction_over_a_dimensionmodularized_mean_reduce_base

Level 1 • Task 48
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
    """
    Reduces the input tensor along the specified dimension by taking the mean.

    Args:
        x (torch.Tensor): Input tensor of arbitrary shape.
        dim (int): The dimension to reduce over.

    Returns:
        torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
    """
    return torch.mean(x, dim=dim)


class Model(nn.Module):
    """
    Simple model that performs mean reduction over a specific dimension.
    """

    def __init__(self, dim: int):
        """
        Initializes the model with the dimension to reduce over.

        Args:
            dim (int): The dimension to reduce over.
        """
        super(Model, self).__init__()
        self.dim = dim

    def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
        """
        Reduces the input tensor along the specified dimension by taking the mean.

        Args:
            x (torch.Tensor): Input tensor of arbitrary shape.

        Returns:
            torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
        """
        return fn(x, self.dim)


batch_size = 16
dim1 = 256
dim2 = 256


def get_inputs():
    x = torch.randn(batch_size, dim1, dim2)
    return [x]


def get_init_inputs():
    return [1]
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Simple model that performs mean reduction over a specific dimension.
    """
    def __init__(self, dim: int):
        """
        Initializes the model with the dimension to reduce over.

        Args:
            dim (int): The dimension to reduce over.
        """
        super(Model, self).__init__()
        self.dim = dim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Reduces the input tensor along the specified dimension by taking the mean.

        Args:
            x (torch.Tensor): Input tensor of arbitrary shape.

        Returns:
            torch.Tensor: Output tensor with reduced dimension. The shape of the output is the same as the input except for the reduced dimension which is removed.
        """
        return torch.mean(x, dim=self.dim)

batch_size = 16
dim1 = 256
dim2 = 256

def get_inputs():
    x = torch.randn(batch_size, dim1, dim2)
    return [x]

def get_init_inputs():
    return [1]

Kernel Information

Related Kernels (Level 1, Task 48 • 48_Mean_reduction_over_a_dimension)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 evenly_distributed_mean_base 0.01 1.76 3.62
🥈 modular_warp_reduce_base 0.01 1.32 2.72
🥈 thread_block_optimization_base 0.01 1.32 2.72
🥈 warp_reduce_shfl_base_edit_1 0.01 1.32 2.72
🥈 warp_reduce_shfl_base_base 0.01 1.32 2.72
6 shared_mean_reduction_edit_1 0.01 1.22 2.51
6 shared_mean_reduction_base 0.01 1.22 2.51
8 mean_reduce_unroll_base 0.01 1.13 2.33
8 hybrid_reduce_warp_shared_edit_1 0.01 1.13 2.33
8 mean_reduce_balanced_threads_edit_1 0.01 1.13 2.33
8 hybrid_mean_reduce_base 0.01 1.13 2.33
8 hybrid_reduce_warp_shared_base 0.01 1.13 2.33
8 mean_reduce_warp_base 0.01 1.13 2.33
8 mean_reduce_unroll_optimized_edit_1 0.01 1.13 2.33
8 modularized_mean_reduce_base 0.01 1.13 2.33
8 mean_reduce_opt_base 0.01 1.13 2.33
8 mean_reduce_warp_edit_1 0.01 1.13 2.33
8 mean_reduce_unroll_optimized_base 0.01 1.13 2.33
8 mean_reduce_memory_optimized_base 0.01 1.13 2.33
8 hybrid_warp_block_mean_reduce_base 0.01 1.13 2.33
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

// Device function to perform block-level reduction using shared memory
template <typename scalar_t>
__device__ __forceinline__ scalar_t block_reduce_sum(scalar_t* sdata, int tid, int blockDim) {
    // Reduce within the block using loop unrolling
    for (int stride = blockDim / 2; stride > 32; stride >>= 1) {
        if (tid < stride) {
            sdata[tid] += sdata[tid + stride];
        }
        __syncthreads();
    }
    if (tid < 32) {
        volatile scalar_t* vsmem = sdata;
        if (blockDim >= 64) vsmem[tid] += vsmem[tid + 32];
        if (blockDim >= 32) vsmem[tid] += vsmem[tid + 16];
        if (blockDim >= 16) vsmem[tid] += vsmem[tid + 8];
        if (blockDim >= 8)  vsmem[tid] += vsmem[tid + 4];
        if (blockDim >= 4)  vsmem[tid] += vsmem[tid + 2];
        if (blockDim >= 2)  vsmem[tid] += vsmem[tid + 1];
    }
    return sdata[0];
}

// CUDA kernel for mean reduction over a specified dimension
template <typename scalar_t>
__global__ void mean_reduce_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    int64_t outer_size,
    int64_t dim_size,
    int64_t inner_size) {

    extern __shared__ char shared_mem[];
    scalar_t* sdata = reinterpret_cast<scalar_t*>(shared_mem);

    const int tid = threadIdx.x;
    const int out_idx = blockIdx.x;

    // Check if the current block corresponds to a valid output element
    if (out_idx >= outer_size * inner_size)
        return;

    int outer_idx = out_idx / inner_size;
    int inner_idx = out_idx % inner_size;
    int base_idx = outer_idx * dim_size * inner_size + inner_idx;

    // Each thread computes a partial sum over elements in the reduction dimension
    scalar_t sum = 0;
    for (int i = tid; i < dim_size; i += blockDim.x) {
        sum += input[base_idx + i * inner_size];
    }
    sdata[tid] = sum;
    __syncthreads();

    // Use the modular block reduction function to sum the partial results
    scalar_t block_sum = block_reduce_sum(sdata, tid, blockDim.x);
    if (tid == 0) {
        output[out_idx] = block_sum / static_cast<scalar_t>(dim_size);
    }
}

// Host function to prepare and launch the CUDA kernel
torch::Tensor mean_reduce_cuda(torch::Tensor input, int64_t dim) {
    if (dim < 0) dim += input.dim();

    auto sizes = input.sizes().vec();
    int64_t dim_size = sizes[dim];

    int64_t outer_size = 1;
    for (int i = 0; i < dim; i++) {
        outer_size *= sizes[i];
    }

    int64_t inner_size = 1;
    for (size_t i = dim + 1; i < sizes.size(); i++) {
        inner_size *= sizes[i];
    }

    // Remove the reduced dimension from the output shape
    sizes.erase(sizes.begin() + dim);
    auto output = torch::empty(sizes, input.options());

    const int threads = 256;
    const int blocks = outer_size * inner_size;

    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "mean_reduce_cuda", ([&] {
        const int shared_mem_size = threads * sizeof(scalar_t);
        mean_reduce_kernel<scalar_t><<<blocks, threads, shared_mem_size>>>(
            input.data_ptr<scalar_t>(),
            output.data_ptr<scalar_t>(),
            outer_size,
            dim_size,
            inner_size
        );
    }));

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &mean_reduce_cuda, "Mean reduction (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.756 inst/cycle 0.001 5
Executed Ipc Elapsed 1.356 inst/cycle 0.000 5
Issue Slots Busy 44.260 % 0.574 5
Issued Ipc Active 1.770 inst/cycle 0.001 5
SM Busy 44.260 % 0.574 5
Memory Throughput 318146021537.816 byte/second 7293715449278270464.000 5
Mem Busy 53.894 % 0.611 5
Max Bandwidth 31.170 % 0.778 5
L1/TEX Hit Rate 6.670 % 0.642 5
L2 Hit Rate 85.536 % 6.547 5
Mem Pipes Busy 19.722 % 0.027 5
Warp Cycles Per Issued Instruction 28.566 cycle 0.037 5
Warp Cycles Per Executed Instruction 28.796 cycle 0.037 5
Avg. Active Threads Per Warp 31.490 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.880 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 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 77.840 % 0.098 5
Achieved Active Warps Per SM 49.816 warp 0.040 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (26.3%) 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 (78.0%) 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::to
CPU Time 490288.15 μs
Device Time 360.41 μs
Self CPU Time 37.51 μ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::_to_copy
CPU Time 490250.64 μs
Device Time 360.41 μs
Self CPU Time 83.10 μ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::empty_strided
CPU Time 489589.46 μs
Device Time 0.00 μs
Self CPU Time 75.59 μ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
cudaDeviceGetStreamPriorityRange
CPU Time 487484.01 μs
Device Time 0.00 μs
Self CPU Time 487484.01 μ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
cudaLaunchKernel
CPU Time 395979.84 μs
Device Time 20501.03 μs
Self CPU Time 395979.84 μs
Self Device Time 20501.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 mean_reduce_kernel<float>(float const*, float*, long, long, long)
CPU Time 0.00 μs
Device Time 83391.90 μs
Self CPU Time 0.00 μs
Self Device Time 83391.90 μ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 25750.89 μs
Device Time 40948.90 μs
Self CPU Time 25750.89 μs
Self Device Time 40948.90 μ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 95000.11 μs
Device Time 610973.21 μs
Self CPU Time 21369.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::fill_
CPU Time 73632.23 μs
Device Time 610973.21 μs
Self CPU Time 27068.86 μs
Self Device Time 610973.21 μ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 610973.21 μs
Self CPU Time 0.00 μs
Self Device Time 610973.21 μ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
45287 warnings generated when compiling for host.
Suppressed 45322 warnings (45275 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/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:7:71 bugprone-easily-swappable-parameters
7 | __device__ __forceinline__ scalar_t block_reduce_sum(scalar_t* sdata, int tid, int blockDim) {
| ^~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:7:75: note: the first parameter in the range is 'tid'
7 | __device__ __forceinline__ scalar_t block_reduce_sum(scalar_t* sdata, int tid, int blockDim) {
| ^~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:7:84: note: the last parameter in the range is 'blockDim'
7 | __device__ __forceinline__ scalar_t block_reduce_sum(scalar_t* sdata, int tid, int blockDim) {
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:32:5: warning: 2 adjacent parameters of 'mean_reduce_kernel' of similar type ('int64_t') are easily swapped by mistake [bugprone-easily-swappable-parameters]
32 | int64_t outer_size,
| ^~~~~~~~~~~~~~~~~~~
33 | int64_t dim_size,
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:32:13: note: the first parameter in the range is 'outer_size'
32 | int64_t outer_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:33:13: note: the last parameter in the range is 'dim_size'
33 | int64_t dim_size,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:39:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
39 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:40:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
40 | const int out_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:46:21: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
46 | int outer_idx = out_idx / inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:47:21: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
47 | int inner_idx = out_idx % inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:48:20: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
48 | int base_idx = outer_idx * dim_size * inner_size + inner_idx;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:52:42: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
52 | for (int i = tid; i < dim_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:87:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
87 | const int blocks = outer_size * inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b2_s3_modularized_mean_reduce/base/base.cu:89:5: warning: inside a lambda, '__func__' expands to the name of the function call operator; consider capturing the name of the enclosing function explicitly [bugprone-lambda-function-name]
89 | AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "mean_reduce_cuda", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:237:34: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES'
237 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:233:3: note: expanded from macro 'AT_DISPATCH_CASE_FLOATING_TYPES'
233 | AT_DISPATCH_CASE(at::ScalarType::Double, __VA_ARGS__) \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:74:3: note: expanded from macro 'AT_DISPATCH_CASE'
74 | AT_PRIVATE_CASE_TYPE_USING_HINT(enum_type, scalar_t, __VA_ARGS__)
| ^
note: (skipping 1 expansions in backtrace; use -fmacro-backtrace-limit=0 to see all)
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:58:7: note: expanded from macro 'AT_PRIVATE_CHECK_SELECTIVE_BUILD'
58 | AT_ERROR( \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:711:32: note: expanded from macro 'AT_ERROR'
711 | C10_EXPAND_MSVC_WORKAROUND(TORCH_CHECK(false, ::c10::str(__VA_ARGS__))); \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/c10/util/Exception.h:536:9: note: expanded from macro 'TORCH_CHECK'
536 | __func__, \
| ^