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>
#include <math.h>

__global__ void robust_scale_huber_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    float center,
    float scale,
    float delta,
    int size
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        float x = input[idx];

        // Robust Standardization: Y = (X - center) / scale
        float y = (x - center) / scale;
        float abs_y = fabsf(y);

        if (abs_y <= delta) {
            // Quadratic: 0.5 * Y^2
            output[idx] = 0.5f * y * y;
        } else {
            // Linear: delta * (|Y| - 0.5 * delta)
            output[idx] = delta * (abs_y - 0.5f * delta);
        }
    }
}

torch::Tensor robust_scale_huber_cuda(torch::Tensor input, float center, float scale, float delta) {
    auto output = torch::empty_like(input);
    int size = input.numel();

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

    robust_scale_huber_kernel<<<num_blocks, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        center,
        scale,
        delta,
        size
    );

    return output;
}
"""

cpp_source = """
torch::Tensor robust_scale_huber_cuda(torch::Tensor input, float center, float scale, float delta);
"""

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


class ModelNew(nn.Module):
    def __init__(self, center, scale, delta):
        super(ModelNew, self).__init__()
        self.center = center
        self.scale = scale
        self.delta = delta
        self.module = module

    def forward(self, x):
        return self.module.robust_scale_huber_cuda(x, self.center, self.scale, self.delta)