← Back to Leaderboard

The AI CUDA Engineer 👷

97_CosineSimilarityLosswarp_shfl_shared_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>

__inline__ __device__ float warp_reduce(float val) {
    for (int offset = warpSize/2; offset > 0; offset >>= 1)
        val += __shfl_down_sync(0xffffffff, val, offset);
    return val;
}

__global__ void optimized_cosine_loss_kernel(const float* __restrict__ pred,
                                             const float* __restrict__ target,
                                             float* output,
                                             int N,
                                             int D) {
    const int row = blockIdx.x;
    const int tid = threadIdx.x;
    const int vec_size = 4;
    const int D_vec = D / vec_size;

    const float4* pred_vec = reinterpret_cast<const float4*>(pred + row*D);
    const float4* target_vec = reinterpret_cast<const float4*>(target + row*D);

    float dot = 0.0f, p_sq = 0.0f, t_sq = 0.0f;

    // Vectorized load with coalesced access
    #pragma unroll
    for (int i = tid; i < D_vec; i += blockDim.x) {
        float4 p = pred_vec[i];
        float4 t = target_vec[i];
        dot += p.x*t.x + p.y*t.y + p.z*t.z + p.w*t.w;
        p_sq += p.x*p.x + p.y*p.y + p.z*p.z + p.w*p.w;
        t_sq += t.x*t.x + t.y*t.y + t.z*t.z + t.w*t.w;
    }

    // Handle remainder elements
    for (int i = D_vec*vec_size + tid; i < D; i += blockDim.x) {
        float p = pred[row*D + i];
        float t = target[row*D + i];
        dot += p * t;
        p_sq += p * p;
        t_sq += t * t;
    }

    // Warp-level reduction
    dot = warp_reduce(dot);
    p_sq = warp_reduce(p_sq);
    t_sq = warp_reduce(t_sq);

    // Shared memory for cross-warp reduction
    __shared__ float smem[3][32];
    if (threadIdx.x % warpSize == 0) {
        smem[0][threadIdx.x/warpSize] = dot;
        smem[1][threadIdx.x/warpSize] = p_sq;
        smem[2][threadIdx.x/warpSize] = t_sq;
    }
    __syncthreads();

    // Final reduction in first warp
    if (threadIdx.x < 32) {
        dot = threadIdx.x < blockDim.x/warpSize ? smem[0][threadIdx.x] : 0;
        p_sq = threadIdx.x < blockDim.x/warpSize ? smem[1][threadIdx.x] : 0;
        t_sq = threadIdx.x < blockDim.x/warpSize ? smem[2][threadIdx.x] : 0;

        dot = warp_reduce(dot);
        p_sq = warp_reduce(p_sq);
        t_sq = warp_reduce(t_sq);

        if (threadIdx.x == 0) {
            const float eps = 1e-8f;
            float denom = sqrtf(p_sq) * sqrtf(t_sq);
            atomicAdd(output, (1.0f - (dot / fmaxf(denom, eps))) / N);
        }
    }
}

