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

cpp_source = """
#include <torch/extension.h>

torch::Tensor fake_quantize_cuda_forward(
    const torch::Tensor& input, 
    const torch::Tensor& scale, 
    const torch::Tensor& zero_point, 
    int64_t quant_min, 
    int64_t quant_max);
"""

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

struct __align__(16) Float4 {
    float x, y, z, w;
};

// Core logic based on user request:
// q = clamp(round(x / s) + z, qmin, qmax)
// out = (q - z) * s
__device__ __forceinline__ float fake_quant_op(
    float x, float s, int z, int qmin, int qmax) 
{
    // 1. Division
    float val = x / s;
    
    // 2. Rounding (rintf rounds to nearest integer, ties to even)
    // Formula correction: round(x/s) then add z
    val = rintf(val);
    
    // 3. Add Zero Point
    val += (float)z;
    
    // 4. Clamp
    val = fmaxf(val, (float)qmin);
    val = fminf(val, (float)qmax);
    
    // 5. Dequantize
    return (val - (float)z) * s;
}

__global__ void fake_quantize_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    const float* __restrict__ scale_ptr,
    const int* __restrict__ zero_point_ptr,
    const int qmin,
    const int qmax,
    const int n_elements) 
{
    // Load scalars once per thread/block (cached)
    float s = *scale_ptr;
    int z = *zero_point_ptr;

    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;

    // 1. Vectorized Loop
    int vec_loops = n_elements / 4;
    const Float4* vec_input = reinterpret_cast<const Float4*>(input);
    Float4* vec_output = reinterpret_cast<Float4*>(output);

    for (int i = idx; i < vec_loops; i += stride) {
        Float4 in_val = vec_input[i];
        Float4 out_val;
        
        out_val.x = fake_quant_op(in_val.x, s, z, qmin, qmax);
        out_val.y = fake_quant_op(in_val.y, s, z, qmin, qmax);
        out_val.z = fake_quant_op(in_val.z, s, z, qmin, qmax);
        out_val.w = fake_quant_op(in_val.w, s, z, qmin, qmax);
        
        vec_output[i] = out_val;
    }

    // 2. Tail Loop
    int tail_start = vec_loops * 4;
    for (int i = tail_start + idx; i < n_elements; i += stride) {
        output[i] = fake_quant_op(input[i], s, z, qmin, qmax);
    }
}

torch::Tensor fake_quantize_cuda_forward(
    const torch::Tensor& input, 
    const torch::Tensor& scale, 
    const torch::Tensor& zero_point, 
    int64_t quant_min, 
    int64_t quant_max) 
{
    TORCH_CHECK(input.is_cuda(), "Input must be CUDA");
    TORCH_CHECK(input.is_contiguous(), "Input must be contiguous");
    TORCH_CHECK(scale.is_cuda(), "Scale must be CUDA");
    TORCH_CHECK(zero_point.is_cuda(), "Zero Point must be CUDA");
    
    auto output = torch::empty_like(input);
    int n_elements = input.numel();

    const int block_size = 256;
    int grid_size = (n_elements + block_size * 4 - 1) / (block_size * 4);
    if (grid_size > 65535) grid_size = 65535;

    fake_quantize_kernel<<<grid_size, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        scale.data_ptr<float>(),
        zero_point.data_ptr<int>(),
        (int)quant_min,
        (int)quant_max,
        n_elements
    );

    return output;
}
"""

fake_quant_op = load_inline(
    name='fake_quant_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['fake_quantize_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3', '--use_fast_math']
)

class FakeQuantizeNew(nn.Module):
    def __init__(self, quant_min, quant_max):
        super(FakeQuantizeNew, self).__init__()
        self.quant_min = quant_min
        self.quant_max = quant_max

    def forward(self, x, scale, zero_point):
        return fake_quant_op.fake_quantize_cuda_forward(
            x, scale, zero_point, self.quant_min, self.quant_max
        )

class ModelNew(nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.fq = FakeQuantizeNew(-128, 127)

    def forward(self, x, scale, zero_point):
        return self.fq(x, scale, zero_point)