← Back to Leaderboard

The AI CUDA Engineer 👷

97_CosineSimilarityLossoptimal_cosine_similarity_loss_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 instructions
__inline__ __device__ float warp_reduce_sum(float val) {
    // use full mask for all active threads in a warp
    for (int offset = warpSize / 2; offset > 0; offset /= 2) {
        val += __shfl_down_sync(0xffffffff, val, offset);
    }
    return val;
}

// Combined kernel that processes one row per block
__global__ void optimal_cosine_similarity_loss_kernel(const float* __restrict__ predictions,
                                                         const float* __restrict__ targets,
                                                         float* output,
                                                         int N,
                                                         int D) {
    // Each block processes one row
    const int row = blockIdx.x;
    const int tid = threadIdx.x;
    const int blockSize = blockDim.x;
    
    // Determine number of warps per block (assuming blockDim.x is a multiple of warpSize or close)
    const int warps_per_block = (blockSize + warpSize - 1) / warpSize;
    
    // Use vectorized loads for coalesced access
    const int vec_size = 4;
    const int D_aligned = (D / vec_size) * vec_size;  // largest multiple of vec_size
    const int numVec = D_aligned / vec_size;

    // Reinterpret pointers to float4 for vectorized loads
    const float4* pred_vec = reinterpret_cast<const float4*>(predictions + row * D);
    const float4* target_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 the vectorized part using coalesced memory accesses
    for (int i = tid; i < numVec; i += blockSize) {
        float4 p = pred_vec[i];
        float4 t = target_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 tail elements
    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;
    }

    // Each warp performs its own reduction
    sum_dot = warp_reduce_sum(sum_dot);
    sum_pred_sq = warp_reduce_sum(sum_pred_sq);
    sum_target_sq = warp_reduce_sum(sum_target_sq);

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

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

    // Final reduction across warps performed by the first warp
    if (warp_id == 0 && lane_id < warps_per_block) {
        float dot_val = s_dot[lane_id];
        float pred_sq_val = s_pred_sq[lane_id];
        float target_sq_val = s_target_sq[lane_id];

        dot_val = warp_reduce_sum(dot_val);
        pred_sq_val = warp_reduce_sum(pred_sq_val);
        target_sq_val = warp_reduce_sum(target_sq_val);

        // Only the first thread computes the final value
        if (lane_id == 0) {
            const float eps = 1e-8f;
            float norm_pred = sqrtf(pred_sq_val);
            float norm_target = sqrtf(target_sq_val);
            float denominator = norm_pred * norm_target;
            denominator = fmaxf(denominator, eps);
            float cos_sim = dot_val / denominator;
            float loss = (1.0f - cos_sim) / N;
            // Atomically accumulate the loss across blocks
            atomicAdd(output, loss);
        }
    }
}

// Host function binding the CUDA kernel to PyTorch

torch::Tensor optimal_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());

    // Launch one block per row; using 512 threads per block facilitates full warp occupancy
    const int block_size = 512;
    optimal_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", &optimal_cosine_similarity_loss_forward, "Optimal Cosine Similarity Loss Forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.770 inst/cycle 0.000 5
Executed Ipc Elapsed 0.476 inst/cycle 0.000 5
Issue Slots Busy 19.520 % 0.205 5
Issued Ipc Active 0.782 inst/cycle 0.000 5
SM Busy 19.520 % 0.205 5
Memory Throughput 687046498741.708 byte/second 63100489207556997120.000 5
Mem Busy 11.900 % 0.020 5
Max Bandwidth 20.588 % 0.054 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 18.772 % 0.001 5
Mem Pipes Busy 3.888 % 0.002 5
Warp Cycles Per Issued Instruction 16.826 cycle 0.078 5
Warp Cycles Per Executed Instruction 17.052 cycle 0.082 5
Avg. Active Threads Per Warp 30.000 0.000 5
Avg. Not Predicated Off Threads Per Warp 28.030 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 11.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 21.148 % 0.008 5
Achieved Active Warps Per SM 13.536 warp 0.003 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 (21.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 419038.30 μs
Device Time 310.97 μs
Self CPU Time 46.16 μ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 5696488.38 μs
Device Time 225284.59 μs
Self CPU Time 151858.07 μ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 6086712.18 μs
Device Time 7456333.20 μs
Self CPU Time 293472.34 μ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 5793240.91 μs
Device Time 7456333.20 μs
Self CPU Time 365040.82 μs
Self Device Time 7456330.87 μ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 5862178.64 μs
Device Time 2845.34 μs
Self CPU Time 5862178.64 μs
Self Device Time 2845.34 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
optimal_cosine_similarity_loss_kernel(float const*, float const*, float*, int, int)
CPU Time 0.00 μs
Device Time 523010.97 μs
Self CPU Time 0.00 μs
Self Device Time 523010.97 μ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 200802.29 μs
Device Time 1199071.80 μs
Self CPU Time 200802.29 μs
Self Device Time 1199071.80 μ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 7231836.19 μs
Self CPU Time 0.00 μs
Self Device Time 7231836.19 μ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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:16:55 bugprone-easily-swappable-parameters
16 | __global__ void optimal_cosine_similarity_loss_kernel(const float* __restrict__ predictions,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 | const float* __restrict__ targets,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:16:81: note: the first parameter in the range is 'predictions'
16 | __global__ void optimal_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:17:84: note: the last parameter in the range is 'targets'
17 | const float* __restrict__ targets,
| ^~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:19:58: warning: 2 adjacent parameters of 'optimal_cosine_similarity_loss_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
19 | int N,
| ^~~~~~
20 | int D) {
| ~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:19:62: note: the first parameter in the range is 'N'
19 | int N,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:20:62: note: the last parameter in the range is 'D'
20 | int D) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:22:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
22 | const int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:23:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
23 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:24:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
24 | const int blockSize = blockDim.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:35:62: 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]
35 | const float4* pred_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:35:76: note: make conversion explicit to silence this warning
5 | const float4* pred_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:35:76: note: perform multiplication in a wider type
35 | const float4* pred_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:36:64: 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]
36 | const float4* target_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:36:74: note: make conversion explicit to silence this warning
36 | const float4* target_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:36:74: note: perform multiplication in a wider type
36 | const float4* target_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:97:45: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
97 | float loss = (1.0f - cos_sim) / N;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:106:68: 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]
106 | torch::Tensor optimal_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:106:95: 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]
106 | torch::Tensor optimal_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/b8_s2_optimal_cosine_similarity_loss/base/base.cu:113:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
113 | int N = predictions.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b8_s2_optimal_cosine_similarity_loss/base/base.cu:114:13: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
114 | int D = predictions.size(1);
| ^