← Back to Leaderboard

The AI CUDA Engineer 👷

99_TripletMarginLosswarp_optimized_tripletloss_base

Level 1 • Task 99
import torch
import torch.nn as nn
import torch.nn.functional as F


def module_fn(
    anchor: torch.Tensor, positive: torch.Tensor, negative: torch.Tensor, margin: float
) -> torch.Tensor:
    """
    Computes the Triplet Margin Loss for metric learning tasks.

    Args:
        anchor (torch.Tensor): Anchor values.
        positive (torch.Tensor): Positive values.
        negative (torch.Tensor): Negative values.
        margin (float): Margin value.

    Returns:
        torch.Tensor: Triplet Margin Loss.
    """
    return F.triplet_margin_loss(anchor, positive, negative, margin=margin)


class Model(nn.Module):
    """
    A model that computes Triplet Margin Loss for metric learning tasks.
    """

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

    def forward(self, anchor, positive, negative, fn=module_fn):
        return fn(anchor, positive, negative, self.margin)


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


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


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

class Model(nn.Module):
    """
    A model that computes Triplet Margin Loss for metric learning tasks.

    Parameters:
        margin (float): The margin between the positive and negative samples.
    """
    def __init__(self, margin=1.0):
        super(Model, self).__init__()
        self.loss_fn = torch.nn.TripletMarginLoss(margin=margin)

    def forward(self, anchor, positive, negative):
        return self.loss_fn(anchor, positive, negative)

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

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

def get_init_inputs():
    return [1.0]  # Default margin

Kernel Information

Related Kernels (Level 1, Task 99 • 99_TripletMarginLoss)

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

__inline__ __device__
float warp_reduce_sum(float val) {
    #pragma unroll
    for (int offset = 16; offset > 0; offset /= 2)
        val += __shfl_down_sync(0xffffffff, val, offset);
    return val;
}

__global__ void triplet_margin_loss_kernel_optimized(
    const float* __restrict__ anchor,
    const float* __restrict__ positive,
    const float* __restrict__ negative,
    float* __restrict__ output,
    const float margin,
    const int batch_size,
    const int feat_size) {

    const int batch_idx = blockIdx.x;
    if (batch_idx >= batch_size) return;

    // Shared memory for partial sums
    extern __shared__ float shared_mem[];
    float* sh_pos = shared_mem;
    float* sh_neg = shared_mem + 32; // Only need warp size

    const int lane_id = threadIdx.x % 32;
    const int warp_id = threadIdx.x / 32;
    const int num_warps = blockDim.x / 32;
    
    // Process elements with vectorized loads
    float4 sum_pos4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
    float4 sum_neg4 = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
    
    const int offset = batch_idx * feat_size;
    const float4* anchor4 = reinterpret_cast<const float4*>(anchor + offset);
    const float4* positive4 = reinterpret_cast<const float4*>(positive + offset);
    const float4* negative4 = reinterpret_cast<const float4*>(negative + offset);
    
    const int vec_elements = feat_size / 4;
    
    // Stride by number of warps for better memory coalescing
    for (int i = threadIdx.x; i < vec_elements; i += blockDim.x) {
        float4 a4 = __ldg(&anchor4[i]);
        float4 p4 = __ldg(&positive4[i]);
        float4 n4 = __ldg(&negative4[i]);
        
        float4 d_pos, d_neg;
        d_pos.x = a4.x - p4.x;
        d_pos.y = a4.y - p4.y;
        d_pos.z = a4.z - p4.z;
        d_pos.w = a4.w - p4.w;
        
        d_neg.x = a4.x - n4.x;
        d_neg.y = a4.y - n4.y;
        d_neg.z = a4.z - n4.z;
        d_neg.w = a4.w - n4.w;
        
        sum_pos4.x += d_pos.x * d_pos.x;
        sum_pos4.y += d_pos.y * d_pos.y;
        sum_pos4.z += d_pos.z * d_pos.z;
        sum_pos4.w += d_pos.w * d_pos.w;
        
        sum_neg4.x += d_neg.x * d_neg.x;
        sum_neg4.y += d_neg.y * d_neg.y;
        sum_neg4.z += d_neg.z * d_neg.z;
        sum_neg4.w += d_neg.w * d_neg.w;
    }
    
    // Reduce float4 to single float
    float sum_pos = sum_pos4.x + sum_pos4.y + sum_pos4.z + sum_pos4.w;
    float sum_neg = sum_neg4.x + sum_neg4.y + sum_neg4.z + sum_neg4.w;
    
    // Handle remaining elements
    for (int i = vec_elements * 4 + threadIdx.x; i < feat_size; i += blockDim.x) {
        float a = __ldg(&anchor[offset + i]);
        float p = __ldg(&positive[offset + i]);
        float n = __ldg(&negative[offset + i]);
        
        float d_pos = a - p;
        float d_neg = a - n;
        sum_pos += d_pos * d_pos;
        sum_neg += d_neg * d_neg;
    }
    
    // Warp-level reduction
    sum_pos = warp_reduce_sum(sum_pos);
    sum_neg = warp_reduce_sum(sum_neg);
    
    // First thread in each warp writes to shared memory
    if (lane_id == 0) {
        sh_pos[warp_id] = sum_pos;
        sh_neg[warp_id] = sum_neg;
    }
    
    __syncthreads();
    
    // First warp reduces results from all warps
    if (warp_id == 0 && lane_id < num_warps) {
        sum_pos = sh_pos[lane_id];
        sum_neg = sh_neg[lane_id];
        
        sum_pos = warp_reduce_sum(sum_pos);
        sum_neg = warp_reduce_sum(sum_neg);
        
        if (lane_id == 0) {
            float loss = sqrtf(sum_pos) - sqrtf(sum_neg) + margin;
            output[batch_idx] = (loss > 0.0f) ? loss : 0.0f;
        }
    }
}

