import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch.nn import Module
import math
from torch.nn.parameter import Parameter
import torch.nn.functional as F
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_mul_sigmoid_tanh_0(in_ptr0, in_ptr1, out_ptr0, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp2 = tl.load(in_ptr1 + x0, xmask)
    tmp1 = libdevice.tanh(tmp0)
    tmp3 = tl.sigmoid(tmp2)
    tmp4 = tmp1 * tmp3
    tl.store(out_ptr0 + x0, tmp4, xmask)


@triton.jit
def triton_poi_fused_abs_add_log_1(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp1 = tl_math.abs(tmp0)
    tmp2 = 0.001
    tmp3 = tmp1 + tmp2
    tmp4 = tl_math.log(tmp3)
    tl.store(out_ptr0 + x0, tmp4, xmask)


@triton.jit
def triton_poi_fused_add_exp_mul_rsub_sigmoid_2(in_ptr0, in_ptr1, in_ptr2,
    out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 256
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + x0, xmask)
    tmp2 = tl.load(in_ptr1 + x0, xmask)
    tmp6 = tl.load(in_ptr2 + x0, xmask)
    tmp1 = tl.sigmoid(tmp0)
    tmp3 = tmp1 * tmp2
    tmp4 = 1.0
    tmp5 = tmp4 - tmp1
    tmp7 = tl_math.exp(tmp6)
    tmp8 = tmp5 * tmp7
    tmp9 = tmp3 + tmp8
    tl.store(out_ptr0 + x0, tmp9, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5, primals_6 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4, 4), (4, 1))
    assert_size_stride(primals_6, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_mul_sigmoid_tanh_0[grid(16)](primals_1, primals_2,
            buf0, 16, XBLOCK=16, num_warps=1, num_stages=1)
        buf1 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
            reinterpret_tensor(buf0, (4, 4), (1, 4), 0), out=buf1)
        buf2 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused_abs_add_log_1[grid(256)](primals_3, buf2, 256,
            XBLOCK=128, num_warps=4, num_stages=1)
        buf3 = buf0
        del buf0
        triton_poi_fused_mul_sigmoid_tanh_0[grid(16)](primals_4, primals_5,
            buf3, 16, XBLOCK=16, num_warps=1, num_stages=1)
        buf4 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf2, (64, 4), (4, 1), 0),
            reinterpret_tensor(buf3, (4, 4), (1, 4), 0), out=buf4)
        del buf3
        buf5 = empty_strided_cuda((64, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(primals_3, (64, 4), (4, 1), 0),
            reinterpret_tensor(primals_6, (4, 4), (1, 4), 0), out=buf5)
        del primals_6
        buf6 = empty_strided_cuda((4, 4, 4, 4), (64, 16, 4, 1), torch.float32)
        triton_poi_fused_add_exp_mul_rsub_sigmoid_2[grid(256)](buf5, buf1,
            buf4, buf6, 256, XBLOCK=256, num_warps=4, num_stages=1)
    return (buf6, primals_1, primals_2, primals_4, primals_5,
        reinterpret_tensor(primals_3, (64, 4), (4, 1), 0), buf1,
        reinterpret_tensor(buf2, (64, 4), (4, 1), 0), buf4, buf5)


class NAC(Module):
    """Neural Accumulator: :math:`y = Wx` where :math:`W = \\tanh(\\hat{W}) * \\sigma(\\hat{M})`

    Args:
        in_features: size of each input sample
        out_features: size of each output sample

    Shape:
        - Input: :math:`(N, *, in\\_features)` where :math:`*` means any number of
          additional dimensions
        - Output: :math:`(N, *, out\\_features)` where all but the last dimension
          are the same shape as the input.

    Attributes:
        weight_tanh: the learnable weights of the module of shape
            `(out_features x in_features)`
        weight_sigma: the learnable weights of the module of shape
            `(out_features x in_features)`

    Examples:
        >>> m = NAC(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])

        >>> m = NAC(2, 1)
        >>> _ = m.weight_tanh.data.fill_(4), m.weight_sigma.data.fill_(4)
        >>> m.weight
        tensor([[0.9814, 0.9814]], grad_fn=<ThMulBackward>)
        >>> input = torch.Tensor([[0, 1], [2, 5], [-1, 4]])
        >>> output = m(input)
        >>> output
        tensor([[0.9814],
                [6.8695],
                [2.9441]], grad_fn=<MmBackward>)
    """

    def __init__(self, in_features, out_features):
        super(NAC, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.weight_tanh = Parameter(torch.Tensor(out_features, in_features))
        self.weight_sigma = Parameter(torch.Tensor(out_features, in_features))
        self.reset_parameters()

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.out_features)
        self.weight_tanh.data.uniform_(-stdv, stdv)
        self.weight_sigma.data.uniform_(-stdv, stdv)

    @property
    def weight(self):
        """
        Effective weight of NAC
        :return:
        """
        return torch.tanh(self.weight_tanh) * torch.sigmoid(self.weight_sigma)

    def forward(self, input):
        return F.linear(input, weight=self.weight)

    def extra_repr(self):
        return 'in_features={}, out_features={}'.format(self.in_features,
            self.out_features)


class NALUNew(Module):
    """Neural Arithmetic Logic Unit: :math:`y = g * a + (1-g) * m` where :math:`g` is a sigmoidal gate,
    :math:`a` is a NAC and :math:`m` is a log-space NAC enabling multiplication.

    Args:
        in_features: size of each input sample
        out_features: size of each output sample

    Shape:
        - Input: :math:`(N, *, in\\_features)` where :math:`*` means any number of
          additional dimensions
        - Output: :math:`(N, *, out\\_features)` where all but the last dimension
          are the same shape as the input.

    Attributes:
        addition_cell: a NAC with learnable weights with the same input and output shapes as the NALU
        multiplication_cell: a NAC with learnable weights with the same input and output shapes as the NALU
        gate_weights: the learnable weights of the gate that interpolates between addition and multiplication of shape
            `(out_features x in_features)`

    Examples:
        >>> m = NALU(20, 30)
        >>> input = torch.randn(128, 20)
        >>> output = m(input)
        >>> print(output.size())
        torch.Size([128, 30])


        Check we can multiply using the multiplication cell:
        >>> m = NALU(2, 1)
        >>> _ = (m.multiplication_cell.weight_tanh.data.fill_(4), m.multiplication_cell.weight_sigma.data.fill_(4),
        ...     m.gate_weights.data.fill_(-4))
        >>> m.multiplication_cell.weight
        tensor([[0.9814, 0.9814]], grad_fn=<ThMulBackward>)
        >>> input = torch.Tensor([[0, 10], [2, 5], [-1, 4]])
        >>> output = m(input)
        >>> torch.round(output)
        tensor([[ 0.],
                [10.],
                [ 4.]], grad_fn=<RoundBackward>)
    """

    def __init__(self, in_features, out_features):
        super(NALUNew, self).__init__()
        self.in_features = in_features
        self.out_features = out_features
        self.addition_cell = NAC(in_features=in_features, out_features=
            out_features)
        self.multiplication_cell = NAC(in_features=in_features,
            out_features=out_features)
        self.gate_weights = Parameter(torch.Tensor(out_features, in_features))
        self.reset_parameters()

    def reset_parameters(self):
        stdv = 1.0 / math.sqrt(self.out_features)
        self.gate_weights.data.uniform_(-stdv, stdv)
        self.addition_cell.reset_parameters()
        self.multiplication_cell.reset_parameters()

    def extra_repr(self):
        return 'in_features={}, out_features={}'.format(self.in_features,
            self.out_features)

    def forward(self, input_0):
        primals_1 = self.gate_weights
        primals_2 = self.addition_cell.weight_tanh
        primals_4 = self.addition_cell.weight_sigma
        primals_5 = self.multiplication_cell.weight_tanh
        primals_6 = self.multiplication_cell.weight_sigma
        primals_3 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6])
        return output[0]


Measured latency_ms: 0.024239