← Back to Leaderboard

The AI CUDA Engineer 👷

49_Max_reduction_over_a_dimensioncoalesced_global_access_max_reduce_base

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>

// Kernel ensuring coalesced global memory access
// Efficient usage of shared memory for block-wide reduction

template <typename scalar_t>
__global__ void coalesced_global_access_max_reduce_kernel(
    const scalar_t* __restrict__ input,
    scalar_t* __restrict__ output,
    const int64_t dim_size,
    const int64_t inner_size,
    const int64_t num_outputs
) {
    for (int out_idx = blockIdx.x; out_idx < num_outputs; out_idx += gridDim.x) {
        int outer_idx = out_idx / inner_size;
        int inner_idx = out_idx % inner_size;
        int64_t base = outer_idx * dim_size * inner_size + inner_idx;

        int tid = threadIdx.x;
        int block_size = blockDim.x;

        scalar_t thread_max = -INFINITY;
        for (int j = tid; j < dim_size; j += block_size) {
            scalar_t val = input[base + j * inner_size]; // Coalesced access
            thread_max = max(thread_max, val);
        }

        extern __shared__ char sdata[];
        scalar_t* shmem = reinterpret_cast<scalar_t*>(sdata);

        shmem[tid] = thread_max;
        __syncthreads();

        for (unsigned int s = block_size / 2; s > 0; s >>= 1) {
            if (tid < s) {
                shmem[tid] = max(shmem[tid], shmem[tid + s]);
            }
            __syncthreads();
        }

        if (tid == 0) {
            output[out_idx] = shmem[0];
        }
    }
}

// CUDA forward function with coalesced memory access
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);
    const int64_t num_outputs = outer_size * inner_size;

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

    int block_size = 256;
    if (dim_size > 512) {
        block_size = 512;
    }

    if (num_outputs < block_size) {
        block_size = num_outputs;
    }

    int blocks = (num_outputs < 1024) ? num_outputs : 1024;

    size_t shared_mem_size = block_size * input.element_size();

    AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "coalesced_max_reduce_forward", ([&] {
        coalesced_global_access_max_reduce_kernel<scalar_t><<<blocks, block_size, shared_mem_size>>>(
            input.data_ptr<scalar_t>(),
            output.data_ptr<scalar_t>(),
            dim_size,
            inner_size,
            num_outputs
        );
    }));

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &max_reduce_cuda_forward, "Max reduce forward with coalesced memory access (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.944 inst/cycle 0.000 5
Executed Ipc Elapsed 1.606 inst/cycle 0.000 5
Issue Slots Busy 48.732 % 0.009 5
Issued Ipc Active 1.948 inst/cycle 0.000 5
SM Busy 48.732 % 0.009 5
Memory Throughput 260532991294.238 byte/second 3585518902691034624.000 5
Mem Busy 59.052 % 0.145 5
Max Bandwidth 31.120 % 1.307 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 86.106 % 1.790 5
Mem Pipes Busy 25.820 % 0.026 5
Warp Cycles Per Issued Instruction 27.600 cycle 0.010 5
Warp Cycles Per Executed Instruction 27.670 cycle 0.010 5
Avg. Active Threads Per Warp 31.740 0.000 5
Avg. Not Predicated Off Threads Per Warp 23.290 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 83.968 % 0.034 5
Achieved Active Warps Per SM 53.738 warp 0.014 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (38.7%) 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.
WRN ThreadDivergence Instructions are executed in warps, which are groups of 32 threads. Optimal instruction throughput is achieved if all 32 threads of a warp execute the same instruction. The chosen launch configuration, early thread completion, and divergent flow control can significantly lower the number of active threads in a warp per cycle. This kernel achieves an average of 31.7 threads being active per cycle. This is further reduced to 23.3 threads per warp due to predication. The compiler may use predication to avoid an actual branch. Instead, all instructions are scheduled, but a per-thread condition code or predicate controls which threads execute the instructions. Try to avoid different execution paths within a warp when possible. In addition, ensure your kernel makes use of Independent Thread Scheduling, which allows a warp to reconverge after a data-dependent conditional block by explicitly calling __syncwarp().
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 (83.9%) 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 377277.74 μs
Device Time 344.86 μs
Self CPU Time 35.22 μ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 377242.52 μs
Device Time 344.86 μs
Self CPU Time 111.57 μ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 376559.50 μs
Device Time 0.00 μs
Self CPU Time 80.40 μ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 375328.59 μs
Device Time 0.00 μs
Self CPU Time 375328.59 μ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 310773.06 μs
Device Time 11533.02 μs
Self CPU Time 310773.06 μs
Self Device Time 11533.02 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
void coalesced_global_access_max_reduce_kernel<float>(float const*, float*, long, long, long)
CPU Time 0.00 μs
Device Time 55336.16 μs
Self CPU Time 0.00 μs
Self Device Time 55336.16 μ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 12277.02 μs
Device Time 22682.36 μs
Self CPU Time 12277.02 μs
Self Device Time 22682.36 μ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 48995.40 μs
Device Time 347367.59 μs
Self CPU Time 6755.21 μ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 42243.41 μs
Device Time 347367.59 μs
Self CPU Time 8550.62 μs
Self Device Time 347367.59 μ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 347367.59 μs
Self CPU Time 0.00 μs
Self Device Time 347367.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
45289 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/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:13:5 bugprone-easily-swappable-parameters
13 | const int64_t inner_size,
| ^~~~~~~~~~~~~~~~~~~~~~~~~
14 | const int64_t num_outputs
| ~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:13:19: note: the first parameter in the range is 'inner_size'
13 | const int64_t inner_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:14:19: note: the last parameter in the range is 'num_outputs'
14 | const int64_t num_outputs
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:16:24: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
16 | for (int out_idx = blockIdx.x; out_idx < num_outputs; out_idx += gridDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:16:70: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
16 | for (int out_idx = blockIdx.x; out_idx < num_outputs; out_idx += gridDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:17:25: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
17 | int outer_idx = out_idx / inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:18:25: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
18 | int inner_idx = out_idx % inner_size;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:21:19: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
21 | int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:22:26: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | int block_size = blockDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:58:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
58 | for (int i = dim + 1; i < input.dim(); i++) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:75:22: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
75 | block_size = num_outputs;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:78:41: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
78 | int blocks = (num_outputs < 1024) ? num_outputs : 1024;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_49/b9_s2_coalesced_global_access_max_reduce/base/base.cu:82: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]
82 | AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.scalar_type(), "coalesced_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__, \
| ^