# AOT ID: ['0_forward']
from ctypes import c_void_p, c_long, c_int
import torch
import math
import random
import os
import tempfile
from math import inf, nan
from torch._inductor.hooks import run_intermediate_hooks
from torch._inductor.utils import maybe_profile
from torch._inductor.codegen.memory_planning import _align as align
from torch import device, empty_strided
from torch._inductor.async_compile import AsyncCompile
from torch._inductor.select_algorithm import extern_kernels
from torch._inductor.codegen.multi_kernel import MultiKernelCall
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid, split_scan_grid, grid_combo_kernels, start_graph, end_graph
from torch._C import _cuda_getCurrentRawStream as get_raw_stream

aten = torch.ops.aten
inductor_ops = torch.ops.inductor
_quantized = torch.ops._quantized
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cpu = torch._C._dynamo.guards._empty_strided_cpu
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
empty_strided_xpu = torch._C._dynamo.guards._empty_strided_xpu
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor
alloc_from_pool = torch.ops.inductor._alloc_from_pool
async_compile = AsyncCompile()


# kernel path: runs/run_shard_7/inductor_cache/j6/cj6hneuwtxuqku4ka6k6f2vxucocdiv6p3b2c4kfrcb5qwbmb6sg.py
# Topologically Sorted Source Nodes: [pow_1, w_norm_sq], Original ATen: [aten.pow, aten.sum]
# Source node to ATen node mapping:
#   pow_1 => pow_1
#   w_norm_sq => sum_1
# Graph fragment:
#   %pow_1 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%select_1, 2), kwargs = {})
#   %sum_1 : [num_users=2] = call_function[target=torch.ops.aten.sum.dim_IntList](args = (%pow_1, [2], True), kwargs = {})
triton_poi_fused_pow_sum_0 = async_compile.triton('triton_poi_fused_pow_sum_0', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_pow_sum_0', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 4, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@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)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/vr/cvryswlc7olf6iscoyyxog3zotceoyz6z6tn3m7r27lzurpsbsjs.py
# Topologically Sorted Source Nodes: [wzb, tanh], Original ATen: [aten.add, aten.tanh]
# Source node to ATen node mapping:
#   tanh => tanh
#   wzb => add_2
# Graph fragment:
#   %add_2 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%bmm_1, %select_2), kwargs = {})
#   %tanh : [num_users=3] = call_function[target=torch.ops.aten.tanh.default](args = (%add_2,), kwargs = {})
triton_poi_fused_add_tanh_1 = async_compile.triton('triton_poi_fused_add_tanh_1', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_tanh_1', 'mutated_arg_names': ['in_out_ptr0'], 'no_x_dim': False, 'num_load': 3, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@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)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/5z/c5zxdmoivium33w2qam24kojs7lyxgbfb6lulnqtriq4xzdmkzgp.py
# Topologically Sorted Source Nodes: [softplus, m_uw, sub, mul, truediv, u_hat, mul_1, z, pow_2, sub_1, psi], Original ATen: [aten.softplus, aten.add, aten.sub, aten.mul, aten.div, aten.pow, aten.rsub]
# Source node to ATen node mapping:
#   m_uw => add
#   mul => mul_1
#   mul_1 => mul_2
#   pow_2 => pow_2
#   psi => mul_3
#   softplus => div, exp, gt, log1p, mul, where
#   sub => sub
#   sub_1 => sub_1
#   truediv => div_1
#   u_hat => add_1
#   z => add_3
# Graph fragment:
#   %mul : [num_users=2] = call_function[target=torch.ops.aten.mul.Tensor](args = (%bmm, 1.0), kwargs = {})
#   %exp : [num_users=1] = call_function[target=torch.ops.aten.exp.default](args = (%mul,), kwargs = {})
#   %log1p : [num_users=1] = call_function[target=torch.ops.aten.log1p.default](args = (%exp,), kwargs = {})
#   %div : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%log1p, 1.0), kwargs = {})
#   %gt : [num_users=1] = call_function[target=torch.ops.aten.gt.Scalar](args = (%mul, 20.0), kwargs = {})
#   %where : [num_users=1] = call_function[target=torch.ops.aten.where.self](args = (%gt, %bmm, %div), kwargs = {})
#   %add : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%where, -1.0), kwargs = {})
#   %sub : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (%add, %bmm), kwargs = {})
#   %mul_1 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%sub, %permute_3), kwargs = {})
#   %div_1 : [num_users=1] = call_function[target=torch.ops.aten.div.Tensor](args = (%mul_1, %sum_1), kwargs = {})
#   %add_1 : [num_users=3] = call_function[target=torch.ops.aten.add.Tensor](args = (%select, %div_1), kwargs = {})
#   %mul_2 : [num_users=1] = call_function[target=torch.ops.aten.mul.Tensor](args = (%add_1, %tanh), kwargs = {})
#   %add_3 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%unsqueeze, %mul_2), kwargs = {})
#   %pow_2 : [num_users=1] = call_function[target=torch.ops.aten.pow.Tensor_Scalar](args = (%tanh, 2), kwargs = {})
#   %sub_1 : [num_users=1] = call_function[target=torch.ops.aten.sub.Tensor](args = (1, %pow_2), kwargs = {})
#   %mul_3 : [num_users=2] = call_function[target=torch.ops.aten.mul.Tensor](args = (%select_1, %sub_1), kwargs = {})
triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2 = async_compile.triton('triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[16], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: '*fp32', 3: '*fp32', 4: '*fp32', 5: '*fp32', 6: '*fp32', 7: '*fp32', 8: '*fp32', 9: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 6, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@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)
''', device_str='cuda')


# kernel path: runs/run_shard_7/inductor_cache/as/casa25kbsjcsboxppwpjigmfgz4dqo5yacivs4ovqvekprlytwt6.py
# Topologically Sorted Source Nodes: [logdet_2], Original ATen: [aten.add]
# Source node to ATen node mapping:
#   logdet_2 => add_5
# Graph fragment:
#   %add_5 : [num_users=1] = call_function[target=torch.ops.aten.add.Tensor](args = (%squeeze_2, 0.0), kwargs = {})
triton_poi_fused_add_3 = async_compile.triton('triton_poi_fused_add_3', '''
import triton
import triton.language as tl
from triton.compiler.compiler import AttrsDescriptor

from torch._inductor.runtime import triton_helpers, triton_heuristics
from torch._inductor.runtime.triton_helpers import libdevice, math as tl_math
from torch._inductor.runtime.hints import AutotuneHint, ReductionHint, TileHint, instance_descriptor, DeviceProperties

@triton_heuristics.pointwise(
    size_hints=[4], 
    filename=__file__,
    triton_meta={'signature': {0: '*fp32', 1: '*fp32', 2: 'i32'}, 'device': DeviceProperties(type='cuda', index=0, cc=80, major=8, regs_per_multiprocessor=65536, max_threads_per_multi_processor=2048, multi_processor_count=108), 'constants': {}, 'configs': [AttrsDescriptor(divisible_by_16=(0, 1), equal_to_1=())]},
    inductor_meta={'autotune_hints': set(), 'kernel_name': 'triton_poi_fused_add_3', 'mutated_arg_names': [], 'no_x_dim': False, 'num_load': 1, 'num_reduction': 0, 'backend_hash': 'A9C866B4A14FD3277824029365D703C2427B2E685E54EC9B3EF4ADC8D1EEAC1D', 'are_deterministic_algorithms_enabled': False, 'assert_indirect_indexing': True, 'autotune_local_cache': True, 'autotune_pointwise': True, 'autotune_remote_cache': None, 'force_disable_caches': False, 'dynamic_scale_rblock': True, 'max_autotune': False, 'max_autotune_pointwise': False, 'min_split_scan_rblock': 256, 'spill_threshold': 16, 'store_cubin': False},
    min_elem_per_thread=0
)
@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)
''', device_str='cuda')


async_compile.wait(globals())
del async_compile

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)
        # Topologically Sorted Source Nodes: [linear], Original ATen: [aten.addmm]
        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)
        # Topologically Sorted Source Nodes: [linear_1], Original ATen: [aten.addmm]
        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)
        # Topologically Sorted Source Nodes: [], Original ATen: []
        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)
        # Topologically Sorted Source Nodes: [uw], Original ATen: [aten.bmm]
        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)
        # Topologically Sorted Source Nodes: [pow_1, w_norm_sq], Original ATen: [aten.pow, aten.sum]
        stream0 = get_raw_stream(0)
        triton_poi_fused_pow_sum_0.run(buf1, buf4, 4, grid=grid(4), stream=stream0)
        buf6 = empty_strided_cuda((4, 1, 1), (1, 1, 1), torch.float32)
        # Topologically Sorted Source Nodes: [bmm_1], Original ATen: [aten.bmm]
        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  # reuse
        # Topologically Sorted Source Nodes: [wzb, tanh], Original ATen: [aten.add, aten.tanh]
        triton_poi_fused_add_tanh_1.run(buf7, buf6, primals_7, 4, grid=grid(4), stream=stream0)
        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)
        # Topologically Sorted Source Nodes: [softplus, m_uw, sub, mul, truediv, u_hat, mul_1, z, pow_2, sub_1, psi], Original ATen: [aten.softplus, aten.add, aten.sub, aten.mul, aten.div, aten.pow, aten.rsub]
        triton_poi_fused_add_div_mul_pow_rsub_softplus_sub_2.run(buf0, buf3, buf1, buf4, primals_8, buf7, buf5, buf8, buf9, 16, grid=grid(16), stream=stream0)
        buf10 = buf6; del buf6  # reuse
        # Topologically Sorted Source Nodes: [bmm_2], Original ATen: [aten.bmm]
        extern_kernels.bmm(buf9, buf5, out=buf10)
        buf11 = empty_strided_cuda((4, ), (1, ), torch.float32)
        # Topologically Sorted Source Nodes: [logdet_2], Original ATen: [aten.add]
        triton_poi_fused_add_3.run(buf10, buf11, 4, grid=grid(4), stream=stream0)
    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), )


def benchmark_compiled_module(times=10, repeat=10):
    from torch._dynamo.testing import rand_strided
    from torch._inductor.utils import print_performance
    primals_1 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_2 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_3 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_4 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_5 = rand_strided((4, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_6 = rand_strided((1, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    primals_7 = rand_strided((1, ), (1, ), device='cuda:0', dtype=torch.float32)
    primals_8 = rand_strided((4, 4), (4, 1), device='cuda:0', dtype=torch.float32)
    fn = lambda: call([primals_1, primals_2, primals_3, primals_4, primals_5, primals_6, primals_7, primals_8])
    return print_performance(fn, times=times, repeat=repeat)


if __name__ == "__main__":
    from torch._inductor.wrapper_benchmark import compiled_module_main
    compiled_module_main('None', benchmark_compiled_module)

import torch
import torch.nn as nn


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 Planar(NormalizingFlow):
    """Planar Normalizing flow with single unit bottleneck."""

    def __init__(self, h_dim, z_dim, flow_depth):
        super(Planar, 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, z, h):
        u = self.h_to_u(h).view(-1, self.flow_depth, self.z_dim, 1)
        w = self.h_to_w(h).view(-1, self.flow_depth, 1, self.z_dim)
        b = self.h_to_b(h).view(-1, self.flow_depth, 1, 1)
        z_k = z
        logdet = 0.0
        for k in range(self.flow_depth):
            z_k, ldj = self.flow(z_k, u[:, k, :, :], w[:, k, :, :], b[:, k,
                :, :])
            logdet += ldj
        return z_k, logdet


def get_inputs():
    return [torch.rand([4, 4]), torch.rand([4, 4])]


def get_init_inputs():
    return [[], {'h_dim': 4, 'z_dim': 4, 'flow_depth': 1}]

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]
