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


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()
        self._compile_cuda_kernel()
        self.epsilon = 1e-5

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor rsg_apply_cuda(torch::Tensor x, torch::Tensor x_flat_sorted, float epsilon);
        """

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

        __device__ __forceinline__ float sigmoid_op(float x) {
            if (x >= 0.0f) {
                return 1.0f / (1.0f + expf(-x));
            } else {
                float z = expf(x);
                return z / (1.0f + z);
            }
        }

        __global__ void rsg_apply_kernel(
            const float* __restrict__ x,
            float* __restrict__ output,
            const int n_elements,
            const float median_val,
            const float iqr_recip) 
        {
            const int tid = blockIdx.x * blockDim.x + threadIdx.x;
            const int stride = blockDim.x * gridDim.x;

            for (int i = tid; i < n_elements; i += stride) {
                float val = x[i];
                float z_robust = (val - median_val) * iqr_recip;
                float gate = sigmoid_op(val);
                output[i] = z_robust * gate;
            }
        }

        torch::Tensor rsg_apply_cuda(torch::Tensor x, torch::Tensor x_flat_sorted, float epsilon) {
            auto x_c = x.contiguous();
            const int n_elements = x_c.numel();

            int n = x_flat_sorted.size(0);

            float median_val, q1_val, q3_val;

            int median_idx = n / 2;
            int q1_idx = n / 4;
            int q3_idx = (3 * n) / 4;

            if (n % 2 == 0) {
                median_val = (x_flat_sorted[median_idx - 1].item<float>() + x_flat_sorted[median_idx].item<float>()) * 0.5f;
            } else {
                median_val = x_flat_sorted[median_idx].item<float>();
            }

            if (n % 4 == 0) {
                q1_val = (x_flat_sorted[q1_idx - 1].item<float>() + x_flat_sorted[q1_idx].item<float>()) * 0.5f;
            } else {
                q1_val = x_flat_sorted[q1_idx].item<float>();
            }

            if ((3 * n) % 4 == 0) {
                q3_val = (x_flat_sorted[q3_idx - 1].item<float>() + x_flat_sorted[q3_idx].item<float>()) * 0.5f;
            } else {
                q3_val = x_flat_sorted[q3_idx].item<float>();
            }

            float iqr = q3_val - q1_val;
            float iqr_recip = 1.0f / (iqr + epsilon);

            auto output = torch::empty_like(x_c);

            const int threads = 256;
            const int blocks = min((n_elements + threads - 1) / threads, 65535);

            rsg_apply_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements,
                median_val,
                iqr_recip
            );

            return output;
        }
        """

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

    def forward(self, x):
        x_flat = x.flatten()
        x_flat_sorted = x_flat.sort()[0]

        return self.op.rsg_apply_cuda(x, x_flat_sorted, self.epsilon)