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


cpp_src = "torch::Tensor bucketize_cuda(torch::Tensor input, torch::Tensor boundaries);"

cuda_src = """
#include <cuda_runtime.h>

extern __shared__ float s_boundaries[];

__device__ int binary_search(const float* data, int n, float val) {
    int left = 0;
    int right = n;

    while (left < right) {
        int mid = left + (right - left) / 2;
        if (data[mid] < val) {
            left = mid + 1;
        } else {
            right = mid;
        }
    }
    return left;
}

__global__ void bucketize_kernel(
    const float* __restrict__ input,
    const float* __restrict__ boundaries,
    long* __restrict__ output, 
    int num_elements,
    int num_boundaries
) {
 
    for (int i = threadIdx.x; i < num_boundaries; i += blockDim.x) {
        s_boundaries[i] = boundaries[i];
    }
    __syncthreads(); 

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

    for (int i = idx; i < num_elements; i += stride) {
        float val = input[i];
        

        int bucket_idx = binary_search(s_boundaries, num_boundaries, val);
        
        output[i] = (long)bucket_idx;
    }
}

torch::Tensor bucketize_cuda(torch::Tensor input, torch::Tensor boundaries) {
    int num_elements = input.numel();
    int num_boundaries = boundaries.numel();
    
    input = input.contiguous();
    boundaries = boundaries.contiguous();

    auto output = torch::empty_like(input, torch::kLong);

    const int block_size = 256;
    int grid_size = (num_elements + block_size - 1) / block_size;

    if (grid_size > 2048) grid_size = 2048;

    int shared_mem_size = num_boundaries * sizeof(float);

    bucketize_kernel<<<grid_size, block_size, shared_mem_size>>>(
        input.data_ptr<float>(),
        boundaries.data_ptr<float>(),
        output.data_ptr<long>(),
        num_elements,
        num_boundaries
    );

    return output;
}
"""

class ModelNew(nn.Module):
    def __init__(self, num_boundaries=128):
        super().__init__()

        self.boundaries = nn.Parameter(
            torch.linspace(0, 100, steps=num_boundaries), 
            requires_grad=False
        )
        
        self.module = load_inline(
            name="bucketize_opt_v1",
            cpp_sources=cpp_src,
            cuda_sources=cuda_src,
            functions=["bucketize_cuda"],
            verbose=False,
            extra_cuda_cflags=["-O3"]
        )

    def forward(self, x):
        return self.module.bucketize_cuda(x, self.boundaries)