← Back to Leaderboard

The AI CUDA Engineer 👷

51_Argmax_over_a_dimensionstride_loop_argmax_final_base

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


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

    Args:
        x (torch.Tensor): Input tensor
        dim (int): Dimension to perform argmax over

    Returns:
        torch.Tensor: Output tensor with argmax applied over specified dimension
    """
    return torch.argmax(x, dim)


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

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

        Args:
            dim (int): The dimension to perform argmax over.
        """
        super(Model, self).__init__()
        self.dim = dim

    def forward(self, x: torch.Tensor, fn=module_fn) -> torch.Tensor:
        """
        Applies argmax 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 with argmax applied, with the specified dimension 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 Argmax over a specified dimension.
    """

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

        Args:
            dim (int): The dimension to perform argmax over.
        """
        super(Model, self).__init__()
        self.dim = dim

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """
        Applies argmax over the specified dimension to the input tensor.

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

        Returns:
            torch.Tensor: Output tensor with argmax applied, with the specified dimension removed.
        """
        return torch.argmax(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 51 • 51_Argmax_over_a_dimension)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 warp_argmax_nosm_edit_1 0.01 1.85 2.54
🥈 warp_level_argmax_base 0.01 1.72 2.36
🥈 warp_level_argmax_edit_1 0.01 1.72 2.36
🥈 efficient_argmax_base 0.01 1.72 2.36
🥈 stride_loop_argmax_stride_base 0.01 1.72 2.36
🥈 stride_loop_argmax_final_edit_1 0.01 1.72 2.36
🥈 argmax_coop_red_tuned_base 0.01 1.72 2.36
🥈 argmax_coop_red_tuned_edit_1 0.01 1.72 2.36
🥈 divergence_free_argmax_base 0.01 1.72 2.36
🥈 optimized_argmax_combination_base 0.01 1.72 2.36
🥈 argmax_ldg_128_opt_base 0.01 1.72 2.36
🥈 argmax_ldg_128_opt_edit_1 0.01 1.72 2.36
🥈 argmax_coop_red_sync_opt_base 0.01 1.72 2.36
🥈 argmax_aligned_mem_base_edit_1 0.01 1.72 2.36
🥈 stride_loop_argmax_final_base 0.01 1.72 2.36
🥈 warp_argmax_nosm_base 0.01 1.72 2.36
17 stride_loop_argmax_base 0.01 1.61 2.20
17 loop_unrolled_argmax_edit_1 0.01 1.61 2.20
17 stride_loop_argmax_edit_1 0.01 1.61 2.20
17 optimized_argmax_kernel_base 0.01 1.61 2.20
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cfloat>
#include <vector>

// Kernel to compute argmax using stride loops and warp-level intrinsics for reduction
__global__ void argmax_stride_loop_kernel(
    const float* __restrict__ x,
    int64_t* __restrict__ indices,
    const int outerSize,
    const int dimSize,
    const int innerSize) {

    const int total = outerSize * innerSize;
    const int warpSize = 32;

    // Loop over outer*inner pairs using a grid-stride loop
    for (int idx = blockIdx.x; idx < total; idx += gridDim.x) {
        // Determine corresponding outer and inner indices
        int outer_idx = idx / innerSize;
        int inner_idx = idx % innerSize;
        int start_offset = outer_idx * dimSize * innerSize + inner_idx;

        // Each thread processes part of the 'dim' dimension with a stride loop
        float local_max = -FLT_MAX;
        int local_idx = 0;
        for (int d = threadIdx.x; d < dimSize; d += blockDim.x) {
            float val = __ldg(&x[start_offset + d * innerSize]);
            if (val > local_max) {
                local_max = val;
                local_idx = d;
            }
        }

        // Warp-level reduction using shuffle intrinsics to combine thread results
        unsigned int mask = 0xffffffff;
        for (int offset = warpSize / 2; offset > 0; offset /= 2) {
            float other_val = __shfl_down_sync(mask, local_max, offset);
            int other_idx = __shfl_down_sync(mask, local_idx, offset);
            if (other_val > local_max) {
                local_max = other_val;
                local_idx = other_idx;
            }
        }

        // Allocate shared memory for inter-warp reduction
        extern __shared__ char shared_mem[]; 
        float* warp_max = (float*)shared_mem;
        int* warp_arg = (int*)(shared_mem + ((blockDim.x + warpSize - 1) / warpSize) * sizeof(float));

        int lane = threadIdx.x & (warpSize - 1);
        int warp_id = threadIdx.x / warpSize;
        if (lane == 0) {
            warp_max[warp_id] = local_max;
            warp_arg[warp_id] = local_idx;
        }
        __syncthreads();

        // Final reduction across warps, performed by a single thread
        int numWarps = (blockDim.x + warpSize - 1) / warpSize;
        if (threadIdx.x == 0) {
            float final_max = warp_max[0];
            int final_idx = warp_arg[0];
            for (int i = 1; i < numWarps; i++) {
                float candidate = warp_max[i];
                int candidate_idx = warp_arg[i];
                if (candidate > final_max) {
                    final_max = candidate;
                    final_idx = candidate_idx;
                }
            }
            indices[idx] = final_idx;
        }
        __syncthreads(); // Ensure all threads are synchronized before next iteration
    }
}

// Host function to launch the CUDA kernel
torch::Tensor argmax_forward_cuda(const torch::Tensor& x, const int64_t dim) {
    TORCH_CHECK(x.scalar_type() == at::kFloat, "Only float32 is supported.");
    auto x_contig = x.contiguous();
    auto sizes = x_contig.sizes();
    int ndim = x_contig.dim();
    TORCH_CHECK(dim >= 0 && dim < ndim, "Invalid dimension for argmax.");

    int outerSize = 1;
    for (int i = 0; i < dim; i++) {
        outerSize *= sizes[i];
    }
    int dimSize = sizes[dim];
    int innerSize = 1;
    for (int i = dim + 1; i < ndim; i++) {
        innerSize *= sizes[i];
    }

    // Build the output shape by removing the 'dim' dimension
    std::vector<int64_t> out_sizes;
    for (int i = 0; i < ndim; i++) {
        if (i != dim) {
            out_sizes.push_back(sizes[i]);
        }
    }

    auto options = torch::TensorOptions().device(x.device()).dtype(torch::kLong);
    auto indices = torch::empty(out_sizes, options);

    // Launch configuration
    const int threads = 256;
    int total = outerSize * innerSize;
    int blocks = (total < 1024) ? total : 1024;  // Cap the number of blocks to 1024
    
    // Calculate shared memory required for warp reduction
    int nWarps = (threads + 31) / 32;
    size_t shared_mem_size = nWarps * (sizeof(float) + sizeof(int));

    argmax_stride_loop_kernel<<<blocks, threads, shared_mem_size>>>(
        x_contig.data_ptr<float>(),
        indices.data_ptr<int64_t>(),
        outerSize,
        dimSize,
        innerSize);

    return indices;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &argmax_forward_cuda, "ArgMax CUDA forward (stride-loop with warp shuffle reduction)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 1.410 inst/cycle 0.000 5
Executed Ipc Elapsed 1.106 inst/cycle 0.000 5
Issue Slots Busy 35.352 % 0.075 5
Issued Ipc Active 1.414 inst/cycle 0.000 5
SM Busy 35.352 % 0.075 5
Memory Throughput 303377323372.046 byte/second 7377651219138054144.000 5
Mem Busy 53.922 % 0.206 5
Max Bandwidth 31.872 % 0.303 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 82.904 % 1.278 5
Mem Pipes Busy 17.610 % 0.022 5
Warp Cycles Per Issued Instruction 40.956 cycle 0.446 5
Warp Cycles Per Executed Instruction 41.066 cycle 0.446 5
Avg. Active Threads Per Warp 29.350 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.210 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 91.558 % 0.330 5
Achieved Active Warps Per SM 58.598 warp 0.136 5
Analysis Rules
Rule Description
INF HighPipeUtilization ALU is the highest-utilized pipeline (29.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.
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.
INF Occupancy This kernel's theoretical occupancy is not impacted by any block limit.
Operation / Metric Value Unit
aten::to
CPU Time 676081.30 μs
Device Time 380.64 μs
Self CPU Time 36.09 μ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 676045.20 μs
Device Time 380.64 μs
Self CPU Time 106.97 μ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 675319.59 μs
Device Time 0.00 μs
Self CPU Time 95.85 μ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 671548.41 μs
Device Time 0.00 μs
Self CPU Time 671548.41 μ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 530250.01 μs
Device Time 20560.16 μs
Self CPU Time 530250.01 μs
Self Device Time 20560.16 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
argmax_stride_loop_kernel(float const*, long*, int, int, int)
CPU Time 0.00 μs
Device Time 82828.39 μs
Self CPU Time 0.00 μs
Self Device Time 82828.39 μ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 22999.19 μs
Device Time 40861.37 μs
Self CPU Time 22999.19 μs
Self Device Time 40861.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 67667.16 μs
Device Time 610695.46 μs
Self CPU Time 13121.05 μ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 54548.20 μs
Device Time 610695.46 μs
Self CPU Time 15976.42 μs
Self Device Time 610695.46 μ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 610695.46 μs
Self CPU Time 0.00 μs
Self Device Time 610695.46 μ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
45288 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/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:11:5 bugprone-easily-swappable-parameters
11 | const int outerSize,
| ^~~~~~~~~~~~~~~~~~~~
12 | const int dimSize,
| ~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:11:15: note: the first parameter in the range is 'outerSize'
11 | const int outerSize,
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:12:15: note: the last parameter in the range is 'dimSize'
12 | const int dimSize,
| ^~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:19:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
19 | for (int idx = blockIdx.x; idx < total; idx += gridDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:19:52: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
19 | for (int idx = blockIdx.x; idx < total; idx += gridDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:28:22: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | for (int d = threadIdx.x; d < dimSize; d += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:28:53: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | for (int d = threadIdx.x; d < dimSize; d += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:52:20: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
52 | int lane = threadIdx.x & (warpSize - 1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:53:23: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
53 | int warp_id = threadIdx.x / warpSize;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:61:24: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
61 | int numWarps = (blockDim.x + warpSize - 1) / warpSize;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:84:16: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
84 | int ndim = x_contig.dim();
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:89:22: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
89 | outerSize *= sizes[i];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:91:19: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
91 | int dimSize = sizes[dim];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:93:18: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
93 | for (int i = dim + 1; i < ndim; i++) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_51/b4_s3_stride_loop_argmax_final/base/base.cu:94:22: warning: narrowing conversion from 'long' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
94 | innerSize *= sizes[i];
| ^