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 beta_divergence_kernel(
    const float* __restrict__ p,
    const float* __restrict__ q,
    float* __restrict__ output,
    int n,
    float beta
) {
    extern __shared__ float sdata[];
    int tid = threadIdx.x;
    int idx = blockIdx.x * blockDim.x + threadIdx.x;

    float local_sum = 0.0f;
    for (int i = idx; i < n; i += blockDim.x * gridDim.x) {
        float p_val = p[i];
        float q_val = q[i];

        float term1 = powf(p_val, beta);
        float term2 = (beta - 1.0f) * powf(q_val, beta);
        float term3 = beta * p_val * powf(q_val, beta - 1.0f);

        local_sum += term1 + term2 - term3;
    }

    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) {
        atomicAdd(output, sdata[0]);
    }
}

torch::Tensor beta_divergence_cuda(torch::Tensor p, torch::Tensor q, float beta) {
    int batch_size = p.size(0);
    int num_classes = p.size(1);
    int n = batch_size * num_classes;

    auto output = at::zeros({1}, p.options());

    int threads = 256;
    int blocks = 128;
    int shared_mem = threads * sizeof(float);

    beta_divergence_kernel<<<blocks, threads, shared_mem>>>(
        p.data_ptr<float>(),
        q.data_ptr<float>(),
        output.data_ptr<float>(),
        n,
        beta
    );

    float sum_val = output.item<float>();
    float mean_sum = sum_val / batch_size;
    float loss = mean_sum / (beta * (beta - 1.0f));

    return torch::tensor(loss, p.options());
}
"""

cpp_source = """
torch::Tensor beta_divergence_cuda(torch::Tensor p, torch::Tensor q, float beta);
"""

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


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

    def forward(self, p, q):
        p_prob = F.softmax(p, dim=1)
        q_prob = F.softmax(q, dim=1)
        return beta_divergence_loss.beta_divergence_cuda(p_prob, q_prob, self.beta)