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

N, C, H, W = 32, 64, 56, 56
EPS = 1e-6

assert (C * H * W) % 4 == 0, "Instance size (C*H*W) must be a multiple of 4"


class ModelNew(nn.Module):
    def __init__(self, p=3.0):
        super().__init__()
        self.p = float(p)
        self.eps = EPS
        self.blocks_per_instance = 16
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        #include <torch/extension.h>
        void minkowski_sum_cuda(
            torch::Tensor x,
            torch::Tensor y,
            torch::Tensor out,
            float p,
            int N,
            int D,
            int blocks_per_instance);
        """

        cuda_source = """
        #include <cuda_runtime.h>
        #include <cmath>
        #define WARP_SIZE 32

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

        __inline__ __device__ float block_reduce_sum(float val) {
            __shared__ float shared[32];
            int lane = threadIdx.x % WARP_SIZE;
            int wid = threadIdx.x / WARP_SIZE;

            val = warp_reduce_sum(val);
            if (lane == 0) shared[wid] = val;
            __syncthreads();

            val = (threadIdx.x < blockDim.x / WARP_SIZE) ? shared[lane] : 0.0f;
            if (wid == 0) val = warp_reduce_sum(val);
            return val;
        }

        __global__ void minkowski_sum_kernel(
            const float* __restrict__ x,
            const float* __restrict__ y,
            float* __restrict__ out,
            float p,
            int N,
            int D_vec
        ) {
            int n_idx = blockIdx.x;
            int stride = blockDim.x * gridDim.y;
            int d_start = blockIdx.y * blockDim.x + threadIdx.x;
            int offset_base = n_idx * D_vec * 4;

            const float4* x4_ptr = reinterpret_cast<const float4*>(x + offset_base);
            const float4* y4_ptr = reinterpret_cast<const float4*>(y + offset_base);

            float local_sum = 0.0f;

            for (int i = d_start; i < D_vec; i += stride) {
                float4 vx = x4_ptr[i];
                float4 vy = y4_ptr[i];

                local_sum += powf(fabsf(vx.x - vy.x), p);
                local_sum += powf(fabsf(vx.y - vy.y), p);
                local_sum += powf(fabsf(vx.z - vy.z), p);
                local_sum += powf(fabsf(vx.w - vy.w), p);
            }

            float block_sum = block_reduce_sum(local_sum);

            if (threadIdx.x == 0) {
                atomicAdd(&out[n_idx], block_sum);
            }
        }

        void minkowski_sum_cuda(
            torch::Tensor x,
            torch::Tensor y,
            torch::Tensor out,
            float p,
            int N,
            int D,
            int blocks_per_instance) 
        {
            dim3 blocks(N, blocks_per_instance);
            dim3 threads(256);
            int D_vec = D / 4;

            minkowski_sum_kernel<<<blocks, threads>>>(
                x.data_ptr<float>(),
                y.data_ptr<float>(),
                out.data_ptr<float>(),
                p,
                N,
                D_vec
            );
        }
        """

        self.op = load_inline(
            name='minkowski_cuda_opt_v2',
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=['minkowski_sum_cuda'],
            extra_cuda_cflags=['-O3', '--use_fast_math'],
            verbose=False
        )

    def forward(self, x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
        if not x.is_cuda: x = x.cuda()
        if not y.is_cuda: y = y.cuda()

        x = x.contiguous()
        y = y.contiguous()

        N, C, H, W = x.size()
        D = C * H * W

        out = torch.zeros(N, device=x.device, dtype=x.dtype)

        self.op.minkowski_sum_cuda(
            x,
            y,
            out,
            self.p,
            N,
            D,
            self.blocks_per_instance
        )

        return torch.pow(out + self.eps, 1.0 / self.p)