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 gce_loss_cuda_forward(
    const torch::Tensor& logits, 
    const torch::Tensor& targets,
    float q,
    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

struct __align__(16) Float4 {
    float x, y, z, w;
};

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;
}

__global__ void gce_loss_kernel(
    float* __restrict__ output,
    const float* __restrict__ logits,
    const int64_t* __restrict__ targets,
    int cols,
    float q) 
{
    // One block per row
    int row = blockIdx.x;
    int tid = threadIdx.x;

    const float* row_logits = logits + row * cols;
    int64_t target_idx = targets[row];

    // 1. Pass 1: Find Max (Vectorized)
    float local_max = -FLT_MAX;
    int i = tid * 4;
    while (i < cols) {
        if (i + 4 <= cols) {
            Float4 vec = reinterpret_cast<const Float4*>(&row_logits[i])[0];
            local_max = fmaxf(local_max, vec.x);
            local_max = fmaxf(local_max, vec.y);
            local_max = fmaxf(local_max, vec.z);
            local_max = fmaxf(local_max, vec.w);
        } else {
            // Tail
            for (int k = 0; k < 4 && (i + k) < cols; ++k) {
                local_max = fmaxf(local_max, row_logits[i+k]);
            }
        }
        i += blockDim.x * 4;
    }
    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 (Vectorized) & Extract Target Logit
    float local_sum = 0.0f;
    float my_target_logit = 0.0f; // Only valid if this thread processes target_idx
    bool has_target = false;

    i = tid * 4;
    while (i < cols) {
        if (i + 4 <= cols) {
            Float4 vec = reinterpret_cast<const Float4*>(&row_logits[i])[0];
            local_sum += __expf(vec.x - global_max);
            local_sum += __expf(vec.y - global_max);
            local_sum += __expf(vec.z - global_max);
            local_sum += __expf(vec.w - global_max);
            
            // Check if target is in this chunk
            if (target_idx >= i && target_idx < i + 4) {
                int offset = target_idx - i;
                if (offset == 0) my_target_logit = vec.x;
                else if (offset == 1) my_target_logit = vec.y;
                else if (offset == 2) my_target_logit = vec.z;
                else if (offset == 3) my_target_logit = vec.w;
                has_target = true;
            }
        } else {
            for (int k = 0; k < 4 && (i + k) < cols; ++k) {
                float val = row_logits[i+k];
                local_sum += __expf(val - global_max);
                if (i + k == target_idx) {
                    my_target_logit = val;
                    has_target = true;
                }
            }
        }
        i += blockDim.x * 4;
    }
    float global_sum = block_reduce_sum(local_sum);

    // 3. Extract Target Logit
    // Use Shared Memory to broadcast target logit from the thread that found it
    __shared__ float s_target_logit;
    if (has_target) {
        s_target_logit = my_target_logit;
    }
    __syncthreads();
    
    // 4. Calculate Loss
    if (tid == 0) {
        float t_val = s_target_logit;
        
        // Pt = exp(t_val - max) / sum
        float pt = __expf(t_val - global_max) / global_sum;
        
        // Loss = (1 - pt^q) / q
        float loss = (1.0f - __powf(pt, q)) / q;
        output[row] = loss;
    }
}

torch::Tensor gce_loss_cuda_forward(
    const torch::Tensor& logits, 
    const torch::Tensor& targets,
    float q,
    std::string reduction) 
{
    TORCH_CHECK(logits.is_cuda() && targets.is_cuda(), "Inputs must be CUDA");
    TORCH_CHECK(logits.is_contiguous() && targets.is_contiguous(), "Inputs must be contiguous");
    
    int batch_size = logits.size(0);
    int num_classes = logits.size(1);

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

    gce_loss_kernel<<<batch_size, BLOCK_SIZE>>>(
        output.data_ptr<float>(),
        logits.data_ptr<float>(),
        targets.data_ptr<int64_t>(),
        num_classes,
        q
    );

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

    return output;
}
"""

class ModelNew(nn.Module):
    def __init__(self, q=0.7, reduction='none'):
        super(ModelNew, self).__init__()
        self.q = q
        self.reduction = reduction
        self.op = load_inline(
            name='gce_loss_op',
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=['gce_loss_cuda_forward'],
            verbose=False,
            extra_cuda_cflags=['-O3']
        )

    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        return self.op.gce_loss_cuda_forward(logits.contiguous(), targets.contiguous(), self.q, self.reduction)