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 complex_abs_angle_polar_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;
        int output_offset = idx * 2;

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

        // 1. Magnitude (Abs): R = hypot(X, Y)
        float R = hypotf(X, Y);

        // 2. Angle (Argument): Theta = atan2(Y, X)
        float Theta = atan2f(Y, X);

        // 3. Polar Conversion (Output [R, Theta])
        output[output_offset] = R;
        output[output_offset + 1] = Theta;
    }
}

torch::Tensor complex_abs_angle_polar_cuda(torch::Tensor input) {
    auto output = torch::empty_like(input);
    int N = input.size(0);

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

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

    return output;
}
"""

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

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


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

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