← Back to Leaderboard

The AI CUDA Engineer 👷

53_Min_reduction_over_a_dimensionmin_reduction_warp_shared_hybrid_base

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


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

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

    Returns:
        torch.Tensor: Output tensor after min reduction over the specified dimension
    """
    return torch.min(x, dim)[0]


class Model(nn.Module):
    """
    Simple model that performs min 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:
        """
        Applies min reduction over the specified dimension to the input tensor.

        Args:
            x (torch.Tensor): Input tensor
            fn: Function to apply (defaults to module_fn)

        Returns:
            torch.Tensor: Output tensor after min reduction over the specified dimension
        """
        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]  # Example, change to desired dimension
import torch
import torch.nn as nn

class Model(nn.Module):
    """
    Simple model that performs min 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:
        """
        Applies min reduction over the specified dimension to the input tensor.

        Args:
            x (torch.Tensor): Input tensor.

        Returns:
            torch.Tensor: Output tensor after min reduction over the specified dimension.
        """
        return torch.min(x, dim=self.dim)[0]

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] # Example, change to desired dimension

Kernel Information

Related Kernels (Level 1, Task 53 • 53_Min_reduction_over_a_dimension)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 min_reduction_warp_base_base 0.01 2.19 3.09
🥇 efficient_min_reduce_kernel_base 0.01 2.19 3.09
🥇 min_reduce_block_size_tuning_base 0.01 2.19 3.09
🥇 min_reduce_optimized_base 0.01 2.19 3.09
🥇 min_reduction_optimized_memory_base 0.01 2.19 3.09
🥇 min_reduce_tunable_blocksize_base 0.01 2.19 3.09
🥇 min_reduce_dynamic_block_base_base 0.01 2.19 3.09
🥇 modular_min_reduce_kernel_base_base 0.01 2.19 3.09
🥇 min_reduce_adaptive_blocks_base_base 0.01 2.19 3.09
🥇 min_reduce_fused_warp_base 0.01 2.19 3.09
🥇 min_reduce_combined_base 0.01 2.19 3.09
🥇 min_reduce_warp_unroll_base 0.01 2.19 3.09
🥇 min_reduce_combined_kernel_base 0.01 2.19 3.09
14 balanced_min_reduction_base 0.01 1.85 2.62
15 min_reduction_warp_shared_hybrid_base 0.01 1.72 2.43
15 optimized_block_size_experiment_base_base 0.01 1.72 2.43
15 min_reduction_shared_base 0.01 1.72 2.43
15 modular_min_reduction_base 0.01 1.72 2.43
15 fast_min_reduction_edit_1 0.01 1.72 2.43
15 vector_load_min_reduction_edit_1 0.01 1.72 2.43
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <vector>
#include <limits>
#include <c10/cuda/CUDAStream.h>

template <typename scalar_t>
__global__ void min_reduce_warp_shared_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    const int outer,
    const int r,
    const int inner) {
    
    extern __shared__ char shared_mem[];
    scalar_t* shared_data = reinterpret_cast<scalar_t*>(shared_mem);
    
    const int warp_size = 32;
    const int warps_per_block = blockDim.x / warp_size;
    const int warp_id = threadIdx.x / warp_size;
    const int lane_id = threadIdx.x % warp_size;
    const int global_warp_id = blockIdx.x * warps_per_block + warp_id;
    
    if (global_warp_id >= outer * inner) return;
    
    const int outer_idx = global_warp_id / inner;
    const int inner_idx = global_warp_id % inner;
    const int base = outer_idx * (r * inner) + inner_idx;
    
    const int tile_size = 128;
    scalar_t warp_min = std::numeric_limits<scalar_t>::max();
    
    #pragma unroll 1
    for (int tile_start = 0; tile_start < r; tile_start += tile_size) {
        const int tile_end = min(tile_start + tile_size, r);
        
        for (int j = tile_start + lane_id; j < tile_end; j += warp_size) {
            const int shared_idx = (j - tile_start) + warp_id * tile_size;
            const int global_idx = base + j * inner;
            shared_data[shared_idx] = input[global_idx];
        }
        __syncthreads();
        
        for (int j = 0; j < (tile_end - tile_start); j++) {
            const int shared_idx = j + warp_id * tile_size;
            scalar_t val = shared_data[shared_idx];
            warp_min = min(warp_min, val);
        }
        __syncthreads();
    }
    
    #pragma unroll
    for (int offset = 16; offset > 0; offset /= 2) {
        scalar_t other = __shfl_down_sync(0xffffffff, warp_min, offset);
        warp_min = min(warp_min, other);
    }
    
    if (lane_id == 0) {
        output[global_warp_id] = warp_min;
    }
}

torch::Tensor forward(torch::Tensor input, int64_t dim) {
    TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor");
    if (!input.is_contiguous()) {
        input = input.contiguous();
    }

    int ndim = input.dim();
    TORCH_CHECK(dim >= 0 && dim < ndim, "dim out of range");

    int outer = 1;
    for (int i = 0; i < dim; i++) {
        outer *= input.size(i);
    }
    int r = input.size(dim);
    int inner = 1;
    for (int i = dim + 1; i < ndim; i++) {
        inner *= input.size(i);
    }

    std::vector<int64_t> output_shape;
    for (int i = 0; i < ndim; i++) {
        if (i != dim) {
            output_shape.push_back(input.size(i));
        }
    }
    
    auto output = torch::empty(output_shape, input.options());

    const int threads_per_block = 128;
    const int warps_per_block = threads_per_block / 32;
    const int num_warps = outer * inner;
    const int num_blocks = (num_warps + warps_per_block - 1) / warps_per_block;
    
    const int shared_mem_size = 128 * warps_per_block * sizeof(float);

    AT_DISPATCH_ALL_TYPES(input.scalar_type(), "min_reduce_warp_shared_cuda", ([&] {
        min_reduce_warp_shared_kernel<scalar_t><<<num_blocks, threads_per_block, shared_mem_size,
            c10::cuda::getCurrentCUDAStream().stream()>>>(
            input.data_ptr<scalar_t>(),
            output.data_ptr<scalar_t>(),
            outer,
            r,
            inner);
    }));

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Min reduction over a specified dimension using warp-level primitives with shared memory (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.270 inst/cycle 0.000 5
Executed Ipc Elapsed 1.008 inst/cycle 0.000 5
Issue Slots Busy 32.186 % 0.014 5
Issued Ipc Active 1.286 inst/cycle 0.000 5
SM Busy 39.446 % 0.021 5
Memory Throughput 333111371020.562 byte/second 5838846536938113024.000 5
Mem Busy 62.464 % 0.163 5
Max Bandwidth 30.940 % 0.039 5
L1/TEX Hit Rate 74.940 % 0.000 5
L2 Hit Rate 63.590 % 0.189 5
Mem Pipes Busy 13.546 % 0.007 5
Warp Cycles Per Issued Instruction 22.406 cycle 0.020 5
Warp Cycles Per Executed Instruction 22.696 cycle 0.020 5
Avg. Active Threads Per Warp 31.760 0.000 5
Avg. Not Predicated Off Threads Per Warp 30.570 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 16.000 block 0.000 5
Block Limit Shared Mem 33.000 block 0.000 5
Block Limit Warps 16.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 45.164 % 0.001 5
Achieved Active Warps Per SM 28.902 warp 0.000 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (39.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 (45.1%) 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 562175.24 μs
Device Time 373.12 μs
Self CPU Time 36.64 μ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 562138.60 μs
Device Time 373.12 μs
Self CPU Time 100.28 μ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 561405.78 μs
Device Time 0.00 μs
Self CPU Time 80.29 μ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 546401.03 μs
Device Time 0.00 μs
Self CPU Time 546401.03 μ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 550234.81 μs
Device Time 705.27 μs
Self CPU Time 550234.81 μs
Self Device Time 705.27 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void min_reduce_warp_shared_kernel<float>(float const*, float*, int, int, int)
CPU Time 0.00 μs
Device Time 81564.02 μs
Self CPU Time 0.00 μs
Self Device Time 81564.02 μ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 69204.45 μs
Device Time 639469.84 μs
Self CPU Time 14642.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
aten::fill_
CPU Time 54566.03 μs
Device Time 639469.84 μs
Self CPU Time 15600.34 μs
Self Device Time 639469.84 μ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 639469.84 μs
Self CPU Time 0.00 μs
Self Device Time 639469.84 μ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
45299 warnings generated when compiling for host.
Suppressed 45327 warnings (45280 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/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:12:5 bugprone-easily-swappable-parameters
12 | const int outer,
| ^~~~~~~~~~~~~~~~
13 | const int r,
| ~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:12:15: note: the first parameter in the range is 'outer'
12 | const int outer,
| ^~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:13:15: note: the last parameter in the range is 'r'
13 | const int r,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:20:33: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
20 | const int warps_per_block = blockDim.x / warp_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:21:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
21 | const int warp_id = threadIdx.x / warp_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:22:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | const int lane_id = threadIdx.x % warp_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:23:32: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
23 | const int global_warp_id = blockIdx.x * warps_per_block + warp_id;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:70:16: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
70 | int ndim = input.dim();
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:75:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
75 | outer *= input.size(i);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:77:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | int r = input.size(dim);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:79:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
79 | for (int i = dim + 1; i < ndim; i++) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:80:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
80 | inner *= input.size(i);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:97:33: warning: performing an implicit widening conversion to type 'unsigned long' of a multiplication performed in type 'int' [bugprone-implicit-widening-of-multiplication-result]
97 | const int shared_mem_size = 128 * warps_per_block * sizeof(float);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:97:33: note: make conversion explicit to silence this warning
4 | const int shared_mem_size = 128 * warps_per_block * sizeof(float);
| ^~~~~~~~~~~~~~~~~~~~~
| static_cast<unsigned long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:97:33: note: perform multiplication in a wider type
97 | const int shared_mem_size = 128 * warps_per_block * sizeof(float);
| ^~~
| static_cast<long>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_53/b3_s2_min_reduction_warp_shared_hybrid/base/base.cu:99: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]
99 | AT_DISPATCH_ALL_TYPES(input.scalar_type(), "min_reduce_warp_shared_cuda", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:482:34: note: expanded from macro 'AT_DISPATCH_ALL_TYPES'
482 | AT_DISPATCH_SWITCH(TYPE, NAME, AT_DISPATCH_CASE_ALL_TYPES(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:478:3: note: expanded from macro 'AT_DISPATCH_CASE_ALL_TYPES'
478 | AT_DISPATCH_CASE_INTEGRAL_TYPES(__VA_ARGS__) \
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:458:3: note: expanded from macro 'AT_DISPATCH_CASE_INTEGRAL_TYPES'
458 | AT_DISPATCH_CASE(at::ScalarType::Byte, __VA_ARGS__) \
| ^
note: (skipping 2 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__, \
| ^