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

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

        __device__ __forceinline__ float gate_op(float x) {
            // max(0, min(1, (x + 1) / 2))
            return fmaxf(0.0f, fminf(1.0f, x * 0.5f + 0.5f));
        }

        __device__ __forceinline__ float hard_elish_op(float x) {
            float g = gate_op(x);
            if (x >= 0.0f) {
                return x * g;
            } else {
                // (exp(x) - 1) * g
                return (expf(x) - 1.0f) * g;
            }
        }

        __global__ void hard_elish_kernel(
            const float* __restrict__ x,
            float* __restrict__ output,
            const int n_elements) 
        {
            const int block_start = blockIdx.x * blockDim.x;
            const int block_end = min(block_start + blockDim.x, n_elements);

            for (int i = block_start + threadIdx.x; i < block_end; i += blockDim.x) {
                output[i] = hard_elish_op(x[i]);
            }
        }

        torch::Tensor hard_elish_cuda(torch::Tensor x) {
            auto x_c = x.contiguous();
            const int n_elements = x_c.numel();
            auto output = torch::empty_like(x_c);

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

            hard_elish_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements
            );

            return output;
        }
        """

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

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