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


class ModelNew(nn.Module):
    def __init__(self, delta=1.0):
        super().__init__()
        self.delta = delta
        self._compile_cuda_kernel()

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

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

        __device__ __forceinline__ double warp_sum(double val) {
            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 huber_kernel_vec4(
            const float* __restrict__ x,
            const float* __restrict__ y,
            float* __restrict__ output,
            int total_elements,
            float delta) 
        {
            int idx = blockIdx.x * blockDim.x + threadIdx.x;

            double sum = 0.0;
            float delta_sq_half = 0.5f * delta * delta;

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

            const float4* x_vec = reinterpret_cast<const float4*>(x);
            const float4* y_vec = reinterpret_cast<const float4*>(y);

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

                float d1 = vx.x - vy.x;
                float d2 = vx.y - vy.y;
                float d3 = vx.z - vy.z;
                float d4 = vx.w - vy.w;

                float a1 = fabsf(d1);
                float a2 = fabsf(d2);
                float a3 = fabsf(d3);
                float a4 = fabsf(d4);

                double l1 = (a1 < delta) ? (0.5f * d1 * d1) : (delta * (a1 - 0.5f * delta));
                double l2 = (a2 < delta) ? (0.5f * d2 * d2) : (delta * (a2 - 0.5f * delta));
                double l3 = (a3 < delta) ? (0.5f * d3 * d3) : (delta * (a3 - 0.5f * delta));
                double l4 = (a4 < delta) ? (0.5f * d4 * d4) : (delta * (a4 - 0.5f * delta));

                sum += l1 + l2 + l3 + l4;
            }

            int tail_start = vec_loops * 4;
            int tail_end = total_elements;

            // Handle remaining elements (non-vectorized)
            // Stride for tail is tricky with grid-stride loop, so we switch to linear check for tail
            // Since tail is small (<4), simple check is fine, but proper grid stride needs care.
            // Simplified: let one block handle tail or mask carefully.
            // Here: Just use a standard linear tail check based on original idx logic for simplicity in stride

            // Re-calculate simple index for tail
            for (int i = tail_start + idx; i < tail_end; i += gridDim.x * blockDim.x) {
                float diff = x[i] - y[i];
                float abs_diff = fabsf(diff);
                if (abs_diff < delta) {
                    sum += 0.5f * diff * diff;
                } else {
                    sum += delta * (abs_diff - 0.5f * delta);
                }
            }

            sum = block_sum(sum);

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

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

            int total_elements = x_c.numel();
            int threads = 256;
            int blocks = (total_elements + threads * 4 - 1) / (threads * 4);
            if (blocks > 1024) blocks = 1024;

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

            huber_kernel_vec4<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                y_c.data_ptr<float>(),
                output.data_ptr<float>(),
                total_elements,
                delta
            );

            return output.sum() / total_elements;
        }
        """

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

    def forward(self, x, y):
        return self.op.huber_cuda(x, y, self.delta)