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>

__global__ void real_imag_hypot_kernel(
    const float* __restrict__ input,
    float* __restrict__ output,
    int N
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < N) {
        int input_offset = idx * 2;

        float X = input[input_offset];     
        float Y = input[input_offset + 1];  

        // Hypotenuse: R = sqrt(X^2 + Y^2)
        output[idx] = hypotf(X, Y);
    }
}

torch::Tensor real_imag_hypot_cuda(torch::Tensor input) {
    int N = input.size(0);

    // Output size is [N], since we reduce the last dim (2) to 1
    auto output = torch::empty({N}, input.options());

    const int block_size = 256;
    int num_blocks = (N + block_size - 1) / block_size;

    real_imag_hypot_kernel<<<num_blocks, block_size>>>(
        input.data_ptr<float>(),
        output.data_ptr<float>(),
        N
    );

    return output;
}
"""

cpp_source = """
torch::Tensor real_imag_hypot_cuda(torch::Tensor input);
"""

module = load_inline(
    name="real_imag_hypot",
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=["real_imag_hypot_cuda"],
    verbose=True
)


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

    def forward(self, x):
        return self.module.real_imag_hypot_cuda(x)