torch::Tensor triplet_margin_loss_cuda_optimized(
    torch::Tensor anchor,
    torch::Tensor positive,
    torch::Tensor negative,
    float margin) {

    TORCH_CHECK(anchor.device().is_cuda(), "anchor must be a CUDA tensor");
    TORCH_CHECK(positive.device().is_cuda(), "positive must be a CUDA tensor");
    TORCH_CHECK(negative.device().is_cuda(), "negative must be a CUDA tensor");

    const int batch_size = anchor.size(0);
    const int feat_size = anchor.size(1);
    auto output = torch::empty({batch_size}, anchor.options());

    const int threads = 256;  // Multiple of warp size (32)
    const int shared_mem_size = 64 * sizeof(float); // 2 arrays of warp size
    
    triplet_margin_loss_kernel_optimized<<<batch_size, threads, shared_mem_size>>>(
        anchor.data_ptr<float>(),
        positive.data_ptr<float>(),
        negative.data_ptr<float>(),
        output.data_ptr<float>(),
        margin,
        batch_size,
        feat_size);
    
    return output.mean();
}

PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
    m.def("forward", &triplet_margin_loss_cuda_optimized, "Triplet margin loss forward optimized (CUDA)");
}
Performance Metrics
Metric Value Unit Variance Samples
Executed Ipc Active 0.260 inst/cycle 0.000 5
Executed Ipc Elapsed 0.156 inst/cycle 0.000 5
Issue Slots Busy 6.712 % 0.045 5
Issued Ipc Active 0.268 inst/cycle 0.000 5
SM Busy 6.712 % 0.045 5
Memory Throughput 1037813722193.048 byte/second 43140473333863784448.000 5
Mem Busy 18.042 % 0.019 5
Max Bandwidth 31.128 % 0.080 5
L1/TEX Hit Rate 0.000 % 0.000 5
L2 Hit Rate 13.090 % 0.001 5
Mem Pipes Busy 2.236 % 0.000 5
Warp Cycles Per Issued Instruction 27.926 cycle 0.082 5
Warp Cycles Per Executed Instruction 28.798 cycle 0.087 5
Avg. Active Threads Per Warp 31.330 0.000 5
Avg. Not Predicated Off Threads Per Warp 29.860 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 25.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.924 % 0.000 5
Achieved Active Warps Per SM 7.628 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 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 427481.06 μs
Device Time 436.32 μs
Self CPU Time 40.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
aten::_to_copy
CPU Time 427440.63 μs
Device Time 436.32 μs
Self CPU Time 102.36 μ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 426426.13 μs
Device Time 0.00 μs
Self CPU Time 98.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
cudaDeviceGetStreamPriorityRange
CPU Time 425457.17 μs
Device Time 0.00 μs
Self CPU Time 425457.17 μ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 802637.09 μs
Device Time 28234.24 μs
Self CPU Time 802637.09 μs
Self Device Time 28234.24 μs
CPU Memory Usage 0 B
Device Memory Usage 0 B
Self CPU Memory Usage 0 B
Self Device Memory Usage 0 B
triplet_margin_loss_kernel_optimized(float const*, float const*, float const*, float*, float, int, int)
CPU Time 0.00 μs
Device Time 80798.33 μs
Self CPU Time 0.00 μs
Self Device Time 80798.33 μ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 27908.46 μs
Device Time 51266.65 μs
Self CPU Time 27908.46 μs
Self Device Time 51266.65 μ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 94572.90 μs
Device Time 1015583.71 μs
Self CPU Time 19484.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::fill_
CPU Time 75089.63 μs
Device Time 1015583.71 μs
Self CPU Time 26285.27 μs
Self Device Time 1015583.71 μ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 1015583.71 μs
Self CPU Time 0.00 μs
Self Device Time 1015583.71 μ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
45292 warnings generated when compiling for host.
Suppressed 45324 warnings (45277 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/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:15:5 bugprone-easily-swappable-parameters
15 | const float* __restrict__ anchor,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16 | const float* __restrict__ positive,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
17 | const float* __restrict__ negative,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:15:31: note: the first parameter in the range is 'anchor'
15 | const float* __restrict__ anchor,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:17:31: note: the last parameter in the range is 'negative'
17 | const float* __restrict__ negative,
| ^~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:19:5: warning: 3 adjacent parameters of 'triplet_margin_loss_kernel_optimized' of convertible types are easily swapped by mistake [bugprone-easily-swappable-parameters]
19 | const float margin,
| ^~~~~~~~~~~~~~~~~~~
20 | const int batch_size,
| ~~~~~~~~~~~~~~~~~~~~~
21 | const int feat_size) {
| ~~~~~~~~~~~~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:19:17: note: the first parameter in the range is 'margin'
19 | const float margin,
| ^~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:21:15: note: the last parameter in the range is 'feat_size'
21 | const int feat_size) {
| ^~~~~~~~~
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:20:5: note: 'const float' and 'const int' may be implicitly converted: 'const float' (as 'float') -> 'const int' (as 'int'), 'const int' (as 'int') -> 'const float' (as 'float')
20 | const int batch_size,
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:23:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
23 | const int batch_idx = blockIdx.x;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:31:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
31 | const int lane_id = threadIdx.x % 32;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:32:25: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
32 | const int warp_id = threadIdx.x / 32;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:33:27: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
33 | const int num_warps = blockDim.x / 32;
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:47:18: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
47 | for (int i = threadIdx.x; i < vec_elements; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:47:54: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
47 | for (int i = threadIdx.x; i < vec_elements; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:79:18: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
79 | for (int i = vec_elements * 4 + threadIdx.x; i < feat_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:79:70: warning: narrowing conversion from 'unsigned int' to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
79 | for (int i = vec_elements * 4 + threadIdx.x; i < feat_size; i += blockDim.x) {
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:118:19: warning: the parameter 'anchor' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
118 | torch::Tensor anchor,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:119:19: warning: the parameter 'positive' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
119 | torch::Tensor positive,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:120:19: warning: the parameter 'negative' is copied for each invocation but only used as a const reference; consider making it a const reference [performance-unnecessary-value-param]
120 | torch::Tensor negative,
| ^
| const &
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:127:28: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
127 | const int batch_size = anchor.size(0);
| ^
/home/robert_sakana_ai/llm_cuda/experiments/20250208_optimize_b5_s4_e1_sweep/level_1/task_99/b3_s2_warp_optimized_tripletloss/base/base.cu:128:27: warning: narrowing conversion from 'int64_t' (aka 'long') to signed type 'int' is implementation-defined [bugprone-narrowing-conversions]
128 | const int feat_size = anchor.size(1);
| ^