torch::Tensor optimized_cosine_loss_forward(torch::Tensor pred, torch::Tensor target) {
    TORCH_CHECK(pred.dim() == 2 && target.dim() == 2, "Inputs must be 2D");
    TORCH_CHECK(pred.sizes() == target.sizes(), "Shape mismatch");

    auto output = torch::zeros({1}, pred.options());
    const int block_size = 512;
    optimized_cosine_loss_kernel<<<pred.size(0), block_size>>>(
        pred.data_ptr<float>(),
        target.data_ptr<float>(),
        output.data_ptr<float>(),
        pred.size(0),
        pred.size(1)
    );
    return output;
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &optimized_cosine_loss_forward, "Optimized Cosine Loss Forward (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.537 inst/cycle 0.000 3
Executed Ipc Elapsed 0.317 inst/cycle 0.000 3
Issue Slots Busy 13.823 % 0.005 3
Issued Ipc Active 0.553 inst/cycle 0.000 3
SM Busy 13.823 % 0.005 3
Memory Throughput 715800315393.760 byte/second 23591452130072330240.000 3
Mem Busy 12.367 % 0.009 3
Max Bandwidth 21.463 % 0.015 3
L1/TEX Hit Rate 0.000 % 0.000 3
L2 Hit Rate 18.437 % 0.002 3
Mem Pipes Busy 4.057 % 0.001 3
Warp Cycles Per Issued Instruction 24.193 cycle 0.005 3
Warp Cycles Per Executed Instruction 24.830 cycle 0.006 3
Avg. Active Threads Per Warp 30.220 0.000 3
Avg. Not Predicated Off Threads Per Warp 28.960 0.000 3
Max Active Clusters 0.000 cluster 0.000 3
Max Cluster Size 8.000 block 0.000 3
Overall GPU Occupancy 0.000 % 0.000 3
Cluster Occupancy 0.000 % 0.000 3
Block Limit SM 32.000 block 0.000 3
Block Limit Registers 4.000 block 0.000 3
Block Limit Shared Mem 11.000 block 0.000 3
Block Limit Warps 4.000 block 0.000 3
Theoretical Active Warps per SM 64.000 warp 0.000 3
Theoretical Occupancy 100.000 % 0.000 3
Achieved Occupancy 21.000 % 0.000 3
Achieved Active Warps Per SM 13.440 warp 0.000 3
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 (21.0%) 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 472258.14 μs
Device Time 308.54 μs
Self CPU Time 51.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
aten::zeros
CPU Time 6157545.96 μs
Device Time 236612.95 μs
Self CPU Time 146889.27 μ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 6496388.70 μs
Device Time 7840532.80 μs
Self CPU Time 320910.12 μ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 6175479.97 μs
Device Time 7840532.80 μs
Self CPU Time 406096.02 μs
Self Device Time 7840530.53 μ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 6145904.81 μs
Device Time 2933.72 μs
Self CPU Time 6145904.81 μs
Self Device Time 2933.72 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
optimized_cosine_loss_kernel(float const*, float const*, float*, int, int)
CPU Time 0.00 μs
Device Time 531163.89 μs
Self CPU Time 0.00 μs
Self Device Time 531163.89 μ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 258624.82 μs
Device Time 1261130.16 μs
Self CPU Time 258624.82 μs
Self Device Time 1261130.16 μ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 7603919.85 μs
Self CPU Time 0.00 μs
Self Device Time 7603919.85 μ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
45288 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/b10_s2_warp_shfl_shared_opt/base/base.cu:12:46 bugprone-easily-swappable-parameters
12 | __global__ void optimized_cosine_loss_kernel(const float* __restrict__ pred,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
13 | const float* __restrict__ target,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:12:72: note: the first parameter in the range is 'pred'
12 | __global__ void optimized_cosine_loss_kernel(const float* __restrict__ pred,
| ^~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:13:72: note: the last parameter in the range is 'target'
13 | const float* __restrict__ target,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:15:46: warning: 2 adjacent parameters of 'optimized_cosine_loss_kernel' of similar type ('int') are easily swapped by mistake [bugprone-easily-swappable-parameters]
15 | int N,
| ^~~~~~
16 | int D) {
| ~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:15:50: note: the first parameter in the range is 'N'
15 | int N,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:16:50: note: the last parameter in the range is 'D'
16 | int D) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:17:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
17 | const int row = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:18:21: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
18 | const int tid = threadIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:22: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]
22 | const float4* pred_vec = reinterpret_cast<const float4*>(pred + row*D);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:22:69: note: make conversion explicit to silence this warning
5 | const float4* pred_vec = reinterpret_cast<const float4*>(pred + row*D);
| ^~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:22:69: note: perform multiplication in a wider type
22 | const float4* pred_vec = reinterpret_cast<const float4*>(pred + row*D);
| ^~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:23: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]
23 | const float4* target_vec = reinterpret_cast<const float4*>(target + row*D);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:23:73: note: make conversion explicit to silence this warning
23 | const float4* target_vec = reinterpret_cast<const float4*>(target + row*D);
| ^~~~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:23:73: note: perform multiplication in a wider type
23 | const float4* target_vec = reinterpret_cast<const float4*>(target + row*D);
| ^~~
| static_cast<ptrdiff_t>( )
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:29:39: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
29 | for (int i = tid; i < D_vec; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:38:52: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
38 | for (int i = D_vec*vec_size + tid; i < D; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:73:68: warning: narrowing conversion from 'int' to 'float' [bugprone-narrowing-conversions]
73 | atomicAdd(output, (1.0f - (dot / fmaxf(denom, eps))) / N);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:78:59: warning: the parameter 'pred' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
78 | torch::Tensor optimized_cosine_loss_forward(torch::Tensor pred, torch::Tensor target) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:78:79: warning: the parameter 'target' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
78 | torch::Tensor optimized_cosine_loss_forward(torch::Tensor pred, torch::Tensor target) {
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:88:9: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
88 | pred.size(0),
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250202_optimize_b10_s4_e0_sweep/level_1/task_97/b10_s2_warp_shfl_shared_opt/base/base.cu:89:9: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
89 | pred.size(1)
| ^