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>

__inline__ __device__ float warp_reduce(float val) {
    for (int offset = 16; offset > 0; offset /= 2)
        val += __shfl_down_sync(0xffffffff, val, offset);
    return val;
}

__global__ void dot_mse_tanh_kernel(
    const float* __restrict__ x, 
    const float* __restrict__ target, 
    float* __restrict__ y, 
    int batch_size, 
    int width) 
{
    int row = blockIdx.x;
    int tid = threadIdx.x;

    if (row >= batch_size) return;

    const float* row_x = x + row * width;

    float sum_dot = 0.0f;
    float sum_sq_diff = 0.0f;

    for (int i = tid; i < width; i += blockDim.x) {
        float val_x = row_x[i];
        float val_t = target[i];

        sum_dot += val_x * val_t;

        float diff = val_x - val_t;
        sum_sq_diff += diff * diff;
    }

    sum_dot = warp_reduce(sum_dot);
    sum_sq_diff = warp_reduce(sum_sq_diff);

    static __shared__ float shared_dot[32];
    static __shared__ float shared_sq_diff[32];

    int lane = tid % 32;
    int wid = tid / 32;

    if (lane == 0) {
        shared_dot[wid] = sum_dot;
        shared_sq_diff[wid] = sum_sq_diff;
    }
    __syncthreads();

    sum_dot = (tid < blockDim.x / 32) ? shared_dot[lane] : 0.0f;
    sum_sq_diff = (tid < blockDim.x / 32) ? shared_sq_diff[lane] : 0.0f;

    if (wid == 0) {
        sum_dot = warp_reduce(sum_dot);
        sum_sq_diff = warp_reduce(sum_sq_diff);
    }

    if (tid == 0) {
        float mse = sum_sq_diff / (float)width;
        y[row] = tanhf(sum_dot - mse);
    }
}

torch::Tensor launch_dot_mse_tanh(torch::Tensor x, torch::Tensor target) {
    auto batch_size = x.size(0);
    auto width = x.size(1);
    auto y = torch::empty({batch_size}, x.options());

    const int threads = 256;
    const int blocks = batch_size;

    dot_mse_tanh_kernel<<<blocks, threads>>>(
        x.data_ptr<float>(), 
        target.data_ptr<float>(), 
        y.data_ptr<float>(), 
        batch_size, 
        width
    );
    return y;
}
"""

cpp_source = """
torch::Tensor launch_dot_mse_tanh(torch::Tensor x, torch::Tensor target);
"""

dot_mse_tanh_module = load_inline(
    name='dot_mse_tanh_op',
    cpp_sources=cpp_source,
    cuda_sources=cuda_source,
    functions=['launch_dot_mse_tanh'],
    verbose=False
)


class ModelNew(nn.Module):
    def __init__(self, target):
        super(ModelNew, self).__init__()
        self.target = nn.Parameter(target)
        self.op = dot_mse_tanh_module

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        return self.op.launch_dot_mse_tanh(x.contiguous(), self.target.contiguous())