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

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

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

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

#define BLOCK_SIZE 256

// double2 for 128-bit vectorization
struct __align__(16) Double2 {
    double x, y;
};

// Gish for double
__device__ __forceinline__ double compute_gish_double(double x) {
    // Clamp for double precision exp
    double clamped_x = fmin(x, 700.0);
    double inner_exp = exp(clamped_x);
    double outer_exp = exp(-inner_exp);
    double log_val = log(2.0 - outer_exp);
    return x * log_val;
}

template <typename T>
__global__ void gish_kernel(
    T* __restrict__ output,
    const T* __restrict__ input,
    const int n) 
{
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    // Vectorization for double is double2
    const int vec_n = n / 2;
    
    int i = idx;
    const int stride = blockDim.x * gridDim.x;

    for (; i < vec_n; i += stride) {
        Double2 in_vec = reinterpret_cast<const Double2*>(input)[i];
        Double2 out_vec;

        out_vec.x = compute_gish_double(in_vec.x);
        out_vec.y = compute_gish_double(in_vec.y);

        reinterpret_cast<Double2*>(output)[i] = out_vec;
    }

    int tail_idx = vec_n * 2 + idx;
    if (idx == 0 && tail_idx < n) {
        output[tail_idx] = compute_gish_double(input[tail_idx]);
    }
}

torch::Tensor gish_cuda_forward(const torch::Tensor& input) {
    TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
    TORCH_CHECK(input.is_contiguous(), "Input must be contiguous");
    
    const int n = input.numel();
    auto output = torch::empty_like(input);

    const int vec_n = n / 2;
    const int grid_size = (vec_n + BLOCK_SIZE - 1) / BLOCK_SIZE;
    
    int final_grid = (grid_size < 1) ? 1 : grid_size;
    if (final_grid > 65535) final_grid = 65535;

    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "gish_kernel", ([&] {
        gish_kernel<scalar_t><<<final_grid, BLOCK_SIZE>>>(
            output.data_ptr<scalar_t>(),
            input.data_ptr<scalar_t>(),
            n
        );
    }));

    return output;
}
"""

gish_op_module = load_inline(
    name='gish_op_double',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['gish_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3']
)

class ModelNew(nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.op = gish_op_module

    def forward(self, input_tensor: torch.Tensor) -> torch.Tensor:
        return self.op.gish_cuda_forward(input_tensor.contiguous())