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


class ModelNew(nn.Module):
    def __init__(self, min_val=-1.0, max_val=1.0):
        super().__init__()
        self.min_val = min_val
        self.max_val = max_val
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor hardtanh_cuda(torch::Tensor x, float min_val, float max_val);
        """

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

        __global__ void hardtanh_kernel_vec4(
            const float* __restrict__ x,
            float* __restrict__ y,
            int n,
            float min_val,
            float max_val) 
        {
            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 = fminf(fmaxf(v.x, min_val), max_val);
                out.y = fminf(fmaxf(v.y, min_val), max_val);
                out.z = fminf(fmaxf(v.z, min_val), max_val);
                out.w = fminf(fmaxf(v.w, min_val), max_val);

                y_vec[i] = out;
            }

            int tail = vec_n * 4;
            for (int i = tail + idx; i < n; i += stride) {
                y[i] = fminf(fmaxf(x[i], min_val), max_val);
            }
        }

        torch::Tensor hardtanh_cuda(torch::Tensor x, float min_val, float max_val) {
            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;

            hardtanh_kernel_vec4<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n,
                min_val,
                max_val
            );

            return output;
        }
        """

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

    def forward(self, x):
        return self.op.hardtanh_cuda(x, self.min_val, self.max_val)