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


class ModelNew(nn.Module):
    def __init__(self, tau=0.5):
        super().__init__()
        self.tau = tau
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor quantile_loss_cuda(torch::Tensor y_pred, torch::Tensor y_true, float tau);
        """

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

        __device__ __forceinline__ float quantile_loss_op(float y_pred, float y_true, float tau) {
            float diff = y_true - y_pred;

            if (diff > 0.0f) {

                return tau * diff;
            } else {

                return (tau - 1.0f) * diff;
            }
        }

        __global__ void quantile_loss_kernel(
            const float* __restrict__ y_pred,
            const float* __restrict__ y_true,
            float* __restrict__ output,
            const int n_elements,
            const float tau) 
        {
            const int tid = blockIdx.x * blockDim.x + threadIdx.x;
            const int stride = blockDim.x * gridDim.x;

            const int vec_loops = n_elements >> 2;
            const float4* y_pred_vec = reinterpret_cast<const float4*>(y_pred);
            const float4* y_true_vec = reinterpret_cast<const float4*>(y_true);
            float4* out_vec = reinterpret_cast<float4*>(output);

            for (int i = tid; i < vec_loops; i += stride) {
                float4 yp = __ldg(&y_pred_vec[i]);
                float4 yt = __ldg(&y_true_vec[i]);
                float4 r;

                r.x = quantile_loss_op(yp.x, yt.x, tau);
                r.y = quantile_loss_op(yp.y, yt.y, tau);
                r.z = quantile_loss_op(yp.z, yt.z, tau);
                r.w = quantile_loss_op(yp.w, yt.w, tau);

                out_vec[i] = r;
            }

            const int tail_start = vec_loops << 2;
            for (int i = tail_start + tid; i < n_elements; i += stride) {
                output[i] = quantile_loss_op(y_pred[i], y_true[i], tau);
            }
        }

        torch::Tensor quantile_loss_cuda(torch::Tensor y_pred, torch::Tensor y_true, float tau) {
            auto y_pred_c = y_pred.contiguous();
            auto y_true_c = y_true.contiguous();

            const int n_elements = y_pred_c.numel();
            auto output = torch::empty_like(y_pred_c);

            const int threads = 256;
            const int max_blocks = 65535;
            const int blocks = std::min((n_elements + threads * 4 - 1) / (threads * 4), max_blocks);

            quantile_loss_kernel<<<blocks, threads>>>(
                y_pred_c.data_ptr<float>(),
                y_true_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements,
                tau
            );

            return output;
        }
        """

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

    def forward(self, y_pred, y_true):
        loss_elementwise = self.op.quantile_loss_cuda(y_pred, y_true, self.tau)
        return loss_elementwise.mean()