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

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

__global__ void renyi_divergence_kernel(
    const float* __restrict__ p,
    const float* __restrict__ q,
    float* __restrict__ output,
    int num_classes,
    float alpha
) {
    extern __shared__ float sdata[];

    int tid = threadIdx.x;
    int bid = blockIdx.x; // Each block handles one row (batch item)

    int row_offset = bid * num_classes;
    float local_sum = 0.0f;

    // Grid-stride loop within the row
    for (int i = tid; i < num_classes; i += blockDim.x) {
        float p_val = p[row_offset + i];
        float q_val = q[row_offset + i];

        // P^alpha * Q^(1-alpha)
        local_sum += powf(p_val, alpha) * powf(q_val, 1.0f - alpha);
    }

    sdata[tid] = local_sum;
    __syncthreads();

    // Block reduction
    for (int s = blockDim.x / 2; s > 0; s >>= 1) {
        if (tid < s) {
            sdata[tid] += sdata[tid + s];
        }
        __syncthreads();
    }

    if (tid == 0) {
        float sum_val = sdata[0];
        // 1/(alpha-1) * log(sum)
        output[bid] = logf(sum_val) / (alpha - 1.0f);
    }
}

torch::Tensor renyi_divergence_cuda(torch::Tensor p, torch::Tensor q, float alpha) {
    int batch_size = p.size(0);
    int num_classes = p.size(1);

    auto output = at::empty({batch_size}, p.options());

    int threads = 256;
    int blocks = batch_size; // One block per sample in batch
    int shared_mem = threads * sizeof(float);

    renyi_divergence_kernel<<<blocks, threads, shared_mem>>>(
        p.data_ptr<float>(),
        q.data_ptr<float>(),
        output.data_ptr<float>(),
        num_classes,
        alpha
    );

    return output.mean();
}
"""

cpp_source = """
torch::Tensor renyi_divergence_cuda(torch::Tensor p, torch::Tensor q, float alpha);
"""

renyi_divergence_loss = load_inline(
    name="renyi_divergence_loss",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["renyi_divergence_cuda"],
    verbose=False
)


class ModelNew(nn.Module):
    def __init__(self, alpha=0.5):
        super(ModelNew, self).__init__()
        self.alpha = alpha

    def forward(self, p, q):
        p_prob = F.softmax(p, dim=1)
        q_prob = F.softmax(q, dim=1)
        return renyi_divergence_loss.renyi_divergence_cuda(p_prob, q_prob, self.alpha)