← Back to Leaderboard

The AI CUDA Engineer 👷

48_Mean_reduction_over_a_dimensionhybrid_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>

// Optimized warp reduction using shuffle instructions
template <typename scalar_t>
__device__ __forceinline__ scalar_t warp_reduce_sum(scalar_t val) {
    unsigned int mask = 0xffffffff;
    for (int offset = 16; offset > 0; offset /= 2) {
        val += __shfl_down_sync(mask, val, offset);
    }
    return val;
}

// Hybrid block reduction combining shared memory and warp shuffles
template <typename scalar_t>
__device__ __forceinline__ scalar_t hybrid_block_reduce(
    scalar_t* sdata,
    scalar_t thread_sum,
    const int tid,
    const int blockSize) {
    
    const int lane = tid & 31;
    const int wid = tid >> 5;
    const int warps = blockSize >> 5;
    
    // First do warp-level reduction
    scalar_t warp_sum = warp_reduce_sum(thread_sum);
    
    // Write reduced warp sums to shared memory
    if (lane == 0) {
        sdata[wid] = warp_sum;
    }
    __syncthreads();
    
    // Final reduction: let first warp handle all partial sums
    scalar_t block_sum = 0;
    if (tid < warps) {
        block_sum = warp_reduce_sum(tid < warps ? sdata[tid] : 0);
    }
    return block_sum;
}

template <typename scalar_t>
__global__ void hybrid_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;
    
    if (out_idx >= outer_size * inner_size)
        return;
        
    const int outer_idx = out_idx / inner_size;
    const int inner_idx = out_idx % inner_size;
    const int base_idx = outer_idx * dim_size * inner_size + inner_idx;
    
    // Coalesced memory access pattern with grid-stride loop
    scalar_t thread_sum = 0;
    #pragma unroll
    for (int i = tid; i < dim_size; i += blockDim.x) {
        thread_sum += input[base_idx + i * inner_size];
    }
    
    // Perform hybrid reduction
    scalar_t block_sum = hybrid_block_reduce(sdata, thread_sum, tid, blockDim.x);
    
    if (tid == 0) {
        output[out_idx] = block_sum / static_cast<scalar_t>(dim_size);
    }
}

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];
    }
    
    sizes.erase(sizes.begin() + dim);
    auto output = torch::empty(sizes, input.options());
    
    const int threads = 256;
    const int blocks = outer_size * inner_size;
    const int warps_per_block = threads >> 5;
    
    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "hybrid_mean_reduce", ([&] {
        const int shared_mem_size = warps_per_block * sizeof(scalar_t);
        hybrid_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, "Hybrid mean reduction (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.646 inst/cycle 0.000 5
Executed Ipc Elapsed 1.306 inst/cycle 0.000 5
Issue Slots Busy 42.156 % 0.114 5
Issued Ipc Active 1.686 inst/cycle 0.000 5
SM Busy 42.156 % 0.114 5
Memory Throughput 334568728200.014 byte/second 13682238193040314368.000 5
Mem Busy 56.690 % 0.944 5
Max Bandwidth 31.754 % 1.534 5
L1/TEX Hit Rate 3.976 % 0.189 5
L2 Hit Rate 85.912 % 0.879 5
Mem Pipes Busy 15.104 % 0.028 5
Warp Cycles Per Issued Instruction 27.714 cycle 0.020 5
Warp Cycles Per Executed Instruction 28.400 cycle 0.021 5
Avg. Active Threads Per Warp 30.090 0.000 5
Avg. Not Predicated Off Threads Per Warp 25.820 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 73.792 % 0.091 5
Achieved Active Warps Per SM 47.226 warp 0.037 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (25.5%) 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 (74.3%) 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 464848.80 μs
Device Time 378.49 μs
Self CPU Time 32.91 μ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 464815.89 μs
Device Time 378.49 μs
Self CPU Time 82.74 μ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 464127.81 μs
Device Time 0.00 μs
Self CPU Time 66.44 μ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 463858.60 μs
Device Time 0.00 μs
Self CPU Time 463858.60 μ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 529803.09 μs
Device Time 20386.31 μs
Self CPU Time 529803.09 μs
Self Device Time 20386.31 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void hybrid_mean_reduce_kernel<float>(float const*, float*, long, long, long)
CPU Time 0.00 μs
Device Time 83386.17 μs
Self CPU Time 0.00 μs
Self Device Time 83386.17 μ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 19194.73 μs
Device Time 40601.19 μs
Self CPU Time 19194.73 μs
Self Device Time 40601.19 μ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 64485.72 μs
Device Time 606649.04 μs
Self CPU Time 12536.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::fill_
CPU Time 51953.13 μs
Device Time 606649.04 μs
Self CPU Time 14794.33 μs
Self Device Time 606649.04 μ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 606649.04 μs
Self CPU Time 0.00 μs
Self Device Time 606649.04 μ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/b4_s3_hybrid_mean_reduce/base/base.cu:20:5 bugprone-easily-swappable-parameters
20 | const int tid,
| ^~~~~~~~~~~~~~
21 | const int blockSize) {
| ~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:20:15: note: the first parameter in the range is 'tid'
20 | const int tid,
| ^~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:21:15: note: the last parameter in the range is 'blockSize'
21 | const int blockSize) {
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:48:5: warning: 2 adjacent parameters of 'hybrid_mean_reduce_kernel' of similar type ('int64_t') are easily swapped by mistake [bugprone-easily-swappable-parameters]
48 | int64_t outer_size,
| ^~~~~~~~~~~~~~~~~~~
49 | int64_t dim_size,
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:48:13: note: the first parameter in the range is 'outer_size'
48 | int64_t outer_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:49:13: note: the last parameter in the range is 'dim_size'
49 | int64_t dim_size,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:55:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
55 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:56:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
56 | const int out_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:61:27: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
61 | const int outer_idx = out_idx / inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:62:27: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
62 | const int inner_idx = out_idx % inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:63:26: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
63 | const 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/b4_s3_hybrid_mean_reduce/base/base.cu:68:42: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
68 | 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/b4_s3_hybrid_mean_reduce/base/base.cu:100:24: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
100 | const int blocks = outer_size * inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250207_optimize_b5_s4_e1_sweep/level_1/task_48/b4_s3_hybrid_mean_reduce/base/base.cu:103: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]
103 | AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "hybrid_mean_reduce", ([&] {
| ^
/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__, \
| ^