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

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

__inline__ __device__ float warp_reduce(float val) {
    for (int offset = 16; offset > 0; offset /= 2)
        val += __shfl_down_sync(0xffffffff, val, offset);
    return val;
}

__global__ void hamming_xor_and_kernel(
    const float* __restrict__ x, 
    const float* __restrict__ target, 
    float* __restrict__ y, 
    int batch_size, 
    int width) 
{
    int row = blockIdx.x;
    int tid = threadIdx.x;

    if (row >= batch_size) return;

    const float* row_x = x + row * width;

    float sum_val = 0.0f;

    for (int i = tid; i < width; i += blockDim.x) {
        float val_x = row_x[i];
        float val_t = target[i];

        float xor_val = fabsf(val_x - val_t);

        float and_val = xor_val * val_t;

        sum_val += and_val;
    }

    sum_val = warp_reduce(sum_val);

    static __shared__ float shared_mem[32];
    int lane = tid % 32;
    int wid = tid / 32;

    if (lane == 0) shared_mem[wid] = sum_val;
    __syncthreads();

    sum_val = (tid < blockDim.x / 32) ? shared_mem[lane] : 0.0f;
    if (wid == 0) sum_val = warp_reduce(sum_val);

    if (tid == 0) {
        y[row] = sum_val;
    }
}

torch::Tensor launch_hamming_xor_and(torch::Tensor x, torch::Tensor target) {
    auto batch_size = x.size(0);
    auto width = x.size(1);
    auto y = torch::empty({batch_size}, x.options());

    const int threads = 256;
    const int blocks = batch_size;

    hamming_xor_and_kernel<<<blocks, threads>>>(
        x.data_ptr<float>(), 
        target.data_ptr<float>(), 
        y.data_ptr<float>(), 
        batch_size, 
        width
    );
    return y;
}
"""

cpp_source = """
torch::Tensor launch_hamming_xor_and(torch::Tensor x, torch::Tensor target);
"""

hamming_xor_and_module = load_inline(
    name='hamming_xor_and_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['launch_hamming_xor_and'],
    verbose=False
)


class ModelNew(nn.Module):
    def __init__(self, target):
        super(ModelNew, self).__init__()
        self.target = nn.Parameter(target)
        self.op = hamming_xor_and_module

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.op.launch_hamming_xor_and(x.contiguous(), self.target.contiguous())