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


class ModelNew(nn.Module):
    def __init__(self, num_features=64, init=0.25):
        super().__init__()
        self.num_features = num_features
        self.weight = nn.Parameter(torch.full((num_features,), init))
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        torch::Tensor prelu_cuda(torch::Tensor x, torch::Tensor w);
        """

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

        __global__ void prelu_channel_vec4(
            const float* __restrict__ x,
            float* __restrict__ y,
            const float* __restrict__ w,
            int total_vecs,
            int spatial_vecs, // spatial_size / 4
            int channels) 
        {
            int idx = blockIdx.x * blockDim.x + threadIdx.x;
            int stride = gridDim.x * blockDim.x;

            const float4* x_vec = reinterpret_cast<const float4*>(x);
            float4* y_vec = reinterpret_cast<float4*>(y);

            for (int i = idx; i < total_vecs; i += stride) {
                float4 v = x_vec[i];
                float4 out;

                int c = (i / spatial_vecs) % channels;
                float slope = w[c];

                out.x = (v.x < 0.0f) ? (v.x * slope) : v.x;
                out.y = (v.y < 0.0f) ? (v.y * slope) : v.y;
                out.z = (v.z < 0.0f) ? (v.z * slope) : v.z;
                out.w = (v.w < 0.0f) ? (v.w * slope) : v.w;

                y_vec[i] = out;
            }
        }

        __global__ void prelu_scalar_kernel(
            const float* __restrict__ x,
            float* __restrict__ y,
            const float* __restrict__ w,
            int total_elements,
            int spatial_size,
            int channels)
        {
            int idx = blockIdx.x * blockDim.x + threadIdx.x;
            int stride = gridDim.x * blockDim.x;

            for (int i = idx; i < total_elements; i += stride) {
                int c = (i / spatial_size) % channels;
                float val = x[i];
                float slope = w[c];
                y[i] = (val < 0.0f) ? (val * slope) : val;
            }
        }

        torch::Tensor prelu_cuda(torch::Tensor x, torch::Tensor w) {
            auto x_c = x.contiguous();
            auto w_c = w.contiguous();

            auto output = torch::empty_like(x_c);

            int N = x_c.size(0);
            int C = x_c.size(1);
            int total_elements = x_c.numel();
            // Spatial size (H*W or L) = Total / (N*C)
            int S = total_elements / (N * C); 

            if (S % 4 == 0) {
                int total_vecs = total_elements / 4;
                int spatial_vecs = S / 4;

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

                prelu_channel_vec4<<<blocks, threads>>>(
                    x_c.data_ptr<float>(),
                    output.data_ptr<float>(),
                    w_c.data_ptr<float>(),
                    total_vecs,
                    spatial_vecs,
                    C
                );
            } else {
                int threads = 256;
                int blocks = (total_elements + threads - 1) / threads;
                if (blocks > 65535) blocks = 65535;

                prelu_scalar_kernel<<<blocks, threads>>>(
                    x_c.data_ptr<float>(),
                    output.data_ptr<float>(),
                    w_c.data_ptr<float>(),
                    total_elements,
                    S,
                    C
                );
            }

            return output;
        }
        """

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

    def forward(self, x):
        return self.op.prelu_cuda(x, self.weight)