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 arcface_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

// --- Reduction 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 ArcFace Kernel ---
__global__ void arcface_kernel(
    float* __restrict__ output,
    const float* __restrict__ cosine,
    const int64_t* __restrict__ label,
    int num_classes,
    float s,
    float cos_m,
    float sin_m) 
{
    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;
    
    for (int i = tid; i < num_classes; i += blockDim.x) {
        float val = row_cosine[i];
        
        // ArcFace Logic: cos(theta + m)
        if (i == target_idx) {
            // Apply Trigonometric Identity:
            // cos(t + m) = cos(t)cos(m) - sin(t)sin(m)
            // val is cos(t). sin(t) = sqrt(1 - val^2)
            // Clamp val to [-1, 1] to avoid nan in sqrt
            float clamped = val;
            if (clamped > 1.0f) clamped = 1.0f;
            if (clamped < -1.0f) clamped = -1.0f;
            
            float sin_t = sqrtf(1.0f - clamped * clamped);
            val = clamped * cos_m - sin_t * sin_m;
        }
        
        val = val * s;
        local_max = fmaxf(local_max, val);
    }
    
    float global_max = block_reduce_max(local_max);
    
    __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;

    for (int i = tid; i < num_classes; i += blockDim.x) {
        float val = row_cosine[i];
        if (i == target_idx) {
            float clamped = val;
            if (clamped > 1.0f) clamped = 1.0f;
            if (clamped < -1.0f) clamped = -1.0f;
            float sin_t = sqrtf(1.0f - clamped * clamped);
            val = clamped * cos_m - sin_t * sin_m;
            target_logit = val * s; // Save un-normalized target logit
        }
        val = val * s;
        local_sum += __expf(val - global_max);
    }

    float global_sum = block_reduce_sum(local_sum);

    // 3. Final Loss
    // Since target_logit is private to one thread (and not broadcasted yet), 
    // it's safest/easiest to just recompute it in thread 0 or broadcast it via Shared Memory.
    // Given the math is cheap compared to memory, let thread 0 recompute.
    
    if (tid == 0) {
        float t_val = row_cosine[target_idx];
        // Recompute target logit
        float clamped = t_val;
        if (clamped > 1.0f) clamped = 1.0f;
        if (clamped < -1.0f) clamped = -1.0f;
        float sin_t = sqrtf(1.0f - clamped * clamped);
        t_val = (clamped * cos_m - sin_t * sin_m) * s;
        
        // Loss = -log( exp(target) / sum )
        //      = - ( target - log(sum) )
        //      = - ( target - (max + log(sum_exp)) )
        //      = max + log(sum_exp) - target
        
        float loss = (global_max + __logf(global_sum)) - t_val;
        output[row] = loss;
    }
}

torch::Tensor arcface_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");
    
    int batch_size = cosine.size(0);
    int num_classes = cosine.size(1);

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

    // Pre-calculate trig values on host to save regs/ops
    float cos_m = cosf(m);
    float sin_m = sinf(m);

    arcface_kernel<<<batch_size, BLOCK_SIZE>>>(
        output.data_ptr<float>(),
        cosine.data_ptr<float>(),
        label.data_ptr<int64_t>(),
        num_classes,
        s,
        cos_m,
        sin_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.50, reduction='none'):
        super(ModelNew, self).__init__()
        self.s = s
        self.m = m
        self.reduction = reduction
        self.op = load_inline(
            name='arcface_loss_op',
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=['arcface_cuda_forward'],
            verbose=False,
            extra_cuda_cflags=['-O3']
        )

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