← Back to Leaderboard

The AI CUDA Engineer 👷

97_CosineSimilarityLosscoalesced_cosine_loss_opt_base

Level 1 • Task 97
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 Cosine Similarity Loss for comparing vectors.

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

    Returns:
        torch.Tensor: Cosine Similarity Loss.
    """
    cosine_sim = F.cosine_similarity(predictions, targets, dim=1)
    return torch.mean(1 - cosine_sim)


class Model(nn.Module):
    """
    A model that computes Cosine Similarity Loss for comparing vectors.

    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),
        torch.randn(batch_size, *input_shape),
    ]


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

class Model(nn.Module):
    """
    A model that computes Cosine Similarity Loss for comparing vectors.

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

    def forward(self, predictions, targets):
        cosine_sim = torch.nn.functional.cosine_similarity(predictions, targets, dim=1)
        return torch.mean(1 - cosine_sim)

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

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

def get_init_inputs():
    return []

Kernel Information

Related Kernels (Level 1, Task 97 • 97_CosineSimilarityLoss)

#include <torch/extension.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <math.h>

// Warp-level reduction using shuffle
__inline__ __device__ float warp_reduce_sum(float val) {
    for (int offset = warpSize / 2; offset > 0; offset /= 2) {
        val += __shfl_down_sync(0xffffffff, val, offset);
    }
    return val;
}

__global__ void coalesced_cosine_similarity_loss_kernel(const float* __restrict__ predictions,
                                                           const float* __restrict__ targets,
                                                           float* output,
                                                           int N,
                                                           int D) {
    // Each block processes one row
    int row = blockIdx.x;
    int tid = threadIdx.x;
    int blockSize = blockDim.x; // Expected to be 512

    // Use vectorized loads to ensure coalescing. We load 4 floats (16 bytes) at a time.
    const int vecSize = 4;
    int D_aligned = (D / vecSize) * vecSize;
    int numVec = D_aligned / vecSize;

    // Reinterpret the row pointers as float4* for aligned access
    const float4* predictions_vec = reinterpret_cast<const float4*>(predictions + row * D);
    const float4* targets_vec = reinterpret_cast<const float4*>(targets + row * D);

    float sum_dot = 0.0f;
    float sum_pred_sq = 0.0f;
    float sum_target_sq = 0.0f;

    // Process vectorized portion; threads in a warp read consecutive float4 elements ensuring coalescing
    for (int i = tid; i < numVec; i += blockSize) {
        float4 p = predictions_vec[i];
        float4 t = targets_vec[i];
        sum_dot     += p.x * t.x + p.y * t.y + p.z * t.z + p.w * t.w;
        sum_pred_sq += p.x * p.x + p.y * p.y + p.z * p.z + p.w * p.w;
        sum_target_sq += t.x * t.x + t.y * t.y + t.z * t.z + t.w * t.w;
    }

    // Process remaining elements if D is not divisible by 4
    for (int i = D_aligned + tid; i < D; i += blockSize) {
        float p = predictions[row * D + i];
        float t = targets[row * D + i];
        sum_dot     += p * t;
        sum_pred_sq += p * p;
        sum_target_sq += t * t;
    }

    // Perform warp-level reduction
    unsigned int mask = 0xffffffff;
    for (int offset = warpSize/2; offset > 0; offset /= 2) {
        sum_dot      += __shfl_down_sync(mask, sum_dot, offset);
        sum_pred_sq  += __shfl_down_sync(mask, sum_pred_sq, offset);
        sum_target_sq += __shfl_down_sync(mask, sum_target_sq, offset);
    }

    // Shared memory to hold results from each warp
    __shared__ float s_dot[512/32];
    __shared__ float s_pred_sq[512/32];
    __shared__ float s_target_sq[512/32];

    int warpId = tid / warpSize;
    if ((tid % warpSize) == 0) {
        s_dot[warpId] = sum_dot;
        s_pred_sq[warpId] = sum_pred_sq;
        s_target_sq[warpId] = sum_target_sq;
    }
    __syncthreads();

    // Final reduction from each warp
    if (tid < (blockSize / warpSize)) {
        sum_dot      = s_dot[tid];
        sum_pred_sq  = s_pred_sq[tid];
        sum_target_sq = s_target_sq[tid];

        for (int offset = (blockSize/warpSize)/2; offset > 0; offset /= 2) {
            sum_dot      += __shfl_down_sync(mask, sum_dot, offset);
            sum_pred_sq  += __shfl_down_sync(mask, sum_pred_sq, offset);
            sum_target_sq += __shfl_down_sync(mask, sum_target_sq, offset);
        }

        if (tid == 0) {
            const float eps = 1e-8f;
            float norm_pred = sqrtf(sum_pred_sq);
            float norm_target = sqrtf(sum_target_sq);
            float denominator = norm_pred * norm_target;
            denominator = fmaxf(denominator, eps);
            float cos_sim = sum_dot / denominator;
            atomicAdd(output, (1.0f - cos_sim) / N);
        }
    }
}

torch::Tensor coalesced_cosine_similarity_loss_forward(torch::Tensor predictions, torch::Tensor targets) {
    TORCH_CHECK(predictions.dim() == 2, "predictions must be 2D");
    TORCH_CHECK(targets.dim() == 2, "targets must be 2D");
    TORCH_CHECK(predictions.sizes() == targets.sizes(), "Input tensors must have the same shape");
    TORCH_CHECK(predictions.scalar_type() == torch::kFloat32, "predictions must be float32");
    TORCH_CHECK(targets.scalar_type() == torch::kFloat32, "targets must be float32");

    int N = predictions.size(0);
    int D = predictions.size(1);
    auto output = torch::zeros({1}, predictions.options());

    const int block_size = 512;
    coalesced_cosine_similarity_loss_kernel<<<N, block_size>>>(
        predictions.data_ptr<float>(),
        targets.data_ptr<float>(),
        output.data_ptr<float>(),
        N,
        D
    );

    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &coalesced_cosine_similarity_loss_forward, "Coalesced Cosine Similarity Loss Forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.768 inst/cycle 0.000 5
Executed Ipc Elapsed 0.426 inst/cycle 0.000 5
Issue Slots Busy 19.588 % 0.013 5
Issued Ipc Active 0.786 inst/cycle 0.000 5
SM Busy 19.588 % 0.013 5
Memory Throughput 755759816533.488 byte/second 92817011235104915456.000 5
Mem Busy 13.086 % 0.034 5
Max Bandwidth 22.696 % 0.090 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 18.706 % 0.003 5
Mem Pipes Busy 4.246 % 0.003 5
Warp Cycles Per Issued Instruction 18.446 cycle 0.002 5
Warp Cycles Per Executed Instruction 18.752 cycle 0.002 5
Avg. Active Threads Per Warp 29.180 0.000 5
Avg. Not Predicated Off Threads Per Warp 27.420 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 3.000 block 0.000 5
Block Limit Shared Mem 6.000 block 0.000 5
Block Limit Warps 4.000 block 0.000 5
Theoretical Active Warps per SM 48.000 warp 0.000 5
Theoretical Occupancy 75.000 % 0.000 5
Achieved Occupancy 22.734 % 0.000 5
Achieved Active Warps Per SM 14.548 warp 0.000 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 (75.0%) is limited by the number of required registers. The difference between calculated theoretical (75.0%) and measured achieved occupancy (22.7%) 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 484511.20 μs
Device Time 308.51 μs
Self CPU Time 49.75 μ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 5857407.49 μs
Device Time 223139.15 μs
Self CPU Time 149117.91 μ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 6191243.57 μs
Device Time 7511950.76 μs
Self CPU Time 310388.98 μ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 5880857.07 μs
Device Time 7511950.76 μs
Self CPU Time 380295.76 μs
Self Device Time 7511950.76 μ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 5860700.39 μs
Device Time 2842.29 μs
Self CPU Time 5860700.39 μs
Self Device Time 2842.29 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
coalesced_cosine_similarity_loss_kernel(float const*, float const*, float*, int, int)
CPU Time 0.00 μs
Device Time 479133.14 μs
Self CPU Time 0.00 μs
Self Device Time 479133.14 μ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 250343.63 μs
Device Time 1208610.94 μs
Self CPU Time 250343.63 μs
Self Device Time 1208610.94 μ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 7289674.96 μs
Self CPU Time 0.00 μs
Self Device Time 7289674.96 μ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
45287 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_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:14:57 bugprone-easily-swappable-parameters
14 | __global__ void coalesced_cosine_similarity_loss_kernel(const float* __restrict__ predictions,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
15 | const float* __restrict__ targets,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:14:83: note: the first parameter in the range is 'predictions'
14 | __global__ void coalesced_cosine_similarity_loss_kernel(const float* __restrict__ predictions,
| ^~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:15:86: note: the last parameter in the range is 'targets'
15 | const float* __restrict__ targets,
| ^~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:17:60: warning: 2 adjacent parameters of 'coalesced_cosine_similarity_loss_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
17 | int N,
| ^~~~~~
18 | int D) {
| ~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:17:64: note: the first parameter in the range is 'N'
17 | int N,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:18:64: note: the last parameter in the range is 'D'
18 | int D) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:20:15: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
20 | int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:21:15: 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_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:22:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | int blockSize = blockDim.x; // Expected to be 512
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:30:69: 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]
30 | const float4* predictions_vec = reinterpret_cast<const float4*>(predictions + row * D);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:30:83: note: make conversion explicit to silence this warning
5 | const float4* predictions_vec = reinterpret_cast<const float4*>(predictions + row * D);
| ^~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:30:83: note: perform multiplication in a wider type
30 | const float4* predictions_vec = reinterpret_cast<const float4*>(predictions + row * D);
| ^~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:31:65: 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]
31 | const float4* targets_vec = reinterpret_cast<const float4*>(targets + row * D);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:31:75: note: make conversion explicit to silence this warning
31 | const float4* targets_vec = reinterpret_cast<const float4*>(targets + row * D);
| ^~~~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:31:75: note: perform multiplication in a wider type
31 | const float4* targets_vec = reinterpret_cast<const float4*>(targets + row * D);
| ^~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:95:50: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
95 | atomicAdd(output, (1.0f - cos_sim) / N);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:100:70: 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]
100 | torch::Tensor coalesced_cosine_similarity_loss_forward(torch::Tensor predictions, torch::Tensor targets) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:100:97: 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]
100 | torch::Tensor coalesced_cosine_similarity_loss_forward(torch::Tensor predictions, torch::Tensor targets) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:107:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
107 | int N = predictions.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b7_s3_coalesced_cosine_loss_opt/base/base.cu:108:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
108 | int D = predictions.size(1);
| ^