import torch
import torch.nn as nn
from torch.utils.cpp_extension import load_inline
 
cpp_source = """
#include <torch/extension.h>

torch::Tensor conj_physical_cuda_forward(const torch::Tensor& input);
"""

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

struct __align__(16) Float4 {
    float x, y, z, w; // R1, I1, R2, I2
};

struct __align__(8) Float2 {
    float x, y; // R, I
};

// Core logic: z = x + iy -> z* = x - iy
// We manipulate raw floats to avoid complex class overhead
__global__ void conj_physical_kernel(
    const float* __restrict__ input, 
    float* __restrict__ output,
    const int n_complex_elements) 
{
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    int stride = blockDim.x * gridDim.x;
    
    int vec_loops = n_complex_elements / 2;

    const Float4* vec_input = reinterpret_cast<const Float4*>(input);
    Float4* vec_output = reinterpret_cast<Float4*>(output);

    for (int i = idx; i < vec_loops; i += stride) {
        Float4 val = vec_input[i];
        
        // Logical layout: x=Real1, y=Imag1, z=Real2, w=Imag2
        // Operation: Negate Imag parts
        val.y = -val.y;
        val.w = -val.w;
        
        vec_output[i] = val;
    }

    // Only happens if n_complex_elements is odd
    int tail_idx = vec_loops * 2; 
    
    // We switch to Float2 pointer to access single complex elements
    const Float2* scalar_input = reinterpret_cast<const Float2*>(input);
    Float2* scalar_output = reinterpret_cast<Float2*>(output);
    
    // Standard grid stride logic applied to the tail part
    // Though usually this loop runs at most once per thread if aligned
    for (int i = tail_idx + idx; i < n_complex_elements; i += stride) {
        Float2 val = scalar_input[i];
        val.y = -val.y; // Negate Imag
        scalar_output[i] = val;
    }
}

torch::Tensor conj_physical_cuda_forward(const torch::Tensor& input) {
    TORCH_CHECK(input.is_cuda(), "Input must be a CUDA tensor");
    TORCH_CHECK(input.is_contiguous(), "Input must be contiguous");
    TORCH_CHECK(input.scalar_type() == torch::kComplexFloat, "Input must be ComplexFloat (complex64)");

    int n_elements = input.numel();
    auto output = torch::empty_like(input);

    const int block_size = 256;
    // Each thread handles 2 elements ideally
    int num_vectors = (n_elements + 1) / 2; 
    int grid_size = (num_vectors + block_size - 1) / block_size;
    if (grid_size > 65535) grid_size = 65535;

    conj_physical_kernel<<<grid_size, block_size>>>(
        reinterpret_cast<float*>(input.data_ptr<c10::complex<float>>()),
        reinterpret_cast<float*>(output.data_ptr<c10::complex<float>>()),
        n_elements
    );

    return output;
}
"""

conj_op = load_inline(
    name='conj_physical_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['conj_physical_cuda_forward'],
    verbose=False,
    extra_cuda_cflags=['-O3']
)

class ConjNew(nn.Module):
    def __init__(self):
        super(ConjNew, self).__init__()

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return conj_op.conj_physical_cuda_forward(x)

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

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.act(x)