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

# C++ 源代码声明
cpp_source = """
#include <torch/extension.h>

torch::Tensor ftswish_cuda_forward(const torch::Tensor& input, float T);
"""

# CUDA 源代码
cuda_source = """
#include <torch/extension.h>
#include <cuda_runtime.h>
#include <math.h>

struct __align__(16) Float4 {
    float x, y, z, w;
};

// 核心计算逻辑 (Device Inline)
// 包含条件分支优化：x < 0 时避免计算 exp
__device__ __forceinline__ float ftswish_op(float x, float T) {
    if (x < 0.0f) {
        return T;
    } else {
        // x >= 0: x * sigmoid(x) + T
        // sigmoid(x) = 1 / (1 + exp(-x))
        // 使用 __expf 加速
        float sig = 1.0f / (1.0f + __expf(-x));
        return x * sig + T;
    }
}

// Kernel
__global__ void ftswish_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const float T,
    const int n_elements) 
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;

    // 1. Vectorized Loop (float4)
    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;
        
        // 分别计算4个分量
        out_val.x = ftswish_op(in_val.x, T);
        out_val.y = ftswish_op(in_val.y, T);
        out_val.z = ftswish_op(in_val.z, T);
        out_val.w = ftswish_op(in_val.w, T);
        
        vec_output[i] = out_val;
    }

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

// Wrapper
torch::Tensor ftswish_cuda_forward(const torch::Tensor& input, float T) {
    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;

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

    return output;
}
"""

# 编译
ftswish_op = load_inline(
    name='ftswish_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['ftswish_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3', '--use_fast_math']
)

class FlattenTSwishNew(nn.Module):
    def __init__(self, T=0.0):
        super(FlattenTSwishNew, self).__init__()
        self.T = T

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return ftswish_op.ftswish_cuda_forward(x, self.T)

class ModelNew(nn.Module):
    def __init__(self, T=0.0):
        super(ModelNew, self).__init__()
        self.act = FlattenTSwishNew(T=T)

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