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

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

__global__ void affine_leaky_clamp_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    float scale,
    float shift,
    float negative_slope,
    float min_val,
    float max_val,
    int size
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        float val = input[idx];

        val = fmaf(val, scale, shift);

        if (val < 0.0f) {
            val = val * negative_slope;
        }

        val = fmaxf(val, min_val);
        val = fminf(val, max_val);

        output[idx] = val;
    }
}

torch::Tensor affine_leaky_clamp_cuda(
    torch::Tensor input,
    float scale,
    float shift,
    float negative_slope,
    float min_val,
    float max_val
) {
    auto output = torch::empty_like(input);
    int size = input.numel();

    const int block_size = 256;
    int num_blocks = (size + block_size - 1) / block_size;

    affine_leaky_clamp_kernel<<<num_blocks, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        scale,
        shift,
        negative_slope,
        min_val,
        max_val,
        size
    );

    return output;
}
"""

cpp_source = """
torch::Tensor affine_leaky_clamp_cuda(
    torch::Tensor input,
    float scale,
    float shift,
    float negative_slope,
    float min_val,
    float max_val
);
"""

module = load_inline(
    name="affine_leaky_clamp",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["affine_leaky_clamp_cuda"],
    verbose=True
)


class ModelNew(nn.Module):
    def __init__(self, scale, shift, negative_slope, min_val, max_val):
        super(ModelNew, self).__init__()
        self.scale = scale
        self.shift = shift
        self.negative_slope = negative_slope
        self.min_val = min_val
        self.max_val = max_val
        self.module = module

    def forward(self, x):
        return self.module.affine_leaky_clamp_cuda(
            x,
            self.scale,
            self.shift,
            self.negative_slope,
            self.min_val,
            self.max_val
        )