← Back to Leaderboard

The AI CUDA Engineer 👷

95_CrossEntropyLossblock_size_experimentation_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>

__global__ void cross_entropy_loss_kernel_block_size(
    const float* __restrict__ logits,
    const int64_t* __restrict__ targets,
    float* __restrict__ losses,
    int batch_size,
    int num_classes
)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < batch_size)
    {
        // Get pointer to logits for sample i
        const float* logits_i = logits + i * num_classes;
        int64_t target = targets[i];

        // Compute max logit for numerical stability
        float max_logit = logits_i[0];
        for (int j = 1; j < num_classes; j++)
        {
            if (logits_i[j] > max_logit)
                max_logit = logits_i[j];
        }

        // Compute sum of exp(logits - max_logit)
        float sum_exp = 0.0f;
        for (int j = 0; j < num_classes; j++)
        {
            sum_exp += expf(logits_i[j] - max_logit);
        }

        // Compute log_sum_exp
        float log_sum_exp = logf(sum_exp);

        // Compute loss for this sample
        float loss = - (logits_i[target] - max_logit - log_sum_exp);
        losses[i] = loss;
    }
}

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

    // Ensure inputs have correct dimensions
    TORCH_CHECK(predictions.dim() == 2, "predictions must be a 2D tensor");
    TORCH_CHECK(targets.dim() == 1, "targets must be a 1D tensor");

    // Ensure data types are correct
    TORCH_CHECK(predictions.dtype() == torch::kFloat32, "predictions must be Float32 tensor");
    TORCH_CHECK(targets.dtype() == torch::kInt64, "targets must be Int64 tensor");

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

    TORCH_CHECK(targets.size(0) == batch_size, "targets must have same batch size as predictions");

    // Output tensor for losses per sample
    auto losses = torch::empty({batch_size}, predictions.options());

    // Experiment with different block sizes
    int threads = 512;  // Experimenting with 512 threads per block
    int blocks = (batch_size + threads - 1) / threads;

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

    // Check for CUDA errors
    cudaError_t err = cudaGetLastError();
    TORCH_CHECK(err == cudaSuccess, "Error in cross_entropy_loss_kernel_block_size: ", cudaGetErrorString(err));

    // Compute mean loss over batch
    auto loss = losses.mean();

    return loss;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &forward, "Cross Entropy Loss forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.972 inst/cycle 0.002 5
Executed Ipc Elapsed 0.030 inst/cycle 0.000 5
Issue Slots Busy 24.752 % 1.403 5
Issued Ipc Active 0.990 inst/cycle 0.002 5
SM Busy 24.752 % 1.403 5
Memory Throughput 46701429289.664 byte/second 2544290970570857472.000 5
Mem Busy 7.858 % 0.066 5
Max Bandwidth 4.264 % 0.019 5
L1/TEX Hit Rate 92.360 % 0.000 5
L2 Hit Rate 87.632 % 0.126 5
Mem Pipes Busy 0.336 % 0.000 5
Warp Cycles Per Issued Instruction 15.276 cycle 0.513 5
Warp Cycles Per Executed Instruction 15.570 cycle 0.536 5
Avg. Active Threads Per Warp 32.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 29.920 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 4.000 block 0.000 5
Block Limit Shared Mem 16.000 block 0.000 5
Block Limit Warps 4.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 22.986 % 0.035 5
Achieved Active Warps Per SM 14.710 warp 0.015 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 (23.2%) 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 461947.06 μs
Device Time 11.49 μs
Self CPU Time 47.18 μ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 461899.88 μs
Device Time 11.49 μs
Self CPU Time 95.11 μ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 461683.70 μs
Device Time 0.00 μs
Self CPU Time 83.66 μ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 461197.42 μs
Device Time 0.00 μs
Self CPU Time 461197.42 μ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 732124.33 μs
Device Time 137953.51 μs
Self CPU Time 732124.33 μs
Self Device Time 137953.51 μ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 174421.87 μs
Device Time 51572.85 μs
Self CPU Time 95604.03 μs
Self Device Time 51572.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::zero_
CPU Time 99289.53 μs
Device Time 977917.26 μs
Self CPU Time 23726.13 μ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 75564.81 μs
Device Time 977917.26 μs
Self CPU Time 25709.31 μs
Self Device Time 977917.26 μ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 977917.26 μs
Self CPU Time 0.00 μs
Self Device Time 977917.26 μ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
45282 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_95/b2_s0_block_size_experimentation/base/base.cu:7:5 bugprone-easily-swappable-parameters
7 | int batch_size,
| ^~~~~~~~~~~~~~~
8 | int num_classes
| ~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:7:9: note: the first parameter in the range is 'batch_size'
7 | int batch_size,
| ^~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:8:9: note: the last parameter in the range is 'num_classes'
8 | int num_classes
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:11:13: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
11 | int i = blockIdx.x * blockDim.x + threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:15:33: 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]
15 | const float* logits_i = logits + i * num_classes;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:15:42: note: make conversion explicit to silence this warning
2 |
3 | __global__ void cross_entropy_loss_kernel_block_size(
4 | const float* __restrict__ logits,
5 | const int64_t* __restrict__ targets,
6 | float* __restrict__ losses,
7 | int batch_size,
8 | int num_classes
9 | )
10 | {
11 | int i = blockIdx.x * blockDim.x + threadIdx.x;
12 | if (i < batch_size)
13 | {
14 | // Get pointer to logits for sample i
15 | const float* logits_i = logits + i * num_classes;
| ^~~~~~~~~~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:15:42: note: perform multiplication in a wider type
15 | const float* logits_i = logits + i * num_classes;
| ^
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:42: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]
42 | torch::Tensor forward(torch::Tensor predictions, torch::Tensor targets)
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:42: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]
42 | torch::Tensor forward(torch::Tensor predictions, torch::Tensor targets)
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:56:22: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
56 | int batch_size = predictions.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_95/b2_s0_block_size_experimentation/base/base.cu:57:23: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
57 | int num_classes = predictions.size(1);
| ^