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


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor double_glu_cuda(torch::Tensor input);
        """

        cuda_source = """
        #include <cuda_runtime.h>

        __device__ __forceinline__ float sigmoid_f(float x) {
            return 1.0f / (1.0f + expf(-x));
        }

        __global__ void double_glu_vec4_kernel(
            const float4* __restrict__ x,
            float4* __restrict__ y,
            int chunk_vec_dim, 
            int total_chunk_vecs) 
        {
            int idx = blockIdx.x * blockDim.x + threadIdx.x;
            int stride = gridDim.x * blockDim.x;

            for (int i = idx; i < total_chunk_vecs; i += stride) {
                int row = i / chunk_vec_dim;
                int col = i % chunk_vec_dim;

                // Input width = 4 * chunk
                // Output width = 2 * chunk

                int row_offset_in = row * 4 * chunk_vec_dim;
                int row_offset_out = row * 2 * chunk_vec_dim;

                // Process Pair 1 (G1, X1)
                int g1_idx = row_offset_in + col;
                int x1_idx = row_offset_in + chunk_vec_dim + col;

                float4 g1 = x[g1_idx];
                float4 x1 = x[x1_idx];
                float4 out1;

                out1.x = sigmoid_f(g1.x) * x1.x;
                out1.y = sigmoid_f(g1.y) * x1.y;
                out1.z = sigmoid_f(g1.z) * x1.z;
                out1.w = sigmoid_f(g1.w) * x1.w;

                y[row_offset_out + col] = out1;

                // Process Pair 2 (G2, X2)
                int g2_idx = row_offset_in + 2 * chunk_vec_dim + col;
                int x2_idx = row_offset_in + 3 * chunk_vec_dim + col;

                float4 g2 = x[g2_idx];
                float4 x2 = x[x2_idx];
                float4 out2;

                out2.x = sigmoid_f(g2.x) * x2.x;
                out2.y = sigmoid_f(g2.y) * x2.y;
                out2.z = sigmoid_f(g2.z) * x2.z;
                out2.w = sigmoid_f(g2.w) * x2.w;

                y[row_offset_out + chunk_vec_dim + col] = out2;
            }
        }

        torch::Tensor double_glu_cuda(torch::Tensor input) {
            auto x_c = input.contiguous();

            int last_dim = x_c.size(-1);
            TORCH_CHECK(last_dim % 16 == 0, "Feature dim must be divisible by 16 (4 chunks * float4) for optimization");

            auto out_sizes = x_c.sizes().vec();
            out_sizes.back() /= 2;
            auto output = torch::empty(out_sizes, x_c.options());

            int chunk_dim = last_dim / 4;
            int chunk_vec_dim = chunk_dim / 4;

            int batch_size = x_c.numel() / last_dim;
            int total_chunk_vecs = batch_size * chunk_vec_dim;

            int threads = 256;
            int blocks = (total_chunk_vecs + threads - 1) / threads;
            if (blocks > 65535) blocks = 65535;
            if (blocks == 0) blocks = 1;

            double_glu_vec4_kernel<<<blocks, threads>>>(
                reinterpret_cast<const float4*>(x_c.data_ptr<float>()),
                reinterpret_cast<float4*>(output.data_ptr<float>()),
                chunk_vec_dim,
                total_chunk_vecs
            );

            return output;
        }
        """

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

    def forward(self, x):
        return self.op.double_glu_cuda(x)