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
import torch.nn as nn
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_pow_sum_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr
    ):
    xnumel = 4
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex
    tmp0 = tl.load(in_ptr0 + 4 * x0, xmask, eviction_policy='evict_last')
    tmp2 = tl.load(in_ptr0 + (1 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp5 = tl.load(in_ptr0 + (2 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp8 = tl.load(in_ptr0 + (3 + 4 * x0), xmask, eviction_policy='evict_last')
    tmp1 = tmp0 * tmp0
    tmp3 = tmp2 * tmp2
    tmp4 = tmp1 + tmp3
    tmp6 = tmp5 * tmp5
    tmp7 = tmp4 + tmp6
    tmp9 = tmp8 * tmp8
    tmp10 = tmp7 + tmp9
    tl.store(out_ptr0 + x0, tmp10, xmask)


@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, in_ptr1, xnumel,
    XBLOCK: tl.constexpr):
    xnumel = 4
    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.load(in_out_ptr0 + x0, xmask)
    tmp2 = tl.load(in_ptr1 + 0)
    tmp3 = tl.broadcast_to(tmp2, [XBLOCK])
    tmp4 = tmp1 + tmp3
    tmp5 = tmp0 + tmp4
    tmp6 = libdevice.tanh(tmp5)
    tl.store(in_out_ptr0 + x0, tmp6, xmask)


@triton.jit
def triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2(in_ptr0, in_ptr1,
    in_ptr2, in_ptr3, in_ptr4, in_ptr5, out_ptr0, out_ptr1, out_ptr2,
    xnumel, XBLOCK: tl.constexpr):
    xnumel = 16
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x1 = xindex // 4
    tmp0 = tl.load(in_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr1 + x1, xmask, eviction_policy='evict_last')
    tmp13 = tl.load(in_ptr2 + x2, xmask)
    tmp15 = tl.load(in_ptr3 + x1, xmask, eviction_policy='evict_last')
    tmp18 = tl.load(in_ptr4 + x2, xmask)
    tmp19 = tl.load(in_ptr5 + x1, xmask, eviction_policy='evict_last')
    tmp2 = 1.0
    tmp3 = tmp1 * tmp2
    tmp4 = 20.0
    tmp5 = tmp3 > tmp4
    tmp6 = tl_math.exp(tmp3)
    tmp7 = libdevice.log1p(tmp6)
    tmp8 = tmp7 * tmp2
    tmp9 = tl.where(tmp5, tmp1, tmp8)
    tmp10 = -1.0
    tmp11 = tmp9 + tmp10
    tmp12 = tmp11 - tmp1
    tmp14 = tmp12 * tmp13
    tmp16 = tmp14 / tmp15
    tmp17 = tmp0 + tmp16
    tmp20 = tmp17 * tmp19
    tmp21 = tmp18 + tmp20
    tmp22 = tmp19 * tmp19
    tmp23 = tmp2 - tmp22
    tmp24 = tmp13 * tmp23
    tl.store(out_ptr0 + x2, tmp17, xmask)
    tl.store(out_ptr1 + x2, tmp21, xmask)
    tl.store(out_ptr2 + x2, tmp24, xmask)


@triton.jit
def triton_poi_fused_add_3(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 4
    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 = 1.0
    tmp2 = tmp0 + tmp1
    tmp3 = tl_math.abs(tmp2)
    tmp4 = tl_math.log(tmp3)
    tmp5 = 0.0
    tmp6 = tmp4 + tmp5
    tl.store(out_ptr0 + x0, tmp6, xmask)


def call(args):
    (primals_1, primals_2, primals_3, primals_4, primals_5, primals_6,
        primals_7, primals_8) = args
    args.clear()
    assert_size_stride(primals_1, (4, 4), (4, 1))
    assert_size_stride(primals_2, (4,), (1,))
    assert_size_stride(primals_3, (4, 4), (4, 1))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4,), (1,))
    assert_size_stride(primals_6, (1, 4), (4, 1))
    assert_size_stride(primals_7, (1,), (1,))
    assert_size_stride(primals_8, (4, 4), (4, 1))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_2, primals_3, reinterpret_tensor(
            primals_1, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf0)
        del primals_1
        del primals_2
        buf1 = empty_strided_cuda((4, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_5, primals_3, reinterpret_tensor(
            primals_4, (4, 4), (1, 4), 0), alpha=1, beta=1, out=buf1)
        del primals_4
        del primals_5
        buf2 = empty_strided_cuda((4, 1), (1, 1), torch.float32)
        extern_kernels.mm(primals_3, reinterpret_tensor(primals_6, (4, 1),
            (1, 4), 0), out=buf2)
        del primals_6
        buf3 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
            ), reinterpret_tensor(buf0, (4, 4, 1), (4, 1, 1), 0), out=buf3)
        buf4 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_pow_sum_0[grid(4)](buf1, buf4, 4, XBLOCK=4,
            num_warps=1, num_stages=1)
        buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        extern_kernels.bmm(reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
            ), reinterpret_tensor(primals_8, (4, 4, 1), (4, 1, 1), 0), out=buf6
            )
        buf7 = reinterpret_tensor(buf2, (4, 1, 1), (1, 1, 1), 0)
        del buf2
        triton_poi_fused_add_tanh_1[grid(4)](buf7, buf6, primals_7, 4,
            XBLOCK=4, num_warps=1, num_stages=1)
        del primals_7
        buf5 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        buf8 = empty_strided_cuda((4, 4, 1), (4, 1, 1), torch.float32)
        buf9 = empty_strided_cuda((4, 1, 4), (4, 16, 1), torch.float32)
        triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2[grid(16)](buf0,
            buf3, buf1, buf4, primals_8, buf7, buf5, buf8, buf9, 16, XBLOCK
            =16, num_warps=1, num_stages=1)
        buf10 = buf6
        del buf6
        extern_kernels.bmm(buf9, buf5, out=buf10)
        buf11 = empty_strided_cuda((4,), (1,), torch.float32)
        triton_poi_fused_add_3[grid(4)](buf10, buf11, 4, XBLOCK=4,
            num_warps=1, num_stages=1)
    return reinterpret_tensor(buf8, (4, 4), (4, 1), 0
        ), buf11, primals_3, reinterpret_tensor(buf1, (4, 1, 4), (4, 4, 1), 0
        ), buf3, buf4, buf5, buf7, buf10, reinterpret_tensor(buf9, (4, 4, 1
        ), (4, 1, 4), 0), reinterpret_tensor(primals_8, (4, 1, 4), (4, 1, 1), 0
        ), reinterpret_tensor(buf0, (4, 1, 4), (4, 1, 1), 0)


