import torch
from torch.utils.cpp_extension import load_inline

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

// Warp优化版本：精度与性能的完美平衡
__global__ void weighted_sum_warp_kernel(
    const float* __restrict__ values,
    const float* __restrict__ weights,
    float* __restrict__ results,
    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;
    
    float sum = 0.0f;
    
    // 高效的warp级处理
    for (int i = tid; i < feature_dim; i += 32) {  // warp大小为32
        sum += values[base + i] * weights[base + i];
    }
    
    // Warp级归约
    for (int offset = 16; offset > 0; offset /= 2) {
        sum += __shfl_down_sync(0xffffffff, sum, offset);
    }
    
    if (tid == 0) {
        results[sample_idx] = sum;
    }
}

torch::Tensor weighted_sum_cuda(
    torch::Tensor values,
    torch::Tensor weights
) {
    auto values_contig = values.contiguous();
    auto weights_contig = weights.contiguous();
    
    int batch_size = values_contig.size(0);
    int feature_dim = values_contig.size(1);
    
    auto results = torch::zeros({batch_size}, values.options());
    
    // Warp优化：最佳平衡点
    const int block_size = 32;  // warp大小
    
    weighted_sum_warp_kernel<<<batch_size, block_size>>>(
        values_contig.data_ptr<float>(),
        weights_contig.data_ptr<float>(),
        results.data_ptr<float>(),
        batch_size,
        feature_dim
    );
    
    return results;
}
"""

weighted_sum_cpp_source = """
torch::Tensor weighted_sum_cuda(torch::Tensor values, torch::Tensor weights);
"""

# 编译CUDA代码
weighted_sum = load_inline(
    name="weighted_sum",
    cpp_sources=weighted_sum_cpp_source,
    cuda_sources=weighted_sum_source,
    functions=["weighted_sum_cuda"],
    extra_cuda_cflags=[
        "-O3", 
        "--use_fast_math",
        "-std=c++17"
    ],
    verbose=True
)

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

    def forward(self, values, weights):
        return self.weighted_sum.weighted_sum_cuda(values, weights)
