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 serf_cuda(torch::Tensor x);
        """

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

        __device__ __forceinline__ float serf_op(float x) {
            return x * erff(logf(1.0f + expf(x))); 
        }

        __global__ void serf_tiled_kernel(
            const float* __restrict__ x,
            float* __restrict__ output,
            const int n_elements) 
        {
            const int block_start = blockIdx.x * blockDim.x;
            const int block_end = min(block_start + blockDim.x, n_elements);

            for (int i = block_start + threadIdx.x; i < block_end; i += blockDim.x) {
                output[i] = serf_op(x[i]);
            }
        }

        torch::Tensor serf_cuda(torch::Tensor x) {
            auto x_c = x.contiguous();
            const int n_elements = x_c.numel();
            auto output = torch::empty_like(x_c);

            const int threads = 256;
            const int max_blocks = 65535;
            const int blocks = std::min((n_elements + threads - 1) / threads, max_blocks);

            serf_tiled_kernel<<<blocks, threads>>>(
                x_c.data_ptr<float>(),
                output.data_ptr<float>(),
                n_elements
            );

            return output;
        }
        """

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

    def forward(self, x):
        return self.op.serf_cuda(x)
