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 euclidean_erfc_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_sq = 0.0f;

    for (int i = tid; i < width; i += blockDim.x) {
        float val = row_x[i];
        float t = target[i];
        float diff = val - t;
        sum_sq += diff * diff;
    }

    sum_sq = warp_reduce(sum_sq);

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

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

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

    if (tid == 0) {
        y[row] = erfcf(sqrtf(sum_sq));
    }
}

torch::Tensor launch_euclidean_erfc(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;

    euclidean_erfc_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_euclidean_erfc(torch::Tensor x, torch::Tensor target);
"""

euclidean_erfc_module = load_inline(
    name='euclidean_erfc_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['launch_euclidean_erfc'],
    verbose=False
)


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

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