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

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

torch::Tensor tanhsoft3_cuda_forward(const torch::Tensor& input, const torch::Tensor& delta);
"""

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;
};

// TanhSoft-3 Logic
__device__ __forceinline__ double compute_tanhsoft3_double(double x, double delta) {
    double clamped_x = fmin(x, 700.0);
    double inner = 1.0 + exp(clamped_x) * tanh(delta * x);
    return log(fmax(inner, 1e-12));
}

template <typename T>
__global__ void tanhsoft3_kernel(
    T* __restrict__ output,
    const T* __restrict__ input,
    const int n,
    T delta) 
{
    const int idx = blockIdx.x * blockDim.x + threadIdx.x;
    const int vec_n = n / 2; // double2
    
    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_tanhsoft3_double(in_vec.x, delta);
        out_vec.y = compute_tanhsoft3_double(in_vec.y, delta);

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

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

torch::Tensor tanhsoft3_cuda_forward(const torch::Tensor& input, const torch::Tensor& delta_t) {
    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 delta = delta_t.item<double>();

    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(), "tanhsoft3_kernel", ([&] {
        tanhsoft3_kernel<scalar_t><<<final_grid, BLOCK_SIZE>>>(
            output.data_ptr<scalar_t>(),
            input.data_ptr<scalar_t>(),
            n,
            static_cast<scalar_t>(delta)
        );
    }));

    return output;
}
"""

tanhsoft3_op_module = load_inline(
    name='tanhsoft3_op_double',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['tanhsoft3_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3']
)

class ModelNew(nn.Module):
    def __init__(self, delta_init=1.0):
        super(ModelNew, self).__init__()
        self.delta = nn.Parameter(torch.tensor(delta_init, dtype=torch.float64))
        self.op = tanhsoft3_op_module

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