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

cpp_source = """
#include <torch/extension.h>
#include <string>

torch::Tensor cosface_cuda_forward(
    const torch::Tensor& cosine, 
    const torch::Tensor& label,
    float s,
    float m,
    std::string reduction);
"""

cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>
#include <cfloat>

#define BLOCK_SIZE 256
#define WARP_SIZE 32

// --- Reductions Helpers ---
template<typename T>
__device__ __forceinline__ T warp_reduce_max(T val) {
    #pragma unroll
    for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
        val = max(val, __shfl_down_sync(0xffffffff, val, offset));
    }
    return val;
}

template<typename T>
__device__ __forceinline__ T warp_reduce_sum(T val) {
    #pragma unroll
    for (int offset = WARP_SIZE / 2; offset > 0; offset /= 2) {
        val += __shfl_down_sync(0xffffffff, val, offset);
    }
    return val;
}

__device__ __forceinline__ float block_reduce_max(float val) {
    static __shared__ float shared[32];
    int lane = threadIdx.x % WARP_SIZE;
    int wid = threadIdx.x / WARP_SIZE;
    val = warp_reduce_max(val);
    if (lane == 0) shared[wid] = val;
    __syncthreads();
    val = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared[lane] : -FLT_MAX;
    if (wid == 0) val = warp_reduce_max(val);
    return val;
}

__device__ __forceinline__ float block_reduce_sum(float val) {
    static __shared__ float shared[32];
    int lane = threadIdx.x % WARP_SIZE;
    int wid = threadIdx.x / WARP_SIZE;
    val = warp_reduce_sum(val);
    if (lane == 0) shared[wid] = val;
    __syncthreads();
    val = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared[lane] : 0.0f;
    if (wid == 0) val = warp_reduce_sum(val);
    return val;
}

// --- Fused CosFace Kernel ---
__global__ void cosface_kernel(
    float* __restrict__ output,
    const float* __restrict__ cosine,
    const int64_t* __restrict__ label,
    int num_classes,
    float s,
    float m) 
{
    // One block per sample (row)
    int row = blockIdx.x;
    int tid = threadIdx.x;

    const float* row_cosine = cosine + row * num_classes;
    int64_t target_idx = label[row];

    // 1. Pass 1: Find Max (of Modified Logits)
    float local_max = -FLT_MAX;
    
    // Grid-Stride Loop
    for (int i = tid; i < num_classes; i += blockDim.x) {
        float val = row_cosine[i];
        // Apply CosFace Margin Logic On-The-Fly
        if (i == target_idx) {
            val = val - m;
        }
        // Scale
        val = val * s;
        
        local_max = fmaxf(local_max, val);
    }
    
    float global_max = block_reduce_max(local_max);
    
    // Broadcast max to all threads in block
    __shared__ float s_max;
    if (tid == 0) s_max = global_max;
    __syncthreads();
    global_max = s_max;

    // 2. Pass 2: Sum Exp
    float local_sum = 0.0f;
    float target_logit = 0.0f; // Cache target logit for final loss

    for (int i = tid; i < num_classes; i += blockDim.x) {
        float val = row_cosine[i];
        if (i == target_idx) {
            val = val - m;
        }
        val = val * s;
        
        // Save target logit if this thread handles it
        if (i == target_idx) {
            target_logit = val;
        }

        local_sum += __expf(val - global_max);
    }

    float global_sum = block_reduce_sum(local_sum);

    // 3. Final Calculation (Thread 0)
    // We need target_logit available to Thread 0.
    // Optimization: Since we don't store target_logit in Shared Memory,
    // let Thread 0 re-calculate it. It's just one memory read, cheaper than shared mem sync.
    
    if (tid == 0) {
        float t_val = row_cosine[target_idx];
        t_val = (t_val - m) * s; // Target logit
        
        // LogSumExp = global_max + log(global_sum)
        // LogSoftmax(target) = target_logit - LogSumExp
        // NLL Loss = -LogSoftmax(target) = LogSumExp - target_logit
        
        float loss = (global_max + __logf(global_sum)) - t_val;
        output[row] = loss;
    }
}

torch::Tensor cosface_cuda_forward(
    const torch::Tensor& cosine, 
    const torch::Tensor& label,
    float s,
    float m,
    std::string reduction) 
{
    TORCH_CHECK(cosine.is_cuda() && label.is_cuda(), "Inputs must be CUDA");
    TORCH_CHECK(cosine.is_contiguous(), "Cosine must be contiguous");
    TORCH_CHECK(cosine.dim() == 2, "Cosine must be 2D (Batch, Class)");
    TORCH_CHECK(label.dim() == 1, "Label must be 1D (Batch)");
    TORCH_CHECK(cosine.size(0) == label.size(0), "Batch size mismatch");

    int batch_size = cosine.size(0);
    int num_classes = cosine.size(1);

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

    // One Block per Sample
    cosface_kernel<<<batch_size, BLOCK_SIZE>>>(
        output.data_ptr<float>(),
        cosine.data_ptr<float>(),
        label.data_ptr<int64_t>(),
        num_classes,
        s,
        m
    );

    if (reduction == "mean") {
        return output.mean();
    } else if (reduction == "sum") {
        return output.sum();
    }

    return output;
}
"""

class ModelNew(nn.Module):
    def __init__(self, s=64.0, m=0.35, reduction='none'):
        super(ModelNew, self).__init__()
        self.s = s
        self.m = m
        self.reduction = reduction
        self.op = load_inline(
            name='cosface_loss_op',
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=['cosface_cuda_forward'],
            verbose=False,
            extra_cuda_cflags=['-O3']
        )

    def forward(self, cosine: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
        return self.op.cosface_cuda_forward(cosine.contiguous(), label.contiguous(), self.s, self.m, self.reduction)