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 hardsigmoid_cuda(torch::Tensor x);
        """

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

        __device__ __forceinline__ float hardsigmoid_op(float x) {
            float val = x * 0.16666667f + 0.5f;
            return fminf(fmaxf(val, 0.0f), 1.0f);
        }

        __global__ void hardsigmoid_kernel(
            const float* __restrict__ x,
            float* __restrict__ y,
            int n) 
        {
            int idx = 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);

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

                out.x = hardsigmoid_op(v.x);
                out.y = hardsigmoid_op(v.y);
                out.z = hardsigmoid_op(v.z);
                out.w = hardsigmoid_op(v.w);

                y_vec[i] = out;
            }

            int tail = vec_n * 4;
            for (int i = tail + idx; i < n; i += stride) {
                y[i] = hardsigmoid_op(x[i]);
            }
        }

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

            int n = x_c.numel();
            int threads = 256;
            int blocks = (n / 4 + threads - 1) / threads;
            if (blocks > 65535) blocks = 65535;
            if (blocks == 0) blocks = 1;

            hardsigmoid_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n
            );

            return output;
        }
        """

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

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