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


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

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor clark_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 clark_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 = 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];

                float t1 = fabsf(vx.x - vy.x) / (fabsf(vx.x) + fabsf(vy.x) + eps);
                float t2 = fabsf(vx.y - vy.y) / (fabsf(vx.y) + fabsf(vy.y) + eps);
                float t3 = fabsf(vx.z - vy.z) / (fabsf(vx.z) + fabsf(vy.z) + eps);
                float t4 = fabsf(vx.w - vy.w) / (fabsf(vx.w) + fabsf(vy.w) + eps);

                sum += (double)(t1 * t1 + t2 * t2 + t3 * t3 + t4 * t4);
            }

            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];

                    float term = fabsf(val_x - val_y) / (fabsf(val_x) + fabsf(val_y) + eps);
                    sum += (double)(term * term);
                }
            }

            sum = block_sum(sum);

            if (threadIdx.x == 0) {
                output[bid] = sqrtf((float)sum);
            }
        }

        torch::Tensor clark_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;

            clark_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="clark_opt_vec4",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["clark_cuda"],
            extra_cuda_cflags=["-O3"],
            verbose=False
        )

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