← Back to Leaderboard

The AI CUDA Engineer 👷

49_Max_reduction_over_a_dimensionmodular_max_reduce_edit_1

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


def module_fn(x: torch.Tensor, dim: int) -> torch.Tensor:
    """
    Applies Max 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 Max reduction over the specified dimension
    """
    return torch.max(x, dim=dim)[0]


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

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

        Returns:
            torch.Tensor: Output tensor after Max reduction over the specified dimension.
        """
        return torch.max(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 49 • 49_Max_reduction_over_a_dimension)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 distributed_max_reduction_base 0.02 1.50 2.04
🥇 adaptive_max_reduce_base 0.02 1.50 2.04
🥇 optimal_blocksize_max_reduce_experiment_base 0.02 1.50 2.04
🥇 optimal_block_size_max_reduce_base 0.02 1.50 2.04
🥇 optimized_max_reduce_base 0.02 1.50 2.04
🥇 adaptive_blocksize_max_reduce_base 0.02 1.50 2.04
🥇 coalesced_global_access_max_reduce_base 0.02 1.50 2.04
8 stride_loop_optimization_base 0.02 1.04 1.42
8 aligned_coalesced_max_reduction_base 0.02 1.04 1.42
8 stride_loop_optimization_edit_1 0.02 1.04 1.42
8 balanced_coalesced_max_reduce_edit_1 0.02 1.04 1.42
8 modular_max_reduce_base 0.02 1.04 1.42
8 optimized_block_size_max_reduce_edit_1 0.02 1.04 1.42
8 optimized_max_reduce_base 0.02 1.04 1.42
8 optimized_block_size_max_reduce_base 0.02 1.04 1.42
8 modular_max_reduce_edit_1 0.02 1.04 1.42
8 warp_divergence_optimization_edit_1 0.02 1.04 1.42
8 warp_divergence_optimization_base 0.02 1.04 1.42
8 coalesced_max_reduce_base 0.02 1.04 1.42
8 balanced_coalesced_max_reduce_base 0.02 1.04 1.42
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

// Modular device function to perform max reduction on a single slice
// This function can be reused for different types of reduction operations

template <typename scalar_t>
__device__ scalar_t max_reduce_slice(const scalar_t* input, int64_t dim_size, int64_t inner_size, int64_t start_idx) {
    const scalar_t* ptr = input + start_idx;
    scalar_t max_val = *ptr;
    for (int i = 1; i < dim_size; i++) {
        ptr += inner_size;
        max_val = max(max_val, *ptr);
    }
    return max_val;
}

// Kernel that utilizes the modular device function

template <typename scalar_t>
__global__ void modular_max_reduce_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    const int64_t outer_size,
    const int64_t dim_size,
    const int64_t inner_size
) {
    int inner_idx = blockIdx.y * blockDim.x + threadIdx.x;
    if (inner_idx >= inner_size) return;

    int outer_idx = blockIdx.x;
    const int64_t input_offset = outer_idx * dim_size * inner_size + inner_idx;

    // Use the device function for max reduction
    scalar_t max_val = max_reduce_slice(input, dim_size, inner_size, input_offset);

    output[outer_idx * inner_size + inner_idx] = max_val;
}

torch::Tensor max_reduce_cuda_forward(torch::Tensor input, int64_t dim) {
    if (dim < 0) dim += input.dim();

    int64_t outer_size = 1;
    for (int i = 0; i < dim; i++) {
        outer_size *= input.size(i);
    }

    int64_t inner_size = 1;
    for (int i = dim + 1; i < input.dim(); i++) {
        inner_size *= input.size(i);
    }

    const int64_t dim_size = input.size(dim);

    auto output_sizes = input.sizes().vec();
    output_sizes.erase(output_sizes.begin() + dim);
    auto output = torch::empty(output_sizes, input.options());

    const int threads = 256;
    const int blocks_y = (inner_size + threads - 1) / threads;
    dim3 grid(outer_size, blocks_y);

    AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "max_reduce_forward", ([&] {
        modular_max_reduce_kernel<scalar_t><<<grid, threads>>>(
            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", &max_reduce_cuda_forward, "Modular Max Reduction Forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.370 inst/cycle 0.000 5
Executed Ipc Elapsed 0.040 inst/cycle 0.000 5
Issue Slots Busy 9.360 % 0.003 5
Issued Ipc Active 0.376 inst/cycle 0.000 5
SM Busy 9.752 % 0.004 5
Memory Throughput 211391218333.466 byte/second 2855431735867275776.000 5
Mem Busy 3.650 % 0.001 5
Max Bandwidth 6.314 % 0.003 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 18.780 % 0.008 5
Mem Pipes Busy 0.794 % 0.000 5
Warp Cycles Per Issued Instruction 21.068 cycle 0.006 5
Warp Cycles Per Executed Instruction 21.150 cycle 0.006 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 31.730 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 8.000 block 0.000 5
Block Limit Shared Mem 32.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 12.274 % 0.002 5
Achieved Active Warps Per SM 7.858 warp 0.001 5
Analysis Rules
Rule Description
WRN HighPipeUtilization All compute pipelines are under-utilized. Either this kernel is very small or it doesn't issue enough warps per scheduler. Check the Launch Statistics and Scheduler Statistics sections for further details.
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 (12.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 498676.20 μs
Device Time 413.44 μs
Self CPU Time 34.68 μ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 498641.51 μs
Device Time 413.44 μs
Self CPU Time 107.35 μ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 497856.44 μs
Device Time 0.00 μs
Self CPU Time 87.47 μ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 496381.36 μs
Device Time 0.00 μs
Self CPU Time 496381.36 μ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 605848.75 μs
Device Time 21395.12 μs
Self CPU Time 605848.75 μs
Self Device Time 21395.12 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void modular_max_reduce_kernel<float>(float const*, float*, long, long, long)
CPU Time 0.00 μs
Device Time 159364.69 μs
Self CPU Time 0.00 μs
Self Device Time 159364.69 μ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 23879.68 μs
Device Time 42373.37 μs
Self CPU Time 23879.68 μs
Self Device Time 42373.37 μ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 132484.21 μs
Device Time 634192.80 μs
Self CPU Time 16062.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
aten::fill_
CPU Time 116425.17 μs
Device Time 634192.80 μs
Self CPU Time 17540.38 μs
Self Device Time 634192.80 μ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 634271.33 μs
Self CPU Time 0.00 μs
Self Device Time 634271.33 μ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/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:9:61 bugprone-easily-swappable-parameters
9 | __device__ scalar_t max_reduce_slice(const scalar_t* input, int64_t dim_size, int64_t inner_size, int64_t start_idx) {
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:9:69: note: the first parameter in the range is 'dim_size'
9 | __device__ scalar_t max_reduce_slice(const scalar_t* input, int64_t dim_size, int64_t inner_size, int64_t start_idx) {
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:9:107: note: the last parameter in the range is 'start_idx'
9 | __device__ scalar_t max_reduce_slice(const scalar_t* input, int64_t dim_size, int64_t inner_size, int64_t start_idx) {
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:25:5: warning: 2 adjacent parameters of 'modular_max_reduce_kernel' of similar type ('const int64_t') are easily swapped by mistake [bugprone-easily-swappable-parameters]
25 | const int64_t outer_size,
| ^~~~~~~~~~~~~~~~~~~~~~~~~
26 | const int64_t dim_size,
| ~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:25:19: note: the first parameter in the range is 'outer_size'
25 | const int64_t outer_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:26:19: note: the last parameter in the range is 'dim_size'
26 | const int64_t dim_size,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:29:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | int inner_idx = blockIdx.y * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:32:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
32 | int outer_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:50:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
50 | for (int i = dim + 1; i < input.dim(); i++) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:61:26: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
61 | const int blocks_y = (inner_size + threads - 1) / threads;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250211_optimize_b5_s4_e1_v2/level_1/task_49/b5_s0_modular_max_reduce/edit_1/edit_1.cu:64: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]
64 | AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "max_reduce_forward", ([&] {
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:246:19: note: expanded from macro 'AT_DISPATCH_FLOATING_TYPES_AND_HALF'
246 | TYPE, NAME, AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF(__VA_ARGS__))
| ^
/home/robert_sakana_ai/miniconda3/envs/llm2cuda/lib/python3.11/site-packages/torch/include/ATen/Dispatch.h:240:3: note: expanded from macro 'AT_DISPATCH_CASE_FLOATING_TYPES_AND_HALF'
240 | 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__, \
| ^