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


class ModelNew(nn.Module):
    def __init__(self, eps=1e-6):
        super().__init__()
        self.eps = eps
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor sorensen_dice_cuda(torch::Tensor x, torch::Tensor y, float eps);
        """

        cuda_source = """
        #include <cuda_runtime.h>

        __device__ __forceinline__ double warp_sum(double val) {
            #pragma unroll
            for (int offset = 16; offset > 0; offset /= 2) {
                val += __shfl_down_sync(0xffffffff, val, offset);
            }
            return val;
        }

        __device__ __forceinline__ double block_sum(double val) {
            static __shared__ double shared[32];
            int lane = threadIdx.x % 32;
            int wid = threadIdx.x / 32;

            val = warp_sum(val);
            if (lane == 0) shared[wid] = val;
            __syncthreads();

            val = (threadIdx.x < blockDim.x / 32) ? shared[lane] : 0.0;
            if (wid == 0) val = warp_sum(val);
            return val;
        }

        __global__ void sorensen_dice_kernel_vec4(
            const float* __restrict__ x,
            const float* __restrict__ y,
            float* __restrict__ output,
            int feature_dim,
            int batch_size,
            float eps) 
        {
            int bid = blockIdx.x;
            if (bid >= batch_size) return;

            const float* x_row = x + bid * feature_dim;
            const float* y_row = y + bid * feature_dim;

            double sum_inter = 0.0;
            double sum_x = 0.0;
            double sum_y = 0.0;

            int vec_loops = feature_dim / 4;
            int vec_remainder = feature_dim % 4;

            const float4* x_vec = reinterpret_cast<const float4*>(x_row);
            const float4* y_vec = reinterpret_cast<const float4*>(y_row);

            for (int i = threadIdx.x; i < vec_loops; i += blockDim.x) {
                float4 vx = x_vec[i];
                float4 vy = y_vec[i];

                sum_inter += (double)(vx.x * vy.x + vx.y * vy.y + vx.z * vy.z + vx.w * vy.w);
                sum_x += (double)(vx.x + vx.y + vx.z + vx.w);
                sum_y += (double)(vy.x + vy.y + vy.z + vy.w);
            }

            if (threadIdx.x == 0 && vec_remainder > 0) {
                int tail_start = vec_loops * 4;
                for (int i = 0; i < vec_remainder; ++i) {
                    int idx = tail_start + i;
                    float val_x = x_row[idx];
                    float val_y = y_row[idx];
                    sum_inter += (double)(val_x * val_y);
                    sum_x += (double)val_x;
                    sum_y += (double)val_y;
                }
            }

            sum_inter = block_sum(sum_inter);
            sum_x = block_sum(sum_x);
            sum_y = block_sum(sum_y);

            if (threadIdx.x == 0) {
                output[bid] = (float)((2.0 * sum_inter) / (sum_x + sum_y + eps));
            }
        }

        torch::Tensor sorensen_dice_cuda(torch::Tensor x, torch::Tensor y, float eps) {
            auto x_c = x.contiguous();
            auto y_c = y.contiguous();

            int batch_size = x_c.size(0);
            int feature_dim = x_c.size(1);

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

            int threads = 256;
            int blocks = batch_size;

            sorensen_dice_kernel_vec4<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                y_c.data_ptr<float>(),
                output.data_ptr<float>(),
                feature_dim,
                batch_size,
                eps
            );

            return output;
        }
        """

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

    def forward(self, x, y):
        return self.op.sorensen_dice_cuda(x, y, self.eps)