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()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor hardmish_cuda(torch::Tensor x);
        """

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

        __global__ void hardmish_kernel_opt(
            const float* __restrict__ x,
            float* __restrict__ y,
            int n) 
        {
            int tid = blockIdx.x * blockDim.x + threadIdx.x;
            int stride = blockDim.x * gridDim.x;

            int vec_n = n / 4;

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

            int i = tid;

            for (; i < vec_n - 1; i += stride) {
                float4 v1 = x_vec[i];
                float4 v2 = x_vec[i + 1]; 

                float4 o1, o2;

                float t1_x = fminf(2.0f, fmaxf(0.0f, v1.x + 2.0f));
                float t1_y = fminf(2.0f, fmaxf(0.0f, v1.y + 2.0f));
                float t1_z = fminf(2.0f, fmaxf(0.0f, v1.z + 2.0f));
                float t1_w = fminf(2.0f, fmaxf(0.0f, v1.w + 2.0f));

                o1.x = 0.5f * v1.x * t1_x;
                o1.y = 0.5f * v1.y * t1_y;
                o1.z = 0.5f * v1.z * t1_z;
                o1.w = 0.5f * v1.w * t1_w;

                float t2_x = fminf(2.0f, fmaxf(0.0f, v2.x + 2.0f));
                float t2_y = fminf(2.0f, fmaxf(0.0f, v2.y + 2.0f));
                float t2_z = fminf(2.0f, fmaxf(0.0f, v2.z + 2.0f));
                float t2_w = fminf(2.0f, fmaxf(0.0f, v2.w + 2.0f));

                o2.x = 0.5f * v2.x * t2_x;
                o2.y = 0.5f * v2.y * t2_y;
                o2.z = 0.5f * v2.z * t2_z;
                o2.w = 0.5f * v2.w * t2_w;

                y_vec[i] = o1;
                y_vec[i + 1] = o2;

                i++; 
            }

            for (; i < vec_n; i += stride) {
                float4 v = x_vec[i];
                float4 o;

                float t_x = fminf(2.0f, fmaxf(0.0f, v.x + 2.0f));
                float t_y = fminf(2.0f, fmaxf(0.0f, v.y + 2.0f));
                float t_z = fminf(2.0f, fmaxf(0.0f, v.z + 2.0f));
                float t_w = fminf(2.0f, fmaxf(0.0f, v.w + 2.0f));

                o.x = 0.5f * v.x * t_x;
                o.y = 0.5f * v.y * t_y;
                o.z = 0.5f * v.z * t_z;
                o.w = 0.5f * v.w * t_w;

                y_vec[i] = o;
            }

            int tail_start = vec_n * 4;
            for (int j = tail_start + tid; j < n; j += stride) {
                float v = x[j];
                float t = fminf(2.0f, fmaxf(0.0f, v + 2.0f));
                y[j] = 0.5f * v * t;
            }
        }

        torch::Tensor hardmish_cuda(torch::Tensor x) {
            auto x_c = x.contiguous();
            auto output = torch::empty_like(x_c);

            int total_elements = x_c.numel();
            int threads = 256;

            int vec_elements = total_elements / 4;
            int blocks = (vec_elements + threads - 1) / threads;

            if (blocks > 65535) blocks = 65535;
            if (blocks == 0) blocks = 1;

            hardmish_kernel_opt<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                total_elements
            );

            return output;
        }
        """

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

    def forward(self, x):
        return self.op.hardmish_cuda(x)