← Back to Leaderboard

The AI CUDA Engineer 👷

98_KLDivLossoptimized_kl_div_cuda_base

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


def module_fn(predictions: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
    """
    Computes the Kullback-Leibler Divergence for comparing two distributions.

    Args:
        predictions (torch.Tensor): Predicted values.
        targets (torch.Tensor): Target values.

    Returns:
        torch.Tensor: Kullback-Leibler Divergence.
    """
    return F.kl_div(torch.log(predictions), targets, reduction="batchmean")


class Model(nn.Module):
    """
    A model that computes Kullback-Leibler Divergence for comparing two distributions.

    Parameters:
        None
    """

    def __init__(self):
        super(Model, self).__init__()

    def forward(self, predictions, targets, fn=module_fn):
        return fn(predictions, targets)


batch_size = 128
input_shape = (4096,)
dim = 1


def get_inputs():
    return [
        torch.randn(batch_size, *input_shape).softmax(dim=-1),
        torch.randn(batch_size, *input_shape).softmax(dim=-1),
    ]


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

class Model(nn.Module):
    """
    A model that computes Kullback-Leibler Divergence for comparing two distributions.

    Parameters:
        None
    """
    def __init__(self):
        super(Model, self).__init__()

    def forward(self, predictions, targets):
        return torch.nn.functional.kl_div(torch.log(predictions), targets, reduction='batchmean')

batch_size = 128
input_shape = (4096, )
dim = 1

def get_inputs():
    return [torch.randn(batch_size, *input_shape).softmax(dim=-1), torch.randn(batch_size, *input_shape).softmax(dim=-1)]

def get_init_inputs():
    return []

Kernel Information

Related Kernels (Level 1, Task 98 • 98_KLDivLoss)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 optimized_kl_div_cuda_base 0.01 2.83 3.20
🥈 kl_div_sync_optimized_base 0.01 2.59 2.93
🥈 optimized_kl_div_kernel_base 0.01 2.59 2.93
🥈 kl_div_balanced_workload_base 0.01 2.59 2.93
🥈 kl_div_warp_reduce_base_base 0.01 2.59 2.93
🥈 optimized_kl_div_base 0.01 2.59 2.93
🥈 kl_div_modular_reduce_base_base 0.01 2.59 2.93
🥈 kldiv_optimized_stride_base_base_base 0.01 2.59 2.93
🥈 vectorized_aligned_kl_base 0.01 2.59 2.93
🥈 98_KLDivLoss_optimal_reduce_edit_1 0.01 2.59 2.93
🥈 strided_warp_kl_base_base 0.01 2.59 2.93
🥈 fast_strided_kl_base 0.01 2.59 2.93
🥈 coalesced_chunked_kl_base 0.01 2.59 2.93
🥈 kldiv_modular_per_thread_base_base 0.01 2.59 2.93
🥈 kldiv_unrolled_reduction_base_base 0.01 2.59 2.93
🥈 kl_div_unrolled_reduce_base_base 0.01 2.59 2.93
🥈 warp_block_vec4_opt_base 0.01 2.59 2.93
🥈 vectorized_kldiv_base_base 0.01 2.59 2.93
🥈 kl_div_even_workload_distribution_base 0.01 2.59 2.93
🥈 adaptive_kl_div_cuda_base 0.01 2.59 2.93
#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>

template<unsigned int blockSize>
__device__ __forceinline__ void warpReduce(volatile float* sdata, unsigned int tid) {
    if (blockSize >= 64) sdata[tid] += sdata[tid + 32];
    if (blockSize >= 32) sdata[tid] += sdata[tid + 16];
    if (blockSize >= 16) sdata[tid] += sdata[tid + 8];
    if (blockSize >= 8) sdata[tid] += sdata[tid + 4];
    if (blockSize >= 4) sdata[tid] += sdata[tid + 2];
    if (blockSize >= 2) sdata[tid] += sdata[tid + 1];
}

__global__ void kl_div_kernel_stage1(
    const float* __restrict__ log_predictions,
    const float* __restrict__ targets,
    float* __restrict__ block_results,
    const int n) {
    
    extern __shared__ float sdata[];
    const unsigned int tid = threadIdx.x;
    unsigned int i = blockIdx.x * blockDim.x * 8 + tid;
    const unsigned int stride = blockDim.x * gridDim.x;
    
    float thread_sum = 0.0f;
    
    float4* log_pred_vec = (float4*)log_predictions;
    float4* target_vec = (float4*)targets;
    
    while (i + 7 * blockDim.x < n) {
        #pragma unroll
        for (int j = 0; j < 2; j++) {
            int vec_idx = (i + j * 4 * blockDim.x) / 4;
            float4 log_pred4 = log_pred_vec[vec_idx];
            float4 target4 = target_vec[vec_idx];
            
            thread_sum += __expf(log_pred4.x) - target4.x * log_pred4.x;
            thread_sum += __expf(log_pred4.y) - target4.y * log_pred4.y;
            thread_sum += __expf(log_pred4.z) - target4.z * log_pred4.z;
            thread_sum += __expf(log_pred4.w) - target4.w * log_pred4.w;
        }
        i += stride * 8;
    }
    
    while (i < n) {
        float log_pred = log_predictions[i];
        float target = targets[i];
        thread_sum += __expf(log_pred) - target * log_pred;
        i += stride;
    }
    
    sdata[tid] = thread_sum;
    __syncthreads();
    
    if (blockDim.x >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); }
    if (blockDim.x >= 256) { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); }
    if (blockDim.x >= 128) { if (tid < 64) { sdata[tid] += sdata[tid + 64]; } __syncthreads(); }
    
    if (tid < 32) warpReduce<256>(sdata, tid);
    
    if (tid == 0) block_results[blockIdx.x] = sdata[0];
}

