← Back to Leaderboard

The AI CUDA Engineer 👷

95_CrossEntropyLossce_loss_grid_stride_unroll_base

Level 1 • Task 95
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 Cross Entropy Loss for multi-class classification tasks.

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

    Returns:
        torch.Tensor: Cross Entropy Loss.
    """
    return F.cross_entropy(predictions, targets)


class Model(nn.Module):
    """
    A model that computes Cross Entropy Loss for multi-class classification tasks.

    Parameters:
        None
    """

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

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


batch_size = 4096
num_classes = 10
input_shape = (num_classes,)  # Output for each class
dim = 1


def get_inputs():
    return [
        torch.randn(batch_size, *input_shape),
        torch.randint(0, num_classes, (batch_size,)),
    ]


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

class Model(nn.Module):
    """
    A model that computes Cross Entropy Loss for multi-class classification tasks.

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

    def forward(self, predictions, targets):
        return torch.nn.functional.cross_entropy(predictions, targets)

batch_size = 4096
num_classes = 10
input_shape = (num_classes, )  # Output for each class
dim = 1

def get_inputs():
    return [torch.randn(batch_size, *input_shape), torch.randint(0, num_classes, (batch_size,))]

def get_init_inputs():
    return []

Kernel Information

Related Kernels (Level 1, Task 95 • 95_CrossEntropyLoss)

Rank Kernel Name Runtime (ms) Speedup Native Speedup Compile
🥇 95_CrossEntropyLoss 0.01 8.97 2.45
🥇 memory_coalescing_base 0.01 8.97 2.45
🥇 block_size_experimentation_base 0.01 8.97 2.45
🥇 stride_loop_boundary_optimization_base 0.01 8.97 2.45
🥇 optimized_thread_block_mapping_base_base 0.01 8.97 2.45
🥇 optimal_blocksize_experiment_base 0.01 8.97 2.45
🥇 modular_crossentropy_base 0.01 8.97 2.45
🥇 warp_aligned_base_base 0.01 8.97 2.45
🥇 warp_divergence_minimization_base_base 0.01 8.97 2.45
🥇 modularized_device_functions_base 0.01 8.97 2.45
🥇 ce_loss_unroll_optimized_base 0.01 8.97 2.45
🥇 ce_loss_ldg_aligned_base 0.01 8.97 2.45
🥇 ce_loss_optimized_blocksize_512_base 0.01 8.97 2.45
🥇 ce_loss_grid_stride_unroll_edit_1 0.01 8.97 2.45
🥇 ce_loss_ldg_aligned_edit_1 0.01 8.97 2.45
🥇 stride_loop_optimization_base_base 0.01 8.97 2.45
🥇 ldg_aligned_access_base 0.01 8.97 2.45
🥇 modular_device_ce_loss_base 0.01 8.97 2.45
🥇 ce_loss_stride_base 0.01 8.97 2.45
🥇 atomic_optimized_crossentropy_edit_1 0.01 8.97 2.45
#include <torch/extension.h>

__forceinline__ __device__ float compute_max_logit(const float* logits, int num_classes) {
    float max_val = logits[0];
    #pragma unroll 4
    for (int j = 1; j < num_classes; j++) {
        max_val = fmaxf(max_val, logits[j]);
    }
    return max_val;
}

__forceinline__ __device__ float compute_exp_sum(float max_val, const float* logits, int num_classes) {
    float sum = 0.0f;
    #pragma unroll 4
    for (int j = 0; j < num_classes; j++) {
        sum += expf(logits[j] - max_val);
    }
    return sum;
}

__global__ void cross_entropy_loss_kernel(
    const float* __restrict__ logits,
    const int64_t* __restrict__ targets,
    float* __restrict__ losses,
    int batch_size,
    int num_classes
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int total_threads = gridDim.x * blockDim.x;

    for (int i = idx; i < batch_size; i += total_threads) {
        const float* sample_logits = logits + i * num_classes;
        int target = targets[i];
        
        float max_logit = compute_max_logit(sample_logits, num_classes);
        float sum_exp = compute_exp_sum(max_logit, sample_logits, num_classes);
        float log_sum_exp = logf(sum_exp);
        
        losses[i] = -(sample_logits[target] - max_logit - log_sum_exp);
    }
}

