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

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

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

// 计算 LiSHT: x * tanh(x)
__device__ __forceinline__ float lisht_op(float x) {
    return x * tanhf(x);
}

// CUDA Kernel: LiSHT Activation
__global__ void lisht_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;

    // 1. 向量化处理循环 (每次处理 4 个 float)
    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 = lisht_op(in_val.x);
        out_val.y = lisht_op(in_val.y);
        out_val.z = lisht_op(in_val.z);
        out_val.w = lisht_op(in_val.w);
        
        vec_output[i] = out_val;
    }

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

torch::Tensor lisht_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);
    
    if (grid_size > 65535) grid_size = 65535;
    
    lisht_kernel<<<grid_size, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        n_elements
    );

    return output;
}
"""

# 编译 CUDA 扩展
lisht_op = load_inline(
    name='lisht_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['lisht_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3', '--use_fast_math']
)

class LiSHTNew(nn.Module):
    def __init__(self):
        super(LiSHTNew, self).__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return lisht_op.lisht_cuda_forward(x)

class ModelNew(nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.lisht = LiSHTNew()

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