__global__ void kl_div_kernel_stage2(
    const float* __restrict__ block_results,
    float* __restrict__ output,
    const int num_blocks,
    const float normalizer) {
    
    extern __shared__ float sdata[];
    const unsigned int tid = threadIdx.x;
    
    float sum = 0.0f;
    if (num_blocks >= 4) {
        float4* block_results_vec = (float4*)block_results;
        for (int i = tid * 4; i < num_blocks - 3; i += blockDim.x * 4) {
            float4 block4 = block_results_vec[i/4];
            sum += block4.x + block4.y + block4.z + block4.w;
        }
    }
    
    for (int i = tid + ((num_blocks/4)*4); i < num_blocks; i += blockDim.x) {
        sum += block_results[i];
    }
    
    sdata[tid] = sum;
    __syncthreads();
    
    if (blockDim.x >= 512) { if (tid < 256) { sdata[tid] += sdata[tid + 256]; } __syncthreads(); }
    if (blockDim.x >= 256) { if (tid < 128) { sdata[tid] += sdata[tid + 128]; } __syncthreads(); }
    if (blockDim.x >= 128) { if (tid < 64) { sdata[tid] += sdata[tid + 64]; } __syncthreads(); }
    
    if (tid < 32) warpReduce<256>(sdata, tid);
    
    if (tid == 0) {
        output[0] = sdata[0] * normalizer;
    }
}

