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 zscore_sigmoid_denormalize_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    float mean,
    float std,
    int size
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        float x = input[idx];

        // 1. Z-Score Normalization
        float y = (x - mean) / std;

        // 2. Sigmoid
        float z = 1.0f / (1.0f + expf(-y));

        // 3. Denormalization (Inverse Z-Score)
        // Use fmaf for better precision/speed: z * std + mean
        output[idx] = fmaf(z, std, mean);
    }
}

torch::Tensor zscore_sigmoid_denormalize_cuda(torch::Tensor input, float mean, float std) {
    auto output = torch::empty_like(input);
    int size = input.numel();

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

    zscore_sigmoid_denormalize_kernel<<<num_blocks, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        mean,
        std,
        size
    );

    return output;
}
"""

cpp_source = """
torch::Tensor zscore_sigmoid_denormalize_cuda(torch::Tensor input, float mean, float std);
"""

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


class ModelNew(nn.Module):
    def __init__(self, mean, std):
        super(ModelNew, self).__init__()
        self.mean = mean
        self.std = std
        self.module = module

    def forward(self, x):
        return self.module.zscore_sigmoid_denormalize_cuda(x, self.mean, self.std)