torch::Tensor forward(torch::Tensor predictions, torch::Tensor targets) {
    TORCH_CHECK(predictions.is_cuda(), "predictions must be a CUDA tensor");
    TORCH_CHECK(targets.is_cuda(), "targets must be a CUDA tensor");

    int batch_size = predictions.size(0);
    int num_classes = predictions.size(1);

    auto losses = torch::empty({batch_size}, predictions.options());

    // H100-optimized parameters
    const int threads = 256;
    int blocks = (batch_size + threads - 1) / threads;
    blocks = min(blocks, 128);  // Cap blocks for better occupancy

    cross_entropy_loss_kernel<<<blocks, threads>>>(
        predictions.data_ptr<float>(),
        targets.data_ptr<int64_t>(),
        losses.data_ptr<float>(),
        batch_size,
        num_classes
    );

    cudaError_t err = cudaGetLastError();
    TORCH_CHECK(err == cudaSuccess, "CUDA error:", cudaGetErrorString(err));

    return losses.mean();
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Optimized CE loss with grid stride and unrolling");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.486 inst/cycle 0.000 5
Executed Ipc Elapsed 0.030 inst/cycle 0.000 5
Issue Slots Busy 12.542 % 0.219 5
Issued Ipc Active 0.502 inst/cycle 0.000 5
SM Busy 12.542 % 0.219 5
Memory Throughput 53703633003.154 byte/second 849534146442815744.000 5
Mem Busy 9.018 % 0.030 5
Max Bandwidth 4.904 % 0.006 5
L1/TEX Hit Rate 92.360 % 0.000 5
L2 Hit Rate 87.360 % 0.096 5
Mem Pipes Busy 0.404 % 0.000 5
Warp Cycles Per Issued Instruction 14.316 cycle 0.008 5
Warp Cycles Per Executed Instruction 14.732 cycle 0.008 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 29.230 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 11.852 % 0.006 5
Achieved Active Warps Per SM 7.586 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.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 308397.82 μs
Device Time 11.39 μs
Self CPU Time 37.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::_to_copy
CPU Time 308360.15 μs
Device Time 11.39 μs
Self CPU Time 86.23 μ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 308152.07 μs
Device Time 0.00 μs
Self CPU Time 79.43 μ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 307873.31 μs
Device Time 0.00 μs
Self CPU Time 307873.31 μ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 713541.30 μs
Device Time 7920.85 μs
Self CPU Time 713541.30 μs
Self Device Time 7920.85 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
aten::mean
CPU Time 162682.22 μs
Device Time 52427.47 μs
Self CPU Time 92086.14 μs
Self Device Time 52427.47 μ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::reduce_kernel<512, 1, at::native::ReduceOp<float, at::native::MeanOps<float, float, float, float>, unsigned int, float, 4> >(at::native::ReduceOp<float, at::native::MeanOps<float, float, float, float>, unsigned int, float, 4>)
CPU Time 0.00 μs
Device Time 52427.47 μs
Self CPU Time 0.00 μs
Self Device Time 52427.47 μ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 94199.56 μs
Device Time 946442.39 μs
Self CPU Time 21890.44 μ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 72310.49 μs
Device Time 946442.39 μs
Self CPU Time 22560.63 μs
Self Device Time 946442.39 μ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 946442.39 μs
Self CPU Time 0.00 μs
Self Device Time 946442.39 μ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
45249 warnings and 1 error generated when compiling for host.
Error while processing /home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/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/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:25:5 bugprone-easily-swappable-parameters
25 | int batch_size,
| ^~~~~~~~~~~~~~~
26 | int num_classes
| ~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:25:9: note: the first parameter in the range is 'batch_size'
25 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:26:9: note: the last parameter in the range is 'num_classes'
26 | int num_classes
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:28:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
28 | int idx = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:29:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | int total_threads = gridDim.x * blockDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:32:38: warning: result of multiplication in type 'int' is used as a pointer offset after an implicit widening conversion to type 'ptrdiff_t' [bugprone-implicit-widening-of-multiplication-result]
32 | const float* sample_logits = logits + i * num_classes;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:32:47: note: make conversion explicit to silence this warning
2 | const float* sample_logits = logits + i * num_classes;
| ^~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:32:47: note: perform multiplication in a wider type
32 | const float* sample_logits = logits + i * num_classes;
| ^
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:33:22: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
33 | int target = targets[i];
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:43:37: warning: the parameter 'predictions' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
43 | torch::Tensor forward(torch::Tensor predictions, torch::Tensor targets) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:43:64: 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]
43 | torch::Tensor forward(torch::Tensor predictions, torch::Tensor targets) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:47:22: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
47 | int batch_size = predictions.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:48:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
48 | int num_classes = predictions.size(1);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250212_optimize_b5_s4_e1_v2/level_1/task_95/b4_s3_ce_loss_grid_stride_unroll/base/base.cu:55:14: error: no matching function for call to 'min' [clang-diagnostic-error]
55 | blocks = min(blocks, 128); // Cap blocks for better occupancy
| ^~~
/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)
| ^