torch::Tensor kl_div_cuda_forward(
    torch::Tensor log_predictions,
    torch::Tensor targets) {
    
    const int n = log_predictions.numel();
    auto output = torch::zeros({1}, log_predictions.options());
    
    const int threads = 256;
    const int blocks = min((n + threads * 8 - 1) / (threads * 8), 1024);
    const float normalizer = 1.0f / static_cast<float>(n);
    
    auto block_results = torch::empty({blocks}, log_predictions.options());
    
    kl_div_kernel_stage1<<<blocks, threads, threads * sizeof(float)>>>(
        log_predictions.data_ptr<float>(),
        targets.data_ptr<float>(),
        block_results.data_ptr<float>(),
        n
    );
    
    kl_div_kernel_stage2<<<1, threads, threads * sizeof(float)>>>(
        block_results.data_ptr<float>(),
        output.data_ptr<float>(),
        blocks,
        normalizer
    );
    
    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &kl_div_cuda_forward, "KL divergence forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.234 inst/cycle 0.000 5
Executed Ipc Elapsed 0.000 inst/cycle 0.000 5
Issue Slots Busy 6.096 % 0.071 5
Issued Ipc Active 0.242 inst/cycle 0.000 5
SM Busy 6.096 % 0.071 5
Memory Throughput 1582234990.140 byte/second 2708268733495107.000 5
Mem Busy 9.646 % 0.082 5
Max Bandwidth 4.920 % 0.015 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 101.870 % 0.053 5
Mem Pipes Busy 0.020 % 0.000 5
Warp Cycles Per Issued Instruction 28.716 cycle 2.530 5
Warp Cycles Per Executed Instruction 29.676 cycle 2.709 5
Avg. Active Threads Per Warp 31.610 0.000 5
Avg. Not Predicated Off Threads Per Warp 26.990 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 11.058 % 0.004 5
Achieved Active Warps Per SM 7.080 warp 0.002 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 (11.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 512582.52 μs
Device Time 336.32 μs
Self CPU Time 44.89 μ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::zeros
CPU Time 4811454.83 μs
Device Time 230118.15 μs
Self CPU Time 141769.71 μ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::zero_
CPU Time 5250929.37 μs
Device Time 7537546.00 μs
Self CPU Time 282165.19 μ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 4968766.38 μs
Device Time 7537546.00 μs
Self CPU Time 372422.54 μs
Self Device Time 7537540.95 μ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 5517415.76 μs
Device Time 4821.66 μs
Self CPU Time 5517415.76 μs
Self Device Time 4821.66 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
kl_div_kernel_stage1(float const*, float const*, float*, int)
CPU Time 0.00 μs
Device Time 401816.11 μs
Self CPU Time 0.00 μs
Self Device Time 401816.11 μ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 257811.76 μs
Device Time 1210316.00 μs
Self CPU Time 257811.76 μs
Self Device Time 1210316.00 μ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 7307814.95 μs
Self CPU Time 0.00 μs
Self Device Time 7307814.95 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
Status: Failed
45250 warnings and 1 error generated when compiling for host.
Error while processing /home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu.
Suppressed 45287 warnings (45240 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.
Found compiler error(s).
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:16:5 bugprone-easily-swappable-parameters
16 | const float* __restrict__ log_predictions,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 | const float* __restrict__ targets,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:16:31: note: the first parameter in the range is 'log_predictions'
16 | const float* __restrict__ log_predictions,
| ^~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:17:31: note: the last parameter in the range is 'targets'
17 | const float* __restrict__ targets,
| ^~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:34:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
34 | int vec_idx = (i + j * 4 * blockDim.x) / 4;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:68:5: warning: 2 adjacent parameters of 'kl_div_kernel_stage2' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
68 | const int num_blocks,
| ^~~~~~~~~~~~~~~~~~~~~
69 | const float normalizer) {
| ~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:68:15: note: the first parameter in the range is 'num_blocks'
68 | const int num_blocks,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:69:17: note: the last parameter in the range is 'normalizer'
69 | const float normalizer) {
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:69:5: note: 'const int' and 'const float' may be implicitly converted: 'const int' (as 'int') -> 'const float' (as 'float'), 'const float' (as 'float') -> 'const int' (as 'int')
69 | const float normalizer) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:77:22: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | for (int i = tid * 4; i < num_blocks - 3; i += blockDim.x * 4) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:77:56: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
77 | for (int i = tid * 4; i < num_blocks - 3; i += blockDim.x * 4) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:83:18: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
83 | for (int i = tid + ((num_blocks/4)*4); i < num_blocks; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:83:65: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
83 | for (int i = tid + ((num_blocks/4)*4); i < num_blocks; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:102:19: warning: the parameter 'log_predictions' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
102 | torch::Tensor log_predictions,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:103:19: warning: the parameter 'targets' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
103 | torch::Tensor targets) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:105:19: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
105 | const int n = log_predictions.numel();
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250213_optimize_b10_s4_e0_models_1/level_1/task_98/b8_s3_optimized_kl_div_cuda/base/base.cu:109:24: error: no matching function for call to 'min' [clang-diagnostic-error]
109 | const int blocks = min((n + threads * 8 - 1) / (threads * 8), 1024);
| ^~~
/home/common_modules/clang-tidy/20.0.0git/lib/clang/20/include/__clang_cuda_math.h:201:16: note: candidate function not viable: call to __device__ function from __host__ function
201 | __DEVICE__ int min(int __a, int __b) { return __nv_min(__a, __b); }
| ^
/usr/local/cuda/include/crt/math_functions.hpp:868:38: note: candidate function not viable: call to __device__ function from __host__ function
868 | __MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const unsigned int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:873:38: note: candidate function not viable: call to __device__ function from __host__ function
873 | __MATH_FUNCTIONS_DECL__ unsigned int min(const int a, const unsigned int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:878:38: note: candidate function not viable: call to __device__ function from __host__ function
878 | __MATH_FUNCTIONS_DECL__ unsigned int min(const unsigned int a, const int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:883:34: note: candidate function not viable: call to __device__ function from __host__ function
883 | __MATH_FUNCTIONS_DECL__ long int min(const long int a, const long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:902:43: note: candidate function not viable: call to __device__ function from __host__ function
902 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const unsigned long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:919:43: note: candidate function not viable: call to __device__ function from __host__ function
919 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const long int a, const unsigned long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:936:43: note: candidate function not viable: call to __device__ function from __host__ function
936 | __MATH_FUNCTIONS_DECL__ unsigned long int min(const unsigned long int a, const long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:953:39: note: candidate function not viable: call to __device__ function from __host__ function
953 | __MATH_FUNCTIONS_DECL__ long long int min(const long long int a, const long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:958:48: note: candidate function not viable: call to __device__ function from __host__ function
958 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const unsigned long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:963:48: note: candidate function not viable: call to __device__ function from __host__ function
963 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const long long int a, const unsigned long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:968:48: note: candidate function not viable: call to __device__ function from __host__ function
968 | __MATH_FUNCTIONS_DECL__ unsigned long long int min(const unsigned long long int a, const long long int b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:973:31: note: candidate function not viable: call to __device__ function from __host__ function
973 | __MATH_FUNCTIONS_DECL__ float min(const float a, const float b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:978:32: note: candidate function not viable: call to __device__ function from __host__ function
978 | __MATH_FUNCTIONS_DECL__ double min(const double a, const double b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:983:32: note: candidate function not viable: call to __device__ function from __host__ function
983 | __MATH_FUNCTIONS_DECL__ double min(const float a, const double b)
| ^
/usr/local/cuda/include/crt/math_functions.hpp:988:32: note: candidate function not viable: call to __device__ function from __host__ function
988 | __MATH_FUNCTIONS_DECL__ double min(const double a, const float b)
| ^