← Back to Leaderboard

The AI CUDA Engineer 👷

47_Sum_reduction_over_a_dimensionhybrid_warp_shared_reduce_base

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


def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
    """
    Applies sum reduction over the specified dimension.

    Args:
        x (torch.Tensor): Input tensor of shape (..., dim, ...).
        dim (int): Dimension to reduce over.

    Returns:
        torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
    """
    return torch.sum(x, dim=dim, keepdim=True)


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

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

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

    def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
        """
        Applies sum reduction over the specified dimension.

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

        Returns:
            torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
        """
        return fn(x, self.dim)


batch_size = 16
dim1 = 256
dim2 = 256
reduce_dim = 1


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


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

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

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

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies sum reduction over the specified dimension.

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

        Returns:
            torch.Tensor: Output tensor after sum reduction, shape (..., 1, ...).
        """
        return torch.sum(x, dim=self.dim, keepdim=True)

batch_size = 16
dim1 = 256
dim2 = 256
reduce_dim = 1

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

def get_init_inputs():
    return [reduce_dim]

Kernel Information

Related Kernels (Level 1, Task 47 • 47_Sum_reduction_over_a_dimension)

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

// Hybrid kernel combining shared memory tiling with warp-level primitives
template <typename scalar_t>
__global__ void hybrid_reduce_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    int64_t reduce_size,
    int64_t inner_size) {
    
    constexpr int WARP_SIZE = 32;
    constexpr int BLOCK_WARPS = 8;  // 8 warps per block = 256 threads
    constexpr int BLOCK_SIZE = WARP_SIZE * BLOCK_WARPS;
    
    // Shared memory for block-level reduction
    extern __shared__ char smem[];
    scalar_t* shared_data = reinterpret_cast<scalar_t*>(smem);
    
    int tid = threadIdx.x;
    int warp_id = tid / WARP_SIZE;
    int lane_id = tid % WARP_SIZE;
    int block_output_idx = blockIdx.x;
    
    // Calculate global indices
    int outer_idx = block_output_idx / inner_size;
    int inner_idx = block_output_idx % inner_size;
    
    // Each thread processes multiple elements with stride equal to block size
    scalar_t thread_sum = 0;
    int base_idx = outer_idx * (reduce_size * inner_size) + inner_idx;
    
    // Phase 1: Parallel reduction with loop unrolling
    #pragma unroll 4
    for (int i = tid; i < reduce_size; i += BLOCK_SIZE) {
        thread_sum += input[base_idx + i * inner_size];
    }
    
    // Phase 2: Warp-level reduction using shuffle
    #pragma unroll
    for (int offset = WARP_SIZE/2; offset > 0; offset /= 2) {
        thread_sum += __shfl_down_sync(0xffffffff, thread_sum, offset);
    }
    
    // First thread in each warp writes to shared memory
    if (lane_id == 0) {
        shared_data[warp_id] = thread_sum;
    }
    __syncthreads();
    
    // Phase 3: Final reduction across warps using first warp
    if (warp_id == 0) {
        // Load warp results
        thread_sum = (lane_id < BLOCK_WARPS) ? shared_data[lane_id] : 0;
        
        // Final warp reduction
        #pragma unroll
        for (int offset = WARP_SIZE/2; offset > 0; offset /= 2) {
            thread_sum += __shfl_down_sync(0xffffffff, thread_sum, offset);
        }
        
        // Write final result
        if (lane_id == 0) {
            output[block_output_idx] = thread_sum;
        }
    }
}

torch::Tensor sum_reduce_cuda(torch::Tensor input, int64_t dim) {
    if (dim < 0) dim += input.dim();
    
    auto sizes = input.sizes().vec();
    int64_t reduce_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[dim] = 1;
    auto output = torch::empty(sizes, input.options());
    
    const int BLOCK_SIZE = 256;
    int total_outputs = outer_size * inner_size;
    int blocks = total_outputs;
    
    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "sum_reduce_cuda", ([&] {
        hybrid_reduce_kernel<scalar_t><<<blocks, BLOCK_SIZE, 
            (BLOCK_SIZE/32) * sizeof(scalar_t)>>>(
            input.data_ptr<scalar_t>(),
            output.data_ptr<scalar_t>(),
            reduce_size,
            inner_size
        );
    }));
    
    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &sum_reduce_cuda, "Hybrid sum reduction (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.554 inst/cycle 0.000 5
Executed Ipc Elapsed 1.236 inst/cycle 0.000 5
Issue Slots Busy 39.070 % 0.025 5
Issued Ipc Active 1.560 inst/cycle 0.000 5
SM Busy 39.070 % 0.025 5
Memory Throughput 365222882624.662 byte/second 5168921417524110336.000 5
Mem Busy 65.996 % 0.084 5
Max Bandwidth 29.988 % 0.111 5
L1/TEX Hit Rate 0.926 % 0.065 5
L2 Hit Rate 86.032 % 0.689 5
Mem Pipes Busy 17.352 % 0.012 5
Warp Cycles Per Issued Instruction 31.956 cycle 0.229 5
Warp Cycles Per Executed Instruction 32.118 cycle 0.231 5
Avg. Active Threads Per Warp 31.660 0.000 5
Avg. Not Predicated Off Threads Per Warp 27.610 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 77.426 % 0.020 5
Achieved Active Warps Per SM 49.554 warp 0.008 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (26.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 (77.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::to
CPU Time 215818.69 μs
Device Time 299.71 μs
Self CPU Time 36.37 μ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 215782.32 μs
Device Time 299.71 μs
Self CPU Time 94.49 μ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 215151.64 μs
Device Time 0.00 μs
Self CPU Time 63.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
cudaDeviceGetStreamPriorityRange
CPU Time 214887.67 μs
Device Time 0.00 μs
Self CPU Time 214887.67 μ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 514920.37 μs
Device Time 21039.16 μs
Self CPU Time 514920.37 μs
Self Device Time 21039.16 μ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_kernel<float>(float const*, float*, long, long)
CPU Time 0.00 μs
Device Time 83896.85 μs
Self CPU Time 0.00 μs
Self Device Time 83896.85 μ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 18179.32 μs
Device Time 38845.98 μs
Self CPU Time 18179.32 μs
Self Device Time 38845.98 μ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 67660.67 μs
Device Time 582399.67 μs
Self CPU Time 13357.38 μ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 54307.79 μs
Device Time 582399.67 μs
Self CPU Time 14171.48 μs
Self Device Time 582399.67 μ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 582399.67 μs
Self CPU Time 0.00 μs
Self Device Time 582399.67 μ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
45285 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/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:21:15 bugprone-narrowing-conversions
21 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:24:28: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | int block_output_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:27:21: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
27 | int outer_idx = block_output_idx / inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:28:21: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | int inner_idx = block_output_idx % inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:32:20: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
32 | int base_idx = outer_idx * (reduce_size * inner_size) + inner_idx;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:80:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
80 | for (int i = dim + 1; i < sizes.size(); i++) inner_size *= sizes[i];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_reduce/base/base.cu:86:25: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
86 | int total_outputs = outer_size * inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250201_optimize_b10_s4_e0_sweep/level_1/task_47/b8_s3_hybrid_warp_shared_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(), "sum_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__, \
| ^