import torch
from torch.utils.cpp_extension import load_inline

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

// 向量化版本 - 最佳性能方案
__global__ void squared_euclidean_kernel_vectorized(
    const float* __restrict__ x,
    const float* __restrict__ y,
    float* __restrict__ distances,
    int batch_size,
    int feature_dim
) {
    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_sum[];
    shared_sum[tid] = 0.0f;
    
    // 每个线程处理4个元素（float4向量化）
    int stride = blockDim.x * 4;
    for (int dim = tid * 4; dim < feature_dim; dim += stride) {
        // 确保不越界
        if (dim + 3 < feature_dim) {
            float4 x_val = *reinterpret_cast<const float4*>(&x[base + dim]);
            float4 y_val = *reinterpret_cast<const float4*>(&y[base + dim]);
            
            // 处理4个分量 - Squared Euclidean Distance计算
            float diff1 = x_val.x - y_val.x;
            shared_sum[tid] += diff1 * diff1;
            
            float diff2 = x_val.y - y_val.y;
            shared_sum[tid] += diff2 * diff2;
            
            float diff3 = x_val.z - y_val.z;
            shared_sum[tid] += diff3 * diff3;
            
            float diff4 = x_val.w - y_val.w;
            shared_sum[tid] += diff4 * diff4;
        } else {
            // 处理剩余元素
            for (int i = dim; i < feature_dim; i++) {
                float diff = x[base + i] - y[base + i];
                shared_sum[tid] += diff * diff;
            }
        }
    }
    
    __syncthreads();
    
    // 块内归约求和
    for (int stride = blockDim.x / 2; stride > 0; stride >>= 1) {
        if (tid < stride) {
            shared_sum[tid] += shared_sum[tid + stride];
        }
        __syncthreads();
    }
    
    // 第一个线程写入结果
    if (tid == 0) {
        distances[sample_idx] = shared_sum[0];
    }
}

torch::Tensor squared_euclidean_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 = 64;
    size_t shared_mem = block_size * sizeof(float);
    
    squared_euclidean_kernel_vectorized<<<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;
}
"""

squared_euclidean_cpp_source = """
torch::Tensor squared_euclidean_cuda(torch::Tensor x, torch::Tensor y);
"""

# Compile the inline CUDA code
squared_euclidean = load_inline(
    name="squared_euclidean",
    cpp_sources=squared_euclidean_cpp_source,
    cuda_sources=squared_euclidean_source,
    functions=["squared_euclidean_cuda"],
    extra_cuda_cflags=[
        "-O3", 
        "--use_fast_math",
        "-gencode=arch=compute_80,code=sm_80"
    ],
    verbose=True
)

class ModelNew(torch.nn.Module):
    def __init__(self):
        super(ModelNew, self).__init__()
        self.squared_euclidean = squared_euclidean

    def forward(self, x, y):
        return self.squared_euclidean.squared_euclidean_cuda(x, y)
