import torch
from torch.utils.cpp_extension import load_inline

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

// 多线程版本 - 每个样本由多个线程并行处理
__global__ void chebyshev_kernel(
    const float* __restrict__ x,
    const float* __restrict__ y,
    float* __restrict__ distances,
    int batch_size,
    int feature_dim
) {
    // 每个block处理一个样本
    int sample_idx = blockIdx.x;
    if (sample_idx >= batch_size) return;
    
    int tid = threadIdx.x;
    int base = sample_idx * feature_dim;
    
    // 使用共享内存进行归约
    extern __shared__ float shared_max[];
    shared_max[tid] = 0.0f;
    
    // 每个线程处理多个元素
    int stride = blockDim.x;
    for (int dim = tid; dim < feature_dim; dim += stride) {
        float diff = x[base + dim] - y[base + dim];
        float abs_diff = fabsf(diff);
        if (abs_diff > shared_max[tid]) {
            shared_max[tid] = abs_diff;
        }
    }
    
    __syncthreads();
    
    // 块内归约找最大值
    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            if (shared_max[tid + stride] > shared_max[tid]) {
                shared_max[tid] = shared_max[tid + stride];
            }
        }
        __syncthreads();
    }
    
    // 第一个线程写入结果
    if (tid == 0) {
        distances[sample_idx] = shared_max[0];
    }
}

torch::Tensor chebyshev_cuda(torch::Tensor x, torch::Tensor y) {
    TORCH_CHECK(x.scalar_type() == torch::kFloat32, "X must be float32");
    TORCH_CHECK(y.scalar_type() == torch::kFloat32, "Y must be float32");
    
    auto x_contig = x.contiguous();
    auto y_contig = y.contiguous();
    
    int batch_size = x_contig.size(0);
    int feature_dim = x_contig.size(1);
    
    auto distances = torch::zeros({batch_size}, x.options());
    
    const int block_size = 256;
    size_t shared_mem = block_size * sizeof(float);
    
    chebyshev_kernel<<<batch_size, block_size, shared_mem>>>(
        x_contig.data_ptr<float>(),
        y_contig.data_ptr<float>(),
        distances.data_ptr<float>(),
        batch_size,
        feature_dim
    );
    
    return distances;
}
"""

chebyshev_cpp_source = """
torch::Tensor chebyshev_cuda(torch::Tensor x, torch::Tensor y);
"""

# Compile the inline CUDA code
chebyshev = load_inline(
    name="chebyshev",
    cpp_sources=chebyshev_cpp_source,
    cuda_sources=chebyshev_source,
    functions=["chebyshev_cuda"],
    verbose=True
)

class ModelNew(torch.nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.chebyshev = chebyshev  # The module containing the kernel

    def forward(self, x, y):
        return self.chebyshev.chebyshev_cuda(x, y)
