← Back to Leaderboard

The AI CUDA Engineer 👷

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

template <typename scalar_t>
__device__ __forceinline__ scalar_t warp_reduce(scalar_t val) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset /= 2) {
        val += __shfl_down_sync(0xffffffff, val, offset);
    }
    return val;
}

template <typename scalar_t>
__global__ void hybrid_reduce_mean_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    int64_t outer_size,
    int64_t dim_size,
    int64_t inner_size) {
    
    constexpr int BLOCK_SIZE = 256;
    constexpr int WARP_SIZE = 32;
    __shared__ scalar_t shared_data[BLOCK_SIZE];
    
    const int tid = threadIdx.x;
    const int wid = tid / WARP_SIZE;
    const int lane = tid % WARP_SIZE;
    const int output_idx = blockIdx.x;
    
    if (output_idx >= outer_size * inner_size) return;
    
    const int outer_idx = output_idx / inner_size;
    const int inner_idx = output_idx % inner_size;
    const int input_offset = outer_idx * dim_size * inner_size + inner_idx;
    
    // First level reduction: threads cooperatively load and sum values
    scalar_t thread_sum = 0;
    #pragma unroll 4
    for (int i = tid; i < dim_size; i += BLOCK_SIZE) {
        thread_sum += input[input_offset + i * inner_size];
    }
    
    // Store partial sum in shared memory
    shared_data[tid] = thread_sum;
    __syncthreads();
    
    // Second level reduction: warp-level reduction of shared memory
    if (tid < WARP_SIZE) {
        scalar_t warp_sum = 0;
        #pragma unroll
        for (int i = tid; i < BLOCK_SIZE; i += WARP_SIZE) {
            warp_sum += shared_data[i];
        }
        
        // Final warp reduction using shuffle
        warp_sum = warp_reduce(warp_sum);
        
        // First thread writes result
        if (lane == 0) {
            output[output_idx] = warp_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 (int 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 BLOCK_SIZE = 256;
    const int num_blocks = outer_size * inner_size;
    
    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "hybrid_reduce_mean_cuda", ([&] {
        hybrid_reduce_mean_kernel<scalar_t><<<num_blocks, BLOCK_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 using hybrid approach (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.522 inst/cycle 0.000 5
Executed Ipc Elapsed 1.218 inst/cycle 0.000 5
Issue Slots Busy 38.460 % 0.054 5
Issued Ipc Active 1.538 inst/cycle 0.000 5
SM Busy 38.460 % 0.054 5
Memory Throughput 372491063610.610 byte/second 262171594067876288.000 5
Mem Busy 65.822 % 0.199 5
Max Bandwidth 30.070 % 0.016 5
L1/TEX Hit Rate 1.386 % 0.281 5
L2 Hit Rate 85.640 % 0.281 5
Mem Pipes Busy 14.446 % 0.001 5
Warp Cycles Per Issued Instruction 30.878 cycle 0.054 5
Warp Cycles Per Executed Instruction 31.204 cycle 0.057 5
Avg. Active Threads Per Warp 31.460 0.000 5
Avg. Not Predicated Off Threads Per Warp 29.110 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 74.434 % 0.015 5
Achieved Active Warps Per SM 47.640 warp 0.006 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (22.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.
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 584957.09 μs
Device Time 453.05 μs
Self CPU Time 40.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
aten::_to_copy
CPU Time 584916.65 μs
Device Time 453.05 μs
Self CPU Time 100.72 μ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 584111.32 μs
Device Time 0.00 μs
Self CPU Time 79.95 μ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 583794.55 μs
Device Time 0.00 μs
Self CPU Time 583794.55 μ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 539926.18 μs
Device Time 21262.90 μs
Self CPU Time 539926.18 μs
Self Device Time 21262.90 μ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_reduce_mean_kernel<float>(float const*, float*, long, long, long)
CPU Time 0.00 μs
Device Time 84006.88 μs
Self CPU Time 0.00 μs
Self Device Time 84006.88 μ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 18246.20 μs
Device Time 42289.51 μs
Self CPU Time 18246.20 μs
Self Device Time 42289.51 μ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 67729.63 μs
Device Time 632088.07 μs
Self CPU Time 14819.45 μ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 52911.23 μs
Device Time 632088.07 μs
Self CPU Time 15330.53 μs
Self Device Time 632088.07 μ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 632166.59 μs
Self CPU Time 0.00 μs
Self Device Time 632166.59 μ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
45286 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/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:18:5 bugprone-easily-swappable-parameters
18 | int64_t outer_size,
| ^~~~~~~~~~~~~~~~~~~
19 | int64_t dim_size,
| ~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:18:13: note: the first parameter in the range is 'outer_size'
18 | int64_t outer_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:19:13: note: the last parameter in the range is 'dim_size'
19 | int64_t dim_size,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:26:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
26 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:29:28: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | const int output_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:33:27: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
33 | const int outer_idx = output_idx / inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:34:27: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
34 | const int inner_idx = output_idx % inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:35:30: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
35 | const int input_offset = outer_idx * dim_size * inner_size + inner_idx;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:78:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
78 | for (int i = dim + 1; i < sizes.size(); i++) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:86:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
86 | const int num_blocks = outer_size * inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_48/b5_s2_hybrid_reduce_warp_shared/base/base.cu:88: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]
88 | AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "hybrid_reduce_mean_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__, \
| ^