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

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

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

#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440f
#endif

// Core Computation (Device Inline)
// f(x) = x * tanh(x * GELU(x))
// GELU(x) = 0.5 * x * (1 + erf(x / sqrt(2)))
__device__ __forceinline__ float phish_op(float x) {
    // 1. Compute GELU(x)
    // using erff (single precision error function)
    float erf_val = erff(x * M_SQRT1_2);
    float gelu_val = 0.5f * x * (1.0f + erf_val);
    
    // 2. Compute Inner: x * GELU(x)
    float inner = x * gelu_val;
    
    // 3. Compute Tanh
    float tanh_val = tanhf(inner);
    
    // 4. Final Result
    return x * tanh_val;
}

__global__ void phish_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. Vectorized Loop
    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 = phish_op(in_val.x);
        out_val.y = phish_op(in_val.y);
        out_val.z = phish_op(in_val.z);
        out_val.w = phish_op(in_val.w);
        
        vec_output[i] = out_val;
    }

    // 2. Scalar Loop
    int tail_start = vec_loops * 4;
    for (int i = tail_start + idx; i < n_elements; i += stride) {
        output[i] = phish_op(input[i]);
    }
}

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

    phish_kernel<<<grid_size, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        n_elements
    );

    return output;
}
"""

phish_op = load_inline(
    name='phish_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['phish_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3']
)

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

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

class ModelNew(nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.act = PhishNew()

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