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

cpp_source = "torch::Tensor finite_difference_cuda(torch::Tensor input);"

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

__global__ void finite_difference_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    int total_vectors,
    int numel
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;

    const float4* in_ptr = reinterpret_cast<const float4*>(input);
    float4* out_ptr = reinterpret_cast<float4*>(output);
    const float* raw_in_ptr = input;
    
    for (int i = idx; i < total_vectors; i += stride) {
        float4 current_vec = in_ptr[i];
        float4 result_vec;
    
        float prev_scalar;
        int prev_idx = i * 4 - 1;
        
        if (i == 0) {
   
            prev_scalar = 0.0f;
        } else {
       
            prev_scalar = raw_in_ptr[prev_idx];
        }


        
        result_vec.x = current_vec.x - prev_scalar;
        result_vec.y = current_vec.y - current_vec.x;
        result_vec.z = current_vec.z - current_vec.y;
        result_vec.w = current_vec.w - current_vec.z;
        
        out_ptr[i] = result_vec;
    }
}

torch::Tensor finite_difference_cuda(torch::Tensor input) {
    int numel = input.numel();
    input = input.contiguous();
    auto output = torch::empty_like(input);

    if (numel % 4 != 0) {

    }

    int total_vectors = numel / 4;
    const int block_size = 256;
    int grid_size = (total_vectors + block_size - 1) / block_size;
    

    if (grid_size > 4096) grid_size = 4096; 

    finite_difference_kernel<<<grid_size, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        total_vectors,
        numel
    );

    return output;
}
"""

class ModelNew(nn.Module):
    def __init__(self, dim=-1):
        super().__init__()
        self.module = load_inline(
            name="finite_difference_opt_v1",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["finite_difference_cuda"],
            verbose=False,
            extra_cuda_cflags=["-O3"]
        )

    def forward(self, x):
        return self.module.finite_difference_cuda(x)