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

class ModelNew(nn.Module):
    def __init__(self, alpha: float = 1.0, beta: float = 1.0):
        super().__init__()
        self.alpha = alpha
        self.beta = beta
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor psmish_cuda(torch::Tensor x, float alpha, float beta);
        """

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

        __device__ __forceinline__ double psmish_op_double(double x, double alpha, double beta) {
            double bx = beta * x;
            double gate = tanh(log(1.0 + exp(bx)));
            return alpha * x * gate;
        }

        __global__ void psmish_kernel_double_intermediate(
            const float* __restrict__ x,
            float* __restrict__ output,
            const int n_elements,
            const float alpha,
            const float beta) 
        {
            const int block_start = blockIdx.x * blockDim.x;
            const int block_end = min(block_start + blockDim.x, n_elements);

            double alpha_d = (double)alpha;
            double beta_d = (double)beta;

            for (int i = block_start + threadIdx.x; i < block_end; i += blockDim.x) {
                double val_d = (double)x[i];
                double result_d = psmish_op_double(val_d, alpha_d, beta_d);
                output[i] = (float)result_d;
            }
        }

        torch::Tensor psmish_cuda(torch::Tensor x, float alpha, float beta) {
            auto x_c = x.contiguous();
            const int n_elements = x_c.numel();
            auto output = torch::empty_like(x_c);

            const int threads = 256;
            const int max_blocks = 65535;
            const int blocks = std::min((n_elements + threads - 1) / threads, max_blocks);

            psmish_kernel_double_intermediate<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements,
                alpha,
                beta
            );

            return output;
        }
        """

        self.op = load_inline(
            name="psmish_v3",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["psmish_cuda"],
            extra_cuda_cflags=["-O3"],
            verbose=False
        )

    def forward(self, x):
        return self.op.psmish_cuda(x, self.alpha, self.beta)