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

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

        __device__ __forceinline__ float logsigmoid_op(float x) {
            if (x > 0.0f) {
                return -log1pf(expf(-x));
            } else {
                return x - log1pf(expf(x));
            }
        }

        __global__ void logsigmoid_kernel_vec4(
            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 = logsigmoid_op(v.x);
                out.y = logsigmoid_op(v.y);
                out.z = logsigmoid_op(v.z);
                out.w = logsigmoid_op(v.w);

                y_vec[i] = out;
            }

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

        torch::Tensor logsigmoid_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;

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

            return output;
        }
        """

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

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