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


class ModelNew(nn.Module):
    def __init__(self, reduction='mean'):
        super().__init__()
        self.reduction = reduction
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor logits_loss_cuda(
            torch::Tensor student, torch::Tensor teacher,
            int reduction_mode);
        """

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

        __global__ void logits_loss_reduction_kernel(
            const float* __restrict__ student,
            const float* __restrict__ teacher,
            float* __restrict__ output,
            const int64_t n_elements)
        {
            extern __shared__ float sdata[];
            unsigned int tid = threadIdx.x;
            unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x;
            unsigned int gridSize = blockDim.x * gridDim.x;

            float local_sum = 0.0f;

            int64_t n_vec = n_elements / 4;
            const float4* stu_4 = reinterpret_cast<const float4*>(student);
            const float4* tea_4 = reinterpret_cast<const float4*>(teacher);

            for (int64_t i = idx; i < n_vec; i += gridSize) {
                float4 s = stu_4[i];
                float4 t = tea_4[i];

                float d1 = s.x - t.x;
                float d2 = s.y - t.y;
                float d3 = s.z - t.z;
                float d4 = s.w - t.w;

                local_sum += d1 * d1 + d2 * d2 + d3 * d3 + d4 * d4;
            }

            for (int64_t i = n_vec * 4 + idx; i < n_elements; i += gridSize) {
                float diff = student[i] - teacher[i];
                local_sum += diff * diff;
            }

            sdata[tid] = local_sum;
            __syncthreads();

            for (unsigned 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]);
            }
        }

        __global__ void logits_loss_elementwise_kernel(
            const float* __restrict__ student,
            const float* __restrict__ teacher,
            float* __restrict__ output,
            const int64_t n_elements)
        {
            int64_t idx = blockIdx.x * blockDim.x + threadIdx.x;
            if (idx < n_elements) {
                float diff = student[idx] - teacher[idx];
                output[idx] = diff * diff;
            }
        }

        torch::Tensor logits_loss_cuda(
            torch::Tensor student, torch::Tensor teacher,
            int reduction_mode) 
        {
            TORCH_CHECK(student.is_cuda(), "student must be on CUDA");
            TORCH_CHECK(teacher.is_cuda(), "teacher must be on CUDA");

            int64_t n = student.numel();
            TORCH_CHECK(teacher.numel() == n, "Size mismatch");

            auto student_c = student.contiguous();
            auto teacher_c = teacher.contiguous();

            if (reduction_mode == 0) {
                auto output = torch::empty_like(student_c);
                int threads = 256;
                int blocks = (n + threads - 1) / threads;
                logits_loss_elementwise_kernel<<<blocks, threads>>>(
                    student_c.data_ptr<float>(), teacher_c.data_ptr<float>(),
                    output.data_ptr<float>(), n
                );
                return output;
            } else {
                auto output = torch::zeros({1}, student.options());
                int threads = 256;
                int blocks = min((int64_t)((n + threads - 1) / threads), (int64_t)1024);
                size_t shared_mem = threads * sizeof(float);

                logits_loss_reduction_kernel<<<blocks, threads, shared_mem>>>(
                    student_c.data_ptr<float>(), teacher_c.data_ptr<float>(),
                    output.data_ptr<float>(), n
                );

                if (reduction_mode == 1) {
                    return output / (float)n;
                } else {
                    return output;
                }
            }
        }
        """

        self.op = load_inline(
            name="logits_loss_op",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["logits_loss_cuda"],
            extra_cuda_cflags=["-O3"],
            verbose=False
        )

    def forward(self, logits_student: torch.Tensor, logits_teacher: torch.Tensor) -> torch.Tensor:
        if not logits_student.is_cuda:
            logits_student = logits_student.cuda()
            logits_teacher = logits_teacher.cuda()

        mode = 0
        if self.reduction == 'mean':
            mode = 1
        elif self.reduction == 'sum':
            mode = 2

        return self.op.logits_loss_cuda(logits_student, logits_teacher, mode)