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 tsallis_divergence_kernel(
    const float* __restrict__ p,
    const float* __restrict__ q,
    float* __restrict__ output,
    int num_classes,
    float q_param
) {
    extern __shared__ float sdata[];

    int tid = threadIdx.x;
    int bid = blockIdx.x;

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

    for (int i = tid; i < num_classes; i += blockDim.x) {
        float p_val = p[row_offset + i];
        float q_val = q[row_offset + i];

        local_sum += powf(p_val, q_param) * powf(q_val, 1.0f - q_param);
    }

    sdata[tid] = local_sum;
    __syncthreads();

    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];
        output[bid] = (sum_val - 1.0f) / (q_param - 1.0f);
    }
}

torch::Tensor tsallis_divergence_cuda(torch::Tensor p, torch::Tensor q, float q_param) {
    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;
    int shared_mem = threads * sizeof(float);

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

    return output.mean();
}
"""

cpp_source = """
torch::Tensor tsallis_divergence_cuda(torch::Tensor p, torch::Tensor q, float q_param);
"""

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


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

    def forward(self, p, target):
        p_prob = F.softmax(p, dim=1)
        q_prob = F.softmax(target, dim=1)
        return tsallis_divergence_loss.tsallis_divergence_cuda(p_prob, q_prob, self.q)