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


class ModelNew(nn.Module):
    def __init__(self, S=1, a_init=-0.2, b_init=0.4):
        super().__init__()
        self.S = S
        self.alpha = nn.Parameter(torch.full((S,), a_init, dtype=torch.float32))
        self.beta = nn.Parameter(torch.full((S,), b_init, dtype=torch.float32))
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor apl_cuda(torch::Tensor x, torch::Tensor alpha, torch::Tensor beta, int S);
        """

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

        __global__ void apl_kernel(
            const float* __restrict__ x,
            const float* __restrict__ alpha,
            const float* __restrict__ beta,
            float* __restrict__ output,
            const int n_elements,
            const int S) 
        {
            const int tid = blockIdx.x * blockDim.x + threadIdx.x;
            const int stride = blockDim.x * gridDim.x;

            const int vec_loops = n_elements >> 2;
            const float4* x_vec = reinterpret_cast<const float4*>(x);
            float4* out_vec = reinterpret_cast<float4*>(output);

            for (int i = tid; i < vec_loops; i += stride) {
                float4 v = __ldg(&x_vec[i]);
                float4 r = {0.0f, 0.0f, 0.0f, 0.0f};

                
                r.x = fmaxf(0.0f, v.x);
                r.y = fmaxf(0.0f, v.y);
                r.z = fmaxf(0.0f, v.z);
                r.w = fmaxf(0.0f, v.w);

                
                for (int s = 0; s < S; ++s) {
                    float a = alpha[s];
                    float b = beta[s];

                    r.x += a * fmaxf(0.0f, b - v.x);
                    r.y += a * fmaxf(0.0f, b - v.y);
                    r.z += a * fmaxf(0.0f, b - v.z);
                    r.w += a * fmaxf(0.0f, b - v.w);
                }

                out_vec[i] = r;
            }

            const int tail_start = vec_loops << 2;
            for (int i = tail_start + tid; i < n_elements; i += stride) {
                float v = x[i];
                float r = fmaxf(0.0f, v);

                for (int s = 0; s < S; ++s) {
                    r += alpha[s] * fmaxf(0.0f, beta[s] - v);
                }
                output[i] = r;
            }
        }

        torch::Tensor apl_cuda(torch::Tensor x, torch::Tensor alpha, torch::Tensor beta, int S) {
            auto x_c = x.contiguous();
            auto alpha_c = alpha.contiguous();
            auto beta_c = beta.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 * 4 - 1) / (threads * 4), max_blocks);

            apl_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                alpha_c.data_ptr<float>(),
                beta_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements,
                S
            );

            return output;
        }
        """

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

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