import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline


class ModelNew(nn.Module):
    def __init__(self, margin=2.0):
        super().__init__()
        self.margin = margin
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor contrastive_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor y, float margin);
        """

        cuda_source = """
        #include <cuda_runtime.h>

        __device__ __forceinline__ double warp_sum(double val) {
            for (int offset = 16; offset > 0; offset /= 2) {
                val += __shfl_down_sync(0xffffffff, val, offset);
            }
            return val;
        }

        __device__ __forceinline__ double block_sum(double val) {
            static __shared__ double shared[32];
            int lane = threadIdx.x % 32;
            int wid = threadIdx.x / 32;

            val = warp_sum(val);
            if (lane == 0) shared[wid] = val;
            __syncthreads();

            val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0;
            if (wid == 0) val = warp_sum(val);
            return val;
        }

        __global__ void contrastive_kernel(
            const float* __restrict__ x1,
            const float* __restrict__ x2,
            const float* __restrict__ y,
            float* __restrict__ output,
            int batch_size,
            int feature_dim,
            float margin) 
        {
            int bid = blockIdx.x;
            if (bid >= batch_size) return;

            const float* row_x1 = x1 + bid * feature_dim;
            const float* row_x2 = x2 + bid * feature_dim;

            double sum_sq = 0.0;

            // Double precision accumulation for distance
            for (int i = threadIdx.x; i < feature_dim; i += blockDim.x) {
                double diff = (double)row_x1[i] - (double)row_x2[i];
                sum_sq += diff * diff;
            }

            sum_sq = block_sum(sum_sq);

            if (threadIdx.x == 0) {
                // dist = sqrt(sum_sq)
                // term1 = (1-y) * dist^2
                // term2 = y * max(0, m - dist)^2
                // Note: dist^2 is just sum_sq, avoiding one sqrt call for term1

                double dist = sqrt(sum_sq);
                double label = (double)y[bid]; // Assuming y is [N, 1] stride is 1 if contiguous

                double loss_sim = (1.0 - label) * sum_sq;

                double margin_diff = (double)margin - dist;
                if (margin_diff < 0.0) margin_diff = 0.0;
                double loss_dis = label * (margin_diff * margin_diff);

                output[bid] = (float)(0.5 * (loss_sim + loss_dis));
            }
        }

        torch::Tensor contrastive_cuda(torch::Tensor x1, torch::Tensor x2, torch::Tensor y, float margin) {
            auto x1_c = x1.contiguous();
            auto x2_c = x2.contiguous();
            auto y_c = y.contiguous();

            int batch_size = x1_c.size(0);
            int feature_dim = x1_c.size(1);

            auto output = torch::empty({batch_size}, x1.options());

            int threads = 256;
            int blocks = batch_size;

            contrastive_kernel<<<blocks, threads>>>(
                x1_c.data_ptr<float>(),
                x2_c.data_ptr<float>(),
                y_c.data_ptr<float>(),
                output.data_ptr<float>(),
                batch_size,
                feature_dim,
                margin
            );

            // Reducing to scalar mean on PyTorch side is usually fast enough and cleaner
            return output.mean(); 
        }
        """

        self.op = load_inline(
            name="contrastive_opt_v1",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["contrastive_cuda"],
            extra_cuda_cflags=["-O3"],
            verbose=False
        )

    def forward(self, x1, x2, y):
        return self.op.contrastive_cuda(x1, x2, y, self.margin)