import torch
from torch.utils.cpp_extension import load_inline

cpp_source = """
#include <torch/extension.h>

torch::Tensor logish_cuda_forward(const torch::Tensor& input);
"""

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

struct __align__(16) Float4 {
    float x, y, z, w;
};

__device__ __forceinline__ float logish_op(float x) {
    // f(x) = x * log(1 + sigmoid(x))
    // sigmoid(x) = 1 / (1 + exp(-x))
    float s = 1.0f / (1.0f + expf(-x));
    return x * logf(1.0f + s);
}

__global__ void logish_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const int n_elements) 
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;

    int vec_loops = n_elements / 4;
    const Float4* vec_input = reinterpret_cast<const Float4*>(input);
    Float4* vec_output = reinterpret_cast<Float4*>(output);

    for (int i = idx; i < vec_loops; i += stride) {
        Float4 in_val = vec_input[i];
        Float4 out_val;
        
        out_val.x = logish_op(in_val.x);
        out_val.y = logish_op(in_val.y);
        out_val.z = logish_op(in_val.z);
        out_val.w = logish_op(in_val.w);
        
        vec_output[i] = out_val;
    }

    // 处理尾部剩余的元素
    int tail_start = vec_loops * 4;
    for (int i = tail_start + idx; i < n_elements; i += stride) {
        output[i] = logish_op(input[i]);
    }
}

// C++ Wrapper
torch::Tensor logish_cuda_forward(const torch::Tensor& input) {
    TORCH_CHECK(input.is_cuda(), "Input tensor must be a CUDA tensor");
    TORCH_CHECK(input.is_contiguous(), "Input tensor must be contiguous");

    auto output = torch::empty_like(input);
    const int n_elements = input.numel();

    const int block_size = 256;

    int grid_size = (n_elements + block_size * 4 - 1) / (block_size * 4);
    
    // 限制 Grid 大小以防止过度占用
    if (grid_size > 65535) grid_size = 65535;

    logish_kernel<<<grid_size, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        n_elements
    );

    return output;
}
"""

class ModelNew(torch.nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        # 即时编译 CUDA 代码
        self.op = load_inline(
            name='logish_op',
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=['logish_cuda_forward'],
            verbose=False,
            extra_cuda_cflags=['-O3']
        )

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.op.logish_cuda_forward(x)