class PlanarStep(nn.Module):

    def __init__(self):
        super(PlanarStep, self).__init__()
        self.h = nn.Tanh()
        self.softplus = nn.Softplus()

    def _der_h(self, x):
        """Derivative of activation function h."""
        return self._der_tanh(x)

    def _der_tanh(self, x):
        """Derivative of the Tanh function."""
        return 1 - self.h(x) ** 2

    def forward(self, zk, u, w, b):
        """
        Forward pass. Assumes amortized u, w and b. Conditions on diagonals of u and w for invertibility
        will be be satisfied inside this function. Computes the following transformation:
        z' = z + u h( w^T z + b)
        or actually
        z'^T = z^T + h(z^T w + b)u^T
        Assumes the following input shapes:
        shape u = (batch_size, z_dim, 1)
        shape w = (batch_size, 1, z_dim)
        shape b = (batch_size, 1, 1)
        shape z = (batch_size, z_dim).
        """
        zk = zk.unsqueeze(2)
        uw = torch.bmm(w, u)
        m_uw = -1.0 + self.softplus(uw)
        w_norm_sq = torch.sum(w ** 2, dim=2, keepdim=True)
        u_hat = u + (m_uw - uw) * w.transpose(2, 1) / w_norm_sq
        wzb = torch.bmm(w, zk) + b
        z = zk + u_hat * self.h(wzb)
        z = z.squeeze(2)
        psi = w * self._der_h(wzb)
        logdet = torch.log(torch.abs(1 + torch.bmm(psi, u_hat)))
        logdet = logdet.squeeze(2).squeeze(1)
        return z, logdet


class Error(Exception):
    """Base error class, from which all other errors derive."""
    pass


class InvalidArgumentError(Error):
    """This error will be shown when a given argument has an invalid value."""
    pass


class NormalizingFlow(nn.Module):
    """Base class for normalizing flows."""

    def __init__(self, h_dim, z_dim, flow_depth, hidden_depth):
        super(NormalizingFlow, self).__init__()
        self.h_dim = h_dim
        self.z_dim = z_dim
        self.flow_depth = flow_depth
        self.hidden_depth = hidden_depth

    @property
    def flow_depth(self):
        return self._flow_depth

    @flow_depth.setter
    def flow_depth(self, value):
        if not isinstance(value, int):
            raise InvalidArgumentError('flow_depth should be an integer.')
        elif value < 1:
            raise InvalidArgumentError(
                'flow_depth should be strictly positive.')
        else:
            self._flow_depth = value

    @property
    def hidden_depth(self):
        return self._hidden_depth

    @hidden_depth.setter
    def hidden_depth(self, value):
        if not isinstance(value, int):
            raise InvalidArgumentError('hidden_depth should be an integer.')
        elif value < 0:
            raise InvalidArgumentError('hidden_depth should be positive.')
        else:
            self._hidden_depth = value


class PlanarNew(NormalizingFlow):
    """Planar Normalizing flow with single unit bottleneck."""

    def __init__(self, h_dim, z_dim, flow_depth):
        super(PlanarNew, self).__init__(h_dim, z_dim, flow_depth, 0)
        self.flow = PlanarStep()
        self.h_to_u = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
        self.h_to_w = nn.Linear(self.h_dim, self.flow_depth * self.z_dim)
        self.h_to_b = nn.Linear(self.h_dim, self.flow_depth)

    def forward(self, input_0, input_1):
        primals_1 = self.h_to_u.weight
        primals_2 = self.h_to_u.bias
        primals_3 = self.h_to_w.weight
        primals_5 = self.h_to_w.bias
        primals_6 = self.h_to_b.weight
        primals_7 = self.h_to_b.bias
        primals_4 = input_0
        primals_8 = input_1
        output = call([primals_1, primals_2, primals_3, primals_4,
            primals_5, primals_6, primals_7, primals_8])
        return output[0], output[1]


Measured latency_ms: 0.016538