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>

__global__ void sign_mul_add_kernel(
    const float* __restrict__ a,
    const float* __restrict__ b,
    const float* __restrict__ c,
    float* __restrict__ output,
    int size
) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    if (idx < size) {
        float a_val = a[idx];
        float b_val = b[idx];
        float c_val = c[idx];

        float sign_val;
        if (a_val > 0.0f) {
            sign_val = 1.0f;
        } else if (a_val < 0.0f) {
            sign_val = -1.0f;
        } else {
            sign_val = 0.0f;
        }

        output[idx] = sign_val * b_val + c_val;
    }
}

torch::Tensor sign_mul_add_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c) {
    auto output = torch::empty_like(a);
    int size = a.numel();

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

    sign_mul_add_kernel<<<num_blocks, block_size>>>(
        a.data_ptr<float>(),
        b.data_ptr<float>(),
        c.data_ptr<float>(),
        output.data_ptr<float>(),
        size
    );

    return output;
}
"""

cpp_source = """
torch::Tensor sign_mul_add_cuda(torch::Tensor a, torch::Tensor b, torch::Tensor c);
"""

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


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

    def forward(self, a, b, c):
        return self.module.sign_mul_add_cuda(a, b, c)