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


class ModelNew(nn.Module):
    def __init__(self):
        super().__init__()
        self._compile_cuda_kernel()

    def _compile_cuda_kernel(self):
        cpp_source = """
        torch::Tensor value_loss_cuda(torch::Tensor values, torch::Tensor returns);
        """

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

        __global__ void value_loss_kernel(
            const float* __restrict__ values,
            const float* __restrict__ returns,
            float* __restrict__ output,
            int n)
        {
            extern __shared__ float sdata[];
            unsigned int tid = threadIdx.x;
            unsigned int i = blockIdx.x * blockDim.x + threadIdx.x;
            unsigned int gridSize = blockDim.x * gridDim.x;

            float local_sum = 0.0f;

            while (i < n) {
                float diff = values[i] - returns[i];
                local_sum += diff * diff;
                i += gridSize;
            }

            sdata[tid] = local_sum;
            __syncthreads();

            for (unsigned int s = blockDim.x / 2; s > 0; s >>= 1) {
                if (tid < s) {
                    sdata[tid] += sdata[tid + s];
                }
                __syncthreads();
            }

            if (tid == 0) {
                atomicAdd(output, sdata[0] / n);
            }
        }

        torch::Tensor value_loss_cuda(torch::Tensor values, torch::Tensor returns) {
            auto values_c = values.contiguous();
            auto returns_c = returns.contiguous();
            int n = values_c.numel();

            auto output = torch::zeros({1}, values.options());

            const int threads = 256;
            const int blocks = min((n + threads - 1) / threads, 1024);
            const int shared_mem = threads * sizeof(float);

            value_loss_kernel<<<blocks, threads, shared_mem>>>(
                values_c.data_ptr<float>(),
                returns_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n
            );

            return output[0];
        }
        """

        self.op = load_inline(
            name="value_loss_op",
            cpp_sources=cpp_source,
            cuda_sources=cuda_source,
            functions=["value_loss_cuda"],
            extra_cuda_cflags=["-O3"],
            verbose=False
        )

    def forward(self, values, returns):
        return self.op.value_loss_cuda(values, returns)