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


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

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

        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 charbonnier_kernel(
            const float* __restrict__ x,
            const float* __restrict__ y,
            float* __restrict__ output,
            int total_elements,
            float eps_sq) 
        {
            int idx = blockIdx.x * blockDim.x + threadIdx.x;

            double sum = 0.0;

            // Grid-Stride Loop
            for (int i = idx; i < total_elements; i += gridDim.x * blockDim.x) {
                float diff = x[i] - y[i];
                // loss = sqrt(diff^2 + eps^2)
                sum += sqrtf(diff * diff + eps_sq);
            }

            sum = block_sum(sum);

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

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

            int total_elements = x_c.numel();
            int threads = 256;
            int blocks = (total_elements + threads - 1) / threads;
            // Cap blocks to maximize occupancy but avoid excessive reduction overhead
            if (blocks > 2048) blocks = 2048; 

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

            float eps_sq = eps * eps;

            charbonnier_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                y_c.data_ptr<float>(),
                output.data_ptr<float>(),
                total_elements,
                eps_sq
            );

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

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

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