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

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

torch::Tensor xsilu_cuda_forward(const torch::Tensor& input, double alpha);
"""

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

#define BLOCK_SIZE 256

// Vector type for double precision (128-bit)
struct __align__(16) Double2 {
    double x, y;
};

// xSiLU for double
__device__ __forceinline__ double compute_xsilu_double(double x, double alpha, double scale) {
    // Use standard double precision `exp`
    double sig = 1.0 / (1.0 + exp(-x));
    double gate = sig * scale - alpha;
    return x * gate;
}

template <typename T>
__global__ void xsilu_kernel(
    T* __restrict__ output,
    const T* __restrict__ input,
    const int n,
    T alpha,
    T scale) 
{
    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_xsilu_double(in_vec.x, alpha, scale);
        out_vec.y = compute_xsilu_double(in_vec.y, alpha, scale);

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

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

torch::Tensor xsilu_cuda_forward(const torch::Tensor& input, double alpha) {
    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 double scale = 1.0 + 2.0 * alpha;

    const int vec_n = n / 2; // double2 vectorization
    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 will call the correct template specialization
    AT_DISPATCH_FLOATING_TYPES(input.scalar_type(), "xsilu_kernel", ([&] {
        xsilu_kernel<scalar_t><<<final_grid, BLOCK_SIZE>>>(
            output.data_ptr<scalar_t>(),
            input.data_ptr<scalar_t>(),
            n,
            static_cast<scalar_t>(alpha),
            static_cast<scalar_t>(scale)
        );
    }));

    return output;
}
"""

xsilu_op_module = load_inline(
    name='xsilu_op_double',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['xsilu_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3']
)

class ModelNew(nn.Module):
    def __init__(self, alpha=0.3):
        super(ModelNew, self).__init__()
        self.alpha = alpha
        self.op = xsilu_op_module

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